xref: /sqlite-3.40.0/src/build.c (revision ef5ecb41)
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 **     PRAGMA
25 **
26 ** $Id: build.c,v 1.216 2004/06/10 14:01:08 danielk1977 Exp $
27 */
28 #include "sqliteInt.h"
29 #include <ctype.h>
30 
31 /*
32 ** This routine is called when a new SQL statement is beginning to
33 ** be parsed.  Check to see if the schema for the database needs
34 ** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
35 ** If it does, then read it.
36 */
37 void sqlite3BeginParse(Parse *pParse, int explainFlag){
38   sqlite *db = pParse->db;
39   int i;
40   pParse->explain = explainFlag;
41 #if 0
42   if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
43     int rc = sqlite3Init(db, &pParse->zErrMsg);
44     if( rc!=SQLITE_OK ){
45       pParse->rc = rc;
46       pParse->nErr++;
47     }
48   }
49 #endif
50   for(i=0; i<db->nDb; i++){
51     DbClearProperty(db, i, DB_Locked);
52     if( !db->aDb[i].inTrans ){
53       DbClearProperty(db, i, DB_Cookie);
54     }
55   }
56   pParse->nVar = 0;
57 }
58 
59 /*
60 ** This routine is called after a single SQL statement has been
61 ** parsed and a VDBE program to execute that statement has been
62 ** prepared.  This routine puts the finishing touches on the
63 ** VDBE program and resets the pParse structure for the next
64 ** parse.
65 **
66 ** Note that if an error occurred, it might be the case that
67 ** no VDBE code was generated.
68 */
69 void sqlite3FinishCoding(Parse *pParse){
70   sqlite *db;
71   Vdbe *v;
72 
73   if( sqlite3_malloc_failed ) return;
74 
75   /* Begin by generating some termination code at the end of the
76   ** vdbe program
77   */
78   db = pParse->db;
79   v = sqlite3GetVdbe(pParse);
80   if( v ){
81     sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
82     if( pParse->cookieMask!=0 ){
83       u32 mask;
84       int iDb;
85       sqlite3VdbeChangeP2(v, pParse->cookieGoto, sqlite3VdbeCurrentAddr(v));
86       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
87         if( (mask & pParse->cookieMask)==0 ) continue;
88         sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
89         if( iDb!=1 ){
90           sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
91         }
92       }
93       sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto+1);
94     }
95   }
96 
97   /* Get the VDBE program ready for execution
98   */
99   if( v && pParse->nErr==0 ){
100     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
101     sqlite3VdbeTrace(v, trace);
102     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->explain);
103     pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
104     pParse->colNamesSet = 0;
105   }else if( pParse->rc==SQLITE_OK ){
106     pParse->rc = SQLITE_ERROR;
107   }
108   pParse->nTab = 0;
109   pParse->nMem = 0;
110   pParse->nSet = 0;
111   pParse->nAgg = 0;
112   pParse->nVar = 0;
113   pParse->cookieMask = 0;
114 }
115 
116 /*
117 ** Locate the in-memory structure that describes
118 ** a particular database table given the name
119 ** of that table and (optionally) the name of the database
120 ** containing the table.  Return NULL if not found.
121 **
122 ** If zDatabase is 0, all databases are searched for the
123 ** table and the first matching table is returned.  (No checking
124 ** for duplicate table names is done.)  The search order is
125 ** TEMP first, then MAIN, then any auxiliary databases added
126 ** using the ATTACH command.
127 **
128 ** See also sqlite3LocateTable().
129 */
130 Table *sqlite3FindTable(sqlite *db, const char *zName, const char *zDatabase){
131   Table *p = 0;
132   int i;
133   int rc = sqlite3ReadSchema(db, 0);
134   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
135     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
136     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
137     p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
138     if( p ) break;
139   }
140   return p;
141 }
142 
143 /*
144 ** Locate the in-memory structure that describes
145 ** a particular database table given the name
146 ** of that table and (optionally) the name of the database
147 ** containing the table.  Return NULL if not found.
148 ** Also leave an error message in pParse->zErrMsg.
149 **
150 ** The difference between this routine and sqlite3FindTable()
151 ** is that this routine leaves an error message in pParse->zErrMsg
152 ** where sqlite3FindTable() does not.
153 */
154 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
155   Table *p;
156 
157   p = sqlite3FindTable(pParse->db, zName, zDbase);
158   if( p==0 ){
159     if( zDbase ){
160       sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
161     }else if( sqlite3FindTable(pParse->db, zName, 0)!=0 ){
162       sqlite3ErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
163          zName, zDbase);
164     }else{
165       sqlite3ErrorMsg(pParse, "no such table: %s", zName);
166     }
167     pParse->checkSchema = 1;
168   }
169   return p;
170 }
171 
172 /*
173 ** Locate the in-memory structure that describes
174 ** a particular index given the name of that index
175 ** and the name of the database that contains the index.
176 ** Return NULL if not found.
177 **
178 ** If zDatabase is 0, all databases are searched for the
179 ** table and the first matching index is returned.  (No checking
180 ** for duplicate index names is done.)  The search order is
181 ** TEMP first, then MAIN, then any auxiliary databases added
182 ** using the ATTACH command.
183 */
184 Index *sqlite3FindIndex(sqlite *db, const char *zName, const char *zDb){
185   Index *p = 0;
186   int i;
187   int rc = sqlite3ReadSchema(db, 0);
188   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
189     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
190     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
191     p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
192     if( p ) break;
193   }
194   return p;
195 }
196 
197 /*
198 ** Remove the given index from the index hash table, and free
199 ** its memory structures.
200 **
201 ** The index is removed from the database hash tables but
202 ** it is not unlinked from the Table that it indexes.
203 ** Unlinking from the Table must be done by the calling function.
204 */
205 static void sqliteDeleteIndex(sqlite *db, Index *p){
206   Index *pOld;
207 
208   assert( db!=0 && p->zName!=0 );
209   pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
210                           strlen(p->zName)+1, 0);
211   if( pOld!=0 && pOld!=p ){
212     sqlite3HashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
213                      strlen(pOld->zName)+1, pOld);
214   }
215   if( p->zColAff ){
216     sqliteFree(p->zColAff);
217   }
218   sqliteFree(p);
219 }
220 
221 /*
222 ** Unlink the given index from its table, then remove
223 ** the index from the index hash table and free its memory
224 ** structures.
225 */
226 void sqlite3UnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
227   if( pIndex->pTable->pIndex==pIndex ){
228     pIndex->pTable->pIndex = pIndex->pNext;
229   }else{
230     Index *p;
231     for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
232     if( p && p->pNext==pIndex ){
233       p->pNext = pIndex->pNext;
234     }
235   }
236   sqliteDeleteIndex(db, pIndex);
237 }
238 
239 /*
240 ** Erase all schema information from the in-memory hash tables of
241 ** database connection.  This routine is called to reclaim memory
242 ** before the connection closes.  It is also called during a rollback
243 ** if there were schema changes during the transaction.
244 **
245 ** If iDb<=0 then reset the internal schema tables for all database
246 ** files.  If iDb>=2 then reset the internal schema for only the
247 ** single file indicated.
248 */
249 void sqlite3ResetInternalSchema(sqlite *db, int iDb){
250   HashElem *pElem;
251   Hash temp1;
252   Hash temp2;
253   int i, j;
254 
255   assert( iDb>=0 && iDb<db->nDb );
256   db->flags &= ~SQLITE_Initialized;
257   for(i=iDb; i<db->nDb; i++){
258     Db *pDb = &db->aDb[i];
259     temp1 = pDb->tblHash;
260     temp2 = pDb->trigHash;
261     sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
262     sqlite3HashClear(&pDb->aFKey);
263     sqlite3HashClear(&pDb->idxHash);
264     for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
265       Trigger *pTrigger = sqliteHashData(pElem);
266       sqlite3DeleteTrigger(pTrigger);
267     }
268     sqlite3HashClear(&temp2);
269     sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
270     for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
271       Table *pTab = sqliteHashData(pElem);
272       sqlite3DeleteTable(db, pTab);
273     }
274     sqlite3HashClear(&temp1);
275     DbClearProperty(db, i, DB_SchemaLoaded);
276     if( iDb>0 ) return;
277   }
278   assert( iDb==0 );
279   db->flags &= ~SQLITE_InternChanges;
280 
281   /* If one or more of the auxiliary database files has been closed,
282   ** then remove then from the auxiliary database list.  We take the
283   ** opportunity to do this here since we have just deleted all of the
284   ** schema hash tables and therefore do not have to make any changes
285   ** to any of those tables.
286   */
287   for(i=0; i<db->nDb; i++){
288     struct Db *pDb = &db->aDb[i];
289     if( pDb->pBt==0 ){
290       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
291       pDb->pAux = 0;
292     }
293   }
294   for(i=j=2; i<db->nDb; i++){
295     struct Db *pDb = &db->aDb[i];
296     if( pDb->pBt==0 ){
297       sqliteFree(pDb->zName);
298       pDb->zName = 0;
299       continue;
300     }
301     if( j<i ){
302       db->aDb[j] = db->aDb[i];
303     }
304     j++;
305   }
306   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
307   db->nDb = j;
308   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
309     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
310     sqliteFree(db->aDb);
311     db->aDb = db->aDbStatic;
312   }
313 }
314 
315 /*
316 ** This routine is called whenever a rollback occurs.  If there were
317 ** schema changes during the transaction, then we have to reset the
318 ** internal hash tables and reload them from disk.
319 */
320 void sqlite3RollbackInternalChanges(sqlite *db){
321   if( db->flags & SQLITE_InternChanges ){
322     sqlite3ResetInternalSchema(db, 0);
323   }
324 }
325 
326 /*
327 ** This routine is called when a commit occurs.
328 */
329 void sqlite3CommitInternalChanges(sqlite *db){
330   db->aDb[0].schema_cookie = db->next_cookie;
331   db->flags &= ~SQLITE_InternChanges;
332 }
333 
334 /*
335 ** Remove the memory data structures associated with the given
336 ** Table.  No changes are made to disk by this routine.
337 **
338 ** This routine just deletes the data structure.  It does not unlink
339 ** the table data structure from the hash table.  Nor does it remove
340 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
341 ** memory structures of the indices and foreign keys associated with
342 ** the table.
343 **
344 ** Indices associated with the table are unlinked from the "db"
345 ** data structure if db!=NULL.  If db==NULL, indices attached to
346 ** the table are deleted, but it is assumed they have already been
347 ** unlinked.
348 */
349 void sqlite3DeleteTable(sqlite *db, Table *pTable){
350   int i;
351   Index *pIndex, *pNext;
352   FKey *pFKey, *pNextFKey;
353 
354   if( pTable==0 ) return;
355 
356   /* Delete all indices associated with this table
357   */
358   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
359     pNext = pIndex->pNext;
360     assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
361     sqliteDeleteIndex(db, pIndex);
362   }
363 
364   /* Delete all foreign keys associated with this table.  The keys
365   ** should have already been unlinked from the db->aFKey hash table
366   */
367   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
368     pNextFKey = pFKey->pNextFrom;
369     assert( pTable->iDb<db->nDb );
370     assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
371                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
372     sqliteFree(pFKey);
373   }
374 
375   /* Delete the Table structure itself.
376   */
377   for(i=0; i<pTable->nCol; i++){
378     sqliteFree(pTable->aCol[i].zName);
379     sqliteFree(pTable->aCol[i].zDflt);
380     sqliteFree(pTable->aCol[i].zType);
381   }
382   sqliteFree(pTable->zName);
383   sqliteFree(pTable->aCol);
384   if( pTable->zColAff ){
385     sqliteFree(pTable->zColAff);
386   }
387   sqlite3SelectDelete(pTable->pSelect);
388   sqliteFree(pTable);
389 }
390 
391 /*
392 ** Unlink the given table from the hash tables and the delete the
393 ** table structure with all its indices and foreign keys.
394 */
395 static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
396   Table *pOld;
397   FKey *pF1, *pF2;
398   int i = p->iDb;
399   assert( db!=0 );
400   pOld = sqlite3HashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
401   assert( pOld==0 || pOld==p );
402   for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
403     int nTo = strlen(pF1->zTo) + 1;
404     pF2 = sqlite3HashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
405     if( pF2==pF1 ){
406       sqlite3HashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
407     }else{
408       while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
409       if( pF2 ){
410         pF2->pNextTo = pF1->pNextTo;
411       }
412     }
413   }
414   sqlite3DeleteTable(db, p);
415 }
416 
417 /*
418 ** Construct the name of a user table or index from a token.
419 **
420 ** Space to hold the name is obtained from sqliteMalloc() and must
421 ** be freed by the calling function.
422 */
423 char *sqlite3TableNameFromToken(Token *pName){
424   char *zName = sqliteStrNDup(pName->z, pName->n);
425   sqlite3Dequote(zName);
426   return zName;
427 }
428 
429 /*
430 ** Open the sqlite_master table stored in database number iDb for
431 ** writing. The table is opened using cursor 0.
432 */
433 void sqlite3OpenMasterTable(Vdbe *v, int iDb){
434   sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
435   sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
436   sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
437 }
438 
439 /*
440 ** The token *pName contains the name of a database (either "main" or
441 ** "temp" or the name of an attached db). This routine returns the
442 ** index of the named database in db->aDb[], or -1 if the named db
443 ** does not exist.
444 */
445 int findDb(sqlite3 *db, Token *pName){
446   int i;
447   for(i=0; i<db->nDb; i++){
448     if( pName->n==strlen(db->aDb[i].zName) &&
449         0==sqlite3StrNICmp(db->aDb[i].zName, pName->z, pName->n) ){
450       return i;
451     }
452   }
453   return -1;
454 }
455 
456 int sqlite3TwoPartName(
457   Parse *pParse,
458   Token *pName1,
459   Token *pName2,
460   Token **pUnqual
461 ){
462   int iDb;
463   sqlite3 *db = pParse->db;
464 
465   if( pName2 && pName2->n>0 ){
466     assert( !db->init.busy );
467     *pUnqual = pName2;
468     iDb = findDb(db, pName1);
469     if( iDb<0 ){
470       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
471       pParse->nErr++;
472       return -1;
473     }
474   }else{
475     assert( db->init.iDb==0 || db->init.busy );
476     iDb = db->init.iDb;
477     *pUnqual = pName1;
478   }
479   return iDb;
480 }
481 
482 /*
483 ** Begin constructing a new table representation in memory.  This is
484 ** the first of several action routines that get called in response
485 ** to a CREATE TABLE statement.  In particular, this routine is called
486 ** after seeing tokens "CREATE" and "TABLE" and the table name.  The
487 ** pStart token is the CREATE and pName is the table name.  The isTemp
488 ** flag is true if the table should be stored in the auxiliary database
489 ** file instead of in the main database file.  This is normally the case
490 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
491 ** CREATE and TABLE.
492 **
493 ** The new table record is initialized and put in pParse->pNewTable.
494 ** As more of the CREATE TABLE statement is parsed, additional action
495 ** routines will be called to add more information to this record.
496 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
497 ** is called to complete the construction of the new table record.
498 */
499 void sqlite3StartTable(
500   Parse *pParse,   /* Parser context */
501   Token *pStart,   /* The "CREATE" token */
502   Token *pName1,   /* First part of the name of the table or view */
503   Token *pName2,   /* Second part of the name of the table or view */
504   int isTemp,      /* True if this is a TEMP table */
505   int isView       /* True if this is a VIEW */
506 ){
507   Table *pTable;
508   Index *pIdx;
509   char *zName;
510   sqlite *db = pParse->db;
511   Vdbe *v;
512   int iDb;         /* Database number to create the table in */
513   Token *pName;    /* Unqualified name of the table to create */
514 
515   /* The table or view name to create is passed to this routine via tokens
516   ** pName1 and pName2. If the table name was fully qualified, for example:
517   **
518   ** CREATE TABLE xxx.yyy (...);
519   **
520   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
521   ** the table name is not fully qualified, i.e.:
522   **
523   ** CREATE TABLE yyy(...);
524   **
525   ** Then pName1 is set to "yyy" and pName2 is "".
526   **
527   ** The call below sets the pName pointer to point at the token (pName1 or
528   ** pName2) that stores the unqualified table name. The variable iDb is
529   ** set to the index of the database that the table or view is to be
530   ** created in.
531   */
532   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
533   if( iDb<0 ) return;
534   if( isTemp && iDb>1 ){
535     /* If creating a temp table, the name may not be qualified */
536     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
537     pParse->nErr++;
538     return;
539   }
540   if( isTemp ) iDb = 1;
541 
542   pParse->sNameToken = *pName;
543   zName = sqlite3TableNameFromToken(pName);
544   if( zName==0 ) return;
545   if( db->init.iDb==1 ) isTemp = 1;
546 #ifndef SQLITE_OMIT_AUTHORIZATION
547   assert( (isTemp & 1)==isTemp );
548   {
549     int code;
550     char *zDb = db->aDb[iDb].zName;
551     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
552       sqliteFree(zName);
553       return;
554     }
555     if( isView ){
556       if( isTemp ){
557         code = SQLITE_CREATE_TEMP_VIEW;
558       }else{
559         code = SQLITE_CREATE_VIEW;
560       }
561     }else{
562       if( isTemp ){
563         code = SQLITE_CREATE_TEMP_TABLE;
564       }else{
565         code = SQLITE_CREATE_TABLE;
566       }
567     }
568     if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
569       sqliteFree(zName);
570       return;
571     }
572   }
573 #endif
574 
575   /* Before trying to create a temporary table, make sure the Btree for
576   ** holding temporary tables is open.
577   */
578   if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
579     int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
580     if( rc!=SQLITE_OK ){
581       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
582         "file for storing temporary tables");
583       pParse->nErr++;
584       return;
585     }
586     if( db->flags & !db->autoCommit ){
587       rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1, 0);
588       if( rc!=SQLITE_OK ){
589         sqlite3ErrorMsg(pParse, "unable to get a write lock on "
590           "the temporary database file");
591         return;
592       }
593     }
594   }
595 
596   /* Make sure the new table name does not collide with an existing
597   ** index or table name in the same database.  Issue an error message if
598   ** it does.
599   */
600   pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
601   if( pTable ){
602     sqlite3ErrorMsg(pParse, "table %T already exists", pName);
603     sqliteFree(zName);
604     return;
605   }
606   if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 &&
607           (pIdx->iDb==0 || !db->init.busy) ){
608     sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
609     sqliteFree(zName);
610     return;
611   }
612   pTable = sqliteMalloc( sizeof(Table) );
613   if( pTable==0 ){
614     sqliteFree(zName);
615     return;
616   }
617   pTable->zName = zName;
618   pTable->nCol = 0;
619   pTable->aCol = 0;
620   pTable->iPKey = -1;
621   pTable->pIndex = 0;
622   pTable->iDb = iDb;
623   if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
624   pParse->pNewTable = pTable;
625 
626   /* Begin generating the code that will insert the table record into
627   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
628   ** and allocate the record number for the table entry now.  Before any
629   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
630   ** indices to be created and the table record must come before the
631   ** indices.  Hence, the record number for the table must be allocated
632   ** now.
633   */
634   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
635     sqlite3BeginWriteOperation(pParse, 0, iDb);
636     if( !isTemp ){
637       /* Every time a new table is created the file-format
638       ** and encoding meta-values are set in the database, in
639       ** case this is the first table created.
640       */
641       sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
642       sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
643       sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
644       sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
645     }
646     sqlite3OpenMasterTable(v, iDb);
647     sqlite3VdbeAddOp(v, OP_NewRecno, 0, 0);
648     sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
649     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
650     sqlite3VdbeAddOp(v, OP_PutIntKey, 0, 0);
651   }
652 }
653 
654 /*
655 ** Add a new column to the table currently being constructed.
656 **
657 ** The parser calls this routine once for each column declaration
658 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
659 ** first to get things going.  Then this routine is called for each
660 ** column.
661 */
662 void sqlite3AddColumn(Parse *pParse, Token *pName){
663   Table *p;
664   int i;
665   char *z = 0;
666   Column *pCol;
667   if( (p = pParse->pNewTable)==0 ) return;
668   sqlite3SetNString(&z, pName->z, pName->n, 0);
669   if( z==0 ) return;
670   sqlite3Dequote(z);
671   for(i=0; i<p->nCol; i++){
672     if( sqlite3StrICmp(z, p->aCol[i].zName)==0 ){
673       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
674       sqliteFree(z);
675       return;
676     }
677   }
678   if( (p->nCol & 0x7)==0 ){
679     Column *aNew;
680     aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
681     if( aNew==0 ) return;
682     p->aCol = aNew;
683   }
684   pCol = &p->aCol[p->nCol];
685   memset(pCol, 0, sizeof(p->aCol[0]));
686   pCol->zName = z;
687 
688   /* If there is no type specified, columns have the default affinity
689   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
690   ** be called next to set pCol->affinity correctly.
691   */
692   pCol->affinity = SQLITE_AFF_NONE;
693   pCol->pColl = pParse->db->pDfltColl;
694   p->nCol++;
695 }
696 
697 /*
698 ** This routine is called by the parser while in the middle of
699 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
700 ** been seen on a column.  This routine sets the notNull flag on
701 ** the column currently under construction.
702 */
703 void sqlite3AddNotNull(Parse *pParse, int onError){
704   Table *p;
705   int i;
706   if( (p = pParse->pNewTable)==0 ) return;
707   i = p->nCol-1;
708   if( i>=0 ) p->aCol[i].notNull = onError;
709 }
710 
711 /*
712 ** This routine is called by the parser while in the middle of
713 ** parsing a CREATE TABLE statement.  The pFirst token is the first
714 ** token in the sequence of tokens that describe the type of the
715 ** column currently under construction.   pLast is the last token
716 ** in the sequence.  Use this information to construct a string
717 ** that contains the typename of the column and store that string
718 ** in zType.
719 */
720 void sqlite3AddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
721   Table *p;
722   int i, j;
723   int n;
724   char *z, **pz;
725   Column *pCol;
726   if( (p = pParse->pNewTable)==0 ) return;
727   i = p->nCol-1;
728   if( i<0 ) return;
729   pCol = &p->aCol[i];
730   pz = &pCol->zType;
731   n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
732   sqlite3SetNString(pz, pFirst->z, n, 0);
733   z = *pz;
734   if( z==0 ) return;
735   for(i=j=0; z[i]; i++){
736     int c = z[i];
737     if( isspace(c) ) continue;
738     z[j++] = c;
739   }
740   z[j] = 0;
741   pCol->affinity = sqlite3AffinityType(z, n);
742 }
743 
744 /*
745 ** The given token is the default value for the last column added to
746 ** the table currently under construction.  If "minusFlag" is true, it
747 ** means the value token was preceded by a minus sign.
748 **
749 ** This routine is called by the parser while in the middle of
750 ** parsing a CREATE TABLE statement.
751 */
752 void sqlite3AddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
753   Table *p;
754   int i;
755   char **pz;
756   if( (p = pParse->pNewTable)==0 ) return;
757   i = p->nCol-1;
758   if( i<0 ) return;
759   pz = &p->aCol[i].zDflt;
760   if( minusFlag ){
761     sqlite3SetNString(pz, "-", 1, pVal->z, pVal->n, 0);
762   }else{
763     sqlite3SetNString(pz, pVal->z, pVal->n, 0);
764   }
765   sqlite3Dequote(*pz);
766 }
767 
768 /*
769 ** Designate the PRIMARY KEY for the table.  pList is a list of names
770 ** of columns that form the primary key.  If pList is NULL, then the
771 ** most recently added column of the table is the primary key.
772 **
773 ** A table can have at most one primary key.  If the table already has
774 ** a primary key (and this is the second primary key) then create an
775 ** error.
776 **
777 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
778 ** then we will try to use that column as the row id.  (Exception:
779 ** For backwards compatibility with older databases, do not do this
780 ** if the file format version number is less than 1.)  Set the Table.iPKey
781 ** field of the table under construction to be the index of the
782 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
783 ** no INTEGER PRIMARY KEY.
784 **
785 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
786 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
787 */
788 void sqlite3AddPrimaryKey(Parse *pParse, ExprList *pList, int onError){
789   Table *pTab = pParse->pNewTable;
790   char *zType = 0;
791   int iCol = -1, i;
792   if( pTab==0 ) goto primary_key_exit;
793   if( pTab->hasPrimKey ){
794     sqlite3ErrorMsg(pParse,
795       "table \"%s\" has more than one primary key", pTab->zName);
796     goto primary_key_exit;
797   }
798   pTab->hasPrimKey = 1;
799   if( pList==0 ){
800     iCol = pTab->nCol - 1;
801     pTab->aCol[iCol].isPrimKey = 1;
802   }else{
803     for(i=0; i<pList->nExpr; i++){
804       for(iCol=0; iCol<pTab->nCol; iCol++){
805         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
806           break;
807         }
808       }
809       if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
810     }
811     if( pList->nExpr>1 ) iCol = -1;
812   }
813   if( iCol>=0 && iCol<pTab->nCol ){
814     zType = pTab->aCol[iCol].zType;
815   }
816   if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
817     pTab->iPKey = iCol;
818     pTab->keyConf = onError;
819   }else{
820     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
821     pList = 0;
822   }
823 
824 primary_key_exit:
825   sqlite3ExprListDelete(pList);
826   return;
827 }
828 
829 /*
830 ** Set the collation function of the most recently parsed table column
831 ** to the CollSeq given.
832 */
833 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
834   Table *p;
835   Index *pIdx;
836   CollSeq *pColl;
837   int i;
838 
839   if( (p = pParse->pNewTable)==0 ) return;
840   i = p->nCol-1;
841 
842   pColl = sqlite3LocateCollSeq(pParse, zType, nType);
843   p->aCol[i].pColl = pColl;
844 
845   /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
846   ** then an index may have been created on this column before the
847   ** collation type was added. Correct this if it is the case.
848   */
849   for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){
850     assert( pIdx->nColumn==1 );
851     if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl;
852   }
853 }
854 
855 /*
856 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
857 ** specified by zName and nName is not found and parameter 'create' is
858 ** true, then create a new entry. Otherwise return NULL.
859 **
860 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
861 ** array of three CollSeq structures. The first is the collation sequence
862 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
863 **
864 ** Stored immediately after the three collation sequences is a copy of
865 ** the collation sequence name. A pointer to this string is stored in
866 ** each collation sequence structure.
867 */
868 static CollSeq * findCollSeqEntry(
869   sqlite *db,
870   const char *zName,
871   int nName,
872   int create
873 ){
874   CollSeq *pColl;
875   if( nName<0 ) nName = strlen(zName);
876   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
877 
878   if( 0==pColl && create ){
879     pColl = sqliteMalloc( 3*sizeof(*pColl) + nName + 1 );
880     if( pColl ){
881       pColl[0].zName = (char*)&pColl[3];
882       pColl[0].enc = TEXT_Utf8;
883       pColl[1].zName = (char*)&pColl[3];
884       pColl[1].enc = TEXT_Utf16le;
885       pColl[2].zName = (char*)&pColl[3];
886       pColl[2].enc = TEXT_Utf16be;
887       memcpy(pColl[0].zName, zName, nName);
888       pColl[0].zName[nName] = 0;
889       sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
890     }
891   }
892   return pColl;
893 }
894 
895 /*
896 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
897 ** Return the CollSeq* pointer for the collation sequence named zName
898 ** for the encoding 'enc' from the database 'db'.
899 **
900 ** If the entry specified is not found and 'create' is true, then create a
901 ** new entry.  Otherwise return NULL.
902 */
903 CollSeq *sqlite3FindCollSeq(
904   sqlite *db,
905   u8 enc,
906   const char *zName,
907   int nName,
908   int create
909 ){
910   CollSeq *pColl = findCollSeqEntry(db, zName, nName, create);
911   if( pColl ) switch( enc ){
912     case TEXT_Utf8:
913       break;
914     case TEXT_Utf16le:
915       pColl = &pColl[1];
916       break;
917     case TEXT_Utf16be:
918       pColl = &pColl[2];
919       break;
920     default:
921       assert(!"Cannot happen");
922   }
923   return pColl;
924 }
925 
926 static void callCollNeeded(sqlite *db, const char *zName, int nName){
927   /* No collation sequence of this type for this encoding is registered.
928   ** Call the collation factory to see if it can supply us with one.
929   */
930   char *zExternal = 0;
931   assert( !db->xCollNeeded || !db->xCollNeeded16 );
932   if( nName<0 ) nName = strlen(zName);
933   if( db->xCollNeeded ){
934     zExternal = sqliteStrNDup(zName, nName);
935     if( !zExternal ) return;
936       db->xCollNeeded(db->pCollNeededArg, db, (int)db->enc, zExternal);
937   }
938   if( db->xCollNeeded16 ){
939     if( SQLITE_BIGENDIAN ){
940       zExternal = sqlite3utf8to16be(zName, nName);
941     }else{
942       zExternal = sqlite3utf8to16le(zName, nName);
943     }
944     if( !zExternal ) return;
945     db->xCollNeeded16(db->pCollNeededArg, db, (int)db->enc, zExternal);
946   }
947   if( zExternal ) sqliteFree(zExternal);
948 }
949 
950 static int synthCollSeq(Parse *pParse, CollSeq *pColl){
951   /* The collation factory failed to deliver a function but there may be
952   ** other versions of this collation function (for other text encodings)
953   ** available. Use one of these instead. Avoid a UTF-8 <-> UTF-16
954   ** conversion if possible.
955   */
956   CollSeq *pColl2 = 0;
957   char *z = pColl->zName;
958   int n = strlen(z);
959   switch( pParse->db->enc ){
960     case TEXT_Utf16le:
961       pColl2 = sqlite3FindCollSeq(pParse->db, TEXT_Utf16be, z, n, 0);
962       assert( pColl2 );
963       if( pColl2->xCmp ) break;
964       pColl2 = sqlite3FindCollSeq(pParse->db, TEXT_Utf8, z, n, 0);
965       assert( pColl2 );
966       break;
967 
968     case TEXT_Utf16be:
969       pColl2 = sqlite3FindCollSeq(pParse->db,TEXT_Utf16le, z, n, 0);
970       assert( pColl2 );
971       if( pColl2->xCmp ) break;
972       pColl2 = sqlite3FindCollSeq(pParse->db,TEXT_Utf8, z, n, 0);
973       assert( pColl2 );
974       break;
975 
976     case TEXT_Utf8:
977       pColl2 = sqlite3FindCollSeq(pParse->db,TEXT_Utf16be, z, n, 0);
978       assert( pColl2 );
979       if( pColl2->xCmp ) break;
980       pColl2 = sqlite3FindCollSeq(pParse->db,TEXT_Utf16le, z, n, 0);
981       assert( pColl2 );
982       break;
983   }
984   if( pColl2->xCmp ){
985     memcpy(pColl, pColl2, sizeof(CollSeq));
986   }else{
987     if( pParse->nErr==0 ){
988       sqlite3SetNString(&pParse->zErrMsg, "no such collation sequence: ",
989           -1, z, n, 0);
990     }
991     pParse->nErr++;
992     return SQLITE_ERROR;
993   }
994   return SQLITE_OK;
995 }
996 
997 /*
998 ** This routine is called on a collation sequence before it is used to
999 ** check that it is defined. An undefined collation sequence exists when
1000 ** a database is loaded that contains references to collation sequences
1001 ** that have not been defined by sqlite3_create_collation() etc.
1002 **
1003 ** If required, this routine calls the 'collation needed' callback to
1004 ** request a definition of the collating sequence. If this doesn't work,
1005 ** an equivalent collating sequence that uses a text encoding different
1006 ** from the main database is substituted, if one is available.
1007 */
1008 int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
1009   if( pColl && !pColl->xCmp ){
1010     callCollNeeded(pParse->db, pColl->zName, strlen(pColl->zName));
1011     if( !pColl->xCmp && synthCollSeq(pParse, pColl) ){
1012       return SQLITE_ERROR;
1013     }
1014   }
1015   return SQLITE_OK;
1016 }
1017 
1018 int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){
1019   if( pIdx ){
1020     int i;
1021     for(i=0; i<pIdx->nColumn; i++){
1022       if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){
1023         return SQLITE_ERROR;
1024       }
1025     }
1026   }
1027   return SQLITE_OK;
1028 }
1029 
1030 /*
1031 ** This function returns the collation sequence for database native text
1032 ** encoding identified by the string zName, length nName.
1033 **
1034 ** If the requested collation sequence is not available, or not available
1035 ** in the database native encoding, the collation factory is invoked to
1036 ** request it. If the collation factory does not supply such a sequence,
1037 ** and the sequence is available in another text encoding, then that is
1038 ** returned instead.
1039 **
1040 ** If no versions of the requested collations sequence are available, or
1041 ** another error occurs, NULL is returned and an error message written into
1042 ** pParse.
1043 */
1044 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
1045   u8 enc = pParse->db->enc;
1046   u8 initbusy = pParse->db->init.busy;
1047   CollSeq *pColl = sqlite3FindCollSeq(pParse->db, enc, zName, nName, initbusy);
1048   if( !initbusy && (!pColl || !pColl->xCmp) ){
1049     /* No collation sequence of this type for this encoding is registered.
1050     ** Call the collation factory to see if it can supply us with one.
1051     */
1052     callCollNeeded(pParse->db, zName, nName);
1053     pColl = sqlite3FindCollSeq(pParse->db, enc, zName, nName, 0);
1054     if( pColl && !pColl->xCmp ){
1055       /* There may be a version of the collation sequence that requires
1056       ** translation between encodings. Search for it with synthCollSeq().
1057       */
1058       if( synthCollSeq(pParse, pColl) ){
1059         return 0;
1060       }
1061     }
1062   }
1063 
1064   /* If nothing has been found, write the error message into pParse */
1065   if( !initbusy && (!pColl || !pColl->xCmp) ){
1066     if( pParse->nErr==0 ){
1067       sqlite3SetNString(&pParse->zErrMsg, "no such collation sequence: ", -1,
1068           zName, nName, 0);
1069     }
1070     pParse->nErr++;
1071     pColl = 0;
1072   }
1073   return pColl;
1074 }
1075 
1076 
1077 
1078 /*
1079 ** Scan the column type name zType (length nType) and return the
1080 ** associated affinity type.
1081 */
1082 char sqlite3AffinityType(const char *zType, int nType){
1083   int n, i;
1084   struct {
1085     const char *zSub;  /* Keywords substring to search for */
1086     int nSub;          /* length of zSub */
1087     char affinity;     /* Affinity to return if it matches */
1088   } substrings[] = {
1089     {"INT",  3, SQLITE_AFF_INTEGER},
1090     {"CHAR", 4, SQLITE_AFF_TEXT},
1091     {"CLOB", 4, SQLITE_AFF_TEXT},
1092     {"TEXT", 4, SQLITE_AFF_TEXT},
1093     {"BLOB", 4, SQLITE_AFF_NONE},
1094   };
1095 
1096   if( nType==0 ){
1097     return SQLITE_AFF_NONE;
1098   }
1099   for(i=0; i<sizeof(substrings)/sizeof(substrings[0]); i++){
1100     int c1 = substrings[i].zSub[0];
1101     int c2 = tolower(c1);
1102     int limit = nType - substrings[i].nSub;
1103     const char *z = substrings[i].zSub;
1104     for(n=0; n<=limit; n++){
1105       int c = zType[n];
1106       if( (c==c1 || c==c2)
1107              && 0==sqlite3StrNICmp(&zType[n], z, substrings[i].nSub) ){
1108         return substrings[i].affinity;
1109       }
1110     }
1111   }
1112   return SQLITE_AFF_NUMERIC;
1113 }
1114 
1115 /*
1116 ** Come up with a new random value for the schema cookie.  Make sure
1117 ** the new value is different from the old.
1118 **
1119 ** The schema cookie is used to determine when the schema for the
1120 ** database changes.  After each schema change, the cookie value
1121 ** changes.  When a process first reads the schema it records the
1122 ** cookie.  Thereafter, whenever it goes to access the database,
1123 ** it checks the cookie to make sure the schema has not changed
1124 ** since it was last read.
1125 **
1126 ** This plan is not completely bullet-proof.  It is possible for
1127 ** the schema to change multiple times and for the cookie to be
1128 ** set back to prior value.  But schema changes are infrequent
1129 ** and the probability of hitting the same cookie value is only
1130 ** 1 chance in 2^32.  So we're safe enough.
1131 */
1132 void sqlite3ChangeCookie(sqlite *db, Vdbe *v, int iDb){
1133   unsigned char r;
1134   int *pSchemaCookie = &(db->aDb[iDb].schema_cookie);
1135 
1136   sqlite3Randomness(1, &r);
1137   *pSchemaCookie = *pSchemaCookie + r + 1;
1138   db->flags |= SQLITE_InternChanges;
1139   sqlite3VdbeAddOp(v, OP_Integer, *pSchemaCookie, 0);
1140   sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
1141 }
1142 
1143 /*
1144 ** Measure the number of characters needed to output the given
1145 ** identifier.  The number returned includes any quotes used
1146 ** but does not include the null terminator.
1147 */
1148 static int identLength(const char *z){
1149   int n;
1150   int needQuote = 0;
1151   for(n=0; *z; n++, z++){
1152     if( *z=='\'' ){ n++; needQuote=1; }
1153   }
1154   return n + needQuote*2;
1155 }
1156 
1157 /*
1158 ** Write an identifier onto the end of the given string.  Add
1159 ** quote characters as needed.
1160 */
1161 static void identPut(char *z, int *pIdx, char *zIdent){
1162   int i, j, needQuote;
1163   i = *pIdx;
1164   for(j=0; zIdent[j]; j++){
1165     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1166   }
1167   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
1168                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
1169   if( needQuote ) z[i++] = '\'';
1170   for(j=0; zIdent[j]; j++){
1171     z[i++] = zIdent[j];
1172     if( zIdent[j]=='\'' ) z[i++] = '\'';
1173   }
1174   if( needQuote ) z[i++] = '\'';
1175   z[i] = 0;
1176   *pIdx = i;
1177 }
1178 
1179 /*
1180 ** Generate a CREATE TABLE statement appropriate for the given
1181 ** table.  Memory to hold the text of the statement is obtained
1182 ** from sqliteMalloc() and must be freed by the calling function.
1183 */
1184 static char *createTableStmt(Table *p){
1185   int i, k, n;
1186   char *zStmt;
1187   char *zSep, *zSep2, *zEnd;
1188   n = 0;
1189   for(i=0; i<p->nCol; i++){
1190     n += identLength(p->aCol[i].zName);
1191     if( p->aCol[i].zType ){
1192       n += (strlen(p->aCol[i].zType) + 1);
1193     }
1194   }
1195   n += identLength(p->zName);
1196   if( n<40 ){
1197     zSep = "";
1198     zSep2 = ",";
1199     zEnd = ")";
1200   }else{
1201     zSep = "\n  ";
1202     zSep2 = ",\n  ";
1203     zEnd = "\n)";
1204   }
1205   n += 35 + 6*p->nCol;
1206   zStmt = sqliteMallocRaw( n );
1207   if( zStmt==0 ) return 0;
1208   strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
1209   k = strlen(zStmt);
1210   identPut(zStmt, &k, p->zName);
1211   zStmt[k++] = '(';
1212   for(i=0; i<p->nCol; i++){
1213     strcpy(&zStmt[k], zSep);
1214     k += strlen(&zStmt[k]);
1215     zSep = zSep2;
1216     identPut(zStmt, &k, p->aCol[i].zName);
1217     if( p->aCol[i].zType ){
1218       zStmt[k++] = ' ';
1219       strcpy(&zStmt[k], p->aCol[i].zType);
1220       k += strlen(p->aCol[i].zType);
1221     }
1222   }
1223   strcpy(&zStmt[k], zEnd);
1224   return zStmt;
1225 }
1226 
1227 /*
1228 ** This routine is called to report the final ")" that terminates
1229 ** a CREATE TABLE statement.
1230 **
1231 ** The table structure that other action routines have been building
1232 ** is added to the internal hash tables, assuming no errors have
1233 ** occurred.
1234 **
1235 ** An entry for the table is made in the master table on disk, unless
1236 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
1237 ** it means we are reading the sqlite_master table because we just
1238 ** connected to the database or because the sqlite_master table has
1239 ** recently changes, so the entry for this table already exists in
1240 ** the sqlite_master table.  We do not want to create it again.
1241 **
1242 ** If the pSelect argument is not NULL, it means that this routine
1243 ** was called to create a table generated from a
1244 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
1245 ** the new table will match the result set of the SELECT.
1246 */
1247 void sqlite3EndTable(Parse *pParse, Token *pEnd, Select *pSelect){
1248   Table *p;
1249   sqlite *db = pParse->db;
1250 
1251   if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
1252   p = pParse->pNewTable;
1253   if( p==0 ) return;
1254 
1255   assert( !db->init.busy || !pSelect );
1256 
1257   /* If the table is generated from a SELECT, then construct the
1258   ** list of columns and the text of the table.
1259   */
1260   if( pSelect ){
1261   }
1262 
1263   /* If the db->init.busy is 1 it means we are reading the SQL off the
1264   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1265   ** So do not write to the disk again.  Extract the root page number
1266   ** for the table from the db->init.newTnum field.  (The page number
1267   ** should have been put there by the sqliteOpenCb routine.)
1268   */
1269   if( db->init.busy ){
1270     p->tnum = db->init.newTnum;
1271   }
1272 
1273   /* If not initializing, then create a record for the new table
1274   ** in the SQLITE_MASTER table of the database.  The record number
1275   ** for the new table entry should already be on the stack.
1276   **
1277   ** If this is a TEMPORARY table, write the entry into the auxiliary
1278   ** file instead of into the main database file.
1279   */
1280   if( !db->init.busy ){
1281     int n;
1282     Vdbe *v;
1283 
1284     v = sqlite3GetVdbe(pParse);
1285     if( v==0 ) return;
1286 
1287     if( p->pSelect==0 ){
1288       /* A regular table */
1289       sqlite3VdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
1290     }else{
1291       /* A view */
1292       sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
1293     }
1294     p->tnum = 0;
1295 
1296     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1297 
1298     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1299     ** statement to populate the new table. The root-page number for the
1300     ** new table is on the top of the vdbe stack.
1301     **
1302     ** Once the SELECT has been coded by sqlite3Select(), it is in a
1303     ** suitable state to query for the column names and types to be used
1304     ** by the new table.
1305     */
1306     if( pSelect ){
1307       Table *pSelTab;
1308       sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1309       sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
1310       sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1311       pParse->nTab = 2;
1312       sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
1313       sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1314       if( pParse->nErr==0 ){
1315         pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1316         if( pSelTab==0 ) return;
1317         assert( p->aCol==0 );
1318         p->nCol = pSelTab->nCol;
1319         p->aCol = pSelTab->aCol;
1320         pSelTab->nCol = 0;
1321         pSelTab->aCol = 0;
1322         sqlite3DeleteTable(0, pSelTab);
1323       }
1324     }
1325 
1326     sqlite3OpenMasterTable(v, p->iDb);
1327 
1328     sqlite3VdbeOp3(v, OP_String8, 0, 0, p->pSelect==0?"table":"view",P3_STATIC);
1329     sqlite3VdbeOp3(v, OP_String8, 0, 0, p->zName, 0);
1330     sqlite3VdbeOp3(v, OP_String8, 0, 0, p->zName, 0);
1331     sqlite3VdbeAddOp(v, OP_Pull, 3, 0);
1332 
1333     if( pSelect ){
1334       char *z = createTableStmt(p);
1335       n = z ? strlen(z) : 0;
1336       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1337       sqlite3VdbeChangeP3(v, -1, z, n);
1338       sqliteFree(z);
1339     }else{
1340       if( p->pSelect ){
1341         sqlite3VdbeOp3(v, OP_String8, 0, 0, "CREATE VIEW ", P3_STATIC);
1342       }else{
1343         sqlite3VdbeOp3(v, OP_String8, 0, 0, "CREATE TABLE ", P3_STATIC);
1344       }
1345       assert( pEnd!=0 );
1346       n = Addr(pEnd->z) - Addr(pParse->sNameToken.z) + 1;
1347       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
1348       sqlite3VdbeChangeP3(v, -1, pParse->sNameToken.z, n);
1349       sqlite3VdbeAddOp(v, OP_Concat, 2, 0);
1350     }
1351     sqlite3VdbeOp3(v, OP_MakeRecord, 5, 0, "tttit", P3_STATIC);
1352     sqlite3VdbeAddOp(v, OP_PutIntKey, 0, 0);
1353     if( p->iDb!=1 ){
1354       sqlite3ChangeCookie(db, v, p->iDb);
1355     }
1356     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1357 
1358     sqlite3EndWriteOperation(pParse);
1359   }
1360 
1361   /* Add the table to the in-memory representation of the database.
1362   */
1363   if( pParse->explain==0 && pParse->nErr==0 ){
1364     Table *pOld;
1365     FKey *pFKey;
1366     pOld = sqlite3HashInsert(&db->aDb[p->iDb].tblHash,
1367                             p->zName, strlen(p->zName)+1, p);
1368     if( pOld ){
1369       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
1370       return;
1371     }
1372     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1373       int nTo = strlen(pFKey->zTo) + 1;
1374       pFKey->pNextTo = sqlite3HashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
1375       sqlite3HashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
1376     }
1377     pParse->pNewTable = 0;
1378     db->nTable++;
1379     db->flags |= SQLITE_InternChanges;
1380   }
1381 }
1382 
1383 /*
1384 ** The parser calls this routine in order to create a new VIEW
1385 */
1386 void sqlite3CreateView(
1387   Parse *pParse,     /* The parsing context */
1388   Token *pBegin,     /* The CREATE token that begins the statement */
1389   Token *pName1,     /* The token that holds the name of the view */
1390   Token *pName2,     /* The token that holds the name of the view */
1391   Select *pSelect,   /* A SELECT statement that will become the new view */
1392   int isTemp         /* TRUE for a TEMPORARY view */
1393 ){
1394   Table *p;
1395   int n;
1396   const char *z;
1397   Token sEnd;
1398   DbFixer sFix;
1399   Token *pName;
1400 
1401   sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
1402   p = pParse->pNewTable;
1403   if( p==0 || pParse->nErr ){
1404     sqlite3SelectDelete(pSelect);
1405     return;
1406   }
1407   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1408   if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
1409     && sqlite3FixSelect(&sFix, pSelect)
1410   ){
1411     sqlite3SelectDelete(pSelect);
1412     return;
1413   }
1414 
1415   /* Make a copy of the entire SELECT statement that defines the view.
1416   ** This will force all the Expr.token.z values to be dynamically
1417   ** allocated rather than point to the input string - which means that
1418   ** they will persist after the current sqlite3_exec() call returns.
1419   */
1420   p->pSelect = sqlite3SelectDup(pSelect);
1421   sqlite3SelectDelete(pSelect);
1422   if( !pParse->db->init.busy ){
1423     sqlite3ViewGetColumnNames(pParse, p);
1424   }
1425 
1426   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
1427   ** the end.
1428   */
1429   sEnd = pParse->sLastToken;
1430   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1431     sEnd.z += sEnd.n;
1432   }
1433   sEnd.n = 0;
1434   n = ((int)sEnd.z) - (int)pBegin->z;
1435   z = pBegin->z;
1436   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1437   sEnd.z = &z[n-1];
1438   sEnd.n = 1;
1439 
1440   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1441   sqlite3EndTable(pParse, &sEnd, 0);
1442   return;
1443 }
1444 
1445 /*
1446 ** The Table structure pTable is really a VIEW.  Fill in the names of
1447 ** the columns of the view in the pTable structure.  Return the number
1448 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
1449 */
1450 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
1451   ExprList *pEList;
1452   Select *pSel;
1453   Table *pSelTab;
1454   int nErr = 0;
1455 
1456   assert( pTable );
1457 
1458   /* A positive nCol means the columns names for this view are
1459   ** already known.
1460   */
1461   if( pTable->nCol>0 ) return 0;
1462 
1463   /* A negative nCol is a special marker meaning that we are currently
1464   ** trying to compute the column names.  If we enter this routine with
1465   ** a negative nCol, it means two or more views form a loop, like this:
1466   **
1467   **     CREATE VIEW one AS SELECT * FROM two;
1468   **     CREATE VIEW two AS SELECT * FROM one;
1469   **
1470   ** Actually, this error is caught previously and so the following test
1471   ** should always fail.  But we will leave it in place just to be safe.
1472   */
1473   if( pTable->nCol<0 ){
1474     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1475     return 1;
1476   }
1477 
1478   /* If we get this far, it means we need to compute the table names.
1479   */
1480   assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
1481   pSel = pTable->pSelect;
1482 
1483   /* Note that the call to sqlite3ResultSetOfSelect() will expand any
1484   ** "*" elements in this list.  But we will need to restore the list
1485   ** back to its original configuration afterwards, so we save a copy of
1486   ** the original in pEList.
1487   */
1488   pEList = pSel->pEList;
1489   pSel->pEList = sqlite3ExprListDup(pEList);
1490   if( pSel->pEList==0 ){
1491     pSel->pEList = pEList;
1492     return 1;  /* Malloc failed */
1493   }
1494   pTable->nCol = -1;
1495   pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1496   if( pSelTab ){
1497     assert( pTable->aCol==0 );
1498     pTable->nCol = pSelTab->nCol;
1499     pTable->aCol = pSelTab->aCol;
1500     pSelTab->nCol = 0;
1501     pSelTab->aCol = 0;
1502     sqlite3DeleteTable(0, pSelTab);
1503     DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
1504   }else{
1505     pTable->nCol = 0;
1506     nErr++;
1507   }
1508   sqlite3SelectUnbind(pSel);
1509   sqlite3ExprListDelete(pSel->pEList);
1510   pSel->pEList = pEList;
1511   return nErr;
1512 }
1513 
1514 /*
1515 ** Clear the column names from the VIEW pTable.
1516 **
1517 ** This routine is called whenever any other table or view is modified.
1518 ** The view passed into this routine might depend directly or indirectly
1519 ** on the modified or deleted table so we need to clear the old column
1520 ** names so that they will be recomputed.
1521 */
1522 static void sqliteViewResetColumnNames(Table *pTable){
1523   int i;
1524   Column *pCol;
1525   assert( pTable!=0 && pTable->pSelect!=0 );
1526   for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
1527     sqliteFree(pCol->zName);
1528     sqliteFree(pCol->zDflt);
1529     sqliteFree(pCol->zType);
1530   }
1531   sqliteFree(pTable->aCol);
1532   pTable->aCol = 0;
1533   pTable->nCol = 0;
1534 }
1535 
1536 /*
1537 ** Clear the column names from every VIEW in database idx.
1538 */
1539 static void sqliteViewResetAll(sqlite *db, int idx){
1540   HashElem *i;
1541   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1542   for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
1543     Table *pTab = sqliteHashData(i);
1544     if( pTab->pSelect ){
1545       sqliteViewResetColumnNames(pTab);
1546     }
1547   }
1548   DbClearProperty(db, idx, DB_UnresetViews);
1549 }
1550 
1551 /*
1552 ** Given a token, look up a table with that name.  If not found, leave
1553 ** an error for the parser to find and return NULL.
1554 */
1555 Table *sqlite3TableFromToken(Parse *pParse, Token *pTok){
1556   char *zName;
1557   Table *pTab;
1558   zName = sqlite3TableNameFromToken(pTok);
1559   if( zName==0 ) return 0;
1560   pTab = sqlite3FindTable(pParse->db, zName, 0);
1561   sqliteFree(zName);
1562   if( pTab==0 ){
1563     sqlite3ErrorMsg(pParse, "no such table: %T", pTok);
1564     pParse->checkSchema = 1;
1565   }
1566   return pTab;
1567 }
1568 
1569 /*
1570 ** This routine is called to do the work of a DROP TABLE statement.
1571 ** pName is the name of the table to be dropped.
1572 */
1573 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
1574   Table *pTab;
1575   Vdbe *v;
1576   int base;
1577   sqlite *db = pParse->db;
1578   int iDb;
1579 
1580   if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
1581   assert( pName->nSrc==1 );
1582   pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1583 
1584   if( pTab==0 ) goto exit_drop_table;
1585   iDb = pTab->iDb;
1586   assert( iDb>=0 && iDb<db->nDb );
1587 #ifndef SQLITE_OMIT_AUTHORIZATION
1588   {
1589     int code;
1590     const char *zTab = SCHEMA_TABLE(pTab->iDb);
1591     const char *zDb = db->aDb[pTab->iDb].zName;
1592     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1593       goto exit_drop_table;
1594     }
1595     if( isView ){
1596       if( iDb==1 ){
1597         code = SQLITE_DROP_TEMP_VIEW;
1598       }else{
1599         code = SQLITE_DROP_VIEW;
1600       }
1601     }else{
1602       if( iDb==1 ){
1603         code = SQLITE_DROP_TEMP_TABLE;
1604       }else{
1605         code = SQLITE_DROP_TABLE;
1606       }
1607     }
1608     if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1609       goto exit_drop_table;
1610     }
1611     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1612       goto exit_drop_table;
1613     }
1614   }
1615 #endif
1616   if( pTab->readOnly ){
1617     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
1618     pParse->nErr++;
1619     goto exit_drop_table;
1620   }
1621   if( isView && pTab->pSelect==0 ){
1622     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1623     goto exit_drop_table;
1624   }
1625   if( !isView && pTab->pSelect ){
1626     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1627     goto exit_drop_table;
1628   }
1629 
1630   /* Generate code to remove the table from the master table
1631   ** on disk.
1632   */
1633   v = sqlite3GetVdbe(pParse);
1634   if( v ){
1635     static VdbeOpList dropTable[] = {
1636       { OP_Rewind,     0, ADDR(13), 0},
1637       { OP_String8,    0, 0,        0}, /* 1 */
1638       { OP_MemStore,   1, 1,        0},
1639       { OP_MemLoad,    1, 0,        0}, /* 3 */
1640       { OP_Column,     0, 2,        0}, /* sqlite_master.tbl_name */
1641       { OP_Ne,         0, ADDR(12), 0},
1642       { OP_String8,    0, 0,        "trigger"},
1643       { OP_Column,     0, 2,        0}, /* sqlite_master.type */
1644       { OP_Eq,         0, ADDR(12), 0},
1645       { OP_Delete,     0, 0,        0},
1646       { OP_Rewind,     0, ADDR(13), 0},
1647       { OP_Goto,       0, ADDR(3),  0},
1648       { OP_Next,       0, ADDR(3),  0}, /* 12 */
1649     };
1650     Index *pIdx;
1651     Trigger *pTrigger;
1652     sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
1653 
1654     /* Drop all triggers associated with the table being dropped. Code
1655     ** is generated to remove entries from sqlite_master and/or
1656     ** sqlite_temp_master if required.
1657     */
1658     pTrigger = pTab->pTrigger;
1659     while( pTrigger ){
1660       assert( pTrigger->iDb==pTab->iDb || pTrigger->iDb==1 );
1661       sqlite3DropTriggerPtr(pParse, pTrigger, 1);
1662       if( pParse->explain ){
1663         pTrigger = pTrigger->pNext;
1664       }else{
1665         pTrigger = pTab->pTrigger;
1666       }
1667     }
1668 
1669     /* Drop all SQLITE_MASTER table and index entries that refer to the
1670     ** table. The program name loops through the master table and deletes
1671     ** every row that refers to a table of the same name as the one being
1672     ** dropped. Triggers are handled seperately because a trigger can be
1673     ** created in the temp database that refers to a table in another
1674     ** database.
1675     */
1676     sqlite3OpenMasterTable(v, pTab->iDb);
1677     base = sqlite3VdbeAddOpList(v, ArraySize(dropTable), dropTable);
1678     sqlite3VdbeChangeP3(v, base+1, pTab->zName, 0);
1679     sqlite3ChangeCookie(db, v, pTab->iDb);
1680     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1681     if( !isView ){
1682       sqlite3VdbeAddOp(v, OP_Destroy, pTab->tnum, pTab->iDb);
1683       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1684         sqlite3VdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb);
1685       }
1686     }
1687     sqlite3EndWriteOperation(pParse);
1688   }
1689 
1690   /* Delete the in-memory description of the table.
1691   **
1692   ** Exception: if the SQL statement began with the EXPLAIN keyword,
1693   ** then no changes should be made.
1694   */
1695   if( !pParse->explain ){
1696     sqliteUnlinkAndDeleteTable(db, pTab);
1697     db->flags |= SQLITE_InternChanges;
1698   }
1699   sqliteViewResetAll(db, iDb);
1700 
1701 exit_drop_table:
1702   sqlite3SrcListDelete(pName);
1703 }
1704 
1705 /*
1706 ** This routine is called to create a new foreign key on the table
1707 ** currently under construction.  pFromCol determines which columns
1708 ** in the current table point to the foreign key.  If pFromCol==0 then
1709 ** connect the key to the last column inserted.  pTo is the name of
1710 ** the table referred to.  pToCol is a list of tables in the other
1711 ** pTo table that the foreign key points to.  flags contains all
1712 ** information about the conflict resolution algorithms specified
1713 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1714 **
1715 ** An FKey structure is created and added to the table currently
1716 ** under construction in the pParse->pNewTable field.  The new FKey
1717 ** is not linked into db->aFKey at this point - that does not happen
1718 ** until sqlite3EndTable().
1719 **
1720 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
1721 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
1722 */
1723 void sqlite3CreateForeignKey(
1724   Parse *pParse,       /* Parsing context */
1725   ExprList *pFromCol,  /* Columns in this table that point to other table */
1726   Token *pTo,          /* Name of the other table */
1727   ExprList *pToCol,    /* Columns in the other table */
1728   int flags            /* Conflict resolution algorithms. */
1729 ){
1730   Table *p = pParse->pNewTable;
1731   int nByte;
1732   int i;
1733   int nCol;
1734   char *z;
1735   FKey *pFKey = 0;
1736 
1737   assert( pTo!=0 );
1738   if( p==0 || pParse->nErr ) goto fk_end;
1739   if( pFromCol==0 ){
1740     int iCol = p->nCol-1;
1741     if( iCol<0 ) goto fk_end;
1742     if( pToCol && pToCol->nExpr!=1 ){
1743       sqlite3ErrorMsg(pParse, "foreign key on %s"
1744          " should reference only one column of table %T",
1745          p->aCol[iCol].zName, pTo);
1746       goto fk_end;
1747     }
1748     nCol = 1;
1749   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
1750     sqlite3ErrorMsg(pParse,
1751         "number of columns in foreign key does not match the number of "
1752         "columns in the referenced table");
1753     goto fk_end;
1754   }else{
1755     nCol = pFromCol->nExpr;
1756   }
1757   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1758   if( pToCol ){
1759     for(i=0; i<pToCol->nExpr; i++){
1760       nByte += strlen(pToCol->a[i].zName) + 1;
1761     }
1762   }
1763   pFKey = sqliteMalloc( nByte );
1764   if( pFKey==0 ) goto fk_end;
1765   pFKey->pFrom = p;
1766   pFKey->pNextFrom = p->pFKey;
1767   z = (char*)&pFKey[1];
1768   pFKey->aCol = (struct sColMap*)z;
1769   z += sizeof(struct sColMap)*nCol;
1770   pFKey->zTo = z;
1771   memcpy(z, pTo->z, pTo->n);
1772   z[pTo->n] = 0;
1773   z += pTo->n+1;
1774   pFKey->pNextTo = 0;
1775   pFKey->nCol = nCol;
1776   if( pFromCol==0 ){
1777     pFKey->aCol[0].iFrom = p->nCol-1;
1778   }else{
1779     for(i=0; i<nCol; i++){
1780       int j;
1781       for(j=0; j<p->nCol; j++){
1782         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
1783           pFKey->aCol[i].iFrom = j;
1784           break;
1785         }
1786       }
1787       if( j>=p->nCol ){
1788         sqlite3ErrorMsg(pParse,
1789           "unknown column \"%s\" in foreign key definition",
1790           pFromCol->a[i].zName);
1791         goto fk_end;
1792       }
1793     }
1794   }
1795   if( pToCol ){
1796     for(i=0; i<nCol; i++){
1797       int n = strlen(pToCol->a[i].zName);
1798       pFKey->aCol[i].zCol = z;
1799       memcpy(z, pToCol->a[i].zName, n);
1800       z[n] = 0;
1801       z += n+1;
1802     }
1803   }
1804   pFKey->isDeferred = 0;
1805   pFKey->deleteConf = flags & 0xff;
1806   pFKey->updateConf = (flags >> 8 ) & 0xff;
1807   pFKey->insertConf = (flags >> 16 ) & 0xff;
1808 
1809   /* Link the foreign key to the table as the last step.
1810   */
1811   p->pFKey = pFKey;
1812   pFKey = 0;
1813 
1814 fk_end:
1815   sqliteFree(pFKey);
1816   sqlite3ExprListDelete(pFromCol);
1817   sqlite3ExprListDelete(pToCol);
1818 }
1819 
1820 /*
1821 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1822 ** clause is seen as part of a foreign key definition.  The isDeferred
1823 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1824 ** The behavior of the most recently created foreign key is adjusted
1825 ** accordingly.
1826 */
1827 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
1828   Table *pTab;
1829   FKey *pFKey;
1830   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1831   pFKey->isDeferred = isDeferred;
1832 }
1833 
1834 /*
1835 ** Create a new index for an SQL table.  pIndex is the name of the index
1836 ** and pTable is the name of the table that is to be indexed.  Both will
1837 ** be NULL for a primary key or an index that is created to satisfy a
1838 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
1839 ** as the table to be indexed.  pParse->pNewTable is a table that is
1840 ** currently being constructed by a CREATE TABLE statement.
1841 **
1842 ** pList is a list of columns to be indexed.  pList will be NULL if this
1843 ** is a primary key or unique-constraint on the most recent column added
1844 ** to the table currently under construction.
1845 */
1846 void sqlite3CreateIndex(
1847   Parse *pParse,   /* All information about this parse */
1848   Token *pName1,   /* First part of index name. May be NULL */
1849   Token *pName2,   /* Second part of index name. May be NULL */
1850   SrcList *pTblName,  /* Table to index. Use pParse->pNewTable if 0 */
1851   ExprList *pList,   /* A list of columns to be indexed */
1852   int onError,     /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1853   Token *pStart,   /* The CREATE token that begins a CREATE TABLE statement */
1854   Token *pEnd      /* The ")" that closes the CREATE INDEX statement */
1855 ){
1856   Table *pTab = 0; /* Table to be indexed */
1857   Index *pIndex;   /* The index to be created */
1858   char *zName = 0;
1859   int i, j;
1860   Token nullId;    /* Fake token for an empty ID list */
1861   DbFixer sFix;    /* For assigning database names to pTable */
1862   int isTemp;      /* True for a temporary index */
1863   sqlite *db = pParse->db;
1864 
1865   int iDb;          /* Index of the database that is being written */
1866   Token *pName = 0; /* Unqualified name of the index to create */
1867 
1868   if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
1869 
1870   /*
1871   ** Find the table that is to be indexed.  Return early if not found.
1872   */
1873   if( pTblName!=0 ){
1874 
1875     /* Use the two-part index name to determine the database
1876     ** to search for the table. 'Fix' the table name to this db
1877     ** before looking up the table.
1878     */
1879     assert( pName1 && pName2 );
1880     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1881     if( iDb<0 ) goto exit_create_index;
1882 
1883     /* If the index name was unqualified, check if the the table
1884     ** is a temp table. If so, set the database to 1.
1885     */
1886     pTab = sqlite3SrcListLookup(pParse, pTblName);
1887     if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){
1888       iDb = 1;
1889     }
1890 
1891     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
1892         sqlite3FixSrcList(&sFix, pTblName)
1893     ){
1894       goto exit_create_index;
1895     }
1896     pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
1897         pTblName->a[0].zDatabase);
1898     if( !pTab ) goto exit_create_index;
1899     assert( iDb==pTab->iDb );
1900   }else{
1901     assert( pName==0 );
1902     pTab =  pParse->pNewTable;
1903     iDb = pTab->iDb;
1904   }
1905 
1906   if( pTab==0 || pParse->nErr ) goto exit_create_index;
1907   if( pTab->readOnly ){
1908     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
1909     goto exit_create_index;
1910   }
1911   if( pTab->pSelect ){
1912     sqlite3ErrorMsg(pParse, "views may not be indexed");
1913     goto exit_create_index;
1914   }
1915   isTemp = pTab->iDb==1;
1916 
1917   /*
1918   ** Find the name of the index.  Make sure there is not already another
1919   ** index or table with the same name.
1920   **
1921   ** Exception:  If we are reading the names of permanent indices from the
1922   ** sqlite_master table (because some other process changed the schema) and
1923   ** one of the index names collides with the name of a temporary table or
1924   ** index, then we will continue to process this index.
1925   **
1926   ** If pName==0 it means that we are
1927   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
1928   ** own name.
1929   */
1930   if( pName && !db->init.busy ){
1931     Index *pISameName;    /* Another index with the same name */
1932     Table *pTSameName;    /* A table with same name as the index */
1933     zName = sqliteStrNDup(pName->z, pName->n);
1934     if( zName==0 ) goto exit_create_index;
1935     if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName))!=0 ){
1936       sqlite3ErrorMsg(pParse, "index %s already exists", zName);
1937       goto exit_create_index;
1938     }
1939     if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 ){
1940       sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
1941       goto exit_create_index;
1942     }
1943   }else if( pName==0 ){
1944     char zBuf[30];
1945     int n;
1946     Index *pLoop;
1947     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
1948     sprintf(zBuf,"%d)",n);
1949     zName = 0;
1950     sqlite3SetString(&zName, "(", pTab->zName, " autoindex ", zBuf, (char*)0);
1951     if( zName==0 ) goto exit_create_index;
1952   }else{
1953     zName = sqliteStrNDup(pName->z, pName->n);
1954   }
1955 
1956   /* Check for authorization to create an index.
1957   */
1958 #ifndef SQLITE_OMIT_AUTHORIZATION
1959   {
1960     const char *zDb = db->aDb[pTab->iDb].zName;
1961     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1962       goto exit_create_index;
1963     }
1964     i = SQLITE_CREATE_INDEX;
1965     if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
1966     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
1967       goto exit_create_index;
1968     }
1969   }
1970 #endif
1971 
1972   /* If pList==0, it means this routine was called to make a primary
1973   ** key out of the last column added to the table under construction.
1974   ** So create a fake list to simulate this.
1975   */
1976   if( pList==0 ){
1977     nullId.z = pTab->aCol[pTab->nCol-1].zName;
1978     nullId.n = strlen(nullId.z);
1979     pList = sqlite3ExprListAppend(0, 0, &nullId);
1980     if( pList==0 ) goto exit_create_index;
1981   }
1982 
1983   /*
1984   ** Allocate the index structure.
1985   */
1986   pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
1987                         (sizeof(int) + sizeof(CollSeq*))*pList->nExpr );
1988   if( pIndex==0 ) goto exit_create_index;
1989   pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
1990   pIndex->zName = (char*)&pIndex->aiColumn[pList->nExpr];
1991   strcpy(pIndex->zName, zName);
1992   pIndex->pTable = pTab;
1993   pIndex->nColumn = pList->nExpr;
1994   pIndex->onError = onError;
1995   pIndex->autoIndex = pName==0;
1996   pIndex->iDb = iDb;
1997 
1998   /* Scan the names of the columns of the table to be indexed and
1999   ** load the column indices into the Index structure.  Report an error
2000   ** if any column is not found.
2001   */
2002   for(i=0; i<pList->nExpr; i++){
2003     for(j=0; j<pTab->nCol; j++){
2004       if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
2005     }
2006     if( j>=pTab->nCol ){
2007       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
2008         pTab->zName, pList->a[i].zName);
2009       sqliteFree(pIndex);
2010       goto exit_create_index;
2011     }
2012     pIndex->aiColumn[i] = j;
2013     if( pList->a[i].pExpr ){
2014       assert( pList->a[i].pExpr->pColl );
2015       pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
2016     }else{
2017       pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
2018     }
2019     assert( pIndex->keyInfo.aColl[i] );
2020     if( !db->init.busy &&
2021         sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i])
2022     ){
2023       goto exit_create_index;
2024     }
2025   }
2026   pIndex->keyInfo.nField = pList->nExpr;
2027 
2028   /* Link the new Index structure to its table and to the other
2029   ** in-memory database structures.
2030   */
2031   if( !pParse->explain ){
2032     Index *p;
2033     p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash,
2034                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
2035     if( p ){
2036       assert( p==pIndex );  /* Malloc must have failed */
2037       sqliteFree(pIndex);
2038       goto exit_create_index;
2039     }
2040     db->flags |= SQLITE_InternChanges;
2041   }
2042 
2043   /* When adding an index to the list of indices for a table, make
2044   ** sure all indices labeled OE_Replace come after all those labeled
2045   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
2046   ** and INSERT.
2047   */
2048   if( onError!=OE_Replace || pTab->pIndex==0
2049        || pTab->pIndex->onError==OE_Replace){
2050     pIndex->pNext = pTab->pIndex;
2051     pTab->pIndex = pIndex;
2052   }else{
2053     Index *pOther = pTab->pIndex;
2054     while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2055       pOther = pOther->pNext;
2056     }
2057     pIndex->pNext = pOther->pNext;
2058     pOther->pNext = pIndex;
2059   }
2060 
2061   /* If the db->init.busy is 1 it means we are reading the SQL off the
2062   ** "sqlite_master" table on the disk.  So do not write to the disk
2063   ** again.  Extract the table number from the db->init.newTnum field.
2064   */
2065   if( db->init.busy && pTblName!=0 ){
2066     pIndex->tnum = db->init.newTnum;
2067   }
2068 
2069   /* If the db->init.busy is 0 then create the index on disk.  This
2070   ** involves writing the index into the master table and filling in the
2071   ** index with the current table contents.
2072   **
2073   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2074   ** command.  db->init.busy is 1 when a database is opened and
2075   ** CREATE INDEX statements are read out of the master table.  In
2076   ** the latter case the index already exists on disk, which is why
2077   ** we don't want to recreate it.
2078   **
2079   ** If pTblName==0 it means this index is generated as a primary key
2080   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
2081   ** has just been created, it contains no data and the index initialization
2082   ** step can be skipped.
2083   */
2084   else if( db->init.busy==0 ){
2085     int n;
2086     Vdbe *v;
2087     int lbl1, lbl2;
2088 
2089     v = sqlite3GetVdbe(pParse);
2090     if( v==0 ) goto exit_create_index;
2091     if( pTblName!=0 ){
2092       sqlite3BeginWriteOperation(pParse, 0, iDb);
2093       sqlite3OpenMasterTable(v, iDb);
2094     }
2095     sqlite3VdbeAddOp(v, OP_NewRecno, 0, 0);
2096     sqlite3VdbeOp3(v, OP_String8, 0, 0, "index", P3_STATIC);
2097     sqlite3VdbeOp3(v, OP_String8, 0, 0, pIndex->zName, 0);
2098     sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
2099     sqlite3VdbeOp3(v, OP_CreateIndex, 0, iDb,(char*)&pIndex->tnum,P3_POINTER);
2100     pIndex->tnum = 0;
2101     if( pTblName ){
2102       sqlite3VdbeCode(v,
2103           OP_Dup,       0,      0,
2104           OP_Integer,   iDb,    0,
2105       0);
2106       sqlite3VdbeOp3(v, OP_OpenWrite, 1, 0,
2107                      (char*)&pIndex->keyInfo, P3_KEYINFO);
2108     }
2109     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
2110     if( pStart && pEnd ){
2111       if( onError==OE_None ){
2112         sqlite3VdbeChangeP3(v, -1, "CREATE INDEX ", P3_STATIC);
2113       }else{
2114         sqlite3VdbeChangeP3(v, -1, "CREATE UNIQUE INDEX ", P3_STATIC);
2115       }
2116       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
2117       n = Addr(pEnd->z) - Addr(pName->z) + 1;
2118       sqlite3VdbeChangeP3(v, -1, pName->z, n);
2119       sqlite3VdbeAddOp(v, OP_Concat, 2, 0);
2120     }
2121     sqlite3VdbeOp3(v, OP_MakeRecord, 5, 0, "tttit", P3_STATIC);
2122     sqlite3VdbeAddOp(v, OP_PutIntKey, 0, 0);
2123     if( pTblName ){
2124       sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
2125       sqlite3VdbeAddOp(v, OP_OpenRead, 2, pTab->tnum);
2126       /* VdbeComment((v, "%s", pTab->zName)); */
2127       sqlite3VdbeAddOp(v, OP_SetNumColumns, 2, pTab->nCol);
2128       lbl2 = sqlite3VdbeMakeLabel(v);
2129       sqlite3VdbeAddOp(v, OP_Rewind, 2, lbl2);
2130       lbl1 = sqlite3VdbeCurrentAddr(v);
2131       sqlite3GenerateIndexKey(v, pIndex, 2);
2132       sqlite3VdbeOp3(v, OP_IdxPut, 1, pIndex->onError!=OE_None,
2133                       "indexed columns are not unique", P3_STATIC);
2134       sqlite3VdbeAddOp(v, OP_Next, 2, lbl1);
2135       sqlite3VdbeResolveLabel(v, lbl2);
2136       sqlite3VdbeAddOp(v, OP_Close, 2, 0);
2137       sqlite3VdbeAddOp(v, OP_Close, 1, 0);
2138     }
2139     if( pTblName!=0 ){
2140       if( !isTemp ){
2141         sqlite3ChangeCookie(db, v, iDb);
2142       }
2143       sqlite3VdbeAddOp(v, OP_Close, 0, 0);
2144       sqlite3EndWriteOperation(pParse);
2145     }
2146   }
2147 
2148   /* Clean up before exiting */
2149 exit_create_index:
2150   sqlite3ExprListDelete(pList);
2151   /* sqlite3SrcListDelete(pTable); */
2152   sqliteFree(zName);
2153   return;
2154 }
2155 
2156 /*
2157 ** This routine will drop an existing named index.  This routine
2158 ** implements the DROP INDEX statement.
2159 */
2160 void sqlite3DropIndex(Parse *pParse, SrcList *pName){
2161   Index *pIndex;
2162   Vdbe *v;
2163   sqlite *db = pParse->db;
2164 
2165   if( pParse->nErr || sqlite3_malloc_failed ) return;
2166   assert( pName->nSrc==1 );
2167   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
2168   if( pIndex==0 ){
2169     sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2170     pParse->checkSchema = 1;
2171     goto exit_drop_index;
2172   }
2173   if( pIndex->autoIndex ){
2174     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
2175       "or PRIMARY KEY constraint cannot be dropped", 0);
2176     goto exit_drop_index;
2177   }
2178 /*
2179   if( pIndex->iDb>1 ){
2180     sqlite3ErrorMsg(pParse, "cannot alter schema of attached "
2181        "databases", 0);
2182     goto exit_drop_index;
2183   }
2184 */
2185 #ifndef SQLITE_OMIT_AUTHORIZATION
2186   {
2187     int code = SQLITE_DROP_INDEX;
2188     Table *pTab = pIndex->pTable;
2189     const char *zDb = db->aDb[pIndex->iDb].zName;
2190     const char *zTab = SCHEMA_TABLE(pIndex->iDb);
2191     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
2192       goto exit_drop_index;
2193     }
2194     if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
2195     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
2196       goto exit_drop_index;
2197     }
2198   }
2199 #endif
2200 
2201   /* Generate code to remove the index and from the master table */
2202   v = sqlite3GetVdbe(pParse);
2203   if( v ){
2204     static VdbeOpList dropIndex[] = {
2205       { OP_Rewind,     0, ADDR(9), 0},
2206       { OP_String8,     0, 0,       0}, /* 1 */
2207       { OP_MemStore,   1, 1,       0},
2208       { OP_MemLoad,    1, 0,       0}, /* 3 */
2209       { OP_Column,     0, 1,       0},
2210       { OP_Eq,         0, ADDR(8), 0},
2211       { OP_Next,       0, ADDR(3), 0},
2212       { OP_Goto,       0, ADDR(9), 0},
2213       { OP_Delete,     0, 0,       0}, /* 8 */
2214     };
2215     int base;
2216 
2217     sqlite3BeginWriteOperation(pParse, 0, pIndex->iDb);
2218     sqlite3OpenMasterTable(v, pIndex->iDb);
2219     base = sqlite3VdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
2220     sqlite3VdbeChangeP3(v, base+1, pIndex->zName, 0);
2221     if( pIndex->iDb!=1 ){
2222       sqlite3ChangeCookie(db, v, pIndex->iDb);
2223     }
2224     sqlite3VdbeAddOp(v, OP_Close, 0, 0);
2225     sqlite3VdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb);
2226     sqlite3EndWriteOperation(pParse);
2227   }
2228 
2229   /* Delete the in-memory description of this index.
2230   */
2231   if( !pParse->explain ){
2232     sqlite3UnlinkAndDeleteIndex(db, pIndex);
2233     db->flags |= SQLITE_InternChanges;
2234   }
2235 
2236 exit_drop_index:
2237   sqlite3SrcListDelete(pName);
2238 }
2239 
2240 /*
2241 ** Append a new element to the given IdList.  Create a new IdList if
2242 ** need be.
2243 **
2244 ** A new IdList is returned, or NULL if malloc() fails.
2245 */
2246 IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
2247   if( pList==0 ){
2248     pList = sqliteMalloc( sizeof(IdList) );
2249     if( pList==0 ) return 0;
2250     pList->nAlloc = 0;
2251   }
2252   if( pList->nId>=pList->nAlloc ){
2253     struct IdList_item *a;
2254     pList->nAlloc = pList->nAlloc*2 + 5;
2255     a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
2256     if( a==0 ){
2257       sqlite3IdListDelete(pList);
2258       return 0;
2259     }
2260     pList->a = a;
2261   }
2262   memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
2263   if( pToken ){
2264     char **pz = &pList->a[pList->nId].zName;
2265     sqlite3SetNString(pz, pToken->z, pToken->n, 0);
2266     if( *pz==0 ){
2267       sqlite3IdListDelete(pList);
2268       return 0;
2269     }else{
2270       sqlite3Dequote(*pz);
2271     }
2272   }
2273   pList->nId++;
2274   return pList;
2275 }
2276 
2277 /*
2278 ** Append a new table name to the given SrcList.  Create a new SrcList if
2279 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
2280 **
2281 ** A new SrcList is returned, or NULL if malloc() fails.
2282 **
2283 ** If pDatabase is not null, it means that the table has an optional
2284 ** database name prefix.  Like this:  "database.table".  The pDatabase
2285 ** points to the table name and the pTable points to the database name.
2286 ** The SrcList.a[].zName field is filled with the table name which might
2287 ** come from pTable (if pDatabase is NULL) or from pDatabase.
2288 ** SrcList.a[].zDatabase is filled with the database name from pTable,
2289 ** or with NULL if no database is specified.
2290 **
2291 ** In other words, if call like this:
2292 **
2293 **         sqlite3SrcListAppend(A,B,0);
2294 **
2295 ** Then B is a table name and the database name is unspecified.  If called
2296 ** like this:
2297 **
2298 **         sqlite3SrcListAppend(A,B,C);
2299 **
2300 ** Then C is the table name and B is the database name.
2301 */
2302 SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
2303   if( pList==0 ){
2304     pList = sqliteMalloc( sizeof(SrcList) );
2305     if( pList==0 ) return 0;
2306     pList->nAlloc = 1;
2307   }
2308   if( pList->nSrc>=pList->nAlloc ){
2309     SrcList *pNew;
2310     pList->nAlloc *= 2;
2311     pNew = sqliteRealloc(pList,
2312                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
2313     if( pNew==0 ){
2314       sqlite3SrcListDelete(pList);
2315       return 0;
2316     }
2317     pList = pNew;
2318   }
2319   memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
2320   if( pDatabase && pDatabase->z==0 ){
2321     pDatabase = 0;
2322   }
2323   if( pDatabase && pTable ){
2324     Token *pTemp = pDatabase;
2325     pDatabase = pTable;
2326     pTable = pTemp;
2327   }
2328   if( pTable ){
2329     char **pz = &pList->a[pList->nSrc].zName;
2330     sqlite3SetNString(pz, pTable->z, pTable->n, 0);
2331     if( *pz==0 ){
2332       sqlite3SrcListDelete(pList);
2333       return 0;
2334     }else{
2335       sqlite3Dequote(*pz);
2336     }
2337   }
2338   if( pDatabase ){
2339     char **pz = &pList->a[pList->nSrc].zDatabase;
2340     sqlite3SetNString(pz, pDatabase->z, pDatabase->n, 0);
2341     if( *pz==0 ){
2342       sqlite3SrcListDelete(pList);
2343       return 0;
2344     }else{
2345       sqlite3Dequote(*pz);
2346     }
2347   }
2348   pList->a[pList->nSrc].iCursor = -1;
2349   pList->nSrc++;
2350   return pList;
2351 }
2352 
2353 /*
2354 ** Assign cursors to all tables in a SrcList
2355 */
2356 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
2357   int i;
2358   for(i=0; i<pList->nSrc; i++){
2359     if( pList->a[i].iCursor<0 ){
2360       pList->a[i].iCursor = pParse->nTab++;
2361     }
2362   }
2363 }
2364 
2365 /*
2366 ** Add an alias to the last identifier on the given identifier list.
2367 */
2368 void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
2369   if( pList && pList->nSrc>0 ){
2370     int i = pList->nSrc - 1;
2371     sqlite3SetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
2372     sqlite3Dequote(pList->a[i].zAlias);
2373   }
2374 }
2375 
2376 /*
2377 ** Delete an IdList.
2378 */
2379 void sqlite3IdListDelete(IdList *pList){
2380   int i;
2381   if( pList==0 ) return;
2382   for(i=0; i<pList->nId; i++){
2383     sqliteFree(pList->a[i].zName);
2384   }
2385   sqliteFree(pList->a);
2386   sqliteFree(pList);
2387 }
2388 
2389 /*
2390 ** Return the index in pList of the identifier named zId.  Return -1
2391 ** if not found.
2392 */
2393 int sqlite3IdListIndex(IdList *pList, const char *zName){
2394   int i;
2395   if( pList==0 ) return -1;
2396   for(i=0; i<pList->nId; i++){
2397     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2398   }
2399   return -1;
2400 }
2401 
2402 /*
2403 ** Delete an entire SrcList including all its substructure.
2404 */
2405 void sqlite3SrcListDelete(SrcList *pList){
2406   int i;
2407   if( pList==0 ) return;
2408   for(i=0; i<pList->nSrc; i++){
2409     sqliteFree(pList->a[i].zDatabase);
2410     sqliteFree(pList->a[i].zName);
2411     sqliteFree(pList->a[i].zAlias);
2412     if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
2413       sqlite3DeleteTable(0, pList->a[i].pTab);
2414     }
2415     sqlite3SelectDelete(pList->a[i].pSelect);
2416     sqlite3ExprDelete(pList->a[i].pOn);
2417     sqlite3IdListDelete(pList->a[i].pUsing);
2418   }
2419   sqliteFree(pList);
2420 }
2421 
2422 /*
2423 ** Begin a transaction
2424 */
2425 void sqlite3BeginTransaction(Parse *pParse){
2426   sqlite *db;
2427   Vdbe *v;
2428 
2429   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2430   if( pParse->nErr || sqlite3_malloc_failed ) return;
2431   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
2432 
2433   v = sqlite3GetVdbe(pParse);
2434   if( !v ) return;
2435   sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
2436 }
2437 
2438 /*
2439 ** Commit a transaction
2440 */
2441 void sqlite3CommitTransaction(Parse *pParse){
2442   sqlite *db;
2443   Vdbe *v;
2444 
2445   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2446   if( pParse->nErr || sqlite3_malloc_failed ) return;
2447   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
2448 
2449   v = sqlite3GetVdbe(pParse);
2450   if( v ){
2451     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
2452   }
2453 }
2454 
2455 /*
2456 ** Rollback a transaction
2457 */
2458 void sqlite3RollbackTransaction(Parse *pParse){
2459   sqlite *db;
2460   Vdbe *v;
2461 
2462   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2463   if( pParse->nErr || sqlite3_malloc_failed ) return;
2464   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
2465 
2466   v = sqlite3GetVdbe(pParse);
2467   if( v ){
2468     sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
2469   }
2470 }
2471 
2472 /*
2473 ** Generate VDBE code that will verify the schema cookie and start
2474 ** a read-transaction for all named database files.
2475 **
2476 ** It is important that all schema cookies be verified and all
2477 ** read transactions be started before anything else happens in
2478 ** the VDBE program.  But this routine can be called after much other
2479 ** code has been generated.  So here is what we do:
2480 **
2481 ** The first time this routine is called, we code an OP_Gosub that
2482 ** will jump to a subroutine at the end of the program.  Then we
2483 ** record every database that needs its schema verified in the
2484 ** pParse->cookieMask field.  Later, after all other code has been
2485 ** generated, the subroutine that does the cookie verifications and
2486 ** starts the transactions will be coded and the OP_Gosub P2 value
2487 ** will be made to point to that subroutine.  The generation of the
2488 ** cookie verification subroutine code happens in sqlite3FinishCoding().
2489 */
2490 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
2491   sqlite *db;
2492   Vdbe *v;
2493   int mask;
2494 
2495   v = sqlite3GetVdbe(pParse);
2496   if( v==0 ) return;  /* This only happens if there was a prior error */
2497   db = pParse->db;
2498   assert( iDb>=0 && iDb<db->nDb );
2499   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
2500   assert( iDb<32 );
2501   if( pParse->cookieMask==0 ){
2502     pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
2503   }
2504   mask = 1<<iDb;
2505   if( (pParse->cookieMask & mask)==0 ){
2506     pParse->cookieMask |= mask;
2507     pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
2508   }
2509 }
2510 
2511 /*
2512 ** Generate VDBE code that prepares for doing an operation that
2513 ** might change the database.
2514 **
2515 ** This routine starts a new transaction if we are not already within
2516 ** a transaction.  If we are already within a transaction, then a checkpoint
2517 ** is set if the setStatement parameter is true.  A checkpoint should
2518 ** be set for operations that might fail (due to a constraint) part of
2519 ** the way through and which will need to undo some writes without having to
2520 ** rollback the whole transaction.  For operations where all constraints
2521 ** can be checked before any changes are made to the database, it is never
2522 ** necessary to undo a write and the checkpoint should not be set.
2523 **
2524 ** Only database iDb and the temp database are made writable by this call.
2525 ** If iDb==0, then the main and temp databases are made writable.   If
2526 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
2527 ** specified auxiliary database and the temp database are made writable.
2528 */
2529 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
2530   Vdbe *v = sqlite3GetVdbe(pParse);
2531   if( v==0 ) return;
2532   sqlite3CodeVerifySchema(pParse, iDb);
2533   pParse->writeMask |= 1<<iDb;
2534   if( setStatement ){
2535     sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
2536   }
2537   if( iDb!=1 ){
2538     sqlite3BeginWriteOperation(pParse, setStatement, 1);
2539   }
2540 }
2541 
2542 /*
2543 ** Generate code that concludes an operation that may have changed
2544 ** the database.  If a statement transaction was started, then emit
2545 ** an OP_Commit that will cause the changes to be committed to disk.
2546 **
2547 ** Note that checkpoints are automatically committed at the end of
2548 ** a statement.  Note also that there can be multiple calls to
2549 ** sqlite3BeginWriteOperation() but there should only be a single
2550 ** call to sqlite3EndWriteOperation() at the conclusion of the statement.
2551 */
2552 void sqlite3EndWriteOperation(Parse *pParse){
2553   /* Delete me! */
2554   return;
2555 }
2556