monotone

monotone Mtn Source Tree

Root/sqlite/build.c

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

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status