xref: /illumos-gate/usr/src/lib/libsqlite/src/build.c (revision c5c4113d)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2001 September 15
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** This file contains C code routines that are called by the SQLite parser
16 ** when syntax rules are reduced.  The routines in this file handle the
17 ** following kinds of SQL syntax:
18 **
19 **     CREATE TABLE
20 **     DROP TABLE
21 **     CREATE INDEX
22 **     DROP INDEX
23 **     creating ID lists
24 **     BEGIN TRANSACTION
25 **     COMMIT
26 **     ROLLBACK
27 **     PRAGMA
28 **
29 ** $Id: build.c,v 1.176.2.2 2004/07/20 00:50:30 drh Exp $
30 */
31 #include "sqliteInt.h"
32 #include <ctype.h>
33 
34 /*
35 ** This routine is called when a new SQL statement is beginning to
36 ** be parsed.  Check to see if the schema for the database needs
37 ** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
38 ** If it does, then read it.
39 */
sqliteBeginParse(Parse * pParse,int explainFlag)40 void sqliteBeginParse(Parse *pParse, int explainFlag){
41   sqlite *db = pParse->db;
42   int i;
43   pParse->explain = explainFlag;
44   if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
45     int rc = sqliteInit(db, &pParse->zErrMsg);
46     if( rc!=SQLITE_OK ){
47       pParse->rc = rc;
48       pParse->nErr++;
49     }
50   }
51   for(i=0; i<db->nDb; i++){
52     DbClearProperty(db, i, DB_Locked);
53     if( !db->aDb[i].inTrans ){
54       DbClearProperty(db, i, DB_Cookie);
55     }
56   }
57   pParse->nVar = 0;
58 }
59 
60 /*
61 ** This routine is called after a single SQL statement has been
62 ** parsed and we want to execute the VDBE code to implement
63 ** that statement.  Prior action routines should have already
64 ** constructed VDBE code to do the work of the SQL statement.
65 ** This routine just has to execute the VDBE code.
66 **
67 ** Note that if an error occurred, it might be the case that
68 ** no VDBE code was generated.
69 */
sqliteExec(Parse * pParse)70 void sqliteExec(Parse *pParse){
71   sqlite *db = pParse->db;
72   Vdbe *v = pParse->pVdbe;
73 
74   if( v==0 && (v = sqliteGetVdbe(pParse))!=0 ){
75     sqliteVdbeAddOp(v, OP_Halt, 0, 0);
76   }
77   if( sqlite_malloc_failed ) return;
78   if( v && pParse->nErr==0 ){
79     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
80     sqliteVdbeTrace(v, trace);
81     sqliteVdbeMakeReady(v, pParse->nVar, pParse->explain);
82     pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
83     pParse->colNamesSet = 0;
84   }else if( pParse->rc==SQLITE_OK ){
85     pParse->rc = SQLITE_ERROR;
86   }
87   pParse->nTab = 0;
88   pParse->nMem = 0;
89   pParse->nSet = 0;
90   pParse->nAgg = 0;
91   pParse->nVar = 0;
92 }
93 
94 /*
95 ** Locate the in-memory structure that describes
96 ** a particular database table given the name
97 ** of that table and (optionally) the name of the database
98 ** containing the table.  Return NULL if not found.
99 **
100 ** If zDatabase is 0, all databases are searched for the
101 ** table and the first matching table is returned.  (No checking
102 ** for duplicate table names is done.)  The search order is
103 ** TEMP first, then MAIN, then any auxiliary databases added
104 ** using the ATTACH command.
105 **
106 ** See also sqliteLocateTable().
107 */
sqliteFindTable(sqlite * db,const char * zName,const char * zDatabase)108 Table *sqliteFindTable(sqlite *db, const char *zName, const char *zDatabase){
109   Table *p = 0;
110   int i;
111   for(i=0; i<db->nDb; i++){
112     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
113     if( zDatabase!=0 && sqliteStrICmp(zDatabase, db->aDb[j].zName) ) continue;
114     p = sqliteHashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
115     if( p ) break;
116   }
117   return p;
118 }
119 
120 /*
121 ** Locate the in-memory structure that describes
122 ** a particular database table given the name
123 ** of that table and (optionally) the name of the database
124 ** containing the table.  Return NULL if not found.
125 ** Also leave an error message in pParse->zErrMsg.
126 **
127 ** The difference between this routine and sqliteFindTable()
128 ** is that this routine leaves an error message in pParse->zErrMsg
129 ** where sqliteFindTable() does not.
130 */
sqliteLocateTable(Parse * pParse,const char * zName,const char * zDbase)131 Table *sqliteLocateTable(Parse *pParse, const char *zName, const char *zDbase){
132   Table *p;
133 
134   p = sqliteFindTable(pParse->db, zName, zDbase);
135   if( p==0 ){
136     if( zDbase ){
137       sqliteErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
138     }else if( sqliteFindTable(pParse->db, zName, 0)!=0 ){
139       sqliteErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
140          zName, zDbase);
141     }else{
142       sqliteErrorMsg(pParse, "no such table: %s", zName);
143     }
144   }
145   return p;
146 }
147 
148 /*
149 ** Locate the in-memory structure that describes
150 ** a particular index given the name of that index
151 ** and the name of the database that contains the index.
152 ** Return NULL if not found.
153 **
154 ** If zDatabase is 0, all databases are searched for the
155 ** table and the first matching index is returned.  (No checking
156 ** for duplicate index names is done.)  The search order is
157 ** TEMP first, then MAIN, then any auxiliary databases added
158 ** using the ATTACH command.
159 */
sqliteFindIndex(sqlite * db,const char * zName,const char * zDb)160 Index *sqliteFindIndex(sqlite *db, const char *zName, const char *zDb){
161   Index *p = 0;
162   int i;
163   for(i=0; i<db->nDb; i++){
164     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
165     if( zDb && sqliteStrICmp(zDb, db->aDb[j].zName) ) continue;
166     p = sqliteHashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
167     if( p ) break;
168   }
169   return p;
170 }
171 
172 /*
173 ** Remove the given index from the index hash table, and free
174 ** its memory structures.
175 **
176 ** The index is removed from the database hash tables but
177 ** it is not unlinked from the Table that it indexes.
178 ** Unlinking from the Table must be done by the calling function.
179 */
sqliteDeleteIndex(sqlite * db,Index * p)180 static void sqliteDeleteIndex(sqlite *db, Index *p){
181   Index *pOld;
182 
183   assert( db!=0 && p->zName!=0 );
184   pOld = sqliteHashInsert(&db->aDb[p->iDb].idxHash, p->zName,
185                           strlen(p->zName)+1, 0);
186   if( pOld!=0 && pOld!=p ){
187     sqliteHashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
188                      strlen(pOld->zName)+1, pOld);
189   }
190   sqliteFree(p);
191 }
192 
193 /*
194 ** Unlink the given index from its table, then remove
195 ** the index from the index hash table and free its memory
196 ** structures.
197 */
sqliteUnlinkAndDeleteIndex(sqlite * db,Index * pIndex)198 void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
199   if( pIndex->pTable->pIndex==pIndex ){
200     pIndex->pTable->pIndex = pIndex->pNext;
201   }else{
202     Index *p;
203     for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
204     if( p && p->pNext==pIndex ){
205       p->pNext = pIndex->pNext;
206     }
207   }
208   sqliteDeleteIndex(db, pIndex);
209 }
210 
211 /*
212 ** Erase all schema information from the in-memory hash tables of
213 ** database connection.  This routine is called to reclaim memory
214 ** before the connection closes.  It is also called during a rollback
215 ** if there were schema changes during the transaction.
216 **
217 ** If iDb<=0 then reset the internal schema tables for all database
218 ** files.  If iDb>=2 then reset the internal schema for only the
219 ** single file indicated.
220 */
sqliteResetInternalSchema(sqlite * db,int iDb)221 void sqliteResetInternalSchema(sqlite *db, int iDb){
222   HashElem *pElem;
223   Hash temp1;
224   Hash temp2;
225   int i, j;
226 
227   assert( iDb>=0 && iDb<db->nDb );
228   db->flags &= ~SQLITE_Initialized;
229   for(i=iDb; i<db->nDb; i++){
230     Db *pDb = &db->aDb[i];
231     temp1 = pDb->tblHash;
232     temp2 = pDb->trigHash;
233     sqliteHashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
234     sqliteHashClear(&pDb->aFKey);
235     sqliteHashClear(&pDb->idxHash);
236     for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
237       Trigger *pTrigger = sqliteHashData(pElem);
238       sqliteDeleteTrigger(pTrigger);
239     }
240     sqliteHashClear(&temp2);
241     sqliteHashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
242     for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
243       Table *pTab = sqliteHashData(pElem);
244       sqliteDeleteTable(db, pTab);
245     }
246     sqliteHashClear(&temp1);
247     DbClearProperty(db, i, DB_SchemaLoaded);
248     if( iDb>0 ) return;
249   }
250   assert( iDb==0 );
251   db->flags &= ~SQLITE_InternChanges;
252 
253   /* If one or more of the auxiliary database files has been closed,
254   ** then remove then from the auxiliary database list.  We take the
255   ** opportunity to do this here since we have just deleted all of the
256   ** schema hash tables and therefore do not have to make any changes
257   ** to any of those tables.
258   */
259   for(i=0; i<db->nDb; i++){
260     struct Db *pDb = &db->aDb[i];
261     if( pDb->pBt==0 ){
262       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
263       pDb->pAux = 0;
264     }
265   }
266   for(i=j=2; i<db->nDb; i++){
267     struct Db *pDb = &db->aDb[i];
268     if( pDb->pBt==0 ){
269       sqliteFree(pDb->zName);
270       pDb->zName = 0;
271       continue;
272     }
273     if( j<i ){
274       db->aDb[j] = db->aDb[i];
275     }
276     j++;
277   }
278   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
279   db->nDb = j;
280   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
281     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
282     sqliteFree(db->aDb);
283     db->aDb = db->aDbStatic;
284   }
285 }
286 
287 /*
288 ** This routine is called whenever a rollback occurs.  If there were
289 ** schema changes during the transaction, then we have to reset the
290 ** internal hash tables and reload them from disk.
291 */
sqliteRollbackInternalChanges(sqlite * db)292 void sqliteRollbackInternalChanges(sqlite *db){
293   if( db->flags & SQLITE_InternChanges ){
294     sqliteResetInternalSchema(db, 0);
295   }
296 }
297 
298 /*
299 ** This routine is called when a commit occurs.
300 */
sqliteCommitInternalChanges(sqlite * db)301 void sqliteCommitInternalChanges(sqlite *db){
302   db->aDb[0].schema_cookie = db->next_cookie;
303   db->flags &= ~SQLITE_InternChanges;
304 }
305 
306 /*
307 ** Remove the memory data structures associated with the given
308 ** Table.  No changes are made to disk by this routine.
309 **
310 ** This routine just deletes the data structure.  It does not unlink
311 ** the table data structure from the hash table.  Nor does it remove
312 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
313 ** memory structures of the indices and foreign keys associated with
314 ** the table.
315 **
316 ** Indices associated with the table are unlinked from the "db"
317 ** data structure if db!=NULL.  If db==NULL, indices attached to
318 ** the table are deleted, but it is assumed they have already been
319 ** unlinked.
320 */
sqliteDeleteTable(sqlite * db,Table * pTable)321 void sqliteDeleteTable(sqlite *db, Table *pTable){
322   int i;
323   Index *pIndex, *pNext;
324   FKey *pFKey, *pNextFKey;
325 
326   if( pTable==0 ) return;
327 
328   /* Delete all indices associated with this table
329   */
330   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
331     pNext = pIndex->pNext;
332     assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
333     sqliteDeleteIndex(db, pIndex);
334   }
335 
336   /* Delete all foreign keys associated with this table.  The keys
337   ** should have already been unlinked from the db->aFKey hash table
338   */
339   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
340     pNextFKey = pFKey->pNextFrom;
341     assert( pTable->iDb<db->nDb );
342     assert( sqliteHashFind(&db->aDb[pTable->iDb].aFKey,
343                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
344     sqliteFree(pFKey);
345   }
346 
347   /* Delete the Table structure itself.
348   */
349   for(i=0; i<pTable->nCol; i++){
350     sqliteFree(pTable->aCol[i].zName);
351     sqliteFree(pTable->aCol[i].zDflt);
352     sqliteFree(pTable->aCol[i].zType);
353   }
354   sqliteFree(pTable->zName);
355   sqliteFree(pTable->aCol);
356   sqliteSelectDelete(pTable->pSelect);
357   sqliteFree(pTable);
358 }
359 
360 /*
361 ** Unlink the given table from the hash tables and the delete the
362 ** table structure with all its indices and foreign keys.
363 */
sqliteUnlinkAndDeleteTable(sqlite * db,Table * p)364 static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
365   Table *pOld;
366   FKey *pF1, *pF2;
367   int i = p->iDb;
368   assert( db!=0 );
369   pOld = sqliteHashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
370   assert( pOld==0 || pOld==p );
371   for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
372     int nTo = strlen(pF1->zTo) + 1;
373     pF2 = sqliteHashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
374     if( pF2==pF1 ){
375       sqliteHashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
376     }else{
377       while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
378       if( pF2 ){
379         pF2->pNextTo = pF1->pNextTo;
380       }
381     }
382   }
383   sqliteDeleteTable(db, p);
384 }
385 
386 /*
387 ** Construct the name of a user table or index from a token.
388 **
389 ** Space to hold the name is obtained from sqliteMalloc() and must
390 ** be freed by the calling function.
391 */
sqliteTableNameFromToken(Token * pName)392 char *sqliteTableNameFromToken(Token *pName){
393   char *zName = sqliteStrNDup(pName->z, pName->n);
394   sqliteDequote(zName);
395   return zName;
396 }
397 
398 /*
399 ** Generate code to open the appropriate master table.  The table
400 ** opened will be SQLITE_MASTER for persistent tables and
401 ** SQLITE_TEMP_MASTER for temporary tables.  The table is opened
402 ** on cursor 0.
403 */
sqliteOpenMasterTable(Vdbe * v,int isTemp)404 void sqliteOpenMasterTable(Vdbe *v, int isTemp){
405   sqliteVdbeAddOp(v, OP_Integer, isTemp, 0);
406   sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
407 }
408 
409 /*
410 ** Begin constructing a new table representation in memory.  This is
411 ** the first of several action routines that get called in response
412 ** to a CREATE TABLE statement.  In particular, this routine is called
413 ** after seeing tokens "CREATE" and "TABLE" and the table name.  The
414 ** pStart token is the CREATE and pName is the table name.  The isTemp
415 ** flag is true if the table should be stored in the auxiliary database
416 ** file instead of in the main database file.  This is normally the case
417 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
418 ** CREATE and TABLE.
419 **
420 ** The new table record is initialized and put in pParse->pNewTable.
421 ** As more of the CREATE TABLE statement is parsed, additional action
422 ** routines will be called to add more information to this record.
423 ** At the end of the CREATE TABLE statement, the sqliteEndTable() routine
424 ** is called to complete the construction of the new table record.
425 */
sqliteStartTable(Parse * pParse,Token * pStart,Token * pName,int isTemp,int isView)426 void sqliteStartTable(
427   Parse *pParse,   /* Parser context */
428   Token *pStart,   /* The "CREATE" token */
429   Token *pName,    /* Name of table or view to create */
430   int isTemp,      /* True if this is a TEMP table */
431   int isView       /* True if this is a VIEW */
432 ){
433   Table *pTable;
434   Index *pIdx;
435   char *zName;
436   sqlite *db = pParse->db;
437   Vdbe *v;
438   int iDb;
439 
440   pParse->sFirstToken = *pStart;
441   zName = sqliteTableNameFromToken(pName);
442   if( zName==0 ) return;
443   if( db->init.iDb==1 ) isTemp = 1;
444 #ifndef SQLITE_OMIT_AUTHORIZATION
445   assert( (isTemp & 1)==isTemp );
446   {
447     int code;
448     char *zDb = isTemp ? "temp" : "main";
449     if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
450       sqliteFree(zName);
451       return;
452     }
453     if( isView ){
454       if( isTemp ){
455         code = SQLITE_CREATE_TEMP_VIEW;
456       }else{
457         code = SQLITE_CREATE_VIEW;
458       }
459     }else{
460       if( isTemp ){
461         code = SQLITE_CREATE_TEMP_TABLE;
462       }else{
463         code = SQLITE_CREATE_TABLE;
464       }
465     }
466     if( sqliteAuthCheck(pParse, code, zName, 0, zDb) ){
467       sqliteFree(zName);
468       return;
469     }
470   }
471 #endif
472 
473 
474   /* Before trying to create a temporary table, make sure the Btree for
475   ** holding temporary tables is open.
476   */
477   if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
478     int rc = sqliteBtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
479     if( rc!=SQLITE_OK ){
480       sqliteErrorMsg(pParse, "unable to open a temporary database "
481         "file for storing temporary tables");
482       pParse->nErr++;
483       return;
484     }
485     if( db->flags & SQLITE_InTrans ){
486       rc = sqliteBtreeBeginTrans(db->aDb[1].pBt);
487       if( rc!=SQLITE_OK ){
488         sqliteErrorMsg(pParse, "unable to get a write lock on "
489           "the temporary database file");
490         return;
491       }
492     }
493   }
494 
495   /* Make sure the new table name does not collide with an existing
496   ** index or table name.  Issue an error message if it does.
497   **
498   ** If we are re-reading the sqlite_master table because of a schema
499   ** change and a new permanent table is found whose name collides with
500   ** an existing temporary table, that is not an error.
501   */
502   pTable = sqliteFindTable(db, zName, 0);
503   iDb = isTemp ? 1 : db->init.iDb;
504   if( pTable!=0 && (pTable->iDb==iDb || !db->init.busy) ){
505     sqliteErrorMsg(pParse, "table %T already exists", pName);
506     sqliteFree(zName);
507     return;
508   }
509   if( (pIdx = sqliteFindIndex(db, zName, 0))!=0 &&
510           (pIdx->iDb==0 || !db->init.busy) ){
511     sqliteErrorMsg(pParse, "there is already an index named %s", zName);
512     sqliteFree(zName);
513     return;
514   }
515   pTable = sqliteMalloc( sizeof(Table) );
516   if( pTable==0 ){
517     sqliteFree(zName);
518     return;
519   }
520   pTable->zName = zName;
521   pTable->nCol = 0;
522   pTable->aCol = 0;
523   pTable->iPKey = -1;
524   pTable->pIndex = 0;
525   pTable->iDb = iDb;
526   if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
527   pParse->pNewTable = pTable;
528 
529   /* Begin generating the code that will insert the table record into
530   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
531   ** and allocate the record number for the table entry now.  Before any
532   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
533   ** indices to be created and the table record must come before the
534   ** indices.  Hence, the record number for the table must be allocated
535   ** now.
536   */
537   if( !db->init.busy && (v = sqliteGetVdbe(pParse))!=0 ){
538     sqliteBeginWriteOperation(pParse, 0, isTemp);
539     if( !isTemp ){
540       sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
541       sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
542     }
543     sqliteOpenMasterTable(v, isTemp);
544     sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
545     sqliteVdbeAddOp(v, OP_Dup, 0, 0);
546     sqliteVdbeAddOp(v, OP_String, 0, 0);
547     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
548   }
549 }
550 
551 /*
552 ** Add a new column to the table currently being constructed.
553 **
554 ** The parser calls this routine once for each column declaration
555 ** in a CREATE TABLE statement.  sqliteStartTable() gets called
556 ** first to get things going.  Then this routine is called for each
557 ** column.
558 */
sqliteAddColumn(Parse * pParse,Token * pName)559 void sqliteAddColumn(Parse *pParse, Token *pName){
560   Table *p;
561   int i;
562   char *z = 0;
563   Column *pCol;
564   if( (p = pParse->pNewTable)==0 ) return;
565   sqliteSetNString(&z, pName->z, pName->n, 0);
566   if( z==0 ) return;
567   sqliteDequote(z);
568   for(i=0; i<p->nCol; i++){
569     if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
570       sqliteErrorMsg(pParse, "duplicate column name: %s", z);
571       sqliteFree(z);
572       return;
573     }
574   }
575   if( (p->nCol & 0x7)==0 ){
576     Column *aNew;
577     aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
578     if( aNew==0 ) return;
579     p->aCol = aNew;
580   }
581   pCol = &p->aCol[p->nCol];
582   memset(pCol, 0, sizeof(p->aCol[0]));
583   pCol->zName = z;
584   pCol->sortOrder = SQLITE_SO_NUM;
585   p->nCol++;
586 }
587 
588 /*
589 ** This routine is called by the parser while in the middle of
590 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
591 ** been seen on a column.  This routine sets the notNull flag on
592 ** the column currently under construction.
593 */
sqliteAddNotNull(Parse * pParse,int onError)594 void sqliteAddNotNull(Parse *pParse, int onError){
595   Table *p;
596   int i;
597   if( (p = pParse->pNewTable)==0 ) return;
598   i = p->nCol-1;
599   if( i>=0 ) p->aCol[i].notNull = onError;
600 }
601 
602 /*
603 ** This routine is called by the parser while in the middle of
604 ** parsing a CREATE TABLE statement.  The pFirst token is the first
605 ** token in the sequence of tokens that describe the type of the
606 ** column currently under construction.   pLast is the last token
607 ** in the sequence.  Use this information to construct a string
608 ** that contains the typename of the column and store that string
609 ** in zType.
610 */
sqliteAddColumnType(Parse * pParse,Token * pFirst,Token * pLast)611 void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
612   Table *p;
613   int i, j;
614   int n;
615   char *z, **pz;
616   Column *pCol;
617   if( (p = pParse->pNewTable)==0 ) return;
618   i = p->nCol-1;
619   if( i<0 ) return;
620   pCol = &p->aCol[i];
621   pz = &pCol->zType;
622   n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
623   sqliteSetNString(pz, pFirst->z, n, 0);
624   z = *pz;
625   if( z==0 ) return;
626   for(i=j=0; z[i]; i++){
627     int c = z[i];
628     if( isspace(c) ) continue;
629     z[j++] = c;
630   }
631   z[j] = 0;
632   if( pParse->db->file_format>=4 ){
633     pCol->sortOrder = sqliteCollateType(z, n);
634   }else{
635     pCol->sortOrder = SQLITE_SO_NUM;
636   }
637 }
638 
639 /*
640 ** The given token is the default value for the last column added to
641 ** the table currently under construction.  If "minusFlag" is true, it
642 ** means the value token was preceded by a minus sign.
643 **
644 ** This routine is called by the parser while in the middle of
645 ** parsing a CREATE TABLE statement.
646 */
sqliteAddDefaultValue(Parse * pParse,Token * pVal,int minusFlag)647 void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
648   Table *p;
649   int i;
650   char **pz;
651   if( (p = pParse->pNewTable)==0 ) return;
652   i = p->nCol-1;
653   if( i<0 ) return;
654   pz = &p->aCol[i].zDflt;
655   if( minusFlag ){
656     sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
657   }else{
658     sqliteSetNString(pz, pVal->z, pVal->n, 0);
659   }
660   sqliteDequote(*pz);
661 }
662 
663 /*
664 ** Designate the PRIMARY KEY for the table.  pList is a list of names
665 ** of columns that form the primary key.  If pList is NULL, then the
666 ** most recently added column of the table is the primary key.
667 **
668 ** A table can have at most one primary key.  If the table already has
669 ** a primary key (and this is the second primary key) then create an
670 ** error.
671 **
672 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
673 ** then we will try to use that column as the row id.  (Exception:
674 ** For backwards compatibility with older databases, do not do this
675 ** if the file format version number is less than 1.)  Set the Table.iPKey
676 ** field of the table under construction to be the index of the
677 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
678 ** no INTEGER PRIMARY KEY.
679 **
680 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
681 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
682 */
sqliteAddPrimaryKey(Parse * pParse,IdList * pList,int onError)683 void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
684   Table *pTab = pParse->pNewTable;
685   char *zType = 0;
686   int iCol = -1, i;
687   if( pTab==0 ) goto primary_key_exit;
688   if( pTab->hasPrimKey ){
689     sqliteErrorMsg(pParse,
690       "table \"%s\" has more than one primary key", pTab->zName);
691     goto primary_key_exit;
692   }
693   pTab->hasPrimKey = 1;
694   if( pList==0 ){
695     iCol = pTab->nCol - 1;
696     pTab->aCol[iCol].isPrimKey = 1;
697   }else{
698     for(i=0; i<pList->nId; i++){
699       for(iCol=0; iCol<pTab->nCol; iCol++){
700         if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break;
701       }
702       if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
703     }
704     if( pList->nId>1 ) iCol = -1;
705   }
706   if( iCol>=0 && iCol<pTab->nCol ){
707     zType = pTab->aCol[iCol].zType;
708   }
709   if( pParse->db->file_format>=1 &&
710            zType && sqliteStrICmp(zType, "INTEGER")==0 ){
711     pTab->iPKey = iCol;
712     pTab->keyConf = onError;
713   }else{
714     sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
715     pList = 0;
716   }
717 
718 primary_key_exit:
719   sqliteIdListDelete(pList);
720   return;
721 }
722 
723 /*
724 ** Return the appropriate collating type given a type name.
725 **
726 ** The collation type is text (SQLITE_SO_TEXT) if the type
727 ** name contains the character stream "text" or "blob" or
728 ** "clob".  Any other type name is collated as numeric
729 ** (SQLITE_SO_NUM).
730 */
sqliteCollateType(const char * zType,int nType)731 int sqliteCollateType(const char *zType, int nType){
732   int i;
733   for(i=0; i<nType-3; i++){
734     int c = *(zType++) | 0x60;
735     if( (c=='b' || c=='c') && sqliteStrNICmp(zType, "lob", 3)==0 ){
736       return SQLITE_SO_TEXT;
737     }
738     if( c=='c' && sqliteStrNICmp(zType, "har", 3)==0 ){
739       return SQLITE_SO_TEXT;
740     }
741     if( c=='t' && sqliteStrNICmp(zType, "ext", 3)==0 ){
742       return SQLITE_SO_TEXT;
743     }
744   }
745   return SQLITE_SO_NUM;
746 }
747 
748 /*
749 ** This routine is called by the parser while in the middle of
750 ** parsing a CREATE TABLE statement.  A "COLLATE" clause has
751 ** been seen on a column.  This routine sets the Column.sortOrder on
752 ** the column currently under construction.
753 */
sqliteAddCollateType(Parse * pParse,int collType)754 void sqliteAddCollateType(Parse *pParse, int collType){
755   Table *p;
756   int i;
757   if( (p = pParse->pNewTable)==0 ) return;
758   i = p->nCol-1;
759   if( i>=0 ) p->aCol[i].sortOrder = collType;
760 }
761 
762 /*
763 ** Come up with a new random value for the schema cookie.  Make sure
764 ** the new value is different from the old.
765 **
766 ** The schema cookie is used to determine when the schema for the
767 ** database changes.  After each schema change, the cookie value
768 ** changes.  When a process first reads the schema it records the
769 ** cookie.  Thereafter, whenever it goes to access the database,
770 ** it checks the cookie to make sure the schema has not changed
771 ** since it was last read.
772 **
773 ** This plan is not completely bullet-proof.  It is possible for
774 ** the schema to change multiple times and for the cookie to be
775 ** set back to prior value.  But schema changes are infrequent
776 ** and the probability of hitting the same cookie value is only
777 ** 1 chance in 2^32.  So we're safe enough.
778 */
sqliteChangeCookie(sqlite * db,Vdbe * v)779 void sqliteChangeCookie(sqlite *db, Vdbe *v){
780   if( db->next_cookie==db->aDb[0].schema_cookie ){
781     unsigned char r;
782     sqliteRandomness(1, &r);
783     db->next_cookie = db->aDb[0].schema_cookie + r + 1;
784     db->flags |= SQLITE_InternChanges;
785     sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
786     sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
787   }
788 }
789 
790 /*
791 ** Measure the number of characters needed to output the given
792 ** identifier.  The number returned includes any quotes used
793 ** but does not include the null terminator.
794 */
identLength(const char * z)795 static int identLength(const char *z){
796   int n;
797   int needQuote = 0;
798   for(n=0; *z; n++, z++){
799     if( *z=='\'' ){ n++; needQuote=1; }
800   }
801   return n + needQuote*2;
802 }
803 
804 /*
805 ** Write an identifier onto the end of the given string.  Add
806 ** quote characters as needed.
807 */
identPut(char * z,int * pIdx,char * zIdent)808 static void identPut(char *z, int *pIdx, char *zIdent){
809   int i, j, needQuote;
810   i = *pIdx;
811   for(j=0; zIdent[j]; j++){
812     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
813   }
814   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
815                   || sqliteKeywordCode(zIdent, j)!=TK_ID;
816   if( needQuote ) z[i++] = '\'';
817   for(j=0; zIdent[j]; j++){
818     z[i++] = zIdent[j];
819     if( zIdent[j]=='\'' ) z[i++] = '\'';
820   }
821   if( needQuote ) z[i++] = '\'';
822   z[i] = 0;
823   *pIdx = i;
824 }
825 
826 /*
827 ** Generate a CREATE TABLE statement appropriate for the given
828 ** table.  Memory to hold the text of the statement is obtained
829 ** from sqliteMalloc() and must be freed by the calling function.
830 */
createTableStmt(Table * p)831 static char *createTableStmt(Table *p){
832   int i, k, n;
833   char *zStmt;
834   char *zSep, *zSep2, *zEnd;
835   n = 0;
836   for(i=0; i<p->nCol; i++){
837     n += identLength(p->aCol[i].zName);
838   }
839   n += identLength(p->zName);
840   if( n<40 ){
841     zSep = "";
842     zSep2 = ",";
843     zEnd = ")";
844   }else{
845     zSep = "\n  ";
846     zSep2 = ",\n  ";
847     zEnd = "\n)";
848   }
849   n += 35 + 6*p->nCol;
850   zStmt = sqliteMallocRaw( n );
851   if( zStmt==0 ) return 0;
852   strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
853   k = strlen(zStmt);
854   identPut(zStmt, &k, p->zName);
855   zStmt[k++] = '(';
856   for(i=0; i<p->nCol; i++){
857     strcpy(&zStmt[k], zSep);
858     k += strlen(&zStmt[k]);
859     zSep = zSep2;
860     identPut(zStmt, &k, p->aCol[i].zName);
861   }
862   strcpy(&zStmt[k], zEnd);
863   return zStmt;
864 }
865 
866 /*
867 ** This routine is called to report the final ")" that terminates
868 ** a CREATE TABLE statement.
869 **
870 ** The table structure that other action routines have been building
871 ** is added to the internal hash tables, assuming no errors have
872 ** occurred.
873 **
874 ** An entry for the table is made in the master table on disk, unless
875 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
876 ** it means we are reading the sqlite_master table because we just
877 ** connected to the database or because the sqlite_master table has
878 ** recently changes, so the entry for this table already exists in
879 ** the sqlite_master table.  We do not want to create it again.
880 **
881 ** If the pSelect argument is not NULL, it means that this routine
882 ** was called to create a table generated from a
883 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
884 ** the new table will match the result set of the SELECT.
885 */
sqliteEndTable(Parse * pParse,Token * pEnd,Select * pSelect)886 void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
887   Table *p;
888   sqlite *db = pParse->db;
889 
890   if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
891   p = pParse->pNewTable;
892   if( p==0 ) return;
893 
894   /* If the table is generated from a SELECT, then construct the
895   ** list of columns and the text of the table.
896   */
897   if( pSelect ){
898     Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
899     if( pSelTab==0 ) return;
900     assert( p->aCol==0 );
901     p->nCol = pSelTab->nCol;
902     p->aCol = pSelTab->aCol;
903     pSelTab->nCol = 0;
904     pSelTab->aCol = 0;
905     sqliteDeleteTable(0, pSelTab);
906   }
907 
908   /* If the db->init.busy is 1 it means we are reading the SQL off the
909   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
910   ** So do not write to the disk again.  Extract the root page number
911   ** for the table from the db->init.newTnum field.  (The page number
912   ** should have been put there by the sqliteOpenCb routine.)
913   */
914   if( db->init.busy ){
915     p->tnum = db->init.newTnum;
916   }
917 
918   /* If not initializing, then create a record for the new table
919   ** in the SQLITE_MASTER table of the database.  The record number
920   ** for the new table entry should already be on the stack.
921   **
922   ** If this is a TEMPORARY table, write the entry into the auxiliary
923   ** file instead of into the main database file.
924   */
925   if( !db->init.busy ){
926     int n;
927     Vdbe *v;
928 
929     v = sqliteGetVdbe(pParse);
930     if( v==0 ) return;
931     if( p->pSelect==0 ){
932       /* A regular table */
933       sqliteVdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
934     }else{
935       /* A view */
936       sqliteVdbeAddOp(v, OP_Integer, 0, 0);
937     }
938     p->tnum = 0;
939     sqliteVdbeAddOp(v, OP_Pull, 1, 0);
940     sqliteVdbeOp3(v, OP_String, 0, 0, p->pSelect==0?"table":"view", P3_STATIC);
941     sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
942     sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
943     sqliteVdbeAddOp(v, OP_Dup, 4, 0);
944     sqliteVdbeAddOp(v, OP_String, 0, 0);
945     if( pSelect ){
946       char *z = createTableStmt(p);
947       n = z ? strlen(z) : 0;
948       sqliteVdbeChangeP3(v, -1, z, n);
949       sqliteFree(z);
950     }else{
951       assert( pEnd!=0 );
952       n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
953       sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
954     }
955     sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
956     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
957     if( !p->iDb ){
958       sqliteChangeCookie(db, v);
959     }
960     sqliteVdbeAddOp(v, OP_Close, 0, 0);
961     if( pSelect ){
962       sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0);
963       sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
964       pParse->nTab = 2;
965       sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
966     }
967     sqliteEndWriteOperation(pParse);
968   }
969 
970   /* Add the table to the in-memory representation of the database.
971   */
972   if( pParse->explain==0 && pParse->nErr==0 ){
973     Table *pOld;
974     FKey *pFKey;
975     pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash,
976                             p->zName, strlen(p->zName)+1, p);
977     if( pOld ){
978       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
979       return;
980     }
981     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
982       int nTo = strlen(pFKey->zTo) + 1;
983       pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
984       sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
985     }
986     pParse->pNewTable = 0;
987     db->nTable++;
988     db->flags |= SQLITE_InternChanges;
989   }
990 }
991 
992 /*
993 ** The parser calls this routine in order to create a new VIEW
994 */
sqliteCreateView(Parse * pParse,Token * pBegin,Token * pName,Select * pSelect,int isTemp)995 void sqliteCreateView(
996   Parse *pParse,     /* The parsing context */
997   Token *pBegin,     /* The CREATE token that begins the statement */
998   Token *pName,      /* The token that holds the name of the view */
999   Select *pSelect,   /* A SELECT statement that will become the new view */
1000   int isTemp         /* TRUE for a TEMPORARY view */
1001 ){
1002   Table *p;
1003   int n;
1004   const char *z;
1005   Token sEnd;
1006   DbFixer sFix;
1007 
1008   sqliteStartTable(pParse, pBegin, pName, isTemp, 1);
1009   p = pParse->pNewTable;
1010   if( p==0 || pParse->nErr ){
1011     sqliteSelectDelete(pSelect);
1012     return;
1013   }
1014   if( sqliteFixInit(&sFix, pParse, p->iDb, "view", pName)
1015     && sqliteFixSelect(&sFix, pSelect)
1016   ){
1017     sqliteSelectDelete(pSelect);
1018     return;
1019   }
1020 
1021   /* Make a copy of the entire SELECT statement that defines the view.
1022   ** This will force all the Expr.token.z values to be dynamically
1023   ** allocated rather than point to the input string - which means that
1024   ** they will persist after the current sqlite_exec() call returns.
1025   */
1026   p->pSelect = sqliteSelectDup(pSelect);
1027   sqliteSelectDelete(pSelect);
1028   if( !pParse->db->init.busy ){
1029     sqliteViewGetColumnNames(pParse, p);
1030   }
1031 
1032   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
1033   ** the end.
1034   */
1035   sEnd = pParse->sLastToken;
1036   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1037     sEnd.z += sEnd.n;
1038   }
1039   sEnd.n = 0;
1040   n = sEnd.z - pBegin->z;
1041   z = pBegin->z;
1042   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1043   sEnd.z = &z[n-1];
1044   sEnd.n = 1;
1045 
1046   /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */
1047   sqliteEndTable(pParse, &sEnd, 0);
1048   return;
1049 }
1050 
1051 /*
1052 ** The Table structure pTable is really a VIEW.  Fill in the names of
1053 ** the columns of the view in the pTable structure.  Return the number
1054 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
1055 */
sqliteViewGetColumnNames(Parse * pParse,Table * pTable)1056 int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){
1057   ExprList *pEList;
1058   Select *pSel;
1059   Table *pSelTab;
1060   int nErr = 0;
1061 
1062   assert( pTable );
1063 
1064   /* A positive nCol means the columns names for this view are
1065   ** already known.
1066   */
1067   if( pTable->nCol>0 ) return 0;
1068 
1069   /* A negative nCol is a special marker meaning that we are currently
1070   ** trying to compute the column names.  If we enter this routine with
1071   ** a negative nCol, it means two or more views form a loop, like this:
1072   **
1073   **     CREATE VIEW one AS SELECT * FROM two;
1074   **     CREATE VIEW two AS SELECT * FROM one;
1075   **
1076   ** Actually, this error is caught previously and so the following test
1077   ** should always fail.  But we will leave it in place just to be safe.
1078   */
1079   if( pTable->nCol<0 ){
1080     sqliteErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
1081     return 1;
1082   }
1083 
1084   /* If we get this far, it means we need to compute the table names.
1085   */
1086   assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
1087   pSel = pTable->pSelect;
1088 
1089   /* Note that the call to sqliteResultSetOfSelect() will expand any
1090   ** "*" elements in this list.  But we will need to restore the list
1091   ** back to its original configuration afterwards, so we save a copy of
1092   ** the original in pEList.
1093   */
1094   pEList = pSel->pEList;
1095   pSel->pEList = sqliteExprListDup(pEList);
1096   if( pSel->pEList==0 ){
1097     pSel->pEList = pEList;
1098     return 1;  /* Malloc failed */
1099   }
1100   pTable->nCol = -1;
1101   pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel);
1102   if( pSelTab ){
1103     assert( pTable->aCol==0 );
1104     pTable->nCol = pSelTab->nCol;
1105     pTable->aCol = pSelTab->aCol;
1106     pSelTab->nCol = 0;
1107     pSelTab->aCol = 0;
1108     sqliteDeleteTable(0, pSelTab);
1109     DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
1110   }else{
1111     pTable->nCol = 0;
1112     nErr++;
1113   }
1114   sqliteSelectUnbind(pSel);
1115   sqliteExprListDelete(pSel->pEList);
1116   pSel->pEList = pEList;
1117   return nErr;
1118 }
1119 
1120 /*
1121 ** Clear the column names from the VIEW pTable.
1122 **
1123 ** This routine is called whenever any other table or view is modified.
1124 ** The view passed into this routine might depend directly or indirectly
1125 ** on the modified or deleted table so we need to clear the old column
1126 ** names so that they will be recomputed.
1127 */
sqliteViewResetColumnNames(Table * pTable)1128 static void sqliteViewResetColumnNames(Table *pTable){
1129   int i;
1130   Column *pCol;
1131   assert( pTable!=0 && pTable->pSelect!=0 );
1132   for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
1133     sqliteFree(pCol->zName);
1134     sqliteFree(pCol->zDflt);
1135     sqliteFree(pCol->zType);
1136   }
1137   sqliteFree(pTable->aCol);
1138   pTable->aCol = 0;
1139   pTable->nCol = 0;
1140 }
1141 
1142 /*
1143 ** Clear the column names from every VIEW in database idx.
1144 */
sqliteViewResetAll(sqlite * db,int idx)1145 static void sqliteViewResetAll(sqlite *db, int idx){
1146   HashElem *i;
1147   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
1148   for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
1149     Table *pTab = sqliteHashData(i);
1150     if( pTab->pSelect ){
1151       sqliteViewResetColumnNames(pTab);
1152     }
1153   }
1154   DbClearProperty(db, idx, DB_UnresetViews);
1155 }
1156 
1157 /*
1158 ** Given a token, look up a table with that name.  If not found, leave
1159 ** an error for the parser to find and return NULL.
1160 */
sqliteTableFromToken(Parse * pParse,Token * pTok)1161 Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
1162   char *zName;
1163   Table *pTab;
1164   zName = sqliteTableNameFromToken(pTok);
1165   if( zName==0 ) return 0;
1166   pTab = sqliteFindTable(pParse->db, zName, 0);
1167   sqliteFree(zName);
1168   if( pTab==0 ){
1169     sqliteErrorMsg(pParse, "no such table: %T", pTok);
1170   }
1171   return pTab;
1172 }
1173 
1174 /*
1175 ** This routine is called to do the work of a DROP TABLE statement.
1176 ** pName is the name of the table to be dropped.
1177 */
sqliteDropTable(Parse * pParse,Token * pName,int isView)1178 void sqliteDropTable(Parse *pParse, Token *pName, int isView){
1179   Table *pTable;
1180   Vdbe *v;
1181   int base;
1182   sqlite *db = pParse->db;
1183   int iDb;
1184 
1185   if( pParse->nErr || sqlite_malloc_failed ) return;
1186   pTable = sqliteTableFromToken(pParse, pName);
1187   if( pTable==0 ) return;
1188   iDb = pTable->iDb;
1189   assert( iDb>=0 && iDb<db->nDb );
1190 #ifndef SQLITE_OMIT_AUTHORIZATION
1191   {
1192     int code;
1193     const char *zTab = SCHEMA_TABLE(pTable->iDb);
1194     const char *zDb = db->aDb[pTable->iDb].zName;
1195     if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
1196       return;
1197     }
1198     if( isView ){
1199       if( iDb==1 ){
1200         code = SQLITE_DROP_TEMP_VIEW;
1201       }else{
1202         code = SQLITE_DROP_VIEW;
1203       }
1204     }else{
1205       if( iDb==1 ){
1206         code = SQLITE_DROP_TEMP_TABLE;
1207       }else{
1208         code = SQLITE_DROP_TABLE;
1209       }
1210     }
1211     if( sqliteAuthCheck(pParse, code, pTable->zName, 0, zDb) ){
1212       return;
1213     }
1214     if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0, zDb) ){
1215       return;
1216     }
1217   }
1218 #endif
1219   if( pTable->readOnly ){
1220     sqliteErrorMsg(pParse, "table %s may not be dropped", pTable->zName);
1221     pParse->nErr++;
1222     return;
1223   }
1224   if( isView && pTable->pSelect==0 ){
1225     sqliteErrorMsg(pParse, "use DROP TABLE to delete table %s", pTable->zName);
1226     return;
1227   }
1228   if( !isView && pTable->pSelect ){
1229     sqliteErrorMsg(pParse, "use DROP VIEW to delete view %s", pTable->zName);
1230     return;
1231   }
1232 
1233   /* Generate code to remove the table from the master table
1234   ** on disk.
1235   */
1236   v = sqliteGetVdbe(pParse);
1237   if( v ){
1238     static VdbeOpList dropTable[] = {
1239       { OP_Rewind,     0, ADDR(8),  0},
1240       { OP_String,     0, 0,        0}, /* 1 */
1241       { OP_MemStore,   1, 1,        0},
1242       { OP_MemLoad,    1, 0,        0}, /* 3 */
1243       { OP_Column,     0, 2,        0},
1244       { OP_Ne,         0, ADDR(7),  0},
1245       { OP_Delete,     0, 0,        0},
1246       { OP_Next,       0, ADDR(3),  0}, /* 7 */
1247     };
1248     Index *pIdx;
1249     Trigger *pTrigger;
1250     sqliteBeginWriteOperation(pParse, 0, pTable->iDb);
1251 
1252     /* Drop all triggers associated with the table being dropped */
1253     pTrigger = pTable->pTrigger;
1254     while( pTrigger ){
1255       assert( pTrigger->iDb==pTable->iDb || pTrigger->iDb==1 );
1256       sqliteDropTriggerPtr(pParse, pTrigger, 1);
1257       if( pParse->explain ){
1258         pTrigger = pTrigger->pNext;
1259       }else{
1260         pTrigger = pTable->pTrigger;
1261       }
1262     }
1263 
1264     /* Drop all SQLITE_MASTER entries that refer to the table */
1265     sqliteOpenMasterTable(v, pTable->iDb);
1266     base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
1267     sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
1268 
1269     /* Drop all SQLITE_TEMP_MASTER entries that refer to the table */
1270     if( pTable->iDb!=1 ){
1271       sqliteOpenMasterTable(v, 1);
1272       base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
1273       sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
1274     }
1275 
1276     if( pTable->iDb==0 ){
1277       sqliteChangeCookie(db, v);
1278     }
1279     sqliteVdbeAddOp(v, OP_Close, 0, 0);
1280     if( !isView ){
1281       sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->iDb);
1282       for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){
1283         sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb);
1284       }
1285     }
1286     sqliteEndWriteOperation(pParse);
1287   }
1288 
1289   /* Delete the in-memory description of the table.
1290   **
1291   ** Exception: if the SQL statement began with the EXPLAIN keyword,
1292   ** then no changes should be made.
1293   */
1294   if( !pParse->explain ){
1295     sqliteUnlinkAndDeleteTable(db, pTable);
1296     db->flags |= SQLITE_InternChanges;
1297   }
1298   sqliteViewResetAll(db, iDb);
1299 }
1300 
1301 /*
1302 ** This routine constructs a P3 string suitable for an OP_MakeIdxKey
1303 ** opcode and adds that P3 string to the most recently inserted instruction
1304 ** in the virtual machine.  The P3 string consists of a single character
1305 ** for each column in the index pIdx of table pTab.  If the column uses
1306 ** a numeric sort order, then the P3 string character corresponding to
1307 ** that column is 'n'.  If the column uses a text sort order, then the
1308 ** P3 string is 't'.  See the OP_MakeIdxKey opcode documentation for
1309 ** additional information.  See also the sqliteAddKeyType() routine.
1310 */
sqliteAddIdxKeyType(Vdbe * v,Index * pIdx)1311 void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){
1312   char *zType;
1313   Table *pTab;
1314   int i, n;
1315   assert( pIdx!=0 && pIdx->pTable!=0 );
1316   pTab = pIdx->pTable;
1317   n = pIdx->nColumn;
1318   zType = sqliteMallocRaw( n+1 );
1319   if( zType==0 ) return;
1320   for(i=0; i<n; i++){
1321     int iCol = pIdx->aiColumn[i];
1322     assert( iCol>=0 && iCol<pTab->nCol );
1323     if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
1324       zType[i] = 't';
1325     }else{
1326       zType[i] = 'n';
1327     }
1328   }
1329   zType[n] = 0;
1330   sqliteVdbeChangeP3(v, -1, zType, n);
1331   sqliteFree(zType);
1332 }
1333 
1334 /*
1335 ** This routine is called to create a new foreign key on the table
1336 ** currently under construction.  pFromCol determines which columns
1337 ** in the current table point to the foreign key.  If pFromCol==0 then
1338 ** connect the key to the last column inserted.  pTo is the name of
1339 ** the table referred to.  pToCol is a list of tables in the other
1340 ** pTo table that the foreign key points to.  flags contains all
1341 ** information about the conflict resolution algorithms specified
1342 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1343 **
1344 ** An FKey structure is created and added to the table currently
1345 ** under construction in the pParse->pNewTable field.  The new FKey
1346 ** is not linked into db->aFKey at this point - that does not happen
1347 ** until sqliteEndTable().
1348 **
1349 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
1350 ** to sqliteDeferForeignKey() might change this to DEFERRED.
1351 */
sqliteCreateForeignKey(Parse * pParse,IdList * pFromCol,Token * pTo,IdList * pToCol,int flags)1352 void sqliteCreateForeignKey(
1353   Parse *pParse,       /* Parsing context */
1354   IdList *pFromCol,    /* Columns in this table that point to other table */
1355   Token *pTo,          /* Name of the other table */
1356   IdList *pToCol,      /* Columns in the other table */
1357   int flags            /* Conflict resolution algorithms. */
1358 ){
1359   Table *p = pParse->pNewTable;
1360   int nByte;
1361   int i;
1362   int nCol;
1363   char *z;
1364   FKey *pFKey = 0;
1365 
1366   assert( pTo!=0 );
1367   if( p==0 || pParse->nErr ) goto fk_end;
1368   if( pFromCol==0 ){
1369     int iCol = p->nCol-1;
1370     if( iCol<0 ) goto fk_end;
1371     if( pToCol && pToCol->nId!=1 ){
1372       sqliteErrorMsg(pParse, "foreign key on %s"
1373          " should reference only one column of table %T",
1374          p->aCol[iCol].zName, pTo);
1375       goto fk_end;
1376     }
1377     nCol = 1;
1378   }else if( pToCol && pToCol->nId!=pFromCol->nId ){
1379     sqliteErrorMsg(pParse,
1380         "number of columns in foreign key does not match the number of "
1381         "columns in the referenced table");
1382     goto fk_end;
1383   }else{
1384     nCol = pFromCol->nId;
1385   }
1386   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1387   if( pToCol ){
1388     for(i=0; i<pToCol->nId; i++){
1389       nByte += strlen(pToCol->a[i].zName) + 1;
1390     }
1391   }
1392   pFKey = sqliteMalloc( nByte );
1393   if( pFKey==0 ) goto fk_end;
1394   pFKey->pFrom = p;
1395   pFKey->pNextFrom = p->pFKey;
1396   z = (char*)&pFKey[1];
1397   pFKey->aCol = (struct sColMap*)z;
1398   z += sizeof(struct sColMap)*nCol;
1399   pFKey->zTo = z;
1400   memcpy(z, pTo->z, pTo->n);
1401   z[pTo->n] = 0;
1402   z += pTo->n+1;
1403   pFKey->pNextTo = 0;
1404   pFKey->nCol = nCol;
1405   if( pFromCol==0 ){
1406     pFKey->aCol[0].iFrom = p->nCol-1;
1407   }else{
1408     for(i=0; i<nCol; i++){
1409       int j;
1410       for(j=0; j<p->nCol; j++){
1411         if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
1412           pFKey->aCol[i].iFrom = j;
1413           break;
1414         }
1415       }
1416       if( j>=p->nCol ){
1417         sqliteErrorMsg(pParse,
1418           "unknown column \"%s\" in foreign key definition",
1419           pFromCol->a[i].zName);
1420         goto fk_end;
1421       }
1422     }
1423   }
1424   if( pToCol ){
1425     for(i=0; i<nCol; i++){
1426       int n = strlen(pToCol->a[i].zName);
1427       pFKey->aCol[i].zCol = z;
1428       memcpy(z, pToCol->a[i].zName, n);
1429       z[n] = 0;
1430       z += n+1;
1431     }
1432   }
1433   pFKey->isDeferred = 0;
1434   pFKey->deleteConf = flags & 0xff;
1435   pFKey->updateConf = (flags >> 8 ) & 0xff;
1436   pFKey->insertConf = (flags >> 16 ) & 0xff;
1437 
1438   /* Link the foreign key to the table as the last step.
1439   */
1440   p->pFKey = pFKey;
1441   pFKey = 0;
1442 
1443 fk_end:
1444   sqliteFree(pFKey);
1445   sqliteIdListDelete(pFromCol);
1446   sqliteIdListDelete(pToCol);
1447 }
1448 
1449 /*
1450 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1451 ** clause is seen as part of a foreign key definition.  The isDeferred
1452 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1453 ** The behavior of the most recently created foreign key is adjusted
1454 ** accordingly.
1455 */
sqliteDeferForeignKey(Parse * pParse,int isDeferred)1456 void sqliteDeferForeignKey(Parse *pParse, int isDeferred){
1457   Table *pTab;
1458   FKey *pFKey;
1459   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1460   pFKey->isDeferred = isDeferred;
1461 }
1462 
1463 /*
1464 ** Create a new index for an SQL table.  pIndex is the name of the index
1465 ** and pTable is the name of the table that is to be indexed.  Both will
1466 ** be NULL for a primary key or an index that is created to satisfy a
1467 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
1468 ** as the table to be indexed.  pParse->pNewTable is a table that is
1469 ** currently being constructed by a CREATE TABLE statement.
1470 **
1471 ** pList is a list of columns to be indexed.  pList will be NULL if this
1472 ** is a primary key or unique-constraint on the most recent column added
1473 ** to the table currently under construction.
1474 */
sqliteCreateIndex(Parse * pParse,Token * pName,SrcList * pTable,IdList * pList,int onError,Token * pStart,Token * pEnd)1475 void sqliteCreateIndex(
1476   Parse *pParse,   /* All information about this parse */
1477   Token *pName,    /* Name of the index.  May be NULL */
1478   SrcList *pTable, /* Name of the table to index.  Use pParse->pNewTable if 0 */
1479   IdList *pList,   /* A list of columns to be indexed */
1480   int onError,     /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1481   Token *pStart,   /* The CREATE token that begins a CREATE TABLE statement */
1482   Token *pEnd      /* The ")" that closes the CREATE INDEX statement */
1483 ){
1484   Table *pTab;     /* Table to be indexed */
1485   Index *pIndex;   /* The index to be created */
1486   char *zName = 0;
1487   int i, j;
1488   Token nullId;    /* Fake token for an empty ID list */
1489   DbFixer sFix;    /* For assigning database names to pTable */
1490   int isTemp;      /* True for a temporary index */
1491   sqlite *db = pParse->db;
1492 
1493   if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
1494   if( db->init.busy
1495      && sqliteFixInit(&sFix, pParse, db->init.iDb, "index", pName)
1496      && sqliteFixSrcList(&sFix, pTable)
1497   ){
1498     goto exit_create_index;
1499   }
1500 
1501   /*
1502   ** Find the table that is to be indexed.  Return early if not found.
1503   */
1504   if( pTable!=0 ){
1505     assert( pName!=0 );
1506     assert( pTable->nSrc==1 );
1507     pTab =  sqliteSrcListLookup(pParse, pTable);
1508   }else{
1509     assert( pName==0 );
1510     pTab =  pParse->pNewTable;
1511   }
1512   if( pTab==0 || pParse->nErr ) goto exit_create_index;
1513   if( pTab->readOnly ){
1514     sqliteErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
1515     goto exit_create_index;
1516   }
1517   if( pTab->iDb>=2 && db->init.busy==0 ){
1518     sqliteErrorMsg(pParse, "table %s may not have indices added", pTab->zName);
1519     goto exit_create_index;
1520   }
1521   if( pTab->pSelect ){
1522     sqliteErrorMsg(pParse, "views may not be indexed");
1523     goto exit_create_index;
1524   }
1525   isTemp = pTab->iDb==1;
1526 
1527   /*
1528   ** Find the name of the index.  Make sure there is not already another
1529   ** index or table with the same name.
1530   **
1531   ** Exception:  If we are reading the names of permanent indices from the
1532   ** sqlite_master table (because some other process changed the schema) and
1533   ** one of the index names collides with the name of a temporary table or
1534   ** index, then we will continue to process this index.
1535   **
1536   ** If pName==0 it means that we are
1537   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
1538   ** own name.
1539   */
1540   if( pName && !db->init.busy ){
1541     Index *pISameName;    /* Another index with the same name */
1542     Table *pTSameName;    /* A table with same name as the index */
1543     zName = sqliteTableNameFromToken(pName);
1544     if( zName==0 ) goto exit_create_index;
1545     if( (pISameName = sqliteFindIndex(db, zName, 0))!=0 ){
1546       sqliteErrorMsg(pParse, "index %s already exists", zName);
1547       goto exit_create_index;
1548     }
1549     if( (pTSameName = sqliteFindTable(db, zName, 0))!=0 ){
1550       sqliteErrorMsg(pParse, "there is already a table named %s", zName);
1551       goto exit_create_index;
1552     }
1553   }else if( pName==0 ){
1554     char zBuf[30];
1555     int n;
1556     Index *pLoop;
1557     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
1558     sprintf(zBuf,"%d)",n);
1559     zName = 0;
1560     sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, (char*)0);
1561     if( zName==0 ) goto exit_create_index;
1562   }else{
1563     zName = sqliteStrNDup(pName->z, pName->n);
1564   }
1565 
1566   /* Check for authorization to create an index.
1567   */
1568 #ifndef SQLITE_OMIT_AUTHORIZATION
1569   {
1570     const char *zDb = db->aDb[pTab->iDb].zName;
1571 
1572     assert( pTab->iDb==db->init.iDb || isTemp );
1573     if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1574       goto exit_create_index;
1575     }
1576     i = SQLITE_CREATE_INDEX;
1577     if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
1578     if( sqliteAuthCheck(pParse, i, zName, pTab->zName, zDb) ){
1579       goto exit_create_index;
1580     }
1581   }
1582 #endif
1583 
1584   /* If pList==0, it means this routine was called to make a primary
1585   ** key out of the last column added to the table under construction.
1586   ** So create a fake list to simulate this.
1587   */
1588   if( pList==0 ){
1589     nullId.z = pTab->aCol[pTab->nCol-1].zName;
1590     nullId.n = strlen(nullId.z);
1591     pList = sqliteIdListAppend(0, &nullId);
1592     if( pList==0 ) goto exit_create_index;
1593   }
1594 
1595   /*
1596   ** Allocate the index structure.
1597   */
1598   pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
1599                         sizeof(int)*pList->nId );
1600   if( pIndex==0 ) goto exit_create_index;
1601   pIndex->aiColumn = (int*)&pIndex[1];
1602   pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
1603   strcpy(pIndex->zName, zName);
1604   pIndex->pTable = pTab;
1605   pIndex->nColumn = pList->nId;
1606   pIndex->onError = onError;
1607   pIndex->autoIndex = pName==0;
1608   pIndex->iDb = isTemp ? 1 : db->init.iDb;
1609 
1610   /* Scan the names of the columns of the table to be indexed and
1611   ** load the column indices into the Index structure.  Report an error
1612   ** if any column is not found.
1613   */
1614   for(i=0; i<pList->nId; i++){
1615     for(j=0; j<pTab->nCol; j++){
1616       if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
1617     }
1618     if( j>=pTab->nCol ){
1619       sqliteErrorMsg(pParse, "table %s has no column named %s",
1620         pTab->zName, pList->a[i].zName);
1621       sqliteFree(pIndex);
1622       goto exit_create_index;
1623     }
1624     pIndex->aiColumn[i] = j;
1625   }
1626 
1627   /* Link the new Index structure to its table and to the other
1628   ** in-memory database structures.
1629   */
1630   if( !pParse->explain ){
1631     Index *p;
1632     p = sqliteHashInsert(&db->aDb[pIndex->iDb].idxHash,
1633                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
1634     if( p ){
1635       assert( p==pIndex );  /* Malloc must have failed */
1636       sqliteFree(pIndex);
1637       goto exit_create_index;
1638     }
1639     db->flags |= SQLITE_InternChanges;
1640   }
1641 
1642   /* When adding an index to the list of indices for a table, make
1643   ** sure all indices labeled OE_Replace come after all those labeled
1644   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
1645   ** and INSERT.
1646   */
1647   if( onError!=OE_Replace || pTab->pIndex==0
1648        || pTab->pIndex->onError==OE_Replace){
1649     pIndex->pNext = pTab->pIndex;
1650     pTab->pIndex = pIndex;
1651   }else{
1652     Index *pOther = pTab->pIndex;
1653     while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
1654       pOther = pOther->pNext;
1655     }
1656     pIndex->pNext = pOther->pNext;
1657     pOther->pNext = pIndex;
1658   }
1659 
1660   /* If the db->init.busy is 1 it means we are reading the SQL off the
1661   ** "sqlite_master" table on the disk.  So do not write to the disk
1662   ** again.  Extract the table number from the db->init.newTnum field.
1663   */
1664   if( db->init.busy && pTable!=0 ){
1665     pIndex->tnum = db->init.newTnum;
1666   }
1667 
1668   /* If the db->init.busy is 0 then create the index on disk.  This
1669   ** involves writing the index into the master table and filling in the
1670   ** index with the current table contents.
1671   **
1672   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
1673   ** command.  db->init.busy is 1 when a database is opened and
1674   ** CREATE INDEX statements are read out of the master table.  In
1675   ** the latter case the index already exists on disk, which is why
1676   ** we don't want to recreate it.
1677   **
1678   ** If pTable==0 it means this index is generated as a primary key
1679   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
1680   ** has just been created, it contains no data and the index initialization
1681   ** step can be skipped.
1682   */
1683   else if( db->init.busy==0 ){
1684     int n;
1685     Vdbe *v;
1686     int lbl1, lbl2;
1687     int i;
1688     int addr;
1689 
1690     v = sqliteGetVdbe(pParse);
1691     if( v==0 ) goto exit_create_index;
1692     if( pTable!=0 ){
1693       sqliteBeginWriteOperation(pParse, 0, isTemp);
1694       sqliteOpenMasterTable(v, isTemp);
1695     }
1696     sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
1697     sqliteVdbeOp3(v, OP_String, 0, 0, "index", P3_STATIC);
1698     sqliteVdbeOp3(v, OP_String, 0, 0, pIndex->zName, 0);
1699     sqliteVdbeOp3(v, OP_String, 0, 0, pTab->zName, 0);
1700     sqliteVdbeOp3(v, OP_CreateIndex, 0, isTemp,(char*)&pIndex->tnum,P3_POINTER);
1701     pIndex->tnum = 0;
1702     if( pTable ){
1703       sqliteVdbeCode(v,
1704           OP_Dup,       0,      0,
1705           OP_Integer,   isTemp, 0,
1706           OP_OpenWrite, 1,      0,
1707       0);
1708     }
1709     addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
1710     if( pStart && pEnd ){
1711       n = Addr(pEnd->z) - Addr(pStart->z) + 1;
1712       sqliteVdbeChangeP3(v, addr, pStart->z, n);
1713     }
1714     sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
1715     sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
1716     if( pTable ){
1717       sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
1718       sqliteVdbeOp3(v, OP_OpenRead, 2, pTab->tnum, pTab->zName, 0);
1719       lbl2 = sqliteVdbeMakeLabel(v);
1720       sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2);
1721       lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0);
1722       for(i=0; i<pIndex->nColumn; i++){
1723         int iCol = pIndex->aiColumn[i];
1724         if( pTab->iPKey==iCol ){
1725           sqliteVdbeAddOp(v, OP_Dup, i, 0);
1726         }else{
1727           sqliteVdbeAddOp(v, OP_Column, 2, iCol);
1728         }
1729       }
1730       sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0);
1731       if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex);
1732       sqliteVdbeOp3(v, OP_IdxPut, 1, pIndex->onError!=OE_None,
1733                       "indexed columns are not unique", P3_STATIC);
1734       sqliteVdbeAddOp(v, OP_Next, 2, lbl1);
1735       sqliteVdbeResolveLabel(v, lbl2);
1736       sqliteVdbeAddOp(v, OP_Close, 2, 0);
1737       sqliteVdbeAddOp(v, OP_Close, 1, 0);
1738     }
1739     if( pTable!=0 ){
1740       if( !isTemp ){
1741         sqliteChangeCookie(db, v);
1742       }
1743       sqliteVdbeAddOp(v, OP_Close, 0, 0);
1744       sqliteEndWriteOperation(pParse);
1745     }
1746   }
1747 
1748   /* Clean up before exiting */
1749 exit_create_index:
1750   sqliteIdListDelete(pList);
1751   sqliteSrcListDelete(pTable);
1752   sqliteFree(zName);
1753   return;
1754 }
1755 
1756 /*
1757 ** This routine will drop an existing named index.  This routine
1758 ** implements the DROP INDEX statement.
1759 */
sqliteDropIndex(Parse * pParse,SrcList * pName)1760 void sqliteDropIndex(Parse *pParse, SrcList *pName){
1761   Index *pIndex;
1762   Vdbe *v;
1763   sqlite *db = pParse->db;
1764 
1765   if( pParse->nErr || sqlite_malloc_failed ) return;
1766   assert( pName->nSrc==1 );
1767   pIndex = sqliteFindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
1768   if( pIndex==0 ){
1769     sqliteErrorMsg(pParse, "no such index: %S", pName, 0);
1770     goto exit_drop_index;
1771   }
1772   if( pIndex->autoIndex ){
1773     sqliteErrorMsg(pParse, "index associated with UNIQUE "
1774       "or PRIMARY KEY constraint cannot be dropped", 0);
1775     goto exit_drop_index;
1776   }
1777   if( pIndex->iDb>1 ){
1778     sqliteErrorMsg(pParse, "cannot alter schema of attached "
1779        "databases", 0);
1780     goto exit_drop_index;
1781   }
1782 #ifndef SQLITE_OMIT_AUTHORIZATION
1783   {
1784     int code = SQLITE_DROP_INDEX;
1785     Table *pTab = pIndex->pTable;
1786     const char *zDb = db->aDb[pIndex->iDb].zName;
1787     const char *zTab = SCHEMA_TABLE(pIndex->iDb);
1788     if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
1789       goto exit_drop_index;
1790     }
1791     if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
1792     if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
1793       goto exit_drop_index;
1794     }
1795   }
1796 #endif
1797 
1798   /* Generate code to remove the index and from the master table */
1799   v = sqliteGetVdbe(pParse);
1800   if( v ){
1801     static VdbeOpList dropIndex[] = {
1802       { OP_Rewind,     0, ADDR(9), 0},
1803       { OP_String,     0, 0,       0}, /* 1 */
1804       { OP_MemStore,   1, 1,       0},
1805       { OP_MemLoad,    1, 0,       0}, /* 3 */
1806       { OP_Column,     0, 1,       0},
1807       { OP_Eq,         0, ADDR(8), 0},
1808       { OP_Next,       0, ADDR(3), 0},
1809       { OP_Goto,       0, ADDR(9), 0},
1810       { OP_Delete,     0, 0,       0}, /* 8 */
1811     };
1812     int base;
1813 
1814     sqliteBeginWriteOperation(pParse, 0, pIndex->iDb);
1815     sqliteOpenMasterTable(v, pIndex->iDb);
1816     base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
1817     sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0);
1818     if( pIndex->iDb==0 ){
1819       sqliteChangeCookie(db, v);
1820     }
1821     sqliteVdbeAddOp(v, OP_Close, 0, 0);
1822     sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb);
1823     sqliteEndWriteOperation(pParse);
1824   }
1825 
1826   /* Delete the in-memory description of this index.
1827   */
1828   if( !pParse->explain ){
1829     sqliteUnlinkAndDeleteIndex(db, pIndex);
1830     db->flags |= SQLITE_InternChanges;
1831   }
1832 
1833 exit_drop_index:
1834   sqliteSrcListDelete(pName);
1835 }
1836 
1837 /*
1838 ** Append a new element to the given IdList.  Create a new IdList if
1839 ** need be.
1840 **
1841 ** A new IdList is returned, or NULL if malloc() fails.
1842 */
sqliteIdListAppend(IdList * pList,Token * pToken)1843 IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
1844   if( pList==0 ){
1845     pList = sqliteMalloc( sizeof(IdList) );
1846     if( pList==0 ) return 0;
1847     pList->nAlloc = 0;
1848   }
1849   if( pList->nId>=pList->nAlloc ){
1850     struct IdList_item *a;
1851     pList->nAlloc = pList->nAlloc*2 + 5;
1852     a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
1853     if( a==0 ){
1854       sqliteIdListDelete(pList);
1855       return 0;
1856     }
1857     pList->a = a;
1858   }
1859   memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
1860   if( pToken ){
1861     char **pz = &pList->a[pList->nId].zName;
1862     sqliteSetNString(pz, pToken->z, pToken->n, 0);
1863     if( *pz==0 ){
1864       sqliteIdListDelete(pList);
1865       return 0;
1866     }else{
1867       sqliteDequote(*pz);
1868     }
1869   }
1870   pList->nId++;
1871   return pList;
1872 }
1873 
1874 /*
1875 ** Append a new table name to the given SrcList.  Create a new SrcList if
1876 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
1877 **
1878 ** A new SrcList is returned, or NULL if malloc() fails.
1879 **
1880 ** If pDatabase is not null, it means that the table has an optional
1881 ** database name prefix.  Like this:  "database.table".  The pDatabase
1882 ** points to the table name and the pTable points to the database name.
1883 ** The SrcList.a[].zName field is filled with the table name which might
1884 ** come from pTable (if pDatabase is NULL) or from pDatabase.
1885 ** SrcList.a[].zDatabase is filled with the database name from pTable,
1886 ** or with NULL if no database is specified.
1887 **
1888 ** In other words, if call like this:
1889 **
1890 **         sqliteSrcListAppend(A,B,0);
1891 **
1892 ** Then B is a table name and the database name is unspecified.  If called
1893 ** like this:
1894 **
1895 **         sqliteSrcListAppend(A,B,C);
1896 **
1897 ** Then C is the table name and B is the database name.
1898 */
sqliteSrcListAppend(SrcList * pList,Token * pTable,Token * pDatabase)1899 SrcList *sqliteSrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
1900   if( pList==0 ){
1901     pList = sqliteMalloc( sizeof(SrcList) );
1902     if( pList==0 ) return 0;
1903     pList->nAlloc = 1;
1904   }
1905   if( pList->nSrc>=pList->nAlloc ){
1906     SrcList *pNew;
1907     pList->nAlloc *= 2;
1908     pNew = sqliteRealloc(pList,
1909                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
1910     if( pNew==0 ){
1911       sqliteSrcListDelete(pList);
1912       return 0;
1913     }
1914     pList = pNew;
1915   }
1916   memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
1917   if( pDatabase && pDatabase->z==0 ){
1918     pDatabase = 0;
1919   }
1920   if( pDatabase && pTable ){
1921     Token *pTemp = pDatabase;
1922     pDatabase = pTable;
1923     pTable = pTemp;
1924   }
1925   if( pTable ){
1926     char **pz = &pList->a[pList->nSrc].zName;
1927     sqliteSetNString(pz, pTable->z, pTable->n, 0);
1928     if( *pz==0 ){
1929       sqliteSrcListDelete(pList);
1930       return 0;
1931     }else{
1932       sqliteDequote(*pz);
1933     }
1934   }
1935   if( pDatabase ){
1936     char **pz = &pList->a[pList->nSrc].zDatabase;
1937     sqliteSetNString(pz, pDatabase->z, pDatabase->n, 0);
1938     if( *pz==0 ){
1939       sqliteSrcListDelete(pList);
1940       return 0;
1941     }else{
1942       sqliteDequote(*pz);
1943     }
1944   }
1945   pList->a[pList->nSrc].iCursor = -1;
1946   pList->nSrc++;
1947   return pList;
1948 }
1949 
1950 /*
1951 ** Assign cursors to all tables in a SrcList
1952 */
sqliteSrcListAssignCursors(Parse * pParse,SrcList * pList)1953 void sqliteSrcListAssignCursors(Parse *pParse, SrcList *pList){
1954   int i;
1955   for(i=0; i<pList->nSrc; i++){
1956     if( pList->a[i].iCursor<0 ){
1957       pList->a[i].iCursor = pParse->nTab++;
1958     }
1959   }
1960 }
1961 
1962 /*
1963 ** Add an alias to the last identifier on the given identifier list.
1964 */
sqliteSrcListAddAlias(SrcList * pList,Token * pToken)1965 void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){
1966   if( pList && pList->nSrc>0 ){
1967     int i = pList->nSrc - 1;
1968     sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
1969     sqliteDequote(pList->a[i].zAlias);
1970   }
1971 }
1972 
1973 /*
1974 ** Delete an IdList.
1975 */
sqliteIdListDelete(IdList * pList)1976 void sqliteIdListDelete(IdList *pList){
1977   int i;
1978   if( pList==0 ) return;
1979   for(i=0; i<pList->nId; i++){
1980     sqliteFree(pList->a[i].zName);
1981   }
1982   sqliteFree(pList->a);
1983   sqliteFree(pList);
1984 }
1985 
1986 /*
1987 ** Return the index in pList of the identifier named zId.  Return -1
1988 ** if not found.
1989 */
sqliteIdListIndex(IdList * pList,const char * zName)1990 int sqliteIdListIndex(IdList *pList, const char *zName){
1991   int i;
1992   if( pList==0 ) return -1;
1993   for(i=0; i<pList->nId; i++){
1994     if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i;
1995   }
1996   return -1;
1997 }
1998 
1999 /*
2000 ** Delete an entire SrcList including all its substructure.
2001 */
sqliteSrcListDelete(SrcList * pList)2002 void sqliteSrcListDelete(SrcList *pList){
2003   int i;
2004   if( pList==0 ) return;
2005   for(i=0; i<pList->nSrc; i++){
2006     sqliteFree(pList->a[i].zDatabase);
2007     sqliteFree(pList->a[i].zName);
2008     sqliteFree(pList->a[i].zAlias);
2009     if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
2010       sqliteDeleteTable(0, pList->a[i].pTab);
2011     }
2012     sqliteSelectDelete(pList->a[i].pSelect);
2013     sqliteExprDelete(pList->a[i].pOn);
2014     sqliteIdListDelete(pList->a[i].pUsing);
2015   }
2016   sqliteFree(pList);
2017 }
2018 
2019 /*
2020 ** Begin a transaction
2021 */
sqliteBeginTransaction(Parse * pParse,int onError)2022 void sqliteBeginTransaction(Parse *pParse, int onError){
2023   sqlite *db;
2024 
2025   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2026   if( pParse->nErr || sqlite_malloc_failed ) return;
2027   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
2028   if( db->flags & SQLITE_InTrans ){
2029     sqliteErrorMsg(pParse, "cannot start a transaction within a transaction");
2030     return;
2031   }
2032   sqliteBeginWriteOperation(pParse, 0, 0);
2033   if( !pParse->explain ){
2034     db->flags |= SQLITE_InTrans;
2035     db->onError = onError;
2036   }
2037 }
2038 
2039 /*
2040 ** Commit a transaction
2041 */
sqliteCommitTransaction(Parse * pParse)2042 void sqliteCommitTransaction(Parse *pParse){
2043   sqlite *db;
2044 
2045   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2046   if( pParse->nErr || sqlite_malloc_failed ) return;
2047   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
2048   if( (db->flags & SQLITE_InTrans)==0 ){
2049     sqliteErrorMsg(pParse, "cannot commit - no transaction is active");
2050     return;
2051   }
2052   if( !pParse->explain ){
2053     db->flags &= ~SQLITE_InTrans;
2054   }
2055   sqliteEndWriteOperation(pParse);
2056   if( !pParse->explain ){
2057     db->onError = OE_Default;
2058   }
2059 }
2060 
2061 /*
2062 ** Rollback a transaction
2063 */
sqliteRollbackTransaction(Parse * pParse)2064 void sqliteRollbackTransaction(Parse *pParse){
2065   sqlite *db;
2066   Vdbe *v;
2067 
2068   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
2069   if( pParse->nErr || sqlite_malloc_failed ) return;
2070   if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
2071   if( (db->flags & SQLITE_InTrans)==0 ){
2072     sqliteErrorMsg(pParse, "cannot rollback - no transaction is active");
2073     return;
2074   }
2075   v = sqliteGetVdbe(pParse);
2076   if( v ){
2077     sqliteVdbeAddOp(v, OP_Rollback, 0, 0);
2078   }
2079   if( !pParse->explain ){
2080     db->flags &= ~SQLITE_InTrans;
2081     db->onError = OE_Default;
2082   }
2083 }
2084 
2085 /*
2086 ** Generate VDBE code that will verify the schema cookie for all
2087 ** named database files.
2088 */
sqliteCodeVerifySchema(Parse * pParse,int iDb)2089 void sqliteCodeVerifySchema(Parse *pParse, int iDb){
2090   sqlite *db = pParse->db;
2091   Vdbe *v = sqliteGetVdbe(pParse);
2092   assert( iDb>=0 && iDb<db->nDb );
2093   assert( db->aDb[iDb].pBt!=0 );
2094   if( iDb!=1 && !DbHasProperty(db, iDb, DB_Cookie) ){
2095     sqliteVdbeAddOp(v, OP_VerifyCookie, iDb, db->aDb[iDb].schema_cookie);
2096     DbSetProperty(db, iDb, DB_Cookie);
2097   }
2098 }
2099 
2100 /*
2101 ** Generate VDBE code that prepares for doing an operation that
2102 ** might change the database.
2103 **
2104 ** This routine starts a new transaction if we are not already within
2105 ** a transaction.  If we are already within a transaction, then a checkpoint
2106 ** is set if the setCheckpoint parameter is true.  A checkpoint should
2107 ** be set for operations that might fail (due to a constraint) part of
2108 ** the way through and which will need to undo some writes without having to
2109 ** rollback the whole transaction.  For operations where all constraints
2110 ** can be checked before any changes are made to the database, it is never
2111 ** necessary to undo a write and the checkpoint should not be set.
2112 **
2113 ** Only database iDb and the temp database are made writable by this call.
2114 ** If iDb==0, then the main and temp databases are made writable.   If
2115 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
2116 ** specified auxiliary database and the temp database are made writable.
2117 */
sqliteBeginWriteOperation(Parse * pParse,int setCheckpoint,int iDb)2118 void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int iDb){
2119   Vdbe *v;
2120   sqlite *db = pParse->db;
2121   if( DbHasProperty(db, iDb, DB_Locked) ) return;
2122   v = sqliteGetVdbe(pParse);
2123   if( v==0 ) return;
2124   if( !db->aDb[iDb].inTrans ){
2125     sqliteVdbeAddOp(v, OP_Transaction, iDb, 0);
2126     DbSetProperty(db, iDb, DB_Locked);
2127     sqliteCodeVerifySchema(pParse, iDb);
2128     if( iDb!=1 ){
2129       sqliteBeginWriteOperation(pParse, setCheckpoint, 1);
2130     }
2131   }else if( setCheckpoint ){
2132     sqliteVdbeAddOp(v, OP_Checkpoint, iDb, 0);
2133     DbSetProperty(db, iDb, DB_Locked);
2134   }
2135 }
2136 
2137 /*
2138 ** Generate code that concludes an operation that may have changed
2139 ** the database.  If a statement transaction was started, then emit
2140 ** an OP_Commit that will cause the changes to be committed to disk.
2141 **
2142 ** Note that checkpoints are automatically committed at the end of
2143 ** a statement.  Note also that there can be multiple calls to
2144 ** sqliteBeginWriteOperation() but there should only be a single
2145 ** call to sqliteEndWriteOperation() at the conclusion of the statement.
2146 */
sqliteEndWriteOperation(Parse * pParse)2147 void sqliteEndWriteOperation(Parse *pParse){
2148   Vdbe *v;
2149   sqlite *db = pParse->db;
2150   if( pParse->trigStack ) return; /* if this is in a trigger */
2151   v = sqliteGetVdbe(pParse);
2152   if( v==0 ) return;
2153   if( db->flags & SQLITE_InTrans ){
2154     /* A BEGIN has executed.  Do not commit until we see an explicit
2155     ** COMMIT statement. */
2156   }else{
2157     sqliteVdbeAddOp(v, OP_Commit, 0, 0);
2158   }
2159 }
2160