• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "pager.h"
28 #include "btree.h"
29 
30 /*
31 ** This routine is called when a new SQL statement is beginning to
32 ** be parsed.  Initialize the pParse structure as needed.
33 */
sqlite3BeginParse(Parse * pParse,int explainFlag)34 void sqlite3BeginParse(Parse *pParse, int explainFlag){
35   pParse->explain = (u8)explainFlag;
36   pParse->nVar = 0;
37 }
38 
39 #ifndef SQLITE_OMIT_SHARED_CACHE
40 /*
41 ** The TableLock structure is only used by the sqlite3TableLock() and
42 ** codeTableLocks() functions.
43 */
44 struct TableLock {
45   int iDb;             /* The database containing the table to be locked */
46   int iTab;            /* The root page of the table to be locked */
47   u8 isWriteLock;      /* True for write lock.  False for a read lock */
48   const char *zName;   /* Name of the table */
49 };
50 
51 /*
52 ** Record the fact that we want to lock a table at run-time.
53 **
54 ** The table to be locked has root page iTab and is found in database iDb.
55 ** A read or a write lock can be taken depending on isWritelock.
56 **
57 ** This routine just records the fact that the lock is desired.  The
58 ** code to make the lock occur is generated by a later call to
59 ** codeTableLocks() which occurs during sqlite3FinishCoding().
60 */
sqlite3TableLock(Parse * pParse,int iDb,int iTab,u8 isWriteLock,const char * zName)61 void sqlite3TableLock(
62   Parse *pParse,     /* Parsing context */
63   int iDb,           /* Index of the database containing the table to lock */
64   int iTab,          /* Root page number of the table to be locked */
65   u8 isWriteLock,    /* True for a write lock */
66   const char *zName  /* Name of the table to be locked */
67 ){
68   Parse *pToplevel = sqlite3ParseToplevel(pParse);
69   int i;
70   int nBytes;
71   TableLock *p;
72   assert( iDb>=0 );
73 
74   for(i=0; i<pToplevel->nTableLock; i++){
75     p = &pToplevel->aTableLock[i];
76     if( p->iDb==iDb && p->iTab==iTab ){
77       p->isWriteLock = (p->isWriteLock || isWriteLock);
78       return;
79     }
80   }
81 
82   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
83   pToplevel->aTableLock =
84       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
85   if( pToplevel->aTableLock ){
86     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
87     p->iDb = iDb;
88     p->iTab = iTab;
89     p->isWriteLock = isWriteLock;
90     p->zName = zName;
91   }else{
92     pToplevel->nTableLock = 0;
93     pToplevel->db->mallocFailed = 1;
94   }
95 }
96 
97 /*
98 ** Code an OP_TableLock instruction for each table locked by the
99 ** statement (configured by calls to sqlite3TableLock()).
100 */
codeTableLocks(Parse * pParse)101 static void codeTableLocks(Parse *pParse){
102   int i;
103   Vdbe *pVdbe;
104 
105   pVdbe = sqlite3GetVdbe(pParse);
106   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
107 
108   for(i=0; i<pParse->nTableLock; i++){
109     TableLock *p = &pParse->aTableLock[i];
110     int p1 = p->iDb;
111     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
112                       p->zName, P4_STATIC);
113   }
114 }
115 #else
116   #define codeTableLocks(x)
117 #endif
118 
119 /*
120 ** This routine is called after a single SQL statement has been
121 ** parsed and a VDBE program to execute that statement has been
122 ** prepared.  This routine puts the finishing touches on the
123 ** VDBE program and resets the pParse structure for the next
124 ** parse.
125 **
126 ** Note that if an error occurred, it might be the case that
127 ** no VDBE code was generated.
128 */
sqlite3FinishCoding(Parse * pParse)129 void sqlite3FinishCoding(Parse *pParse){
130   sqlite3 *db;
131   Vdbe *v;
132 
133   db = pParse->db;
134   if( db->mallocFailed ) return;
135   if( pParse->nested ) return;
136   if( pParse->nErr ) return;
137 
138   /* Begin by generating some termination code at the end of the
139   ** vdbe program
140   */
141   v = sqlite3GetVdbe(pParse);
142   assert( !pParse->isMultiWrite
143        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
144   if( v ){
145     sqlite3VdbeAddOp0(v, OP_Halt);
146 
147     /* The cookie mask contains one bit for each database file open.
148     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
149     ** set for each database that is used.  Generate code to start a
150     ** transaction on each used database and to verify the schema cookie
151     ** on each used database.
152     */
153     if( pParse->cookieGoto>0 ){
154       yDbMask mask;
155       int iDb;
156       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
157       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
158         if( (mask & pParse->cookieMask)==0 ) continue;
159         sqlite3VdbeUsesBtree(v, iDb);
160         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
161         if( db->init.busy==0 ){
162           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
163           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
164                             iDb, pParse->cookieValue[iDb],
165                             db->aDb[iDb].pSchema->iGeneration);
166         }
167       }
168 #ifndef SQLITE_OMIT_VIRTUALTABLE
169       {
170         int i;
171         for(i=0; i<pParse->nVtabLock; i++){
172           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
173           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
174         }
175         pParse->nVtabLock = 0;
176       }
177 #endif
178 
179       /* Once all the cookies have been verified and transactions opened,
180       ** obtain the required table-locks. This is a no-op unless the
181       ** shared-cache feature is enabled.
182       */
183       codeTableLocks(pParse);
184 
185       /* Initialize any AUTOINCREMENT data structures required.
186       */
187       sqlite3AutoincrementBegin(pParse);
188 
189       /* Finally, jump back to the beginning of the executable code. */
190       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
191     }
192   }
193 
194 
195   /* Get the VDBE program ready for execution
196   */
197   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
198 #ifdef SQLITE_DEBUG
199     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
200     sqlite3VdbeTrace(v, trace);
201 #endif
202     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
203     /* A minimum of one cursor is required if autoincrement is used
204     *  See ticket [a696379c1f08866] */
205     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
206     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
207                          pParse->nTab, pParse->nMaxArg, pParse->explain,
208                          pParse->isMultiWrite && pParse->mayAbort);
209     pParse->rc = SQLITE_DONE;
210     pParse->colNamesSet = 0;
211   }else{
212     pParse->rc = SQLITE_ERROR;
213   }
214   pParse->nTab = 0;
215   pParse->nMem = 0;
216   pParse->nSet = 0;
217   pParse->nVar = 0;
218   pParse->cookieMask = 0;
219   pParse->cookieGoto = 0;
220 }
221 
222 /*
223 ** Run the parser and code generator recursively in order to generate
224 ** code for the SQL statement given onto the end of the pParse context
225 ** currently under construction.  When the parser is run recursively
226 ** this way, the final OP_Halt is not appended and other initialization
227 ** and finalization steps are omitted because those are handling by the
228 ** outermost parser.
229 **
230 ** Not everything is nestable.  This facility is designed to permit
231 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
232 ** care if you decide to try to use this routine for some other purposes.
233 */
sqlite3NestedParse(Parse * pParse,const char * zFormat,...)234 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
235   va_list ap;
236   char *zSql;
237   char *zErrMsg = 0;
238   sqlite3 *db = pParse->db;
239 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
240   char saveBuf[SAVE_SZ];
241 
242   if( pParse->nErr ) return;
243   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
244   va_start(ap, zFormat);
245   zSql = sqlite3VMPrintf(db, zFormat, ap);
246   va_end(ap);
247   if( zSql==0 ){
248     return;   /* A malloc must have failed */
249   }
250   pParse->nested++;
251   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
252   memset(&pParse->nVar, 0, SAVE_SZ);
253   sqlite3RunParser(pParse, zSql, &zErrMsg);
254   sqlite3DbFree(db, zErrMsg);
255   sqlite3DbFree(db, zSql);
256   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
257   pParse->nested--;
258 }
259 
260 /*
261 ** Locate the in-memory structure that describes a particular database
262 ** table given the name of that table and (optionally) the name of the
263 ** database containing the table.  Return NULL if not found.
264 **
265 ** If zDatabase is 0, all databases are searched for the table and the
266 ** first matching table is returned.  (No checking for duplicate table
267 ** names is done.)  The search order is TEMP first, then MAIN, then any
268 ** auxiliary databases added using the ATTACH command.
269 **
270 ** See also sqlite3LocateTable().
271 */
sqlite3FindTable(sqlite3 * db,const char * zName,const char * zDatabase)272 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
273   Table *p = 0;
274   int i;
275   int nName;
276   assert( zName!=0 );
277   nName = sqlite3Strlen30(zName);
278   /* All mutexes are required for schema access.  Make sure we hold them. */
279   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
280   for(i=OMIT_TEMPDB; i<db->nDb; i++){
281     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
282     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
283     assert( sqlite3SchemaMutexHeld(db, j, 0) );
284     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
285     if( p ) break;
286   }
287   return p;
288 }
289 
290 /*
291 ** Locate the in-memory structure that describes a particular database
292 ** table given the name of that table and (optionally) the name of the
293 ** database containing the table.  Return NULL if not found.  Also leave an
294 ** error message in pParse->zErrMsg.
295 **
296 ** The difference between this routine and sqlite3FindTable() is that this
297 ** routine leaves an error message in pParse->zErrMsg where
298 ** sqlite3FindTable() does not.
299 */
sqlite3LocateTable(Parse * pParse,int isView,const char * zName,const char * zDbase)300 Table *sqlite3LocateTable(
301   Parse *pParse,         /* context in which to report errors */
302   int isView,            /* True if looking for a VIEW rather than a TABLE */
303   const char *zName,     /* Name of the table we are looking for */
304   const char *zDbase     /* Name of the database.  Might be NULL */
305 ){
306   Table *p;
307 
308   /* Read the database schema. If an error occurs, leave an error message
309   ** and code in pParse and return NULL. */
310   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
311     return 0;
312   }
313 
314   p = sqlite3FindTable(pParse->db, zName, zDbase);
315   if( p==0 ){
316     const char *zMsg = isView ? "no such view" : "no such table";
317     if( zDbase ){
318       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
319     }else{
320       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
321     }
322     pParse->checkSchema = 1;
323   }
324   return p;
325 }
326 
327 /*
328 ** Locate the in-memory structure that describes
329 ** a particular index given the name of that index
330 ** and the name of the database that contains the index.
331 ** Return NULL if not found.
332 **
333 ** If zDatabase is 0, all databases are searched for the
334 ** table and the first matching index is returned.  (No checking
335 ** for duplicate index names is done.)  The search order is
336 ** TEMP first, then MAIN, then any auxiliary databases added
337 ** using the ATTACH command.
338 */
sqlite3FindIndex(sqlite3 * db,const char * zName,const char * zDb)339 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
340   Index *p = 0;
341   int i;
342   int nName = sqlite3Strlen30(zName);
343   /* All mutexes are required for schema access.  Make sure we hold them. */
344   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
345   for(i=OMIT_TEMPDB; i<db->nDb; i++){
346     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
347     Schema *pSchema = db->aDb[j].pSchema;
348     assert( pSchema );
349     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
350     assert( sqlite3SchemaMutexHeld(db, j, 0) );
351     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
352     if( p ) break;
353   }
354   return p;
355 }
356 
357 /*
358 ** Reclaim the memory used by an index
359 */
freeIndex(sqlite3 * db,Index * p)360 static void freeIndex(sqlite3 *db, Index *p){
361 #ifndef SQLITE_OMIT_ANALYZE
362   sqlite3DeleteIndexSamples(db, p);
363 #endif
364   sqlite3DbFree(db, p->zColAff);
365   sqlite3DbFree(db, p);
366 }
367 
368 /*
369 ** For the index called zIdxName which is found in the database iDb,
370 ** unlike that index from its Table then remove the index from
371 ** the index hash table and free all memory structures associated
372 ** with the index.
373 */
sqlite3UnlinkAndDeleteIndex(sqlite3 * db,int iDb,const char * zIdxName)374 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
375   Index *pIndex;
376   int len;
377   Hash *pHash;
378 
379   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
380   pHash = &db->aDb[iDb].pSchema->idxHash;
381   len = sqlite3Strlen30(zIdxName);
382   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
383   if( ALWAYS(pIndex) ){
384     if( pIndex->pTable->pIndex==pIndex ){
385       pIndex->pTable->pIndex = pIndex->pNext;
386     }else{
387       Index *p;
388       /* Justification of ALWAYS();  The index must be on the list of
389       ** indices. */
390       p = pIndex->pTable->pIndex;
391       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
392       if( ALWAYS(p && p->pNext==pIndex) ){
393         p->pNext = pIndex->pNext;
394       }
395     }
396     freeIndex(db, pIndex);
397   }
398   db->flags |= SQLITE_InternChanges;
399 }
400 
401 /*
402 ** Erase all schema information from the in-memory hash tables of
403 ** a single database.  This routine is called to reclaim memory
404 ** before the database closes.  It is also called during a rollback
405 ** if there were schema changes during the transaction or if a
406 ** schema-cookie mismatch occurs.
407 **
408 ** If iDb<0 then reset the internal schema tables for all database
409 ** files.  If iDb>=0 then reset the internal schema for only the
410 ** single file indicated.
411 */
sqlite3ResetInternalSchema(sqlite3 * db,int iDb)412 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
413   int i, j;
414   assert( iDb<db->nDb );
415 
416   if( iDb>=0 ){
417     /* Case 1:  Reset the single schema identified by iDb */
418     Db *pDb = &db->aDb[iDb];
419     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
420     assert( pDb->pSchema!=0 );
421     sqlite3SchemaClear(pDb->pSchema);
422 
423     /* If any database other than TEMP is reset, then also reset TEMP
424     ** since TEMP might be holding triggers that reference tables in the
425     ** other database.
426     */
427     if( iDb!=1 ){
428       pDb = &db->aDb[1];
429       assert( pDb->pSchema!=0 );
430       sqlite3SchemaClear(pDb->pSchema);
431     }
432     return;
433   }
434   /* Case 2 (from here to the end): Reset all schemas for all attached
435   ** databases. */
436   assert( iDb<0 );
437   sqlite3BtreeEnterAll(db);
438   for(i=0; i<db->nDb; i++){
439     Db *pDb = &db->aDb[i];
440     if( pDb->pSchema ){
441       sqlite3SchemaClear(pDb->pSchema);
442     }
443   }
444   db->flags &= ~SQLITE_InternChanges;
445   sqlite3VtabUnlockList(db);
446   sqlite3BtreeLeaveAll(db);
447 
448   /* If one or more of the auxiliary database files has been closed,
449   ** then remove them from the auxiliary database list.  We take the
450   ** opportunity to do this here since we have just deleted all of the
451   ** schema hash tables and therefore do not have to make any changes
452   ** to any of those tables.
453   */
454   for(i=j=2; i<db->nDb; i++){
455     struct Db *pDb = &db->aDb[i];
456     if( pDb->pBt==0 ){
457       sqlite3DbFree(db, pDb->zName);
458       pDb->zName = 0;
459       continue;
460     }
461     if( j<i ){
462       db->aDb[j] = db->aDb[i];
463     }
464     j++;
465   }
466   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
467   db->nDb = j;
468   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
469     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
470     sqlite3DbFree(db, db->aDb);
471     db->aDb = db->aDbStatic;
472   }
473 }
474 
475 /*
476 ** This routine is called when a commit occurs.
477 */
sqlite3CommitInternalChanges(sqlite3 * db)478 void sqlite3CommitInternalChanges(sqlite3 *db){
479   db->flags &= ~SQLITE_InternChanges;
480 }
481 
482 /*
483 ** Delete memory allocated for the column names of a table or view (the
484 ** Table.aCol[] array).
485 */
sqliteDeleteColumnNames(sqlite3 * db,Table * pTable)486 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
487   int i;
488   Column *pCol;
489   assert( pTable!=0 );
490   if( (pCol = pTable->aCol)!=0 ){
491     for(i=0; i<pTable->nCol; i++, pCol++){
492       sqlite3DbFree(db, pCol->zName);
493       sqlite3ExprDelete(db, pCol->pDflt);
494       sqlite3DbFree(db, pCol->zDflt);
495       sqlite3DbFree(db, pCol->zType);
496       sqlite3DbFree(db, pCol->zColl);
497     }
498     sqlite3DbFree(db, pTable->aCol);
499   }
500 }
501 
502 /*
503 ** Remove the memory data structures associated with the given
504 ** Table.  No changes are made to disk by this routine.
505 **
506 ** This routine just deletes the data structure.  It does not unlink
507 ** the table data structure from the hash table.  But it does destroy
508 ** memory structures of the indices and foreign keys associated with
509 ** the table.
510 */
sqlite3DeleteTable(sqlite3 * db,Table * pTable)511 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
512   Index *pIndex, *pNext;
513 
514   assert( !pTable || pTable->nRef>0 );
515 
516   /* Do not delete the table until the reference count reaches zero. */
517   if( !pTable ) return;
518   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
519 
520   /* Delete all indices associated with this table. */
521   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
522     pNext = pIndex->pNext;
523     assert( pIndex->pSchema==pTable->pSchema );
524     if( !db || db->pnBytesFreed==0 ){
525       char *zName = pIndex->zName;
526       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
527 	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
528       );
529       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
530       assert( pOld==pIndex || pOld==0 );
531     }
532     freeIndex(db, pIndex);
533   }
534 
535   /* Delete any foreign keys attached to this table. */
536   sqlite3FkDelete(db, pTable);
537 
538   /* Delete the Table structure itself.
539   */
540   sqliteDeleteColumnNames(db, pTable);
541   sqlite3DbFree(db, pTable->zName);
542   sqlite3DbFree(db, pTable->zColAff);
543   sqlite3SelectDelete(db, pTable->pSelect);
544 #ifndef SQLITE_OMIT_CHECK
545   sqlite3ExprDelete(db, pTable->pCheck);
546 #endif
547 #ifndef SQLITE_OMIT_VIRTUALTABLE
548   sqlite3VtabClear(db, pTable);
549 #endif
550   sqlite3DbFree(db, pTable);
551 }
552 
553 /*
554 ** Unlink the given table from the hash tables and the delete the
555 ** table structure with all its indices and foreign keys.
556 */
sqlite3UnlinkAndDeleteTable(sqlite3 * db,int iDb,const char * zTabName)557 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
558   Table *p;
559   Db *pDb;
560 
561   assert( db!=0 );
562   assert( iDb>=0 && iDb<db->nDb );
563   assert( zTabName );
564   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
565   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
566   pDb = &db->aDb[iDb];
567   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
568                         sqlite3Strlen30(zTabName),0);
569   sqlite3DeleteTable(db, p);
570   db->flags |= SQLITE_InternChanges;
571 }
572 
573 /*
574 ** Given a token, return a string that consists of the text of that
575 ** token.  Space to hold the returned string
576 ** is obtained from sqliteMalloc() and must be freed by the calling
577 ** function.
578 **
579 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
580 ** surround the body of the token are removed.
581 **
582 ** Tokens are often just pointers into the original SQL text and so
583 ** are not \000 terminated and are not persistent.  The returned string
584 ** is \000 terminated and is persistent.
585 */
sqlite3NameFromToken(sqlite3 * db,Token * pName)586 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
587   char *zName;
588   if( pName ){
589     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
590     sqlite3Dequote(zName);
591   }else{
592     zName = 0;
593   }
594   return zName;
595 }
596 
597 /*
598 ** Open the sqlite_master table stored in database number iDb for
599 ** writing. The table is opened using cursor 0.
600 */
sqlite3OpenMasterTable(Parse * p,int iDb)601 void sqlite3OpenMasterTable(Parse *p, int iDb){
602   Vdbe *v = sqlite3GetVdbe(p);
603   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
604   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
605   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
606   if( p->nTab==0 ){
607     p->nTab = 1;
608   }
609 }
610 
611 /*
612 ** Parameter zName points to a nul-terminated buffer containing the name
613 ** of a database ("main", "temp" or the name of an attached db). This
614 ** function returns the index of the named database in db->aDb[], or
615 ** -1 if the named db cannot be found.
616 */
sqlite3FindDbName(sqlite3 * db,const char * zName)617 int sqlite3FindDbName(sqlite3 *db, const char *zName){
618   int i = -1;         /* Database number */
619   if( zName ){
620     Db *pDb;
621     int n = sqlite3Strlen30(zName);
622     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
623       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
624           0==sqlite3StrICmp(pDb->zName, zName) ){
625         break;
626       }
627     }
628   }
629   return i;
630 }
631 
632 /*
633 ** The token *pName contains the name of a database (either "main" or
634 ** "temp" or the name of an attached db). This routine returns the
635 ** index of the named database in db->aDb[], or -1 if the named db
636 ** does not exist.
637 */
sqlite3FindDb(sqlite3 * db,Token * pName)638 int sqlite3FindDb(sqlite3 *db, Token *pName){
639   int i;                               /* Database number */
640   char *zName;                         /* Name we are searching for */
641   zName = sqlite3NameFromToken(db, pName);
642   i = sqlite3FindDbName(db, zName);
643   sqlite3DbFree(db, zName);
644   return i;
645 }
646 
647 /* The table or view or trigger name is passed to this routine via tokens
648 ** pName1 and pName2. If the table name was fully qualified, for example:
649 **
650 ** CREATE TABLE xxx.yyy (...);
651 **
652 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
653 ** the table name is not fully qualified, i.e.:
654 **
655 ** CREATE TABLE yyy(...);
656 **
657 ** Then pName1 is set to "yyy" and pName2 is "".
658 **
659 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
660 ** pName2) that stores the unqualified table name.  The index of the
661 ** database "xxx" is returned.
662 */
sqlite3TwoPartName(Parse * pParse,Token * pName1,Token * pName2,Token ** pUnqual)663 int sqlite3TwoPartName(
664   Parse *pParse,      /* Parsing and code generating context */
665   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
666   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
667   Token **pUnqual     /* Write the unqualified object name here */
668 ){
669   int iDb;                    /* Database holding the object */
670   sqlite3 *db = pParse->db;
671 
672   if( ALWAYS(pName2!=0) && pName2->n>0 ){
673     if( db->init.busy ) {
674       sqlite3ErrorMsg(pParse, "corrupt database");
675       pParse->nErr++;
676       return -1;
677     }
678     *pUnqual = pName2;
679     iDb = sqlite3FindDb(db, pName1);
680     if( iDb<0 ){
681       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
682       pParse->nErr++;
683       return -1;
684     }
685   }else{
686     assert( db->init.iDb==0 || db->init.busy );
687     iDb = db->init.iDb;
688     *pUnqual = pName1;
689   }
690   return iDb;
691 }
692 
693 /*
694 ** This routine is used to check if the UTF-8 string zName is a legal
695 ** unqualified name for a new schema object (table, index, view or
696 ** trigger). All names are legal except those that begin with the string
697 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
698 ** is reserved for internal use.
699 */
sqlite3CheckObjectName(Parse * pParse,const char * zName)700 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
701   if( !pParse->db->init.busy && pParse->nested==0
702           && (pParse->db->flags & SQLITE_WriteSchema)==0
703           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
704     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
705     return SQLITE_ERROR;
706   }
707   return SQLITE_OK;
708 }
709 
710 /*
711 ** Begin constructing a new table representation in memory.  This is
712 ** the first of several action routines that get called in response
713 ** to a CREATE TABLE statement.  In particular, this routine is called
714 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
715 ** flag is true if the table should be stored in the auxiliary database
716 ** file instead of in the main database file.  This is normally the case
717 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
718 ** CREATE and TABLE.
719 **
720 ** The new table record is initialized and put in pParse->pNewTable.
721 ** As more of the CREATE TABLE statement is parsed, additional action
722 ** routines will be called to add more information to this record.
723 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
724 ** is called to complete the construction of the new table record.
725 */
sqlite3StartTable(Parse * pParse,Token * pName1,Token * pName2,int isTemp,int isView,int isVirtual,int noErr)726 void sqlite3StartTable(
727   Parse *pParse,   /* Parser context */
728   Token *pName1,   /* First part of the name of the table or view */
729   Token *pName2,   /* Second part of the name of the table or view */
730   int isTemp,      /* True if this is a TEMP table */
731   int isView,      /* True if this is a VIEW */
732   int isVirtual,   /* True if this is a VIRTUAL table */
733   int noErr        /* Do nothing if table already exists */
734 ){
735   Table *pTable;
736   char *zName = 0; /* The name of the new table */
737   sqlite3 *db = pParse->db;
738   Vdbe *v;
739   int iDb;         /* Database number to create the table in */
740   Token *pName;    /* Unqualified name of the table to create */
741 
742   /* The table or view name to create is passed to this routine via tokens
743   ** pName1 and pName2. If the table name was fully qualified, for example:
744   **
745   ** CREATE TABLE xxx.yyy (...);
746   **
747   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
748   ** the table name is not fully qualified, i.e.:
749   **
750   ** CREATE TABLE yyy(...);
751   **
752   ** Then pName1 is set to "yyy" and pName2 is "".
753   **
754   ** The call below sets the pName pointer to point at the token (pName1 or
755   ** pName2) that stores the unqualified table name. The variable iDb is
756   ** set to the index of the database that the table or view is to be
757   ** created in.
758   */
759   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
760   if( iDb<0 ) return;
761   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
762     /* If creating a temp table, the name may not be qualified. Unless
763     ** the database name is "temp" anyway.  */
764     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
765     return;
766   }
767   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
768 
769   pParse->sNameToken = *pName;
770   zName = sqlite3NameFromToken(db, pName);
771   if( zName==0 ) return;
772   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
773     goto begin_table_error;
774   }
775   if( db->init.iDb==1 ) isTemp = 1;
776 #ifndef SQLITE_OMIT_AUTHORIZATION
777   assert( (isTemp & 1)==isTemp );
778   {
779     int code;
780     char *zDb = db->aDb[iDb].zName;
781     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
782       goto begin_table_error;
783     }
784     if( isView ){
785       if( !OMIT_TEMPDB && isTemp ){
786         code = SQLITE_CREATE_TEMP_VIEW;
787       }else{
788         code = SQLITE_CREATE_VIEW;
789       }
790     }else{
791       if( !OMIT_TEMPDB && isTemp ){
792         code = SQLITE_CREATE_TEMP_TABLE;
793       }else{
794         code = SQLITE_CREATE_TABLE;
795       }
796     }
797     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
798       goto begin_table_error;
799     }
800   }
801 #endif
802 
803   /* Make sure the new table name does not collide with an existing
804   ** index or table name in the same database.  Issue an error message if
805   ** it does. The exception is if the statement being parsed was passed
806   ** to an sqlite3_declare_vtab() call. In that case only the column names
807   ** and types will be used, so there is no need to test for namespace
808   ** collisions.
809   */
810   if( !IN_DECLARE_VTAB ){
811     char *zDb = db->aDb[iDb].zName;
812     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
813       goto begin_table_error;
814     }
815     pTable = sqlite3FindTable(db, zName, zDb);
816     if( pTable ){
817       if( !noErr ){
818         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
819       }else{
820         assert( !db->init.busy );
821         sqlite3CodeVerifySchema(pParse, iDb);
822       }
823       goto begin_table_error;
824     }
825     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
826       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
827       goto begin_table_error;
828     }
829   }
830 
831   pTable = sqlite3DbMallocZero(db, sizeof(Table));
832   if( pTable==0 ){
833     db->mallocFailed = 1;
834     pParse->rc = SQLITE_NOMEM;
835     pParse->nErr++;
836     goto begin_table_error;
837   }
838   pTable->zName = zName;
839   pTable->iPKey = -1;
840   pTable->pSchema = db->aDb[iDb].pSchema;
841   pTable->nRef = 1;
842   pTable->nRowEst = 1000000;
843   assert( pParse->pNewTable==0 );
844   pParse->pNewTable = pTable;
845 
846   /* If this is the magic sqlite_sequence table used by autoincrement,
847   ** then record a pointer to this table in the main database structure
848   ** so that INSERT can find the table easily.
849   */
850 #ifndef SQLITE_OMIT_AUTOINCREMENT
851   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
852     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
853     pTable->pSchema->pSeqTab = pTable;
854   }
855 #endif
856 
857   /* Begin generating the code that will insert the table record into
858   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
859   ** and allocate the record number for the table entry now.  Before any
860   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
861   ** indices to be created and the table record must come before the
862   ** indices.  Hence, the record number for the table must be allocated
863   ** now.
864   */
865   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
866     int j1;
867     int fileFormat;
868     int reg1, reg2, reg3;
869     sqlite3BeginWriteOperation(pParse, 0, iDb);
870 
871 #ifndef SQLITE_OMIT_VIRTUALTABLE
872     if( isVirtual ){
873       sqlite3VdbeAddOp0(v, OP_VBegin);
874     }
875 #endif
876 
877     /* If the file format and encoding in the database have not been set,
878     ** set them now.
879     */
880     reg1 = pParse->regRowid = ++pParse->nMem;
881     reg2 = pParse->regRoot = ++pParse->nMem;
882     reg3 = ++pParse->nMem;
883     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
884     sqlite3VdbeUsesBtree(v, iDb);
885     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
886     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
887                   1 : SQLITE_MAX_FILE_FORMAT;
888     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
889     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
890     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
891     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
892     sqlite3VdbeJumpHere(v, j1);
893 
894     /* This just creates a place-holder record in the sqlite_master table.
895     ** The record created does not contain anything yet.  It will be replaced
896     ** by the real entry in code generated at sqlite3EndTable().
897     **
898     ** The rowid for the new entry is left in register pParse->regRowid.
899     ** The root page number of the new table is left in reg pParse->regRoot.
900     ** The rowid and root page number values are needed by the code that
901     ** sqlite3EndTable will generate.
902     */
903 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
904     if( isView || isVirtual ){
905       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
906     }else
907 #endif
908     {
909       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
910     }
911     sqlite3OpenMasterTable(pParse, iDb);
912     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
913     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
914     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
915     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
916     sqlite3VdbeAddOp0(v, OP_Close);
917   }
918 
919   /* Normal (non-error) return. */
920   return;
921 
922   /* If an error occurs, we jump here */
923 begin_table_error:
924   sqlite3DbFree(db, zName);
925   return;
926 }
927 
928 /*
929 ** This macro is used to compare two strings in a case-insensitive manner.
930 ** It is slightly faster than calling sqlite3StrICmp() directly, but
931 ** produces larger code.
932 **
933 ** WARNING: This macro is not compatible with the strcmp() family. It
934 ** returns true if the two strings are equal, otherwise false.
935 */
936 #define STRICMP(x, y) (\
937 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
938 sqlite3UpperToLower[*(unsigned char *)(y)]     \
939 && sqlite3StrICmp((x)+1,(y)+1)==0 )
940 
941 /*
942 ** Add a new column to the table currently being constructed.
943 **
944 ** The parser calls this routine once for each column declaration
945 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
946 ** first to get things going.  Then this routine is called for each
947 ** column.
948 */
sqlite3AddColumn(Parse * pParse,Token * pName)949 void sqlite3AddColumn(Parse *pParse, Token *pName){
950   Table *p;
951   int i;
952   char *z;
953   Column *pCol;
954   sqlite3 *db = pParse->db;
955   if( (p = pParse->pNewTable)==0 ) return;
956 #if SQLITE_MAX_COLUMN
957   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
958     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
959     return;
960   }
961 #endif
962   z = sqlite3NameFromToken(db, pName);
963   if( z==0 ) return;
964   for(i=0; i<p->nCol; i++){
965     if( STRICMP(z, p->aCol[i].zName) ){
966       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
967       sqlite3DbFree(db, z);
968       return;
969     }
970   }
971   if( (p->nCol & 0x7)==0 ){
972     Column *aNew;
973     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
974     if( aNew==0 ){
975       sqlite3DbFree(db, z);
976       return;
977     }
978     p->aCol = aNew;
979   }
980   pCol = &p->aCol[p->nCol];
981   memset(pCol, 0, sizeof(p->aCol[0]));
982   pCol->zName = z;
983 
984   /* If there is no type specified, columns have the default affinity
985   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
986   ** be called next to set pCol->affinity correctly.
987   */
988   pCol->affinity = SQLITE_AFF_NONE;
989   p->nCol++;
990 }
991 
992 /*
993 ** This routine is called by the parser while in the middle of
994 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
995 ** been seen on a column.  This routine sets the notNull flag on
996 ** the column currently under construction.
997 */
sqlite3AddNotNull(Parse * pParse,int onError)998 void sqlite3AddNotNull(Parse *pParse, int onError){
999   Table *p;
1000   p = pParse->pNewTable;
1001   if( p==0 || NEVER(p->nCol<1) ) return;
1002   p->aCol[p->nCol-1].notNull = (u8)onError;
1003 }
1004 
1005 /*
1006 ** Scan the column type name zType (length nType) and return the
1007 ** associated affinity type.
1008 **
1009 ** This routine does a case-independent search of zType for the
1010 ** substrings in the following table. If one of the substrings is
1011 ** found, the corresponding affinity is returned. If zType contains
1012 ** more than one of the substrings, entries toward the top of
1013 ** the table take priority. For example, if zType is 'BLOBINT',
1014 ** SQLITE_AFF_INTEGER is returned.
1015 **
1016 ** Substring     | Affinity
1017 ** --------------------------------
1018 ** 'INT'         | SQLITE_AFF_INTEGER
1019 ** 'CHAR'        | SQLITE_AFF_TEXT
1020 ** 'CLOB'        | SQLITE_AFF_TEXT
1021 ** 'TEXT'        | SQLITE_AFF_TEXT
1022 ** 'BLOB'        | SQLITE_AFF_NONE
1023 ** 'REAL'        | SQLITE_AFF_REAL
1024 ** 'FLOA'        | SQLITE_AFF_REAL
1025 ** 'DOUB'        | SQLITE_AFF_REAL
1026 **
1027 ** If none of the substrings in the above table are found,
1028 ** SQLITE_AFF_NUMERIC is returned.
1029 */
sqlite3AffinityType(const char * zIn)1030 char sqlite3AffinityType(const char *zIn){
1031   u32 h = 0;
1032   char aff = SQLITE_AFF_NUMERIC;
1033 
1034   if( zIn ) while( zIn[0] ){
1035     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
1036     zIn++;
1037     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
1038       aff = SQLITE_AFF_TEXT;
1039     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
1040       aff = SQLITE_AFF_TEXT;
1041     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
1042       aff = SQLITE_AFF_TEXT;
1043     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
1044         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1045       aff = SQLITE_AFF_NONE;
1046 #ifndef SQLITE_OMIT_FLOATING_POINT
1047     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
1048         && aff==SQLITE_AFF_NUMERIC ){
1049       aff = SQLITE_AFF_REAL;
1050     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
1051         && aff==SQLITE_AFF_NUMERIC ){
1052       aff = SQLITE_AFF_REAL;
1053     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
1054         && aff==SQLITE_AFF_NUMERIC ){
1055       aff = SQLITE_AFF_REAL;
1056 #endif
1057     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
1058       aff = SQLITE_AFF_INTEGER;
1059       break;
1060     }
1061   }
1062 
1063   return aff;
1064 }
1065 
1066 /*
1067 ** This routine is called by the parser while in the middle of
1068 ** parsing a CREATE TABLE statement.  The pFirst token is the first
1069 ** token in the sequence of tokens that describe the type of the
1070 ** column currently under construction.   pLast is the last token
1071 ** in the sequence.  Use this information to construct a string
1072 ** that contains the typename of the column and store that string
1073 ** in zType.
1074 */
sqlite3AddColumnType(Parse * pParse,Token * pType)1075 void sqlite3AddColumnType(Parse *pParse, Token *pType){
1076   Table *p;
1077   Column *pCol;
1078 
1079   p = pParse->pNewTable;
1080   if( p==0 || NEVER(p->nCol<1) ) return;
1081   pCol = &p->aCol[p->nCol-1];
1082   assert( pCol->zType==0 );
1083   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
1084   pCol->affinity = sqlite3AffinityType(pCol->zType);
1085 }
1086 
1087 /*
1088 ** The expression is the default value for the most recently added column
1089 ** of the table currently under construction.
1090 **
1091 ** Default value expressions must be constant.  Raise an exception if this
1092 ** is not the case.
1093 **
1094 ** This routine is called by the parser while in the middle of
1095 ** parsing a CREATE TABLE statement.
1096 */
sqlite3AddDefaultValue(Parse * pParse,ExprSpan * pSpan)1097 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
1098   Table *p;
1099   Column *pCol;
1100   sqlite3 *db = pParse->db;
1101   p = pParse->pNewTable;
1102   if( p!=0 ){
1103     pCol = &(p->aCol[p->nCol-1]);
1104     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
1105       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1106           pCol->zName);
1107     }else{
1108       /* A copy of pExpr is used instead of the original, as pExpr contains
1109       ** tokens that point to volatile memory. The 'span' of the expression
1110       ** is required by pragma table_info.
1111       */
1112       sqlite3ExprDelete(db, pCol->pDflt);
1113       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1114       sqlite3DbFree(db, pCol->zDflt);
1115       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1116                                      (int)(pSpan->zEnd - pSpan->zStart));
1117     }
1118   }
1119   sqlite3ExprDelete(db, pSpan->pExpr);
1120 }
1121 
1122 /*
1123 ** Designate the PRIMARY KEY for the table.  pList is a list of names
1124 ** of columns that form the primary key.  If pList is NULL, then the
1125 ** most recently added column of the table is the primary key.
1126 **
1127 ** A table can have at most one primary key.  If the table already has
1128 ** a primary key (and this is the second primary key) then create an
1129 ** error.
1130 **
1131 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1132 ** then we will try to use that column as the rowid.  Set the Table.iPKey
1133 ** field of the table under construction to be the index of the
1134 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
1135 ** no INTEGER PRIMARY KEY.
1136 **
1137 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
1138 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
1139 */
sqlite3AddPrimaryKey(Parse * pParse,ExprList * pList,int onError,int autoInc,int sortOrder)1140 void sqlite3AddPrimaryKey(
1141   Parse *pParse,    /* Parsing context */
1142   ExprList *pList,  /* List of field names to be indexed */
1143   int onError,      /* What to do with a uniqueness conflict */
1144   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
1145   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1146 ){
1147   Table *pTab = pParse->pNewTable;
1148   char *zType = 0;
1149   int iCol = -1, i;
1150   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
1151   if( pTab->tabFlags & TF_HasPrimaryKey ){
1152     sqlite3ErrorMsg(pParse,
1153       "table \"%s\" has more than one primary key", pTab->zName);
1154     goto primary_key_exit;
1155   }
1156   pTab->tabFlags |= TF_HasPrimaryKey;
1157   if( pList==0 ){
1158     iCol = pTab->nCol - 1;
1159     pTab->aCol[iCol].isPrimKey = 1;
1160   }else{
1161     for(i=0; i<pList->nExpr; i++){
1162       for(iCol=0; iCol<pTab->nCol; iCol++){
1163         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1164           break;
1165         }
1166       }
1167       if( iCol<pTab->nCol ){
1168         pTab->aCol[iCol].isPrimKey = 1;
1169       }
1170     }
1171     if( pList->nExpr>1 ) iCol = -1;
1172   }
1173   if( iCol>=0 && iCol<pTab->nCol ){
1174     zType = pTab->aCol[iCol].zType;
1175   }
1176   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1177         && sortOrder==SQLITE_SO_ASC ){
1178     pTab->iPKey = iCol;
1179     pTab->keyConf = (u8)onError;
1180     assert( autoInc==0 || autoInc==1 );
1181     pTab->tabFlags |= autoInc*TF_Autoincrement;
1182   }else if( autoInc ){
1183 #ifndef SQLITE_OMIT_AUTOINCREMENT
1184     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1185        "INTEGER PRIMARY KEY");
1186 #endif
1187   }else{
1188     Index *p;
1189     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
1190     if( p ){
1191       p->autoIndex = 2;
1192     }
1193     pList = 0;
1194   }
1195 
1196 primary_key_exit:
1197   sqlite3ExprListDelete(pParse->db, pList);
1198   return;
1199 }
1200 
1201 /*
1202 ** Add a new CHECK constraint to the table currently under construction.
1203 */
sqlite3AddCheckConstraint(Parse * pParse,Expr * pCheckExpr)1204 void sqlite3AddCheckConstraint(
1205   Parse *pParse,    /* Parsing context */
1206   Expr *pCheckExpr  /* The check expression */
1207 ){
1208   sqlite3 *db = pParse->db;
1209 #ifndef SQLITE_OMIT_CHECK
1210   Table *pTab = pParse->pNewTable;
1211   if( pTab && !IN_DECLARE_VTAB ){
1212     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
1213   }else
1214 #endif
1215   {
1216     sqlite3ExprDelete(db, pCheckExpr);
1217   }
1218 }
1219 
1220 /*
1221 ** Set the collation function of the most recently parsed table column
1222 ** to the CollSeq given.
1223 */
sqlite3AddCollateType(Parse * pParse,Token * pToken)1224 void sqlite3AddCollateType(Parse *pParse, Token *pToken){
1225   Table *p;
1226   int i;
1227   char *zColl;              /* Dequoted name of collation sequence */
1228   sqlite3 *db;
1229 
1230   if( (p = pParse->pNewTable)==0 ) return;
1231   i = p->nCol-1;
1232   db = pParse->db;
1233   zColl = sqlite3NameFromToken(db, pToken);
1234   if( !zColl ) return;
1235 
1236   if( sqlite3LocateCollSeq(pParse, zColl) ){
1237     Index *pIdx;
1238     p->aCol[i].zColl = zColl;
1239 
1240     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1241     ** then an index may have been created on this column before the
1242     ** collation type was added. Correct this if it is the case.
1243     */
1244     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1245       assert( pIdx->nColumn==1 );
1246       if( pIdx->aiColumn[0]==i ){
1247         pIdx->azColl[0] = p->aCol[i].zColl;
1248       }
1249     }
1250   }else{
1251     sqlite3DbFree(db, zColl);
1252   }
1253 }
1254 
1255 /*
1256 ** This function returns the collation sequence for database native text
1257 ** encoding identified by the string zName, length nName.
1258 **
1259 ** If the requested collation sequence is not available, or not available
1260 ** in the database native encoding, the collation factory is invoked to
1261 ** request it. If the collation factory does not supply such a sequence,
1262 ** and the sequence is available in another text encoding, then that is
1263 ** returned instead.
1264 **
1265 ** If no versions of the requested collations sequence are available, or
1266 ** another error occurs, NULL is returned and an error message written into
1267 ** pParse.
1268 **
1269 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
1270 ** invokes the collation factory if the named collation cannot be found
1271 ** and generates an error message.
1272 **
1273 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
1274 */
sqlite3LocateCollSeq(Parse * pParse,const char * zName)1275 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
1276   sqlite3 *db = pParse->db;
1277   u8 enc = ENC(db);
1278   u8 initbusy = db->init.busy;
1279   CollSeq *pColl;
1280 
1281   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
1282   if( !initbusy && (!pColl || !pColl->xCmp) ){
1283     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
1284     if( !pColl ){
1285       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
1286     }
1287   }
1288 
1289   return pColl;
1290 }
1291 
1292 
1293 /*
1294 ** Generate code that will increment the schema cookie.
1295 **
1296 ** The schema cookie is used to determine when the schema for the
1297 ** database changes.  After each schema change, the cookie value
1298 ** changes.  When a process first reads the schema it records the
1299 ** cookie.  Thereafter, whenever it goes to access the database,
1300 ** it checks the cookie to make sure the schema has not changed
1301 ** since it was last read.
1302 **
1303 ** This plan is not completely bullet-proof.  It is possible for
1304 ** the schema to change multiple times and for the cookie to be
1305 ** set back to prior value.  But schema changes are infrequent
1306 ** and the probability of hitting the same cookie value is only
1307 ** 1 chance in 2^32.  So we're safe enough.
1308 */
sqlite3ChangeCookie(Parse * pParse,int iDb)1309 void sqlite3ChangeCookie(Parse *pParse, int iDb){
1310   int r1 = sqlite3GetTempReg(pParse);
1311   sqlite3 *db = pParse->db;
1312   Vdbe *v = pParse->pVdbe;
1313   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1314   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1315   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
1316   sqlite3ReleaseTempReg(pParse, r1);
1317 }
1318 
1319 /*
1320 ** Measure the number of characters needed to output the given
1321 ** identifier.  The number returned includes any quotes used
1322 ** but does not include the null terminator.
1323 **
1324 ** The estimate is conservative.  It might be larger that what is
1325 ** really needed.
1326 */
identLength(const char * z)1327 static int identLength(const char *z){
1328   int n;
1329   for(n=0; *z; n++, z++){
1330     if( *z=='"' ){ n++; }
1331   }
1332   return n + 2;
1333 }
1334 
1335 /*
1336 ** The first parameter is a pointer to an output buffer. The second
1337 ** parameter is a pointer to an integer that contains the offset at
1338 ** which to write into the output buffer. This function copies the
1339 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
1340 ** to the specified offset in the buffer and updates *pIdx to refer
1341 ** to the first byte after the last byte written before returning.
1342 **
1343 ** If the string zSignedIdent consists entirely of alpha-numeric
1344 ** characters, does not begin with a digit and is not an SQL keyword,
1345 ** then it is copied to the output buffer exactly as it is. Otherwise,
1346 ** it is quoted using double-quotes.
1347 */
identPut(char * z,int * pIdx,char * zSignedIdent)1348 static void identPut(char *z, int *pIdx, char *zSignedIdent){
1349   unsigned char *zIdent = (unsigned char*)zSignedIdent;
1350   int i, j, needQuote;
1351   i = *pIdx;
1352 
1353   for(j=0; zIdent[j]; j++){
1354     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1355   }
1356   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1357   if( !needQuote ){
1358     needQuote = zIdent[j];
1359   }
1360 
1361   if( needQuote ) z[i++] = '"';
1362   for(j=0; zIdent[j]; j++){
1363     z[i++] = zIdent[j];
1364     if( zIdent[j]=='"' ) z[i++] = '"';
1365   }
1366   if( needQuote ) z[i++] = '"';
1367   z[i] = 0;
1368   *pIdx = i;
1369 }
1370 
1371 /*
1372 ** Generate a CREATE TABLE statement appropriate for the given
1373 ** table.  Memory to hold the text of the statement is obtained
1374 ** from sqliteMalloc() and must be freed by the calling function.
1375 */
createTableStmt(sqlite3 * db,Table * p)1376 static char *createTableStmt(sqlite3 *db, Table *p){
1377   int i, k, n;
1378   char *zStmt;
1379   char *zSep, *zSep2, *zEnd;
1380   Column *pCol;
1381   n = 0;
1382   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1383     n += identLength(pCol->zName) + 5;
1384   }
1385   n += identLength(p->zName);
1386   if( n<50 ){
1387     zSep = "";
1388     zSep2 = ",";
1389     zEnd = ")";
1390   }else{
1391     zSep = "\n  ";
1392     zSep2 = ",\n  ";
1393     zEnd = "\n)";
1394   }
1395   n += 35 + 6*p->nCol;
1396   zStmt = sqlite3DbMallocRaw(0, n);
1397   if( zStmt==0 ){
1398     db->mallocFailed = 1;
1399     return 0;
1400   }
1401   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
1402   k = sqlite3Strlen30(zStmt);
1403   identPut(zStmt, &k, p->zName);
1404   zStmt[k++] = '(';
1405   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
1406     static const char * const azType[] = {
1407         /* SQLITE_AFF_TEXT    */ " TEXT",
1408         /* SQLITE_AFF_NONE    */ "",
1409         /* SQLITE_AFF_NUMERIC */ " NUM",
1410         /* SQLITE_AFF_INTEGER */ " INT",
1411         /* SQLITE_AFF_REAL    */ " REAL"
1412     };
1413     int len;
1414     const char *zType;
1415 
1416     sqlite3_snprintf(n-k, &zStmt[k], zSep);
1417     k += sqlite3Strlen30(&zStmt[k]);
1418     zSep = zSep2;
1419     identPut(zStmt, &k, pCol->zName);
1420     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
1421     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
1422     testcase( pCol->affinity==SQLITE_AFF_TEXT );
1423     testcase( pCol->affinity==SQLITE_AFF_NONE );
1424     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1425     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1426     testcase( pCol->affinity==SQLITE_AFF_REAL );
1427 
1428     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1429     len = sqlite3Strlen30(zType);
1430     assert( pCol->affinity==SQLITE_AFF_NONE
1431             || pCol->affinity==sqlite3AffinityType(zType) );
1432     memcpy(&zStmt[k], zType, len);
1433     k += len;
1434     assert( k<=n );
1435   }
1436   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
1437   return zStmt;
1438 }
1439 
1440 /*
1441 ** This routine is called to report the final ")" that terminates
1442 ** a CREATE TABLE statement.
1443 **
1444 ** The table structure that other action routines have been building
1445 ** is added to the internal hash tables, assuming no errors have
1446 ** occurred.
1447 **
1448 ** An entry for the table is made in the master table on disk, unless
1449 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
1450 ** it means we are reading the sqlite_master table because we just
1451 ** connected to the database or because the sqlite_master table has
1452 ** recently changed, so the entry for this table already exists in
1453 ** the sqlite_master table.  We do not want to create it again.
1454 **
1455 ** If the pSelect argument is not NULL, it means that this routine
1456 ** was called to create a table generated from a
1457 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
1458 ** the new table will match the result set of the SELECT.
1459 */
sqlite3EndTable(Parse * pParse,Token * pCons,Token * pEnd,Select * pSelect)1460 void sqlite3EndTable(
1461   Parse *pParse,          /* Parse context */
1462   Token *pCons,           /* The ',' token after the last column defn. */
1463   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
1464   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
1465 ){
1466   Table *p;
1467   sqlite3 *db = pParse->db;
1468   int iDb;
1469 
1470   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1471     return;
1472   }
1473   p = pParse->pNewTable;
1474   if( p==0 ) return;
1475 
1476   assert( !db->init.busy || !pSelect );
1477 
1478   iDb = sqlite3SchemaToIndex(db, p->pSchema);
1479 
1480 #ifndef SQLITE_OMIT_CHECK
1481   /* Resolve names in all CHECK constraint expressions.
1482   */
1483   if( p->pCheck ){
1484     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
1485     NameContext sNC;                /* Name context for pParse->pNewTable */
1486 
1487     memset(&sNC, 0, sizeof(sNC));
1488     memset(&sSrc, 0, sizeof(sSrc));
1489     sSrc.nSrc = 1;
1490     sSrc.a[0].zName = p->zName;
1491     sSrc.a[0].pTab = p;
1492     sSrc.a[0].iCursor = -1;
1493     sNC.pParse = pParse;
1494     sNC.pSrcList = &sSrc;
1495     sNC.isCheck = 1;
1496     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
1497       return;
1498     }
1499   }
1500 #endif /* !defined(SQLITE_OMIT_CHECK) */
1501 
1502   /* If the db->init.busy is 1 it means we are reading the SQL off the
1503   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1504   ** So do not write to the disk again.  Extract the root page number
1505   ** for the table from the db->init.newTnum field.  (The page number
1506   ** should have been put there by the sqliteOpenCb routine.)
1507   */
1508   if( db->init.busy ){
1509     p->tnum = db->init.newTnum;
1510   }
1511 
1512   /* If not initializing, then create a record for the new table
1513   ** in the SQLITE_MASTER table of the database.
1514   **
1515   ** If this is a TEMPORARY table, write the entry into the auxiliary
1516   ** file instead of into the main database file.
1517   */
1518   if( !db->init.busy ){
1519     int n;
1520     Vdbe *v;
1521     char *zType;    /* "view" or "table" */
1522     char *zType2;   /* "VIEW" or "TABLE" */
1523     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
1524 
1525     v = sqlite3GetVdbe(pParse);
1526     if( NEVER(v==0) ) return;
1527 
1528     sqlite3VdbeAddOp1(v, OP_Close, 0);
1529 
1530     /*
1531     ** Initialize zType for the new view or table.
1532     */
1533     if( p->pSelect==0 ){
1534       /* A regular table */
1535       zType = "table";
1536       zType2 = "TABLE";
1537 #ifndef SQLITE_OMIT_VIEW
1538     }else{
1539       /* A view */
1540       zType = "view";
1541       zType2 = "VIEW";
1542 #endif
1543     }
1544 
1545     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1546     ** statement to populate the new table. The root-page number for the
1547     ** new table is in register pParse->regRoot.
1548     **
1549     ** Once the SELECT has been coded by sqlite3Select(), it is in a
1550     ** suitable state to query for the column names and types to be used
1551     ** by the new table.
1552     **
1553     ** A shared-cache write-lock is not required to write to the new table,
1554     ** as a schema-lock must have already been obtained to create it. Since
1555     ** a schema-lock excludes all other database users, the write-lock would
1556     ** be redundant.
1557     */
1558     if( pSelect ){
1559       SelectDest dest;
1560       Table *pSelTab;
1561 
1562       assert(pParse->nTab==1);
1563       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
1564       sqlite3VdbeChangeP5(v, 1);
1565       pParse->nTab = 2;
1566       sqlite3SelectDestInit(&dest, SRT_Table, 1);
1567       sqlite3Select(pParse, pSelect, &dest);
1568       sqlite3VdbeAddOp1(v, OP_Close, 1);
1569       if( pParse->nErr==0 ){
1570         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1571         if( pSelTab==0 ) return;
1572         assert( p->aCol==0 );
1573         p->nCol = pSelTab->nCol;
1574         p->aCol = pSelTab->aCol;
1575         pSelTab->nCol = 0;
1576         pSelTab->aCol = 0;
1577         sqlite3DeleteTable(db, pSelTab);
1578       }
1579     }
1580 
1581     /* Compute the complete text of the CREATE statement */
1582     if( pSelect ){
1583       zStmt = createTableStmt(db, p);
1584     }else{
1585       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
1586       zStmt = sqlite3MPrintf(db,
1587           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1588       );
1589     }
1590 
1591     /* A slot for the record has already been allocated in the
1592     ** SQLITE_MASTER table.  We just need to update that slot with all
1593     ** the information we've collected.
1594     */
1595     sqlite3NestedParse(pParse,
1596       "UPDATE %Q.%s "
1597          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1598        "WHERE rowid=#%d",
1599       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
1600       zType,
1601       p->zName,
1602       p->zName,
1603       pParse->regRoot,
1604       zStmt,
1605       pParse->regRowid
1606     );
1607     sqlite3DbFree(db, zStmt);
1608     sqlite3ChangeCookie(pParse, iDb);
1609 
1610 #ifndef SQLITE_OMIT_AUTOINCREMENT
1611     /* Check to see if we need to create an sqlite_sequence table for
1612     ** keeping track of autoincrement keys.
1613     */
1614     if( p->tabFlags & TF_Autoincrement ){
1615       Db *pDb = &db->aDb[iDb];
1616       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1617       if( pDb->pSchema->pSeqTab==0 ){
1618         sqlite3NestedParse(pParse,
1619           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1620           pDb->zName
1621         );
1622       }
1623     }
1624 #endif
1625 
1626     /* Reparse everything to update our internal data structures */
1627     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1628         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
1629   }
1630 
1631 
1632   /* Add the table to the in-memory representation of the database.
1633   */
1634   if( db->init.busy ){
1635     Table *pOld;
1636     Schema *pSchema = p->pSchema;
1637     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1638     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
1639                              sqlite3Strlen30(p->zName),p);
1640     if( pOld ){
1641       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
1642       db->mallocFailed = 1;
1643       return;
1644     }
1645     pParse->pNewTable = 0;
1646     db->nTable++;
1647     db->flags |= SQLITE_InternChanges;
1648 
1649 #ifndef SQLITE_OMIT_ALTERTABLE
1650     if( !p->pSelect ){
1651       const char *zName = (const char *)pParse->sNameToken.z;
1652       int nName;
1653       assert( !pSelect && pCons && pEnd );
1654       if( pCons->z==0 ){
1655         pCons = pEnd;
1656       }
1657       nName = (int)((const char *)pCons->z - zName);
1658       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
1659     }
1660 #endif
1661   }
1662 }
1663 
1664 #ifndef SQLITE_OMIT_VIEW
1665 /*
1666 ** The parser calls this routine in order to create a new VIEW
1667 */
sqlite3CreateView(Parse * pParse,Token * pBegin,Token * pName1,Token * pName2,Select * pSelect,int isTemp,int noErr)1668 void sqlite3CreateView(
1669   Parse *pParse,     /* The parsing context */
1670   Token *pBegin,     /* The CREATE token that begins the statement */
1671   Token *pName1,     /* The token that holds the name of the view */
1672   Token *pName2,     /* The token that holds the name of the view */
1673   Select *pSelect,   /* A SELECT statement that will become the new view */
1674   int isTemp,        /* TRUE for a TEMPORARY view */
1675   int noErr          /* Suppress error messages if VIEW already exists */
1676 ){
1677   Table *p;
1678   int n;
1679   const char *z;
1680   Token sEnd;
1681   DbFixer sFix;
1682   Token *pName;
1683   int iDb;
1684   sqlite3 *db = pParse->db;
1685 
1686   if( pParse->nVar>0 ){
1687     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1688     sqlite3SelectDelete(db, pSelect);
1689     return;
1690   }
1691   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
1692   p = pParse->pNewTable;
1693   if( p==0 || pParse->nErr ){
1694     sqlite3SelectDelete(db, pSelect);
1695     return;
1696   }
1697   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1698   iDb = sqlite3SchemaToIndex(db, p->pSchema);
1699   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
1700     && sqlite3FixSelect(&sFix, pSelect)
1701   ){
1702     sqlite3SelectDelete(db, pSelect);
1703     return;
1704   }
1705 
1706   /* Make a copy of the entire SELECT statement that defines the view.
1707   ** This will force all the Expr.token.z values to be dynamically
1708   ** allocated rather than point to the input string - which means that
1709   ** they will persist after the current sqlite3_exec() call returns.
1710   */
1711   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
1712   sqlite3SelectDelete(db, pSelect);
1713   if( db->mallocFailed ){
1714     return;
1715   }
1716   if( !db->init.busy ){
1717     sqlite3ViewGetColumnNames(pParse, p);
1718   }
1719 
1720   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
1721   ** the end.
1722   */
1723   sEnd = pParse->sLastToken;
1724   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
1725     sEnd.z += sEnd.n;
1726   }
1727   sEnd.n = 0;
1728   n = (int)(sEnd.z - pBegin->z);
1729   z = pBegin->z;
1730   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
1731   sEnd.z = &z[n-1];
1732   sEnd.n = 1;
1733 
1734   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1735   sqlite3EndTable(pParse, 0, &sEnd, 0);
1736   return;
1737 }
1738 #endif /* SQLITE_OMIT_VIEW */
1739 
1740 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1741 /*
1742 ** The Table structure pTable is really a VIEW.  Fill in the names of
1743 ** the columns of the view in the pTable structure.  Return the number
1744 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
1745 */
sqlite3ViewGetColumnNames(Parse * pParse,Table * pTable)1746 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1747   Table *pSelTab;   /* A fake table from which we get the result set */
1748   Select *pSel;     /* Copy of the SELECT that implements the view */
1749   int nErr = 0;     /* Number of errors encountered */
1750   int n;            /* Temporarily holds the number of cursors assigned */
1751   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
1752   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
1753 
1754   assert( pTable );
1755 
1756 #ifndef SQLITE_OMIT_VIRTUALTABLE
1757   if( sqlite3VtabCallConnect(pParse, pTable) ){
1758     return SQLITE_ERROR;
1759   }
1760   if( IsVirtual(pTable) ) return 0;
1761 #endif
1762 
1763 #ifndef SQLITE_OMIT_VIEW
1764   /* A positive nCol means the columns names for this view are
1765   ** already known.
1766   */
1767   if( pTable->nCol>0 ) return 0;
1768 
1769   /* A negative nCol is a special marker meaning that we are currently
1770   ** trying to compute the column names.  If we enter this routine with
1771   ** a negative nCol, it means two or more views form a loop, like this:
1772   **
1773   **     CREATE VIEW one AS SELECT * FROM two;
1774   **     CREATE VIEW two AS SELECT * FROM one;
1775   **
1776   ** Actually, the error above is now caught prior to reaching this point.
1777   ** But the following test is still important as it does come up
1778   ** in the following:
1779   **
1780   **     CREATE TABLE main.ex1(a);
1781   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
1782   **     SELECT * FROM temp.ex1;
1783   */
1784   if( pTable->nCol<0 ){
1785     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1786     return 1;
1787   }
1788   assert( pTable->nCol>=0 );
1789 
1790   /* If we get this far, it means we need to compute the table names.
1791   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1792   ** "*" elements in the results set of the view and will assign cursors
1793   ** to the elements of the FROM clause.  But we do not want these changes
1794   ** to be permanent.  So the computation is done on a copy of the SELECT
1795   ** statement that defines the view.
1796   */
1797   assert( pTable->pSelect );
1798   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
1799   if( pSel ){
1800     u8 enableLookaside = db->lookaside.bEnabled;
1801     n = pParse->nTab;
1802     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1803     pTable->nCol = -1;
1804     db->lookaside.bEnabled = 0;
1805 #ifndef SQLITE_OMIT_AUTHORIZATION
1806     xAuth = db->xAuth;
1807     db->xAuth = 0;
1808     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1809     db->xAuth = xAuth;
1810 #else
1811     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
1812 #endif
1813     db->lookaside.bEnabled = enableLookaside;
1814     pParse->nTab = n;
1815     if( pSelTab ){
1816       assert( pTable->aCol==0 );
1817       pTable->nCol = pSelTab->nCol;
1818       pTable->aCol = pSelTab->aCol;
1819       pSelTab->nCol = 0;
1820       pSelTab->aCol = 0;
1821       sqlite3DeleteTable(db, pSelTab);
1822       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
1823       pTable->pSchema->flags |= DB_UnresetViews;
1824     }else{
1825       pTable->nCol = 0;
1826       nErr++;
1827     }
1828     sqlite3SelectDelete(db, pSel);
1829   } else {
1830     nErr++;
1831   }
1832 #endif /* SQLITE_OMIT_VIEW */
1833   return nErr;
1834 }
1835 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
1836 
1837 #ifndef SQLITE_OMIT_VIEW
1838 /*
1839 ** Clear the column names from every VIEW in database idx.
1840 */
sqliteViewResetAll(sqlite3 * db,int idx)1841 static void sqliteViewResetAll(sqlite3 *db, int idx){
1842   HashElem *i;
1843   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
1844   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1845   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
1846     Table *pTab = sqliteHashData(i);
1847     if( pTab->pSelect ){
1848       sqliteDeleteColumnNames(db, pTab);
1849       pTab->aCol = 0;
1850       pTab->nCol = 0;
1851     }
1852   }
1853   DbClearProperty(db, idx, DB_UnresetViews);
1854 }
1855 #else
1856 # define sqliteViewResetAll(A,B)
1857 #endif /* SQLITE_OMIT_VIEW */
1858 
1859 /*
1860 ** This function is called by the VDBE to adjust the internal schema
1861 ** used by SQLite when the btree layer moves a table root page. The
1862 ** root-page of a table or index in database iDb has changed from iFrom
1863 ** to iTo.
1864 **
1865 ** Ticket #1728:  The symbol table might still contain information
1866 ** on tables and/or indices that are the process of being deleted.
1867 ** If you are unlucky, one of those deleted indices or tables might
1868 ** have the same rootpage number as the real table or index that is
1869 ** being moved.  So we cannot stop searching after the first match
1870 ** because the first match might be for one of the deleted indices
1871 ** or tables and not the table/index that is actually being moved.
1872 ** We must continue looping until all tables and indices with
1873 ** rootpage==iFrom have been converted to have a rootpage of iTo
1874 ** in order to be certain that we got the right one.
1875 */
1876 #ifndef SQLITE_OMIT_AUTOVACUUM
sqlite3RootPageMoved(sqlite3 * db,int iDb,int iFrom,int iTo)1877 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
1878   HashElem *pElem;
1879   Hash *pHash;
1880   Db *pDb;
1881 
1882   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1883   pDb = &db->aDb[iDb];
1884   pHash = &pDb->pSchema->tblHash;
1885   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1886     Table *pTab = sqliteHashData(pElem);
1887     if( pTab->tnum==iFrom ){
1888       pTab->tnum = iTo;
1889     }
1890   }
1891   pHash = &pDb->pSchema->idxHash;
1892   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
1893     Index *pIdx = sqliteHashData(pElem);
1894     if( pIdx->tnum==iFrom ){
1895       pIdx->tnum = iTo;
1896     }
1897   }
1898 }
1899 #endif
1900 
1901 /*
1902 ** Write code to erase the table with root-page iTable from database iDb.
1903 ** Also write code to modify the sqlite_master table and internal schema
1904 ** if a root-page of another table is moved by the btree-layer whilst
1905 ** erasing iTable (this can happen with an auto-vacuum database).
1906 */
destroyRootPage(Parse * pParse,int iTable,int iDb)1907 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1908   Vdbe *v = sqlite3GetVdbe(pParse);
1909   int r1 = sqlite3GetTempReg(pParse);
1910   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
1911   sqlite3MayAbort(pParse);
1912 #ifndef SQLITE_OMIT_AUTOVACUUM
1913   /* OP_Destroy stores an in integer r1. If this integer
1914   ** is non-zero, then it is the root page number of a table moved to
1915   ** location iTable. The following code modifies the sqlite_master table to
1916   ** reflect this.
1917   **
1918   ** The "#NNN" in the SQL is a special constant that means whatever value
1919   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
1920   ** token for additional information.
1921   */
1922   sqlite3NestedParse(pParse,
1923      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1924      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
1925 #endif
1926   sqlite3ReleaseTempReg(pParse, r1);
1927 }
1928 
1929 /*
1930 ** Write VDBE code to erase table pTab and all associated indices on disk.
1931 ** Code to update the sqlite_master tables and internal schema definitions
1932 ** in case a root-page belonging to another table is moved by the btree layer
1933 ** is also added (this can happen with an auto-vacuum database).
1934 */
destroyTable(Parse * pParse,Table * pTab)1935 static void destroyTable(Parse *pParse, Table *pTab){
1936 #ifdef SQLITE_OMIT_AUTOVACUUM
1937   Index *pIdx;
1938   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1939   destroyRootPage(pParse, pTab->tnum, iDb);
1940   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1941     destroyRootPage(pParse, pIdx->tnum, iDb);
1942   }
1943 #else
1944   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1945   ** is not defined), then it is important to call OP_Destroy on the
1946   ** table and index root-pages in order, starting with the numerically
1947   ** largest root-page number. This guarantees that none of the root-pages
1948   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1949   ** following were coded:
1950   **
1951   ** OP_Destroy 4 0
1952   ** ...
1953   ** OP_Destroy 5 0
1954   **
1955   ** and root page 5 happened to be the largest root-page number in the
1956   ** database, then root page 5 would be moved to page 4 by the
1957   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1958   ** a free-list page.
1959   */
1960   int iTab = pTab->tnum;
1961   int iDestroyed = 0;
1962 
1963   while( 1 ){
1964     Index *pIdx;
1965     int iLargest = 0;
1966 
1967     if( iDestroyed==0 || iTab<iDestroyed ){
1968       iLargest = iTab;
1969     }
1970     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1971       int iIdx = pIdx->tnum;
1972       assert( pIdx->pSchema==pTab->pSchema );
1973       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1974         iLargest = iIdx;
1975       }
1976     }
1977     if( iLargest==0 ){
1978       return;
1979     }else{
1980       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1981       destroyRootPage(pParse, iLargest, iDb);
1982       iDestroyed = iLargest;
1983     }
1984   }
1985 #endif
1986 }
1987 
1988 /*
1989 ** This routine is called to do the work of a DROP TABLE statement.
1990 ** pName is the name of the table to be dropped.
1991 */
sqlite3DropTable(Parse * pParse,SrcList * pName,int isView,int noErr)1992 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
1993   Table *pTab;
1994   Vdbe *v;
1995   sqlite3 *db = pParse->db;
1996   int iDb;
1997 
1998   if( db->mallocFailed ){
1999     goto exit_drop_table;
2000   }
2001   assert( pParse->nErr==0 );
2002   assert( pName->nSrc==1 );
2003   if( noErr ) db->suppressErr++;
2004   pTab = sqlite3LocateTable(pParse, isView,
2005                             pName->a[0].zName, pName->a[0].zDatabase);
2006   if( noErr ) db->suppressErr--;
2007 
2008   if( pTab==0 ){
2009     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2010     goto exit_drop_table;
2011   }
2012   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2013   assert( iDb>=0 && iDb<db->nDb );
2014 
2015   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2016   ** it is initialized.
2017   */
2018   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2019     goto exit_drop_table;
2020   }
2021 #ifndef SQLITE_OMIT_AUTHORIZATION
2022   {
2023     int code;
2024     const char *zTab = SCHEMA_TABLE(iDb);
2025     const char *zDb = db->aDb[iDb].zName;
2026     const char *zArg2 = 0;
2027     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
2028       goto exit_drop_table;
2029     }
2030     if( isView ){
2031       if( !OMIT_TEMPDB && iDb==1 ){
2032         code = SQLITE_DROP_TEMP_VIEW;
2033       }else{
2034         code = SQLITE_DROP_VIEW;
2035       }
2036 #ifndef SQLITE_OMIT_VIRTUALTABLE
2037     }else if( IsVirtual(pTab) ){
2038       code = SQLITE_DROP_VTABLE;
2039       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
2040 #endif
2041     }else{
2042       if( !OMIT_TEMPDB && iDb==1 ){
2043         code = SQLITE_DROP_TEMP_TABLE;
2044       }else{
2045         code = SQLITE_DROP_TABLE;
2046       }
2047     }
2048     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
2049       goto exit_drop_table;
2050     }
2051     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2052       goto exit_drop_table;
2053     }
2054   }
2055 #endif
2056   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
2057     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
2058     goto exit_drop_table;
2059   }
2060 
2061 #ifndef SQLITE_OMIT_VIEW
2062   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2063   ** on a table.
2064   */
2065   if( isView && pTab->pSelect==0 ){
2066     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2067     goto exit_drop_table;
2068   }
2069   if( !isView && pTab->pSelect ){
2070     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2071     goto exit_drop_table;
2072   }
2073 #endif
2074 
2075   /* Generate code to remove the table from the master table
2076   ** on disk.
2077   */
2078   v = sqlite3GetVdbe(pParse);
2079   if( v ){
2080     Trigger *pTrigger;
2081     Db *pDb = &db->aDb[iDb];
2082     sqlite3BeginWriteOperation(pParse, 1, iDb);
2083 
2084 #ifndef SQLITE_OMIT_VIRTUALTABLE
2085     if( IsVirtual(pTab) ){
2086       sqlite3VdbeAddOp0(v, OP_VBegin);
2087     }
2088 #endif
2089     sqlite3FkDropTable(pParse, pName, pTab);
2090 
2091     /* Drop all triggers associated with the table being dropped. Code
2092     ** is generated to remove entries from sqlite_master and/or
2093     ** sqlite_temp_master if required.
2094     */
2095     pTrigger = sqlite3TriggerList(pParse, pTab);
2096     while( pTrigger ){
2097       assert( pTrigger->pSchema==pTab->pSchema ||
2098           pTrigger->pSchema==db->aDb[1].pSchema );
2099       sqlite3DropTriggerPtr(pParse, pTrigger);
2100       pTrigger = pTrigger->pNext;
2101     }
2102 
2103 #ifndef SQLITE_OMIT_AUTOINCREMENT
2104     /* Remove any entries of the sqlite_sequence table associated with
2105     ** the table being dropped. This is done before the table is dropped
2106     ** at the btree level, in case the sqlite_sequence table needs to
2107     ** move as a result of the drop (can happen in auto-vacuum mode).
2108     */
2109     if( pTab->tabFlags & TF_Autoincrement ){
2110       sqlite3NestedParse(pParse,
2111         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2112         pDb->zName, pTab->zName
2113       );
2114     }
2115 #endif
2116 
2117     /* Drop all SQLITE_MASTER table and index entries that refer to the
2118     ** table. The program name loops through the master table and deletes
2119     ** every row that refers to a table of the same name as the one being
2120     ** dropped. Triggers are handled seperately because a trigger can be
2121     ** created in the temp database that refers to a table in another
2122     ** database.
2123     */
2124     sqlite3NestedParse(pParse,
2125         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2126         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
2127 
2128     /* Drop any statistics from the sqlite_stat1 table, if it exists */
2129     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2130       sqlite3NestedParse(pParse,
2131         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2132       );
2133     }
2134 
2135     if( !isView && !IsVirtual(pTab) ){
2136       destroyTable(pParse, pTab);
2137     }
2138 
2139     /* Remove the table entry from SQLite's internal schema and modify
2140     ** the schema cookie.
2141     */
2142     if( IsVirtual(pTab) ){
2143       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2144     }
2145     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2146     sqlite3ChangeCookie(pParse, iDb);
2147   }
2148   sqliteViewResetAll(db, iDb);
2149 
2150 exit_drop_table:
2151   sqlite3SrcListDelete(db, pName);
2152 }
2153 
2154 /*
2155 ** This routine is called to create a new foreign key on the table
2156 ** currently under construction.  pFromCol determines which columns
2157 ** in the current table point to the foreign key.  If pFromCol==0 then
2158 ** connect the key to the last column inserted.  pTo is the name of
2159 ** the table referred to.  pToCol is a list of tables in the other
2160 ** pTo table that the foreign key points to.  flags contains all
2161 ** information about the conflict resolution algorithms specified
2162 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2163 **
2164 ** An FKey structure is created and added to the table currently
2165 ** under construction in the pParse->pNewTable field.
2166 **
2167 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
2168 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
2169 */
sqlite3CreateForeignKey(Parse * pParse,ExprList * pFromCol,Token * pTo,ExprList * pToCol,int flags)2170 void sqlite3CreateForeignKey(
2171   Parse *pParse,       /* Parsing context */
2172   ExprList *pFromCol,  /* Columns in this table that point to other table */
2173   Token *pTo,          /* Name of the other table */
2174   ExprList *pToCol,    /* Columns in the other table */
2175   int flags            /* Conflict resolution algorithms. */
2176 ){
2177   sqlite3 *db = pParse->db;
2178 #ifndef SQLITE_OMIT_FOREIGN_KEY
2179   FKey *pFKey = 0;
2180   FKey *pNextTo;
2181   Table *p = pParse->pNewTable;
2182   int nByte;
2183   int i;
2184   int nCol;
2185   char *z;
2186 
2187   assert( pTo!=0 );
2188   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
2189   if( pFromCol==0 ){
2190     int iCol = p->nCol-1;
2191     if( NEVER(iCol<0) ) goto fk_end;
2192     if( pToCol && pToCol->nExpr!=1 ){
2193       sqlite3ErrorMsg(pParse, "foreign key on %s"
2194          " should reference only one column of table %T",
2195          p->aCol[iCol].zName, pTo);
2196       goto fk_end;
2197     }
2198     nCol = 1;
2199   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
2200     sqlite3ErrorMsg(pParse,
2201         "number of columns in foreign key does not match the number of "
2202         "columns in the referenced table");
2203     goto fk_end;
2204   }else{
2205     nCol = pFromCol->nExpr;
2206   }
2207   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2208   if( pToCol ){
2209     for(i=0; i<pToCol->nExpr; i++){
2210       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
2211     }
2212   }
2213   pFKey = sqlite3DbMallocZero(db, nByte );
2214   if( pFKey==0 ){
2215     goto fk_end;
2216   }
2217   pFKey->pFrom = p;
2218   pFKey->pNextFrom = p->pFKey;
2219   z = (char*)&pFKey->aCol[nCol];
2220   pFKey->zTo = z;
2221   memcpy(z, pTo->z, pTo->n);
2222   z[pTo->n] = 0;
2223   sqlite3Dequote(z);
2224   z += pTo->n+1;
2225   pFKey->nCol = nCol;
2226   if( pFromCol==0 ){
2227     pFKey->aCol[0].iFrom = p->nCol-1;
2228   }else{
2229     for(i=0; i<nCol; i++){
2230       int j;
2231       for(j=0; j<p->nCol; j++){
2232         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
2233           pFKey->aCol[i].iFrom = j;
2234           break;
2235         }
2236       }
2237       if( j>=p->nCol ){
2238         sqlite3ErrorMsg(pParse,
2239           "unknown column \"%s\" in foreign key definition",
2240           pFromCol->a[i].zName);
2241         goto fk_end;
2242       }
2243     }
2244   }
2245   if( pToCol ){
2246     for(i=0; i<nCol; i++){
2247       int n = sqlite3Strlen30(pToCol->a[i].zName);
2248       pFKey->aCol[i].zCol = z;
2249       memcpy(z, pToCol->a[i].zName, n);
2250       z[n] = 0;
2251       z += n+1;
2252     }
2253   }
2254   pFKey->isDeferred = 0;
2255   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
2256   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
2257 
2258   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
2259   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
2260       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
2261   );
2262   if( pNextTo==pFKey ){
2263     db->mallocFailed = 1;
2264     goto fk_end;
2265   }
2266   if( pNextTo ){
2267     assert( pNextTo->pPrevTo==0 );
2268     pFKey->pNextTo = pNextTo;
2269     pNextTo->pPrevTo = pFKey;
2270   }
2271 
2272   /* Link the foreign key to the table as the last step.
2273   */
2274   p->pFKey = pFKey;
2275   pFKey = 0;
2276 
2277 fk_end:
2278   sqlite3DbFree(db, pFKey);
2279 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
2280   sqlite3ExprListDelete(db, pFromCol);
2281   sqlite3ExprListDelete(db, pToCol);
2282 }
2283 
2284 /*
2285 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2286 ** clause is seen as part of a foreign key definition.  The isDeferred
2287 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2288 ** The behavior of the most recently created foreign key is adjusted
2289 ** accordingly.
2290 */
sqlite3DeferForeignKey(Parse * pParse,int isDeferred)2291 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
2292 #ifndef SQLITE_OMIT_FOREIGN_KEY
2293   Table *pTab;
2294   FKey *pFKey;
2295   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2296   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
2297   pFKey->isDeferred = (u8)isDeferred;
2298 #endif
2299 }
2300 
2301 /*
2302 ** Generate code that will erase and refill index *pIdx.  This is
2303 ** used to initialize a newly created index or to recompute the
2304 ** content of an index in response to a REINDEX command.
2305 **
2306 ** if memRootPage is not negative, it means that the index is newly
2307 ** created.  The register specified by memRootPage contains the
2308 ** root page number of the index.  If memRootPage is negative, then
2309 ** the index already exists and must be cleared before being refilled and
2310 ** the root page number of the index is taken from pIndex->tnum.
2311 */
sqlite3RefillIndex(Parse * pParse,Index * pIndex,int memRootPage)2312 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2313   Table *pTab = pIndex->pTable;  /* The table that is indexed */
2314   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
2315   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
2316   int addr1;                     /* Address of top of loop */
2317   int tnum;                      /* Root page of index */
2318   Vdbe *v;                       /* Generate code into this virtual machine */
2319   KeyInfo *pKey;                 /* KeyInfo for index */
2320   int regIdxKey;                 /* Registers containing the index key */
2321   int regRecord;                 /* Register holding assemblied index record */
2322   sqlite3 *db = pParse->db;      /* The database connection */
2323   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2324 
2325 #ifndef SQLITE_OMIT_AUTHORIZATION
2326   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2327       db->aDb[iDb].zName ) ){
2328     return;
2329   }
2330 #endif
2331 
2332   /* Require a write-lock on the table to perform this operation */
2333   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2334 
2335   v = sqlite3GetVdbe(pParse);
2336   if( v==0 ) return;
2337   if( memRootPage>=0 ){
2338     tnum = memRootPage;
2339   }else{
2340     tnum = pIndex->tnum;
2341     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2342   }
2343   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2344   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
2345                     (char *)pKey, P4_KEYINFO_HANDOFF);
2346   if( memRootPage>=0 ){
2347     sqlite3VdbeChangeP5(v, 1);
2348   }
2349   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2350   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
2351   regRecord = sqlite3GetTempReg(pParse);
2352   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
2353   if( pIndex->onError!=OE_None ){
2354     const int regRowid = regIdxKey + pIndex->nColumn;
2355     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
2356     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
2357 
2358     /* The registers accessed by the OP_IsUnique opcode were allocated
2359     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
2360     ** call above. Just before that function was freed they were released
2361     ** (made available to the compiler for reuse) using
2362     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
2363     ** opcode use the values stored within seems dangerous. However, since
2364     ** we can be sure that no other temp registers have been allocated
2365     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
2366     */
2367     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
2368     sqlite3HaltConstraint(
2369         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
2370   }
2371   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
2372   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2373   sqlite3ReleaseTempReg(pParse, regRecord);
2374   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
2375   sqlite3VdbeJumpHere(v, addr1);
2376   sqlite3VdbeAddOp1(v, OP_Close, iTab);
2377   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
2378 }
2379 
2380 /*
2381 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
2382 ** and pTblList is the name of the table that is to be indexed.  Both will
2383 ** be NULL for a primary key or an index that is created to satisfy a
2384 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
2385 ** as the table to be indexed.  pParse->pNewTable is a table that is
2386 ** currently being constructed by a CREATE TABLE statement.
2387 **
2388 ** pList is a list of columns to be indexed.  pList will be NULL if this
2389 ** is a primary key or unique-constraint on the most recent column added
2390 ** to the table currently under construction.
2391 **
2392 ** If the index is created successfully, return a pointer to the new Index
2393 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
2394 ** as the tables primary key (Index.autoIndex==2).
2395 */
sqlite3CreateIndex(Parse * pParse,Token * pName1,Token * pName2,SrcList * pTblName,ExprList * pList,int onError,Token * pStart,Token * pEnd,int sortOrder,int ifNotExist)2396 Index *sqlite3CreateIndex(
2397   Parse *pParse,     /* All information about this parse */
2398   Token *pName1,     /* First part of index name. May be NULL */
2399   Token *pName2,     /* Second part of index name. May be NULL */
2400   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
2401   ExprList *pList,   /* A list of columns to be indexed */
2402   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2403   Token *pStart,     /* The CREATE token that begins this statement */
2404   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
2405   int sortOrder,     /* Sort order of primary key when pList==NULL */
2406   int ifNotExist     /* Omit error if index already exists */
2407 ){
2408   Index *pRet = 0;     /* Pointer to return */
2409   Table *pTab = 0;     /* Table to be indexed */
2410   Index *pIndex = 0;   /* The index to be created */
2411   char *zName = 0;     /* Name of the index */
2412   int nName;           /* Number of characters in zName */
2413   int i, j;
2414   Token nullId;        /* Fake token for an empty ID list */
2415   DbFixer sFix;        /* For assigning database names to pTable */
2416   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
2417   sqlite3 *db = pParse->db;
2418   Db *pDb;             /* The specific table containing the indexed database */
2419   int iDb;             /* Index of the database that is being written */
2420   Token *pName = 0;    /* Unqualified name of the index to create */
2421   struct ExprList_item *pListItem; /* For looping over pList */
2422   int nCol;
2423   int nExtra = 0;
2424   char *zExtra;
2425 
2426   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
2427   assert( pParse->nErr==0 );      /* Never called with prior errors */
2428   if( db->mallocFailed || IN_DECLARE_VTAB ){
2429     goto exit_create_index;
2430   }
2431   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2432     goto exit_create_index;
2433   }
2434 
2435   /*
2436   ** Find the table that is to be indexed.  Return early if not found.
2437   */
2438   if( pTblName!=0 ){
2439 
2440     /* Use the two-part index name to determine the database
2441     ** to search for the table. 'Fix' the table name to this db
2442     ** before looking up the table.
2443     */
2444     assert( pName1 && pName2 );
2445     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
2446     if( iDb<0 ) goto exit_create_index;
2447 
2448 #ifndef SQLITE_OMIT_TEMPDB
2449     /* If the index name was unqualified, check if the the table
2450     ** is a temp table. If so, set the database to 1. Do not do this
2451     ** if initialising a database schema.
2452     */
2453     if( !db->init.busy ){
2454       pTab = sqlite3SrcListLookup(pParse, pTblName);
2455       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2456         iDb = 1;
2457       }
2458     }
2459 #endif
2460 
2461     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2462         sqlite3FixSrcList(&sFix, pTblName)
2463     ){
2464       /* Because the parser constructs pTblName from a single identifier,
2465       ** sqlite3FixSrcList can never fail. */
2466       assert(0);
2467     }
2468     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
2469         pTblName->a[0].zDatabase);
2470     if( !pTab || db->mallocFailed ) goto exit_create_index;
2471     assert( db->aDb[iDb].pSchema==pTab->pSchema );
2472   }else{
2473     assert( pName==0 );
2474     pTab = pParse->pNewTable;
2475     if( !pTab ) goto exit_create_index;
2476     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2477   }
2478   pDb = &db->aDb[iDb];
2479 
2480   assert( pTab!=0 );
2481   assert( pParse->nErr==0 );
2482   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2483        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
2484     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
2485     goto exit_create_index;
2486   }
2487 #ifndef SQLITE_OMIT_VIEW
2488   if( pTab->pSelect ){
2489     sqlite3ErrorMsg(pParse, "views may not be indexed");
2490     goto exit_create_index;
2491   }
2492 #endif
2493 #ifndef SQLITE_OMIT_VIRTUALTABLE
2494   if( IsVirtual(pTab) ){
2495     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2496     goto exit_create_index;
2497   }
2498 #endif
2499 
2500   /*
2501   ** Find the name of the index.  Make sure there is not already another
2502   ** index or table with the same name.
2503   **
2504   ** Exception:  If we are reading the names of permanent indices from the
2505   ** sqlite_master table (because some other process changed the schema) and
2506   ** one of the index names collides with the name of a temporary table or
2507   ** index, then we will continue to process this index.
2508   **
2509   ** If pName==0 it means that we are
2510   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
2511   ** own name.
2512   */
2513   if( pName ){
2514     zName = sqlite3NameFromToken(db, pName);
2515     if( zName==0 ) goto exit_create_index;
2516     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
2517       goto exit_create_index;
2518     }
2519     if( !db->init.busy ){
2520       if( sqlite3FindTable(db, zName, 0)!=0 ){
2521         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2522         goto exit_create_index;
2523       }
2524     }
2525     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2526       if( !ifNotExist ){
2527         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2528       }else{
2529         assert( !db->init.busy );
2530         sqlite3CodeVerifySchema(pParse, iDb);
2531       }
2532       goto exit_create_index;
2533     }
2534   }else{
2535     int n;
2536     Index *pLoop;
2537     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
2538     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
2539     if( zName==0 ){
2540       goto exit_create_index;
2541     }
2542   }
2543 
2544   /* Check for authorization to create an index.
2545   */
2546 #ifndef SQLITE_OMIT_AUTHORIZATION
2547   {
2548     const char *zDb = pDb->zName;
2549     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
2550       goto exit_create_index;
2551     }
2552     i = SQLITE_CREATE_INDEX;
2553     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
2554     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
2555       goto exit_create_index;
2556     }
2557   }
2558 #endif
2559 
2560   /* If pList==0, it means this routine was called to make a primary
2561   ** key out of the last column added to the table under construction.
2562   ** So create a fake list to simulate this.
2563   */
2564   if( pList==0 ){
2565     nullId.z = pTab->aCol[pTab->nCol-1].zName;
2566     nullId.n = sqlite3Strlen30((char*)nullId.z);
2567     pList = sqlite3ExprListAppend(pParse, 0, 0);
2568     if( pList==0 ) goto exit_create_index;
2569     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
2570     pList->a[0].sortOrder = (u8)sortOrder;
2571   }
2572 
2573   /* Figure out how many bytes of space are required to store explicitly
2574   ** specified collation sequence names.
2575   */
2576   for(i=0; i<pList->nExpr; i++){
2577     Expr *pExpr = pList->a[i].pExpr;
2578     if( pExpr ){
2579       CollSeq *pColl = pExpr->pColl;
2580       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
2581       ** failure we have quit before reaching this point. */
2582       if( ALWAYS(pColl) ){
2583         nExtra += (1 + sqlite3Strlen30(pColl->zName));
2584       }
2585     }
2586   }
2587 
2588   /*
2589   ** Allocate the index structure.
2590   */
2591   nName = sqlite3Strlen30(zName);
2592   nCol = pList->nExpr;
2593   pIndex = sqlite3DbMallocZero(db,
2594       sizeof(Index) +              /* Index structure  */
2595       sizeof(int)*nCol +           /* Index.aiColumn   */
2596       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
2597       sizeof(char *)*nCol +        /* Index.azColl     */
2598       sizeof(u8)*nCol +            /* Index.aSortOrder */
2599       nName + 1 +                  /* Index.zName      */
2600       nExtra                       /* Collation sequence names */
2601   );
2602   if( db->mallocFailed ){
2603     goto exit_create_index;
2604   }
2605   pIndex->azColl = (char**)(&pIndex[1]);
2606   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
2607   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
2608   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
2609   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2610   zExtra = (char *)(&pIndex->zName[nName+1]);
2611   memcpy(pIndex->zName, zName, nName+1);
2612   pIndex->pTable = pTab;
2613   pIndex->nColumn = pList->nExpr;
2614   pIndex->onError = (u8)onError;
2615   pIndex->autoIndex = (u8)(pName==0);
2616   pIndex->pSchema = db->aDb[iDb].pSchema;
2617   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2618 
2619   /* Check to see if we should honor DESC requests on index columns
2620   */
2621   if( pDb->pSchema->file_format>=4 ){
2622     sortOrderMask = -1;   /* Honor DESC */
2623   }else{
2624     sortOrderMask = 0;    /* Ignore DESC */
2625   }
2626 
2627   /* Scan the names of the columns of the table to be indexed and
2628   ** load the column indices into the Index structure.  Report an error
2629   ** if any column is not found.
2630   **
2631   ** TODO:  Add a test to make sure that the same column is not named
2632   ** more than once within the same index.  Only the first instance of
2633   ** the column will ever be used by the optimizer.  Note that using the
2634   ** same column more than once cannot be an error because that would
2635   ** break backwards compatibility - it needs to be a warning.
2636   */
2637   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2638     const char *zColName = pListItem->zName;
2639     Column *pTabCol;
2640     int requestedSortOrder;
2641     char *zColl;                   /* Collation sequence name */
2642 
2643     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2644       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
2645     }
2646     if( j>=pTab->nCol ){
2647       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2648         pTab->zName, zColName);
2649       pParse->checkSchema = 1;
2650       goto exit_create_index;
2651     }
2652     pIndex->aiColumn[i] = j;
2653     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
2654     ** the way the "idxlist" non-terminal is constructed by the parser,
2655     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
2656     ** must exist or else there must have been an OOM error.  But if there
2657     ** was an OOM error, we would never reach this point. */
2658     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
2659       int nColl;
2660       zColl = pListItem->pExpr->pColl->zName;
2661       nColl = sqlite3Strlen30(zColl) + 1;
2662       assert( nExtra>=nColl );
2663       memcpy(zExtra, zColl, nColl);
2664       zColl = zExtra;
2665       zExtra += nColl;
2666       nExtra -= nColl;
2667     }else{
2668       zColl = pTab->aCol[j].zColl;
2669       if( !zColl ){
2670         zColl = db->pDfltColl->zName;
2671       }
2672     }
2673     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
2674       goto exit_create_index;
2675     }
2676     pIndex->azColl[i] = zColl;
2677     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
2678     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
2679   }
2680   sqlite3DefaultRowEst(pIndex);
2681 
2682   if( pTab==pParse->pNewTable ){
2683     /* This routine has been called to create an automatic index as a
2684     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2685     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2686     ** i.e. one of:
2687     **
2688     ** CREATE TABLE t(x PRIMARY KEY, y);
2689     ** CREATE TABLE t(x, y, UNIQUE(x, y));
2690     **
2691     ** Either way, check to see if the table already has such an index. If
2692     ** so, don't bother creating this one. This only applies to
2693     ** automatically created indices. Users can do as they wish with
2694     ** explicit indices.
2695     **
2696     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
2697     ** (and thus suppressing the second one) even if they have different
2698     ** sort orders.
2699     **
2700     ** If there are different collating sequences or if the columns of
2701     ** the constraint occur in different orders, then the constraints are
2702     ** considered distinct and both result in separate indices.
2703     */
2704     Index *pIdx;
2705     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2706       int k;
2707       assert( pIdx->onError!=OE_None );
2708       assert( pIdx->autoIndex );
2709       assert( pIndex->onError!=OE_None );
2710 
2711       if( pIdx->nColumn!=pIndex->nColumn ) continue;
2712       for(k=0; k<pIdx->nColumn; k++){
2713         const char *z1;
2714         const char *z2;
2715         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2716         z1 = pIdx->azColl[k];
2717         z2 = pIndex->azColl[k];
2718         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
2719       }
2720       if( k==pIdx->nColumn ){
2721         if( pIdx->onError!=pIndex->onError ){
2722           /* This constraint creates the same index as a previous
2723           ** constraint specified somewhere in the CREATE TABLE statement.
2724           ** However the ON CONFLICT clauses are different. If both this
2725           ** constraint and the previous equivalent constraint have explicit
2726           ** ON CONFLICT clauses this is an error. Otherwise, use the
2727           ** explicitly specified behaviour for the index.
2728           */
2729           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2730             sqlite3ErrorMsg(pParse,
2731                 "conflicting ON CONFLICT clauses specified", 0);
2732           }
2733           if( pIdx->onError==OE_Default ){
2734             pIdx->onError = pIndex->onError;
2735           }
2736         }
2737         goto exit_create_index;
2738       }
2739     }
2740   }
2741 
2742   /* Link the new Index structure to its table and to the other
2743   ** in-memory database structures.
2744   */
2745   if( db->init.busy ){
2746     Index *p;
2747     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
2748     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
2749                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
2750                           pIndex);
2751     if( p ){
2752       assert( p==pIndex );  /* Malloc must have failed */
2753       db->mallocFailed = 1;
2754       goto exit_create_index;
2755     }
2756     db->flags |= SQLITE_InternChanges;
2757     if( pTblName!=0 ){
2758       pIndex->tnum = db->init.newTnum;
2759     }
2760   }
2761 
2762   /* If the db->init.busy is 0 then create the index on disk.  This
2763   ** involves writing the index into the master table and filling in the
2764   ** index with the current table contents.
2765   **
2766   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2767   ** command.  db->init.busy is 1 when a database is opened and
2768   ** CREATE INDEX statements are read out of the master table.  In
2769   ** the latter case the index already exists on disk, which is why
2770   ** we don't want to recreate it.
2771   **
2772   ** If pTblName==0 it means this index is generated as a primary key
2773   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
2774   ** has just been created, it contains no data and the index initialization
2775   ** step can be skipped.
2776   */
2777   else{ /* if( db->init.busy==0 ) */
2778     Vdbe *v;
2779     char *zStmt;
2780     int iMem = ++pParse->nMem;
2781 
2782     v = sqlite3GetVdbe(pParse);
2783     if( v==0 ) goto exit_create_index;
2784 
2785 
2786     /* Create the rootpage for the index
2787     */
2788     sqlite3BeginWriteOperation(pParse, 1, iDb);
2789     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
2790 
2791     /* Gather the complete text of the CREATE INDEX statement into
2792     ** the zStmt variable
2793     */
2794     if( pStart ){
2795       assert( pEnd!=0 );
2796       /* A named index with an explicit CREATE INDEX statement */
2797       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
2798         onError==OE_None ? "" : " UNIQUE",
2799         pEnd->z - pName->z + 1,
2800         pName->z);
2801     }else{
2802       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
2803       /* zStmt = sqlite3MPrintf(""); */
2804       zStmt = 0;
2805     }
2806 
2807     /* Add an entry in sqlite_master for this index
2808     */
2809     sqlite3NestedParse(pParse,
2810         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
2811         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2812         pIndex->zName,
2813         pTab->zName,
2814         iMem,
2815         zStmt
2816     );
2817     sqlite3DbFree(db, zStmt);
2818 
2819     /* Fill the index with data and reparse the schema. Code an OP_Expire
2820     ** to invalidate all pre-compiled statements.
2821     */
2822     if( pTblName ){
2823       sqlite3RefillIndex(pParse, pIndex, iMem);
2824       sqlite3ChangeCookie(pParse, iDb);
2825       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2826          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
2827          P4_DYNAMIC);
2828       sqlite3VdbeAddOp1(v, OP_Expire, 0);
2829     }
2830   }
2831 
2832   /* When adding an index to the list of indices for a table, make
2833   ** sure all indices labeled OE_Replace come after all those labeled
2834   ** OE_Ignore.  This is necessary for the correct constraint check
2835   ** processing (in sqlite3GenerateConstraintChecks()) as part of
2836   ** UPDATE and INSERT statements.
2837   */
2838   if( db->init.busy || pTblName==0 ){
2839     if( onError!=OE_Replace || pTab->pIndex==0
2840          || pTab->pIndex->onError==OE_Replace){
2841       pIndex->pNext = pTab->pIndex;
2842       pTab->pIndex = pIndex;
2843     }else{
2844       Index *pOther = pTab->pIndex;
2845       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2846         pOther = pOther->pNext;
2847       }
2848       pIndex->pNext = pOther->pNext;
2849       pOther->pNext = pIndex;
2850     }
2851     pRet = pIndex;
2852     pIndex = 0;
2853   }
2854 
2855   /* Clean up before exiting */
2856 exit_create_index:
2857   if( pIndex ){
2858     sqlite3DbFree(db, pIndex->zColAff);
2859     sqlite3DbFree(db, pIndex);
2860   }
2861   sqlite3ExprListDelete(db, pList);
2862   sqlite3SrcListDelete(db, pTblName);
2863   sqlite3DbFree(db, zName);
2864   return pRet;
2865 }
2866 
2867 /*
2868 ** Fill the Index.aiRowEst[] array with default information - information
2869 ** to be used when we have not run the ANALYZE command.
2870 **
2871 ** aiRowEst[0] is suppose to contain the number of elements in the index.
2872 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
2873 ** number of rows in the table that match any particular value of the
2874 ** first column of the index.  aiRowEst[2] is an estimate of the number
2875 ** of rows that match any particular combiniation of the first 2 columns
2876 ** of the index.  And so forth.  It must always be the case that
2877 *
2878 **           aiRowEst[N]<=aiRowEst[N-1]
2879 **           aiRowEst[N]>=1
2880 **
2881 ** Apart from that, we have little to go on besides intuition as to
2882 ** how aiRowEst[] should be initialized.  The numbers generated here
2883 ** are based on typical values found in actual indices.
2884 */
sqlite3DefaultRowEst(Index * pIdx)2885 void sqlite3DefaultRowEst(Index *pIdx){
2886   unsigned *a = pIdx->aiRowEst;
2887   int i;
2888   unsigned n;
2889   assert( a!=0 );
2890   a[0] = pIdx->pTable->nRowEst;
2891   if( a[0]<10 ) a[0] = 10;
2892   n = 10;
2893   for(i=1; i<=pIdx->nColumn; i++){
2894     a[i] = n;
2895     if( n>5 ) n--;
2896   }
2897   if( pIdx->onError!=OE_None ){
2898     a[pIdx->nColumn] = 1;
2899   }
2900 }
2901 
2902 /*
2903 ** This routine will drop an existing named index.  This routine
2904 ** implements the DROP INDEX statement.
2905 */
sqlite3DropIndex(Parse * pParse,SrcList * pName,int ifExists)2906 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
2907   Index *pIndex;
2908   Vdbe *v;
2909   sqlite3 *db = pParse->db;
2910   int iDb;
2911 
2912   assert( pParse->nErr==0 );   /* Never called with prior errors */
2913   if( db->mallocFailed ){
2914     goto exit_drop_index;
2915   }
2916   assert( pName->nSrc==1 );
2917   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2918     goto exit_drop_index;
2919   }
2920   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2921   if( pIndex==0 ){
2922     if( !ifExists ){
2923       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2924     }else{
2925       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
2926     }
2927     pParse->checkSchema = 1;
2928     goto exit_drop_index;
2929   }
2930   if( pIndex->autoIndex ){
2931     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2932       "or PRIMARY KEY constraint cannot be dropped", 0);
2933     goto exit_drop_index;
2934   }
2935   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
2936 #ifndef SQLITE_OMIT_AUTHORIZATION
2937   {
2938     int code = SQLITE_DROP_INDEX;
2939     Table *pTab = pIndex->pTable;
2940     const char *zDb = db->aDb[iDb].zName;
2941     const char *zTab = SCHEMA_TABLE(iDb);
2942     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2943       goto exit_drop_index;
2944     }
2945     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
2946     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2947       goto exit_drop_index;
2948     }
2949   }
2950 #endif
2951 
2952   /* Generate code to remove the index and from the master table */
2953   v = sqlite3GetVdbe(pParse);
2954   if( v ){
2955     sqlite3BeginWriteOperation(pParse, 1, iDb);
2956     sqlite3NestedParse(pParse,
2957        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
2958        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2959        pIndex->zName
2960     );
2961     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2962       sqlite3NestedParse(pParse,
2963         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2964         db->aDb[iDb].zName, pIndex->zName
2965       );
2966     }
2967     sqlite3ChangeCookie(pParse, iDb);
2968     destroyRootPage(pParse, pIndex->tnum, iDb);
2969     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
2970   }
2971 
2972 exit_drop_index:
2973   sqlite3SrcListDelete(db, pName);
2974 }
2975 
2976 /*
2977 ** pArray is a pointer to an array of objects.  Each object in the
2978 ** array is szEntry bytes in size.  This routine allocates a new
2979 ** object on the end of the array.
2980 **
2981 ** *pnEntry is the number of entries already in use.  *pnAlloc is
2982 ** the previously allocated size of the array.  initSize is the
2983 ** suggested initial array size allocation.
2984 **
2985 ** The index of the new entry is returned in *pIdx.
2986 **
2987 ** This routine returns a pointer to the array of objects.  This
2988 ** might be the same as the pArray parameter or it might be a different
2989 ** pointer if the array was resized.
2990 */
sqlite3ArrayAllocate(sqlite3 * db,void * pArray,int szEntry,int initSize,int * pnEntry,int * pnAlloc,int * pIdx)2991 void *sqlite3ArrayAllocate(
2992   sqlite3 *db,      /* Connection to notify of malloc failures */
2993   void *pArray,     /* Array of objects.  Might be reallocated */
2994   int szEntry,      /* Size of each object in the array */
2995   int initSize,     /* Suggested initial allocation, in elements */
2996   int *pnEntry,     /* Number of objects currently in use */
2997   int *pnAlloc,     /* Current size of the allocation, in elements */
2998   int *pIdx         /* Write the index of a new slot here */
2999 ){
3000   char *z;
3001   if( *pnEntry >= *pnAlloc ){
3002     void *pNew;
3003     int newSize;
3004     newSize = (*pnAlloc)*2 + initSize;
3005     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
3006     if( pNew==0 ){
3007       *pIdx = -1;
3008       return pArray;
3009     }
3010     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
3011     pArray = pNew;
3012   }
3013   z = (char*)pArray;
3014   memset(&z[*pnEntry * szEntry], 0, szEntry);
3015   *pIdx = *pnEntry;
3016   ++*pnEntry;
3017   return pArray;
3018 }
3019 
3020 /*
3021 ** Append a new element to the given IdList.  Create a new IdList if
3022 ** need be.
3023 **
3024 ** A new IdList is returned, or NULL if malloc() fails.
3025 */
sqlite3IdListAppend(sqlite3 * db,IdList * pList,Token * pToken)3026 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
3027   int i;
3028   if( pList==0 ){
3029     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
3030     if( pList==0 ) return 0;
3031     pList->nAlloc = 0;
3032   }
3033   pList->a = sqlite3ArrayAllocate(
3034       db,
3035       pList->a,
3036       sizeof(pList->a[0]),
3037       5,
3038       &pList->nId,
3039       &pList->nAlloc,
3040       &i
3041   );
3042   if( i<0 ){
3043     sqlite3IdListDelete(db, pList);
3044     return 0;
3045   }
3046   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
3047   return pList;
3048 }
3049 
3050 /*
3051 ** Delete an IdList.
3052 */
sqlite3IdListDelete(sqlite3 * db,IdList * pList)3053 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
3054   int i;
3055   if( pList==0 ) return;
3056   for(i=0; i<pList->nId; i++){
3057     sqlite3DbFree(db, pList->a[i].zName);
3058   }
3059   sqlite3DbFree(db, pList->a);
3060   sqlite3DbFree(db, pList);
3061 }
3062 
3063 /*
3064 ** Return the index in pList of the identifier named zId.  Return -1
3065 ** if not found.
3066 */
sqlite3IdListIndex(IdList * pList,const char * zName)3067 int sqlite3IdListIndex(IdList *pList, const char *zName){
3068   int i;
3069   if( pList==0 ) return -1;
3070   for(i=0; i<pList->nId; i++){
3071     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3072   }
3073   return -1;
3074 }
3075 
3076 /*
3077 ** Expand the space allocated for the given SrcList object by
3078 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
3079 ** New slots are zeroed.
3080 **
3081 ** For example, suppose a SrcList initially contains two entries: A,B.
3082 ** To append 3 new entries onto the end, do this:
3083 **
3084 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3085 **
3086 ** After the call above it would contain:  A, B, nil, nil, nil.
3087 ** If the iStart argument had been 1 instead of 2, then the result
3088 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
3089 ** the iStart value would be 0.  The result then would
3090 ** be: nil, nil, nil, A, B.
3091 **
3092 ** If a memory allocation fails the SrcList is unchanged.  The
3093 ** db->mallocFailed flag will be set to true.
3094 */
sqlite3SrcListEnlarge(sqlite3 * db,SrcList * pSrc,int nExtra,int iStart)3095 SrcList *sqlite3SrcListEnlarge(
3096   sqlite3 *db,       /* Database connection to notify of OOM errors */
3097   SrcList *pSrc,     /* The SrcList to be enlarged */
3098   int nExtra,        /* Number of new slots to add to pSrc->a[] */
3099   int iStart         /* Index in pSrc->a[] of first new slot */
3100 ){
3101   int i;
3102 
3103   /* Sanity checking on calling parameters */
3104   assert( iStart>=0 );
3105   assert( nExtra>=1 );
3106   assert( pSrc!=0 );
3107   assert( iStart<=pSrc->nSrc );
3108 
3109   /* Allocate additional space if needed */
3110   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3111     SrcList *pNew;
3112     int nAlloc = pSrc->nSrc+nExtra;
3113     int nGot;
3114     pNew = sqlite3DbRealloc(db, pSrc,
3115                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3116     if( pNew==0 ){
3117       assert( db->mallocFailed );
3118       return pSrc;
3119     }
3120     pSrc = pNew;
3121     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3122     pSrc->nAlloc = (u16)nGot;
3123   }
3124 
3125   /* Move existing slots that come after the newly inserted slots
3126   ** out of the way */
3127   for(i=pSrc->nSrc-1; i>=iStart; i--){
3128     pSrc->a[i+nExtra] = pSrc->a[i];
3129   }
3130   pSrc->nSrc += (i16)nExtra;
3131 
3132   /* Zero the newly allocated slots */
3133   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3134   for(i=iStart; i<iStart+nExtra; i++){
3135     pSrc->a[i].iCursor = -1;
3136   }
3137 
3138   /* Return a pointer to the enlarged SrcList */
3139   return pSrc;
3140 }
3141 
3142 
3143 /*
3144 ** Append a new table name to the given SrcList.  Create a new SrcList if
3145 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
3146 **
3147 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
3148 ** SrcList might be the same as the SrcList that was input or it might be
3149 ** a new one.  If an OOM error does occurs, then the prior value of pList
3150 ** that is input to this routine is automatically freed.
3151 **
3152 ** If pDatabase is not null, it means that the table has an optional
3153 ** database name prefix.  Like this:  "database.table".  The pDatabase
3154 ** points to the table name and the pTable points to the database name.
3155 ** The SrcList.a[].zName field is filled with the table name which might
3156 ** come from pTable (if pDatabase is NULL) or from pDatabase.
3157 ** SrcList.a[].zDatabase is filled with the database name from pTable,
3158 ** or with NULL if no database is specified.
3159 **
3160 ** In other words, if call like this:
3161 **
3162 **         sqlite3SrcListAppend(D,A,B,0);
3163 **
3164 ** Then B is a table name and the database name is unspecified.  If called
3165 ** like this:
3166 **
3167 **         sqlite3SrcListAppend(D,A,B,C);
3168 **
3169 ** Then C is the table name and B is the database name.  If C is defined
3170 ** then so is B.  In other words, we never have a case where:
3171 **
3172 **         sqlite3SrcListAppend(D,A,0,C);
3173 **
3174 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
3175 ** before being added to the SrcList.
3176 */
sqlite3SrcListAppend(sqlite3 * db,SrcList * pList,Token * pTable,Token * pDatabase)3177 SrcList *sqlite3SrcListAppend(
3178   sqlite3 *db,        /* Connection to notify of malloc failures */
3179   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
3180   Token *pTable,      /* Table to append */
3181   Token *pDatabase    /* Database of the table */
3182 ){
3183   struct SrcList_item *pItem;
3184   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
3185   if( pList==0 ){
3186     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
3187     if( pList==0 ) return 0;
3188     pList->nAlloc = 1;
3189   }
3190   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3191   if( db->mallocFailed ){
3192     sqlite3SrcListDelete(db, pList);
3193     return 0;
3194   }
3195   pItem = &pList->a[pList->nSrc-1];
3196   if( pDatabase && pDatabase->z==0 ){
3197     pDatabase = 0;
3198   }
3199   if( pDatabase ){
3200     Token *pTemp = pDatabase;
3201     pDatabase = pTable;
3202     pTable = pTemp;
3203   }
3204   pItem->zName = sqlite3NameFromToken(db, pTable);
3205   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
3206   return pList;
3207 }
3208 
3209 /*
3210 ** Assign VdbeCursor index numbers to all tables in a SrcList
3211 */
sqlite3SrcListAssignCursors(Parse * pParse,SrcList * pList)3212 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
3213   int i;
3214   struct SrcList_item *pItem;
3215   assert(pList || pParse->db->mallocFailed );
3216   if( pList ){
3217     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3218       if( pItem->iCursor>=0 ) break;
3219       pItem->iCursor = pParse->nTab++;
3220       if( pItem->pSelect ){
3221         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3222       }
3223     }
3224   }
3225 }
3226 
3227 /*
3228 ** Delete an entire SrcList including all its substructure.
3229 */
sqlite3SrcListDelete(sqlite3 * db,SrcList * pList)3230 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
3231   int i;
3232   struct SrcList_item *pItem;
3233   if( pList==0 ) return;
3234   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
3235     sqlite3DbFree(db, pItem->zDatabase);
3236     sqlite3DbFree(db, pItem->zName);
3237     sqlite3DbFree(db, pItem->zAlias);
3238     sqlite3DbFree(db, pItem->zIndex);
3239     sqlite3DeleteTable(db, pItem->pTab);
3240     sqlite3SelectDelete(db, pItem->pSelect);
3241     sqlite3ExprDelete(db, pItem->pOn);
3242     sqlite3IdListDelete(db, pItem->pUsing);
3243   }
3244   sqlite3DbFree(db, pList);
3245 }
3246 
3247 /*
3248 ** This routine is called by the parser to add a new term to the
3249 ** end of a growing FROM clause.  The "p" parameter is the part of
3250 ** the FROM clause that has already been constructed.  "p" is NULL
3251 ** if this is the first term of the FROM clause.  pTable and pDatabase
3252 ** are the name of the table and database named in the FROM clause term.
3253 ** pDatabase is NULL if the database name qualifier is missing - the
3254 ** usual case.  If the term has a alias, then pAlias points to the
3255 ** alias token.  If the term is a subquery, then pSubquery is the
3256 ** SELECT statement that the subquery encodes.  The pTable and
3257 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
3258 ** parameters are the content of the ON and USING clauses.
3259 **
3260 ** Return a new SrcList which encodes is the FROM with the new
3261 ** term added.
3262 */
sqlite3SrcListAppendFromTerm(Parse * pParse,SrcList * p,Token * pTable,Token * pDatabase,Token * pAlias,Select * pSubquery,Expr * pOn,IdList * pUsing)3263 SrcList *sqlite3SrcListAppendFromTerm(
3264   Parse *pParse,          /* Parsing context */
3265   SrcList *p,             /* The left part of the FROM clause already seen */
3266   Token *pTable,          /* Name of the table to add to the FROM clause */
3267   Token *pDatabase,       /* Name of the database containing pTable */
3268   Token *pAlias,          /* The right-hand side of the AS subexpression */
3269   Select *pSubquery,      /* A subquery used in place of a table name */
3270   Expr *pOn,              /* The ON clause of a join */
3271   IdList *pUsing          /* The USING clause of a join */
3272 ){
3273   struct SrcList_item *pItem;
3274   sqlite3 *db = pParse->db;
3275   if( !p && (pOn || pUsing) ){
3276     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3277       (pOn ? "ON" : "USING")
3278     );
3279     goto append_from_error;
3280   }
3281   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
3282   if( p==0 || NEVER(p->nSrc==0) ){
3283     goto append_from_error;
3284   }
3285   pItem = &p->a[p->nSrc-1];
3286   assert( pAlias!=0 );
3287   if( pAlias->n ){
3288     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
3289   }
3290   pItem->pSelect = pSubquery;
3291   pItem->pOn = pOn;
3292   pItem->pUsing = pUsing;
3293   return p;
3294 
3295  append_from_error:
3296   assert( p==0 );
3297   sqlite3ExprDelete(db, pOn);
3298   sqlite3IdListDelete(db, pUsing);
3299   sqlite3SelectDelete(db, pSubquery);
3300   return 0;
3301 }
3302 
3303 /*
3304 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3305 ** element of the source-list passed as the second argument.
3306 */
sqlite3SrcListIndexedBy(Parse * pParse,SrcList * p,Token * pIndexedBy)3307 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3308   assert( pIndexedBy!=0 );
3309   if( p && ALWAYS(p->nSrc>0) ){
3310     struct SrcList_item *pItem = &p->a[p->nSrc-1];
3311     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3312     if( pIndexedBy->n==1 && !pIndexedBy->z ){
3313       /* A "NOT INDEXED" clause was supplied. See parse.y
3314       ** construct "indexed_opt" for details. */
3315       pItem->notIndexed = 1;
3316     }else{
3317       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3318     }
3319   }
3320 }
3321 
3322 /*
3323 ** When building up a FROM clause in the parser, the join operator
3324 ** is initially attached to the left operand.  But the code generator
3325 ** expects the join operator to be on the right operand.  This routine
3326 ** Shifts all join operators from left to right for an entire FROM
3327 ** clause.
3328 **
3329 ** Example: Suppose the join is like this:
3330 **
3331 **           A natural cross join B
3332 **
3333 ** The operator is "natural cross join".  The A and B operands are stored
3334 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
3335 ** operator with A.  This routine shifts that operator over to B.
3336 */
sqlite3SrcListShiftJoinType(SrcList * p)3337 void sqlite3SrcListShiftJoinType(SrcList *p){
3338   if( p && p->a ){
3339     int i;
3340     for(i=p->nSrc-1; i>0; i--){
3341       p->a[i].jointype = p->a[i-1].jointype;
3342     }
3343     p->a[0].jointype = 0;
3344   }
3345 }
3346 
3347 /*
3348 ** Begin a transaction
3349 */
sqlite3BeginTransaction(Parse * pParse,int type)3350 void sqlite3BeginTransaction(Parse *pParse, int type){
3351   sqlite3 *db;
3352   Vdbe *v;
3353   int i;
3354 
3355   assert( pParse!=0 );
3356   db = pParse->db;
3357   assert( db!=0 );
3358 /*  if( db->aDb[0].pBt==0 ) return; */
3359   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3360     return;
3361   }
3362   v = sqlite3GetVdbe(pParse);
3363   if( !v ) return;
3364   if( type!=TK_DEFERRED ){
3365     for(i=0; i<db->nDb; i++){
3366       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
3367       sqlite3VdbeUsesBtree(v, i);
3368     }
3369   }
3370   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
3371 }
3372 
3373 /*
3374 ** Commit a transaction
3375 */
sqlite3CommitTransaction(Parse * pParse)3376 void sqlite3CommitTransaction(Parse *pParse){
3377   sqlite3 *db;
3378   Vdbe *v;
3379 
3380   assert( pParse!=0 );
3381   db = pParse->db;
3382   assert( db!=0 );
3383 /*  if( db->aDb[0].pBt==0 ) return; */
3384   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3385     return;
3386   }
3387   v = sqlite3GetVdbe(pParse);
3388   if( v ){
3389     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
3390   }
3391 }
3392 
3393 /*
3394 ** Rollback a transaction
3395 */
sqlite3RollbackTransaction(Parse * pParse)3396 void sqlite3RollbackTransaction(Parse *pParse){
3397   sqlite3 *db;
3398   Vdbe *v;
3399 
3400   assert( pParse!=0 );
3401   db = pParse->db;
3402   assert( db!=0 );
3403 /*  if( db->aDb[0].pBt==0 ) return; */
3404   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3405     return;
3406   }
3407   v = sqlite3GetVdbe(pParse);
3408   if( v ){
3409     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
3410   }
3411 }
3412 
3413 /*
3414 ** This function is called by the parser when it parses a command to create,
3415 ** release or rollback an SQL savepoint.
3416 */
sqlite3Savepoint(Parse * pParse,int op,Token * pName)3417 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
3418   char *zName = sqlite3NameFromToken(pParse->db, pName);
3419   if( zName ){
3420     Vdbe *v = sqlite3GetVdbe(pParse);
3421 #ifndef SQLITE_OMIT_AUTHORIZATION
3422     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3423     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3424 #endif
3425     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3426       sqlite3DbFree(pParse->db, zName);
3427       return;
3428     }
3429     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
3430   }
3431 }
3432 
3433 /*
3434 ** Make sure the TEMP database is open and available for use.  Return
3435 ** the number of errors.  Leave any error messages in the pParse structure.
3436 */
sqlite3OpenTempDatabase(Parse * pParse)3437 int sqlite3OpenTempDatabase(Parse *pParse){
3438   sqlite3 *db = pParse->db;
3439   if( db->aDb[1].pBt==0 && !pParse->explain ){
3440     int rc;
3441     Btree *pBt;
3442     static const int flags =
3443           SQLITE_OPEN_READWRITE |
3444           SQLITE_OPEN_CREATE |
3445           SQLITE_OPEN_EXCLUSIVE |
3446           SQLITE_OPEN_DELETEONCLOSE |
3447           SQLITE_OPEN_TEMP_DB;
3448 
3449     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
3450     if( rc!=SQLITE_OK ){
3451       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3452         "file for storing temporary tables");
3453       pParse->rc = rc;
3454       return 1;
3455     }
3456     db->aDb[1].pBt = pBt;
3457     assert( db->aDb[1].pSchema );
3458     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3459       db->mallocFailed = 1;
3460       return 1;
3461     }
3462   }
3463   return 0;
3464 }
3465 
3466 /*
3467 ** Generate VDBE code that will verify the schema cookie and start
3468 ** a read-transaction for all named database files.
3469 **
3470 ** It is important that all schema cookies be verified and all
3471 ** read transactions be started before anything else happens in
3472 ** the VDBE program.  But this routine can be called after much other
3473 ** code has been generated.  So here is what we do:
3474 **
3475 ** The first time this routine is called, we code an OP_Goto that
3476 ** will jump to a subroutine at the end of the program.  Then we
3477 ** record every database that needs its schema verified in the
3478 ** pParse->cookieMask field.  Later, after all other code has been
3479 ** generated, the subroutine that does the cookie verifications and
3480 ** starts the transactions will be coded and the OP_Goto P2 value
3481 ** will be made to point to that subroutine.  The generation of the
3482 ** cookie verification subroutine code happens in sqlite3FinishCoding().
3483 **
3484 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3485 ** schema on any databases.  This can be used to position the OP_Goto
3486 ** early in the code, before we know if any database tables will be used.
3487 */
sqlite3CodeVerifySchema(Parse * pParse,int iDb)3488 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
3489   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3490 
3491   if( pToplevel->cookieGoto==0 ){
3492     Vdbe *v = sqlite3GetVdbe(pToplevel);
3493     if( v==0 ) return;  /* This only happens if there was a prior error */
3494     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
3495   }
3496   if( iDb>=0 ){
3497     sqlite3 *db = pToplevel->db;
3498     yDbMask mask;
3499 
3500     assert( iDb<db->nDb );
3501     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3502     assert( iDb<SQLITE_MAX_ATTACHED+2 );
3503     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3504     mask = ((yDbMask)1)<<iDb;
3505     if( (pToplevel->cookieMask & mask)==0 ){
3506       pToplevel->cookieMask |= mask;
3507       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3508       if( !OMIT_TEMPDB && iDb==1 ){
3509         sqlite3OpenTempDatabase(pToplevel);
3510       }
3511     }
3512   }
3513 }
3514 
3515 /*
3516 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3517 ** attached database. Otherwise, invoke it for the database named zDb only.
3518 */
sqlite3CodeVerifyNamedSchema(Parse * pParse,const char * zDb)3519 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3520   sqlite3 *db = pParse->db;
3521   int i;
3522   for(i=0; i<db->nDb; i++){
3523     Db *pDb = &db->aDb[i];
3524     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3525       sqlite3CodeVerifySchema(pParse, i);
3526     }
3527   }
3528 }
3529 
3530 /*
3531 ** Generate VDBE code that prepares for doing an operation that
3532 ** might change the database.
3533 **
3534 ** This routine starts a new transaction if we are not already within
3535 ** a transaction.  If we are already within a transaction, then a checkpoint
3536 ** is set if the setStatement parameter is true.  A checkpoint should
3537 ** be set for operations that might fail (due to a constraint) part of
3538 ** the way through and which will need to undo some writes without having to
3539 ** rollback the whole transaction.  For operations where all constraints
3540 ** can be checked before any changes are made to the database, it is never
3541 ** necessary to undo a write and the checkpoint should not be set.
3542 */
sqlite3BeginWriteOperation(Parse * pParse,int setStatement,int iDb)3543 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
3544   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3545   sqlite3CodeVerifySchema(pParse, iDb);
3546   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
3547   pToplevel->isMultiWrite |= setStatement;
3548 }
3549 
3550 /*
3551 ** Indicate that the statement currently under construction might write
3552 ** more than one entry (example: deleting one row then inserting another,
3553 ** inserting multiple rows in a table, or inserting a row and index entries.)
3554 ** If an abort occurs after some of these writes have completed, then it will
3555 ** be necessary to undo the completed writes.
3556 */
sqlite3MultiWrite(Parse * pParse)3557 void sqlite3MultiWrite(Parse *pParse){
3558   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3559   pToplevel->isMultiWrite = 1;
3560 }
3561 
3562 /*
3563 ** The code generator calls this routine if is discovers that it is
3564 ** possible to abort a statement prior to completion.  In order to
3565 ** perform this abort without corrupting the database, we need to make
3566 ** sure that the statement is protected by a statement transaction.
3567 **
3568 ** Technically, we only need to set the mayAbort flag if the
3569 ** isMultiWrite flag was previously set.  There is a time dependency
3570 ** such that the abort must occur after the multiwrite.  This makes
3571 ** some statements involving the REPLACE conflict resolution algorithm
3572 ** go a little faster.  But taking advantage of this time dependency
3573 ** makes it more difficult to prove that the code is correct (in
3574 ** particular, it prevents us from writing an effective
3575 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
3576 ** to take the safe route and skip the optimization.
3577 */
sqlite3MayAbort(Parse * pParse)3578 void sqlite3MayAbort(Parse *pParse){
3579   Parse *pToplevel = sqlite3ParseToplevel(pParse);
3580   pToplevel->mayAbort = 1;
3581 }
3582 
3583 /*
3584 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3585 ** error. The onError parameter determines which (if any) of the statement
3586 ** and/or current transaction is rolled back.
3587 */
sqlite3HaltConstraint(Parse * pParse,int onError,char * p4,int p4type)3588 void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
3589   Vdbe *v = sqlite3GetVdbe(pParse);
3590   if( onError==OE_Abort ){
3591     sqlite3MayAbort(pParse);
3592   }
3593   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
3594 }
3595 
3596 /*
3597 ** Check to see if pIndex uses the collating sequence pColl.  Return
3598 ** true if it does and false if it does not.
3599 */
3600 #ifndef SQLITE_OMIT_REINDEX
collationMatch(const char * zColl,Index * pIndex)3601 static int collationMatch(const char *zColl, Index *pIndex){
3602   int i;
3603   assert( zColl!=0 );
3604   for(i=0; i<pIndex->nColumn; i++){
3605     const char *z = pIndex->azColl[i];
3606     assert( z!=0 );
3607     if( 0==sqlite3StrICmp(z, zColl) ){
3608       return 1;
3609     }
3610   }
3611   return 0;
3612 }
3613 #endif
3614 
3615 /*
3616 ** Recompute all indices of pTab that use the collating sequence pColl.
3617 ** If pColl==0 then recompute all indices of pTab.
3618 */
3619 #ifndef SQLITE_OMIT_REINDEX
reindexTable(Parse * pParse,Table * pTab,char const * zColl)3620 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
3621   Index *pIndex;              /* An index associated with pTab */
3622 
3623   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
3624     if( zColl==0 || collationMatch(zColl, pIndex) ){
3625       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3626       sqlite3BeginWriteOperation(pParse, 0, iDb);
3627       sqlite3RefillIndex(pParse, pIndex, -1);
3628     }
3629   }
3630 }
3631 #endif
3632 
3633 /*
3634 ** Recompute all indices of all tables in all databases where the
3635 ** indices use the collating sequence pColl.  If pColl==0 then recompute
3636 ** all indices everywhere.
3637 */
3638 #ifndef SQLITE_OMIT_REINDEX
reindexDatabases(Parse * pParse,char const * zColl)3639 static void reindexDatabases(Parse *pParse, char const *zColl){
3640   Db *pDb;                    /* A single database */
3641   int iDb;                    /* The database index number */
3642   sqlite3 *db = pParse->db;   /* The database connection */
3643   HashElem *k;                /* For looping over tables in pDb */
3644   Table *pTab;                /* A table in the database */
3645 
3646   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
3647   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3648     assert( pDb!=0 );
3649     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
3650       pTab = (Table*)sqliteHashData(k);
3651       reindexTable(pParse, pTab, zColl);
3652     }
3653   }
3654 }
3655 #endif
3656 
3657 /*
3658 ** Generate code for the REINDEX command.
3659 **
3660 **        REINDEX                            -- 1
3661 **        REINDEX  <collation>               -- 2
3662 **        REINDEX  ?<database>.?<tablename>  -- 3
3663 **        REINDEX  ?<database>.?<indexname>  -- 4
3664 **
3665 ** Form 1 causes all indices in all attached databases to be rebuilt.
3666 ** Form 2 rebuilds all indices in all databases that use the named
3667 ** collating function.  Forms 3 and 4 rebuild the named index or all
3668 ** indices associated with the named table.
3669 */
3670 #ifndef SQLITE_OMIT_REINDEX
sqlite3Reindex(Parse * pParse,Token * pName1,Token * pName2)3671 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3672   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
3673   char *z;                    /* Name of a table or index */
3674   const char *zDb;            /* Name of the database */
3675   Table *pTab;                /* A table in the database */
3676   Index *pIndex;              /* An index associated with pTab */
3677   int iDb;                    /* The database index number */
3678   sqlite3 *db = pParse->db;   /* The database connection */
3679   Token *pObjName;            /* Name of the table or index to be reindexed */
3680 
3681   /* Read the database schema. If an error occurs, leave an error message
3682   ** and code in pParse and return NULL. */
3683   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3684     return;
3685   }
3686 
3687   if( pName1==0 ){
3688     reindexDatabases(pParse, 0);
3689     return;
3690   }else if( NEVER(pName2==0) || pName2->z==0 ){
3691     char *zColl;
3692     assert( pName1->z );
3693     zColl = sqlite3NameFromToken(pParse->db, pName1);
3694     if( !zColl ) return;
3695     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
3696     if( pColl ){
3697       reindexDatabases(pParse, zColl);
3698       sqlite3DbFree(db, zColl);
3699       return;
3700     }
3701     sqlite3DbFree(db, zColl);
3702   }
3703   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3704   if( iDb<0 ) return;
3705   z = sqlite3NameFromToken(db, pObjName);
3706   if( z==0 ) return;
3707   zDb = db->aDb[iDb].zName;
3708   pTab = sqlite3FindTable(db, z, zDb);
3709   if( pTab ){
3710     reindexTable(pParse, pTab, 0);
3711     sqlite3DbFree(db, z);
3712     return;
3713   }
3714   pIndex = sqlite3FindIndex(db, z, zDb);
3715   sqlite3DbFree(db, z);
3716   if( pIndex ){
3717     sqlite3BeginWriteOperation(pParse, 0, iDb);
3718     sqlite3RefillIndex(pParse, pIndex, -1);
3719     return;
3720   }
3721   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3722 }
3723 #endif
3724 
3725 /*
3726 ** Return a dynamicly allocated KeyInfo structure that can be used
3727 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3728 **
3729 ** If successful, a pointer to the new structure is returned. In this case
3730 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
3731 ** pointer. If an error occurs (out of memory or missing collation
3732 ** sequence), NULL is returned and the state of pParse updated to reflect
3733 ** the error.
3734 */
sqlite3IndexKeyinfo(Parse * pParse,Index * pIdx)3735 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3736   int i;
3737   int nCol = pIdx->nColumn;
3738   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3739   sqlite3 *db = pParse->db;
3740   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
3741 
3742   if( pKey ){
3743     pKey->db = pParse->db;
3744     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3745     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3746     for(i=0; i<nCol; i++){
3747       char *zColl = pIdx->azColl[i];
3748       assert( zColl );
3749       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
3750       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3751     }
3752     pKey->nField = (u16)nCol;
3753   }
3754 
3755   if( pParse->nErr ){
3756     sqlite3DbFree(db, pKey);
3757     pKey = 0;
3758   }
3759   return pKey;
3760 }
3761 
3762 /* Begin preload-cache.patch for Chromium */
3763 /* See declaration in sqlite3.h for information */
sqlite3_preload(sqlite3 * db)3764 int sqlite3_preload(sqlite3 *db)
3765 {
3766   Pager *pPager;
3767   Btree *pBt;
3768   int rc;
3769   int i;
3770   int dbsLoaded = 0;
3771 
3772   for(i=0; i<db->nDb; i++) {
3773     pBt = db->aDb[i].pBt;
3774     if( !pBt )
3775       continue;
3776     pPager = sqlite3BtreePager(pBt);
3777     if( pPager ) {
3778       rc = sqlite3PagerLoadall(pPager);
3779       if (rc == SQLITE_OK)
3780         dbsLoaded++;
3781     }
3782   }
3783   if (dbsLoaded == 0)
3784     return SQLITE_ERROR;
3785   return SQLITE_OK;
3786 }
3787 /* End preload-cache.patch for Chromium */
3788