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.159 2003/08/24 16:38:18 drh Exp $ 27 */ 28 #include "sqliteInt.h" 29 #include <ctype.h> 30 31 /* 32 ** This routine is called when a new SQL statement is beginning to 33 ** be parsed. Check to see if the schema for the database needs 34 ** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables. 35 ** If it does, then read it. 36 */ 37 void 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 */ 63 static 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 */ 77 void 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 */ 129 Table *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 */ 152 Table *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 */ 181 Index *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 */ 201 static 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 */ 219 void 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 */ 242 void 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 */ 305 void 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 */ 314 void 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 */ 334 void 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 */ 377 static 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 */ 405 char *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 */ 417 void 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 */ 439 void 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 */ 577 void 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 */ 613 void 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 */ 630 void 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 */ 666 void 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 */ 702 void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){ 703 Table *pTab = pParse->pNewTable; 704 char *zType = 0; 705 int iCol = -1, i; 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 pTab->aCol[iCol].isPrimKey = 1; 717 }else{ 718 for(i=0; i<pList->nId; i++){ 719 for(iCol=0; iCol<pTab->nCol; iCol++){ 720 if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break; 721 } 722 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1; 723 } 724 if( pList->nId>1 ) iCol = -1; 725 } 726 if( iCol>=0 && iCol<pTab->nCol ){ 727 zType = pTab->aCol[iCol].zType; 728 } 729 if( pParse->db->file_format>=1 && 730 zType && sqliteStrICmp(zType, "INTEGER")==0 ){ 731 pTab->iPKey = iCol; 732 pTab->keyConf = onError; 733 }else{ 734 sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0, 0); 735 pList = 0; 736 } 737 738 primary_key_exit: 739 sqliteIdListDelete(pList); 740 return; 741 } 742 743 /* 744 ** Return the appropriate collating type given a type name. 745 ** 746 ** The collation type is text (SQLITE_SO_TEXT) if the type 747 ** name contains the character stream "text" or "blob" or 748 ** "clob". Any other type name is collated as numeric 749 ** (SQLITE_SO_NUM). 750 */ 751 int sqliteCollateType(const char *zType, int nType){ 752 int i; 753 for(i=0; i<nType-1; i++){ 754 switch( zType[i] ){ 755 case 'b': 756 case 'B': { 757 if( i<nType-3 && sqliteStrNICmp(&zType[i],"blob",4)==0 ){ 758 return SQLITE_SO_TEXT; 759 } 760 break; 761 } 762 case 'c': 763 case 'C': { 764 if( i<nType-3 && (sqliteStrNICmp(&zType[i],"char",4)==0 || 765 sqliteStrNICmp(&zType[i],"clob",4)==0) 766 ){ 767 return SQLITE_SO_TEXT; 768 } 769 break; 770 } 771 case 'x': 772 case 'X': { 773 if( i>=2 && sqliteStrNICmp(&zType[i-2],"text",4)==0 ){ 774 return SQLITE_SO_TEXT; 775 } 776 break; 777 } 778 default: { 779 break; 780 } 781 } 782 } 783 return SQLITE_SO_NUM; 784 } 785 786 /* 787 ** This routine is called by the parser while in the middle of 788 ** parsing a CREATE TABLE statement. A "COLLATE" clause has 789 ** been seen on a column. This routine sets the Column.sortOrder on 790 ** the column currently under construction. 791 */ 792 void sqliteAddCollateType(Parse *pParse, int collType){ 793 Table *p; 794 int i; 795 if( (p = pParse->pNewTable)==0 ) return; 796 i = p->nCol-1; 797 if( i>=0 ) p->aCol[i].sortOrder = collType; 798 } 799 800 /* 801 ** Come up with a new random value for the schema cookie. Make sure 802 ** the new value is different from the old. 803 ** 804 ** The schema cookie is used to determine when the schema for the 805 ** database changes. After each schema change, the cookie value 806 ** changes. When a process first reads the schema it records the 807 ** cookie. Thereafter, whenever it goes to access the database, 808 ** it checks the cookie to make sure the schema has not changed 809 ** since it was last read. 810 ** 811 ** This plan is not completely bullet-proof. It is possible for 812 ** the schema to change multiple times and for the cookie to be 813 ** set back to prior value. But schema changes are infrequent 814 ** and the probability of hitting the same cookie value is only 815 ** 1 chance in 2^32. So we're safe enough. 816 */ 817 void sqliteChangeCookie(sqlite *db, Vdbe *v){ 818 if( db->next_cookie==db->aDb[0].schema_cookie ){ 819 db->next_cookie = db->aDb[0].schema_cookie + sqliteRandomByte() + 1; 820 db->flags |= SQLITE_InternChanges; 821 sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0); 822 sqliteVdbeAddOp(v, OP_SetCookie, 0, 0); 823 } 824 } 825 826 /* 827 ** Measure the number of characters needed to output the given 828 ** identifier. The number returned includes any quotes used 829 ** but does not include the null terminator. 830 */ 831 static int identLength(const char *z){ 832 int n; 833 int needQuote = 0; 834 for(n=0; *z; n++, z++){ 835 if( *z=='\'' ){ n++; needQuote=1; } 836 } 837 return n + needQuote*2; 838 } 839 840 /* 841 ** Write an identifier onto the end of the given string. Add 842 ** quote characters as needed. 843 */ 844 static void identPut(char *z, int *pIdx, char *zIdent){ 845 int i, j, needQuote; 846 i = *pIdx; 847 for(j=0; zIdent[j]; j++){ 848 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 849 } 850 needQuote = zIdent[j]!=0 || isdigit(zIdent[0]) 851 || sqliteKeywordCode(zIdent, j)!=TK_ID; 852 if( needQuote ) z[i++] = '\''; 853 for(j=0; zIdent[j]; j++){ 854 z[i++] = zIdent[j]; 855 if( zIdent[j]=='\'' ) z[i++] = '\''; 856 } 857 if( needQuote ) z[i++] = '\''; 858 z[i] = 0; 859 *pIdx = i; 860 } 861 862 /* 863 ** Generate a CREATE TABLE statement appropriate for the given 864 ** table. Memory to hold the text of the statement is obtained 865 ** from sqliteMalloc() and must be freed by the calling function. 866 */ 867 static char *createTableStmt(Table *p){ 868 int i, k, n; 869 char *zStmt; 870 char *zSep, *zSep2, *zEnd; 871 n = 0; 872 for(i=0; i<p->nCol; i++){ 873 n += identLength(p->aCol[i].zName); 874 } 875 n += identLength(p->zName); 876 if( n<40 ){ 877 zSep = ""; 878 zSep2 = ","; 879 zEnd = ")"; 880 }else{ 881 zSep = "\n "; 882 zSep2 = ",\n "; 883 zEnd = "\n)"; 884 } 885 n += 35 + 6*p->nCol; 886 zStmt = sqliteMallocRaw( n ); 887 if( zStmt==0 ) return 0; 888 strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE "); 889 k = strlen(zStmt); 890 identPut(zStmt, &k, p->zName); 891 zStmt[k++] = '('; 892 for(i=0; i<p->nCol; i++){ 893 strcpy(&zStmt[k], zSep); 894 k += strlen(&zStmt[k]); 895 zSep = zSep2; 896 identPut(zStmt, &k, p->aCol[i].zName); 897 } 898 strcpy(&zStmt[k], zEnd); 899 return zStmt; 900 } 901 902 /* 903 ** This routine is called to report the final ")" that terminates 904 ** a CREATE TABLE statement. 905 ** 906 ** The table structure that other action routines have been building 907 ** is added to the internal hash tables, assuming no errors have 908 ** occurred. 909 ** 910 ** An entry for the table is made in the master table on disk, 911 ** unless this is a temporary table or initFlag==1. When initFlag==1, 912 ** it means we are reading the sqlite_master table because we just 913 ** connected to the database or because the sqlite_master table has 914 ** recently changes, so the entry for this table already exists in 915 ** the sqlite_master table. We do not want to create it again. 916 ** 917 ** If the pSelect argument is not NULL, it means that this routine 918 ** was called to create a table generated from a 919 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 920 ** the new table will match the result set of the SELECT. 921 */ 922 void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){ 923 Table *p; 924 sqlite *db = pParse->db; 925 926 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return; 927 p = pParse->pNewTable; 928 if( p==0 ) return; 929 930 /* If the table is generated from a SELECT, then construct the 931 ** list of columns and the text of the table. 932 */ 933 if( pSelect ){ 934 Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect); 935 if( pSelTab==0 ) return; 936 assert( p->aCol==0 ); 937 p->nCol = pSelTab->nCol; 938 p->aCol = pSelTab->aCol; 939 pSelTab->nCol = 0; 940 pSelTab->aCol = 0; 941 sqliteDeleteTable(0, pSelTab); 942 } 943 944 /* If the initFlag is 1 it means we are reading the SQL off the 945 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 946 ** So do not write to the disk again. Extract the root page number 947 ** for the table from the pParse->newTnum field. (The page number 948 ** should have been put there by the sqliteOpenCb routine.) 949 */ 950 if( pParse->initFlag ){ 951 p->tnum = pParse->newTnum; 952 } 953 954 /* If not initializing, then create a record for the new table 955 ** in the SQLITE_MASTER table of the database. The record number 956 ** for the new table entry should already be on the stack. 957 ** 958 ** If this is a TEMPORARY table, write the entry into the auxiliary 959 ** file instead of into the main database file. 960 */ 961 if( !pParse->initFlag ){ 962 int n; 963 Vdbe *v; 964 965 v = sqliteGetVdbe(pParse); 966 if( v==0 ) return; 967 if( p->pSelect==0 ){ 968 /* A regular table */ 969 sqliteVdbeAddOp(v, OP_CreateTable, 0, p->iDb); 970 sqliteVdbeChangeP3(v, -1, (char *)&p->tnum, P3_POINTER); 971 }else{ 972 /* A view */ 973 sqliteVdbeAddOp(v, OP_Integer, 0, 0); 974 } 975 p->tnum = 0; 976 sqliteVdbeAddOp(v, OP_Pull, 1, 0); 977 sqliteVdbeAddOp(v, OP_String, 0, 0); 978 if( p->pSelect==0 ){ 979 sqliteVdbeChangeP3(v, -1, "table", P3_STATIC); 980 }else{ 981 sqliteVdbeChangeP3(v, -1, "view", P3_STATIC); 982 } 983 sqliteVdbeAddOp(v, OP_String, 0, 0); 984 sqliteVdbeChangeP3(v, -1, p->zName, P3_STATIC); 985 sqliteVdbeAddOp(v, OP_String, 0, 0); 986 sqliteVdbeChangeP3(v, -1, p->zName, P3_STATIC); 987 sqliteVdbeAddOp(v, OP_Dup, 4, 0); 988 sqliteVdbeAddOp(v, OP_String, 0, 0); 989 if( pSelect ){ 990 char *z = createTableStmt(p); 991 n = z ? strlen(z) : 0; 992 sqliteVdbeChangeP3(v, -1, z, n); 993 sqliteFree(z); 994 }else{ 995 assert( pEnd!=0 ); 996 n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1; 997 sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n); 998 } 999 sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0); 1000 sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0); 1001 if( !p->iDb ){ 1002 sqliteChangeCookie(db, v); 1003 } 1004 sqliteVdbeAddOp(v, OP_Close, 0, 0); 1005 if( pSelect ){ 1006 sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0); 1007 sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0); 1008 pParse->nTab = 2; 1009 sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0); 1010 } 1011 sqliteEndWriteOperation(pParse); 1012 } 1013 1014 /* Add the table to the in-memory representation of the database. 1015 */ 1016 if( pParse->explain==0 && pParse->nErr==0 ){ 1017 Table *pOld; 1018 FKey *pFKey; 1019 pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash, 1020 p->zName, strlen(p->zName)+1, p); 1021 if( pOld ){ 1022 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 1023 return; 1024 } 1025 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1026 int nTo = strlen(pFKey->zTo) + 1; 1027 pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo); 1028 sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey); 1029 } 1030 pParse->pNewTable = 0; 1031 db->nTable++; 1032 db->flags |= SQLITE_InternChanges; 1033 } 1034 } 1035 1036 /* 1037 ** The parser calls this routine in order to create a new VIEW 1038 */ 1039 void sqliteCreateView( 1040 Parse *pParse, /* The parsing context */ 1041 Token *pBegin, /* The CREATE token that begins the statement */ 1042 Token *pName, /* The token that holds the name of the view */ 1043 Select *pSelect, /* A SELECT statement that will become the new view */ 1044 int isTemp /* TRUE for a TEMPORARY view */ 1045 ){ 1046 Table *p; 1047 int n; 1048 const char *z; 1049 Token sEnd; 1050 DbFixer sFix; 1051 1052 sqliteStartTable(pParse, pBegin, pName, isTemp, 1); 1053 p = pParse->pNewTable; 1054 if( p==0 || pParse->nErr ){ 1055 sqliteSelectDelete(pSelect); 1056 return; 1057 } 1058 if( sqliteFixInit(&sFix, pParse, p->iDb, "view", pName) 1059 && sqliteFixSelect(&sFix, pSelect) 1060 ){ 1061 sqliteSelectDelete(pSelect); 1062 return; 1063 } 1064 1065 /* Make a copy of the entire SELECT statement that defines the view. 1066 ** This will force all the Expr.token.z values to be dynamically 1067 ** allocated rather than point to the input string - which means that 1068 ** they will persist after the current sqlite_exec() call returns. 1069 */ 1070 p->pSelect = sqliteSelectDup(pSelect); 1071 sqliteSelectDelete(pSelect); 1072 if( !pParse->initFlag ){ 1073 sqliteViewGetColumnNames(pParse, p); 1074 } 1075 1076 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 1077 ** the end. 1078 */ 1079 sEnd = pParse->sLastToken; 1080 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ 1081 sEnd.z += sEnd.n; 1082 } 1083 sEnd.n = 0; 1084 n = ((int)sEnd.z) - (int)pBegin->z; 1085 z = pBegin->z; 1086 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } 1087 sEnd.z = &z[n-1]; 1088 sEnd.n = 1; 1089 1090 /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */ 1091 sqliteEndTable(pParse, &sEnd, 0); 1092 return; 1093 } 1094 1095 /* 1096 ** The Table structure pTable is really a VIEW. Fill in the names of 1097 ** the columns of the view in the pTable structure. Return the number 1098 ** of errors. If an error is seen leave an error message in pPare->zErrMsg. 1099 */ 1100 int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){ 1101 ExprList *pEList; 1102 Select *pSel; 1103 Table *pSelTab; 1104 int nErr = 0; 1105 1106 assert( pTable ); 1107 1108 /* A positive nCol means the columns names for this view are 1109 ** already known. 1110 */ 1111 if( pTable->nCol>0 ) return 0; 1112 1113 /* A negative nCol is a special marker meaning that we are currently 1114 ** trying to compute the column names. If we enter this routine with 1115 ** a negative nCol, it means two or more views form a loop, like this: 1116 ** 1117 ** CREATE VIEW one AS SELECT * FROM two; 1118 ** CREATE VIEW two AS SELECT * FROM one; 1119 ** 1120 ** Actually, this error is caught previously and so the following test 1121 ** should always fail. But we will leave it in place just to be safe. 1122 */ 1123 if( pTable->nCol<0 ){ 1124 sqliteSetString(&pParse->zErrMsg, "view ", pTable->zName, 1125 " is circularly defined", 0); 1126 pParse->nErr++; 1127 return 1; 1128 } 1129 1130 /* If we get this far, it means we need to compute the table names. 1131 */ 1132 assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */ 1133 pSel = pTable->pSelect; 1134 1135 /* Note that the call to sqliteResultSetOfSelect() will expand any 1136 ** "*" elements in this list. But we will need to restore the list 1137 ** back to its original configuration afterwards, so we save a copy of 1138 ** the original in pEList. 1139 */ 1140 pEList = pSel->pEList; 1141 pSel->pEList = sqliteExprListDup(pEList); 1142 if( pSel->pEList==0 ){ 1143 pSel->pEList = pEList; 1144 return 1; /* Malloc failed */ 1145 } 1146 pTable->nCol = -1; 1147 pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel); 1148 if( pSelTab ){ 1149 assert( pTable->aCol==0 ); 1150 pTable->nCol = pSelTab->nCol; 1151 pTable->aCol = pSelTab->aCol; 1152 pSelTab->nCol = 0; 1153 pSelTab->aCol = 0; 1154 sqliteDeleteTable(0, pSelTab); 1155 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews); 1156 }else{ 1157 pTable->nCol = 0; 1158 nErr++; 1159 } 1160 sqliteSelectUnbind(pSel); 1161 sqliteExprListDelete(pSel->pEList); 1162 pSel->pEList = pEList; 1163 return nErr; 1164 } 1165 1166 /* 1167 ** Clear the column names from the VIEW pTable. 1168 ** 1169 ** This routine is called whenever any other table or view is modified. 1170 ** The view passed into this routine might depend directly or indirectly 1171 ** on the modified or deleted table so we need to clear the old column 1172 ** names so that they will be recomputed. 1173 */ 1174 static void sqliteViewResetColumnNames(Table *pTable){ 1175 int i; 1176 if( pTable==0 || pTable->pSelect==0 ) return; 1177 if( pTable->nCol==0 ) return; 1178 for(i=0; i<pTable->nCol; i++){ 1179 sqliteFree(pTable->aCol[i].zName); 1180 sqliteFree(pTable->aCol[i].zDflt); 1181 sqliteFree(pTable->aCol[i].zType); 1182 } 1183 sqliteFree(pTable->aCol); 1184 pTable->aCol = 0; 1185 pTable->nCol = 0; 1186 } 1187 1188 /* 1189 ** Clear the column names from every VIEW in database idx. 1190 */ 1191 static void sqliteViewResetAll(sqlite *db, int idx){ 1192 HashElem *i; 1193 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 1194 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){ 1195 Table *pTab = sqliteHashData(i); 1196 if( pTab->pSelect ){ 1197 sqliteViewResetColumnNames(pTab); 1198 } 1199 } 1200 DbClearProperty(db, idx, DB_UnresetViews); 1201 } 1202 1203 /* 1204 ** Given a token, look up a table with that name. If not found, leave 1205 ** an error for the parser to find and return NULL. 1206 */ 1207 Table *sqliteTableFromToken(Parse *pParse, Token *pTok){ 1208 char *zName; 1209 Table *pTab; 1210 zName = sqliteTableNameFromToken(pTok); 1211 if( zName==0 ) return 0; 1212 pTab = sqliteFindTable(pParse->db, zName, 0); 1213 sqliteFree(zName); 1214 if( pTab==0 ){ 1215 sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0, 1216 pTok->z, pTok->n, 0); 1217 pParse->nErr++; 1218 } 1219 return pTab; 1220 } 1221 1222 /* 1223 ** This routine is called to do the work of a DROP TABLE statement. 1224 ** pName is the name of the table to be dropped. 1225 */ 1226 void sqliteDropTable(Parse *pParse, Token *pName, int isView){ 1227 Table *pTable; 1228 Vdbe *v; 1229 int base; 1230 sqlite *db = pParse->db; 1231 int iDb; 1232 1233 if( pParse->nErr || sqlite_malloc_failed ) return; 1234 pTable = sqliteTableFromToken(pParse, pName); 1235 if( pTable==0 ) return; 1236 iDb = pTable->iDb; 1237 assert( iDb>=0 && iDb<db->nDb ); 1238 #ifndef SQLITE_OMIT_AUTHORIZATION 1239 { 1240 int code; 1241 const char *zTab = SCHEMA_TABLE(pTable->iDb); 1242 const char *zDb = db->aDb[pTable->iDb].zName; 1243 if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 1244 return; 1245 } 1246 if( isView ){ 1247 if( iDb==1 ){ 1248 code = SQLITE_DROP_TEMP_VIEW; 1249 }else{ 1250 code = SQLITE_DROP_VIEW; 1251 } 1252 }else{ 1253 if( iDb==1 ){ 1254 code = SQLITE_DROP_TEMP_TABLE; 1255 }else{ 1256 code = SQLITE_DROP_TABLE; 1257 } 1258 } 1259 if( sqliteAuthCheck(pParse, code, pTable->zName, 0, zDb) ){ 1260 return; 1261 } 1262 if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0, zDb) ){ 1263 return; 1264 } 1265 } 1266 #endif 1267 if( pTable->readOnly ){ 1268 sqliteSetString(&pParse->zErrMsg, "table ", pTable->zName, 1269 " may not be dropped", 0); 1270 pParse->nErr++; 1271 return; 1272 } 1273 if( isView && pTable->pSelect==0 ){ 1274 sqliteSetString(&pParse->zErrMsg, "use DROP TABLE to delete table ", 1275 pTable->zName, 0); 1276 pParse->nErr++; 1277 return; 1278 } 1279 if( !isView && pTable->pSelect ){ 1280 sqliteSetString(&pParse->zErrMsg, "use DROP VIEW to delete view ", 1281 pTable->zName, 0); 1282 pParse->nErr++; 1283 return; 1284 } 1285 1286 /* Generate code to remove the table from the master table 1287 ** on disk. 1288 */ 1289 v = sqliteGetVdbe(pParse); 1290 if( v ){ 1291 static VdbeOp dropTable[] = { 1292 { OP_Rewind, 0, ADDR(8), 0}, 1293 { OP_String, 0, 0, 0}, /* 1 */ 1294 { OP_MemStore, 1, 1, 0}, 1295 { OP_MemLoad, 1, 0, 0}, /* 3 */ 1296 { OP_Column, 0, 2, 0}, 1297 { OP_Ne, 0, ADDR(7), 0}, 1298 { OP_Delete, 0, 0, 0}, 1299 { OP_Next, 0, ADDR(3), 0}, /* 7 */ 1300 }; 1301 Index *pIdx; 1302 Trigger *pTrigger; 1303 sqliteBeginWriteOperation(pParse, 0, pTable->iDb); 1304 1305 /* Drop all triggers associated with the table being dropped */ 1306 pTrigger = pTable->pTrigger; 1307 while( pTrigger ){ 1308 assert( pTrigger->iDb==pTable->iDb || pTrigger->iDb==1 ); 1309 sqliteDropTriggerPtr(pParse, pTrigger, 1); 1310 if( pParse->explain ){ 1311 pTrigger = pTrigger->pNext; 1312 }else{ 1313 pTrigger = pTable->pTrigger; 1314 } 1315 } 1316 1317 /* Drop all SQLITE_MASTER entries that refer to the table */ 1318 sqliteOpenMasterTable(v, pTable->iDb); 1319 base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable); 1320 sqliteVdbeChangeP3(v, base+1, pTable->zName, 0); 1321 1322 /* Drop all SQLITE_TEMP_MASTER entries that refer to the table */ 1323 if( pTable->iDb!=1 ){ 1324 sqliteOpenMasterTable(v, 1); 1325 base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable); 1326 sqliteVdbeChangeP3(v, base+1, pTable->zName, 0); 1327 } 1328 1329 if( pTable->iDb==0 ){ 1330 sqliteChangeCookie(db, v); 1331 } 1332 sqliteVdbeAddOp(v, OP_Close, 0, 0); 1333 if( !isView ){ 1334 sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->iDb); 1335 for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){ 1336 sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb); 1337 } 1338 } 1339 sqliteEndWriteOperation(pParse); 1340 } 1341 1342 /* Delete the in-memory description of the table. 1343 ** 1344 ** Exception: if the SQL statement began with the EXPLAIN keyword, 1345 ** then no changes should be made. 1346 */ 1347 if( !pParse->explain ){ 1348 sqliteUnlinkAndDeleteTable(db, pTable); 1349 db->flags |= SQLITE_InternChanges; 1350 } 1351 sqliteViewResetAll(db, iDb); 1352 } 1353 1354 /* 1355 ** This routine constructs a P3 string suitable for an OP_MakeIdxKey 1356 ** opcode and adds that P3 string to the most recently inserted instruction 1357 ** in the virtual machine. The P3 string consists of a single character 1358 ** for each column in the index pIdx of table pTab. If the column uses 1359 ** a numeric sort order, then the P3 string character corresponding to 1360 ** that column is 'n'. If the column uses a text sort order, then the 1361 ** P3 string is 't'. See the OP_MakeIdxKey opcode documentation for 1362 ** additional information. See also the sqliteAddKeyType() routine. 1363 */ 1364 void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){ 1365 char *zType; 1366 Table *pTab; 1367 int i, n; 1368 assert( pIdx!=0 && pIdx->pTable!=0 ); 1369 pTab = pIdx->pTable; 1370 n = pIdx->nColumn; 1371 zType = sqliteMallocRaw( n+1 ); 1372 if( zType==0 ) return; 1373 for(i=0; i<n; i++){ 1374 int iCol = pIdx->aiColumn[i]; 1375 assert( iCol>=0 && iCol<pTab->nCol ); 1376 if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){ 1377 zType[i] = 't'; 1378 }else{ 1379 zType[i] = 'n'; 1380 } 1381 } 1382 zType[n] = 0; 1383 sqliteVdbeChangeP3(v, -1, zType, n); 1384 sqliteFree(zType); 1385 } 1386 1387 /* 1388 ** This routine is called to create a new foreign key on the table 1389 ** currently under construction. pFromCol determines which columns 1390 ** in the current table point to the foreign key. If pFromCol==0 then 1391 ** connect the key to the last column inserted. pTo is the name of 1392 ** the table referred to. pToCol is a list of tables in the other 1393 ** pTo table that the foreign key points to. flags contains all 1394 ** information about the conflict resolution algorithms specified 1395 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 1396 ** 1397 ** An FKey structure is created and added to the table currently 1398 ** under construction in the pParse->pNewTable field. The new FKey 1399 ** is not linked into db->aFKey at this point - that does not happen 1400 ** until sqliteEndTable(). 1401 ** 1402 ** The foreign key is set for IMMEDIATE processing. A subsequent call 1403 ** to sqliteDeferForeignKey() might change this to DEFERRED. 1404 */ 1405 void sqliteCreateForeignKey( 1406 Parse *pParse, /* Parsing context */ 1407 IdList *pFromCol, /* Columns in this table that point to other table */ 1408 Token *pTo, /* Name of the other table */ 1409 IdList *pToCol, /* Columns in the other table */ 1410 int flags /* Conflict resolution algorithms. */ 1411 ){ 1412 Table *p = pParse->pNewTable; 1413 int nByte; 1414 int i; 1415 int nCol; 1416 char *z; 1417 FKey *pFKey = 0; 1418 1419 assert( pTo!=0 ); 1420 if( p==0 || pParse->nErr ) goto fk_end; 1421 if( pFromCol==0 ){ 1422 int iCol = p->nCol-1; 1423 if( iCol<0 ) goto fk_end; 1424 if( pToCol && pToCol->nId!=1 ){ 1425 sqliteSetNString(&pParse->zErrMsg, "foreign key on ", -1, 1426 p->aCol[iCol].zName, -1, 1427 " should reference only one column of table ", -1, 1428 pTo->z, pTo->n, 0); 1429 pParse->nErr++; 1430 goto fk_end; 1431 } 1432 nCol = 1; 1433 }else if( pToCol && pToCol->nId!=pFromCol->nId ){ 1434 sqliteSetString(&pParse->zErrMsg, 1435 "number of columns in foreign key does not match the number of " 1436 "columns in the referenced table", 0); 1437 pParse->nErr++; 1438 goto fk_end; 1439 }else{ 1440 nCol = pFromCol->nId; 1441 } 1442 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; 1443 if( pToCol ){ 1444 for(i=0; i<pToCol->nId; i++){ 1445 nByte += strlen(pToCol->a[i].zName) + 1; 1446 } 1447 } 1448 pFKey = sqliteMalloc( nByte ); 1449 if( pFKey==0 ) goto fk_end; 1450 pFKey->pFrom = p; 1451 pFKey->pNextFrom = p->pFKey; 1452 z = (char*)&pFKey[1]; 1453 pFKey->aCol = (struct sColMap*)z; 1454 z += sizeof(struct sColMap)*nCol; 1455 pFKey->zTo = z; 1456 memcpy(z, pTo->z, pTo->n); 1457 z[pTo->n] = 0; 1458 z += pTo->n+1; 1459 pFKey->pNextTo = 0; 1460 pFKey->nCol = nCol; 1461 if( pFromCol==0 ){ 1462 pFKey->aCol[0].iFrom = p->nCol-1; 1463 }else{ 1464 for(i=0; i<nCol; i++){ 1465 int j; 1466 for(j=0; j<p->nCol; j++){ 1467 if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 1468 pFKey->aCol[i].iFrom = j; 1469 break; 1470 } 1471 } 1472 if( j>=p->nCol ){ 1473 sqliteSetString(&pParse->zErrMsg, "unknown column \"", 1474 pFromCol->a[i].zName, "\" in foreign key definition", 0); 1475 pParse->nErr++; 1476 goto fk_end; 1477 } 1478 } 1479 } 1480 if( pToCol ){ 1481 for(i=0; i<nCol; i++){ 1482 int n = strlen(pToCol->a[i].zName); 1483 pFKey->aCol[i].zCol = z; 1484 memcpy(z, pToCol->a[i].zName, n); 1485 z[n] = 0; 1486 z += n+1; 1487 } 1488 } 1489 pFKey->isDeferred = 0; 1490 pFKey->deleteConf = flags & 0xff; 1491 pFKey->updateConf = (flags >> 8 ) & 0xff; 1492 pFKey->insertConf = (flags >> 16 ) & 0xff; 1493 1494 /* Link the foreign key to the table as the last step. 1495 */ 1496 p->pFKey = pFKey; 1497 pFKey = 0; 1498 1499 fk_end: 1500 sqliteFree(pFKey); 1501 sqliteIdListDelete(pFromCol); 1502 sqliteIdListDelete(pToCol); 1503 } 1504 1505 /* 1506 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 1507 ** clause is seen as part of a foreign key definition. The isDeferred 1508 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 1509 ** The behavior of the most recently created foreign key is adjusted 1510 ** accordingly. 1511 */ 1512 void sqliteDeferForeignKey(Parse *pParse, int isDeferred){ 1513 Table *pTab; 1514 FKey *pFKey; 1515 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 1516 pFKey->isDeferred = isDeferred; 1517 } 1518 1519 /* 1520 ** Create a new index for an SQL table. pIndex is the name of the index 1521 ** and pTable is the name of the table that is to be indexed. Both will 1522 ** be NULL for a primary key or an index that is created to satisfy a 1523 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 1524 ** as the table to be indexed. pParse->pNewTable is a table that is 1525 ** currently being constructed by a CREATE TABLE statement. 1526 ** 1527 ** pList is a list of columns to be indexed. pList will be NULL if this 1528 ** is a primary key or unique-constraint on the most recent column added 1529 ** to the table currently under construction. 1530 */ 1531 void sqliteCreateIndex( 1532 Parse *pParse, /* All information about this parse */ 1533 Token *pName, /* Name of the index. May be NULL */ 1534 SrcList *pTable, /* Name of the table to index. Use pParse->pNewTable if 0 */ 1535 IdList *pList, /* A list of columns to be indexed */ 1536 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 1537 int isTemp, /* True if this is a temporary index */ 1538 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */ 1539 Token *pEnd /* The ")" that closes the CREATE INDEX statement */ 1540 ){ 1541 Table *pTab; /* Table to be indexed */ 1542 Index *pIndex; /* The index to be created */ 1543 char *zName = 0; 1544 int i, j; 1545 Token nullId; /* Fake token for an empty ID list */ 1546 DbFixer sFix; /* For assigning database names to pTable */ 1547 sqlite *db = pParse->db; 1548 1549 if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index; 1550 if( !isTemp && pParse->initFlag 1551 && sqliteFixInit(&sFix, pParse, pParse->iDb, "index", pName) 1552 && sqliteFixSrcList(&sFix, pTable) 1553 ){ 1554 goto exit_create_index; 1555 } 1556 1557 /* 1558 ** Find the table that is to be indexed. Return early if not found. 1559 */ 1560 if( pTable!=0 ){ 1561 assert( pName!=0 ); 1562 assert( pTable->nSrc==1 ); 1563 pTab = sqliteSrcListLookup(pParse, pTable); 1564 }else{ 1565 assert( pName==0 ); 1566 pTab = pParse->pNewTable; 1567 } 1568 if( pTab==0 || pParse->nErr ) goto exit_create_index; 1569 if( pTab->readOnly ){ 1570 sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName, 1571 " may not be indexed", 0); 1572 pParse->nErr++; 1573 goto exit_create_index; 1574 } 1575 if( !isTemp && pTab->iDb>=2 && pParse->initFlag==0 ){ 1576 sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName, 1577 " may not have non-temporary indices added", 0); 1578 pParse->nErr++; 1579 goto exit_create_index; 1580 } 1581 if( pTab->pSelect ){ 1582 sqliteSetString(&pParse->zErrMsg, "views may not be indexed", 0); 1583 pParse->nErr++; 1584 goto exit_create_index; 1585 } 1586 if( pTab->iDb==1 ){ 1587 isTemp = 1; 1588 } 1589 1590 /* 1591 ** Find the name of the index. Make sure there is not already another 1592 ** index or table with the same name. 1593 ** 1594 ** Exception: If we are reading the names of permanent indices from the 1595 ** sqlite_master table (because some other process changed the schema) and 1596 ** one of the index names collides with the name of a temporary table or 1597 ** index, then we will continue to process this index. 1598 ** 1599 ** If pName==0 it means that we are 1600 ** dealing with a primary key or UNIQUE constraint. We have to invent our 1601 ** own name. 1602 */ 1603 if( pName && !pParse->initFlag ){ 1604 Index *pISameName; /* Another index with the same name */ 1605 Table *pTSameName; /* A table with same name as the index */ 1606 zName = sqliteStrNDup(pName->z, pName->n); 1607 if( zName==0 ) goto exit_create_index; 1608 if( (pISameName = sqliteFindIndex(db, zName, 0))!=0 ){ 1609 sqliteSetString(&pParse->zErrMsg, "index ", zName, 1610 " already exists", 0); 1611 pParse->nErr++; 1612 goto exit_create_index; 1613 } 1614 if( (pTSameName = sqliteFindTable(db, zName, 0))!=0 ){ 1615 sqliteSetString(&pParse->zErrMsg, "there is already a table named ", 1616 zName, 0); 1617 pParse->nErr++; 1618 goto exit_create_index; 1619 } 1620 }else if( pName==0 ){ 1621 char zBuf[30]; 1622 int n; 1623 Index *pLoop; 1624 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 1625 sprintf(zBuf,"%d)",n); 1626 zName = 0; 1627 sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, 0); 1628 if( zName==0 ) goto exit_create_index; 1629 }else{ 1630 zName = sqliteStrNDup(pName->z, pName->n); 1631 } 1632 1633 /* Check for authorization to create an index. 1634 */ 1635 #ifndef SQLITE_OMIT_AUTHORIZATION 1636 { 1637 const char *zDb = db->aDb[pTab->iDb].zName; 1638 1639 assert( isTemp==0 || isTemp==1 ); 1640 assert( pTab->iDb==pParse->iDb || isTemp==1 ); 1641 if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 1642 goto exit_create_index; 1643 } 1644 i = SQLITE_CREATE_INDEX; 1645 if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX; 1646 if( sqliteAuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 1647 goto exit_create_index; 1648 } 1649 } 1650 #endif 1651 1652 /* If pList==0, it means this routine was called to make a primary 1653 ** key out of the last column added to the table under construction. 1654 ** So create a fake list to simulate this. 1655 */ 1656 if( pList==0 ){ 1657 nullId.z = pTab->aCol[pTab->nCol-1].zName; 1658 nullId.n = strlen(nullId.z); 1659 pList = sqliteIdListAppend(0, &nullId); 1660 if( pList==0 ) goto exit_create_index; 1661 } 1662 1663 /* 1664 ** Allocate the index structure. 1665 */ 1666 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + 1667 sizeof(int)*pList->nId ); 1668 if( pIndex==0 ) goto exit_create_index; 1669 pIndex->aiColumn = (int*)&pIndex[1]; 1670 pIndex->zName = (char*)&pIndex->aiColumn[pList->nId]; 1671 strcpy(pIndex->zName, zName); 1672 pIndex->pTable = pTab; 1673 pIndex->nColumn = pList->nId; 1674 pIndex->onError = onError; 1675 pIndex->autoIndex = pName==0; 1676 pIndex->iDb = isTemp ? 1 : pParse->iDb; 1677 1678 /* Scan the names of the columns of the table to be indexed and 1679 ** load the column indices into the Index structure. Report an error 1680 ** if any column is not found. 1681 */ 1682 for(i=0; i<pList->nId; i++){ 1683 for(j=0; j<pTab->nCol; j++){ 1684 if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break; 1685 } 1686 if( j>=pTab->nCol ){ 1687 sqliteSetString(&pParse->zErrMsg, "table ", pTab->zName, 1688 " has no column named ", pList->a[i].zName, 0); 1689 pParse->nErr++; 1690 sqliteFree(pIndex); 1691 goto exit_create_index; 1692 } 1693 pIndex->aiColumn[i] = j; 1694 } 1695 1696 /* Link the new Index structure to its table and to the other 1697 ** in-memory database structures. 1698 */ 1699 if( !pParse->explain ){ 1700 Index *p; 1701 p = sqliteHashInsert(&db->aDb[pIndex->iDb].idxHash, 1702 pIndex->zName, strlen(pIndex->zName)+1, pIndex); 1703 if( p ){ 1704 assert( p==pIndex ); /* Malloc must have failed */ 1705 sqliteFree(pIndex); 1706 goto exit_create_index; 1707 } 1708 db->flags |= SQLITE_InternChanges; 1709 } 1710 1711 /* When adding an index to the list of indices for a table, make 1712 ** sure all indices labeled OE_Replace come after all those labeled 1713 ** OE_Ignore. This is necessary for the correct operation of UPDATE 1714 ** and INSERT. 1715 */ 1716 if( onError!=OE_Replace || pTab->pIndex==0 1717 || pTab->pIndex->onError==OE_Replace){ 1718 pIndex->pNext = pTab->pIndex; 1719 pTab->pIndex = pIndex; 1720 }else{ 1721 Index *pOther = pTab->pIndex; 1722 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 1723 pOther = pOther->pNext; 1724 } 1725 pIndex->pNext = pOther->pNext; 1726 pOther->pNext = pIndex; 1727 } 1728 1729 /* If the initFlag is 1 it means we are reading the SQL off the 1730 ** "sqlite_master" table on the disk. So do not write to the disk 1731 ** again. Extract the table number from the pParse->newTnum field. 1732 */ 1733 if( pParse->initFlag && pTable!=0 ){ 1734 pIndex->tnum = pParse->newTnum; 1735 } 1736 1737 /* If the initFlag is 0 then create the index on disk. This 1738 ** involves writing the index into the master table and filling in the 1739 ** index with the current table contents. 1740 ** 1741 ** The initFlag is 0 when the user first enters a CREATE INDEX 1742 ** command. The initFlag is 1 when a database is opened and 1743 ** CREATE INDEX statements are read out of the master table. In 1744 ** the latter case the index already exists on disk, which is why 1745 ** we don't want to recreate it. 1746 ** 1747 ** If pTable==0 it means this index is generated as a primary key 1748 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table 1749 ** has just been created, it contains no data and the index initialization 1750 ** step can be skipped. 1751 */ 1752 else if( pParse->initFlag==0 ){ 1753 int n; 1754 Vdbe *v; 1755 int lbl1, lbl2; 1756 int i; 1757 int addr; 1758 1759 v = sqliteGetVdbe(pParse); 1760 if( v==0 ) goto exit_create_index; 1761 if( pTable!=0 ){ 1762 sqliteBeginWriteOperation(pParse, 0, isTemp); 1763 sqliteOpenMasterTable(v, isTemp); 1764 } 1765 sqliteVdbeAddOp(v, OP_NewRecno, 0, 0); 1766 sqliteVdbeAddOp(v, OP_String, 0, 0); 1767 sqliteVdbeChangeP3(v, -1, "index", P3_STATIC); 1768 sqliteVdbeAddOp(v, OP_String, 0, 0); 1769 sqliteVdbeChangeP3(v, -1, pIndex->zName, P3_STATIC); 1770 sqliteVdbeAddOp(v, OP_String, 0, 0); 1771 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC); 1772 addr = sqliteVdbeAddOp(v, OP_CreateIndex, 0, isTemp); 1773 sqliteVdbeChangeP3(v, addr, (char*)&pIndex->tnum, P3_POINTER); 1774 pIndex->tnum = 0; 1775 if( pTable ){ 1776 sqliteVdbeAddOp(v, OP_Dup, 0, 0); 1777 sqliteVdbeAddOp(v, OP_Integer, isTemp, 0); 1778 sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0); 1779 } 1780 addr = sqliteVdbeAddOp(v, OP_String, 0, 0); 1781 if( pStart && pEnd ){ 1782 n = Addr(pEnd->z) - Addr(pStart->z) + 1; 1783 sqliteVdbeChangeP3(v, addr, pStart->z, n); 1784 } 1785 sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0); 1786 sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0); 1787 if( pTable ){ 1788 sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0); 1789 sqliteVdbeAddOp(v, OP_OpenRead, 2, pTab->tnum); 1790 sqliteVdbeChangeP3(v, -1, pTab->zName, P3_STATIC); 1791 lbl2 = sqliteVdbeMakeLabel(v); 1792 sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2); 1793 lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0); 1794 for(i=0; i<pIndex->nColumn; i++){ 1795 int iCol = pIndex->aiColumn[i]; 1796 if( pTab->iPKey==iCol ){ 1797 sqliteVdbeAddOp(v, OP_Dup, i, 0); 1798 }else{ 1799 sqliteVdbeAddOp(v, OP_Column, 2, iCol); 1800 } 1801 } 1802 sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0); 1803 if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex); 1804 sqliteVdbeAddOp(v, OP_IdxPut, 1, pIndex->onError!=OE_None); 1805 sqliteVdbeChangeP3(v, -1, "indexed columns are not unique", P3_STATIC); 1806 sqliteVdbeAddOp(v, OP_Next, 2, lbl1); 1807 sqliteVdbeResolveLabel(v, lbl2); 1808 sqliteVdbeAddOp(v, OP_Close, 2, 0); 1809 sqliteVdbeAddOp(v, OP_Close, 1, 0); 1810 } 1811 if( pTable!=0 ){ 1812 if( !isTemp ){ 1813 sqliteChangeCookie(db, v); 1814 } 1815 sqliteVdbeAddOp(v, OP_Close, 0, 0); 1816 sqliteEndWriteOperation(pParse); 1817 } 1818 } 1819 1820 /* Clean up before exiting */ 1821 exit_create_index: 1822 sqliteIdListDelete(pList); 1823 sqliteSrcListDelete(pTable); 1824 sqliteFree(zName); 1825 return; 1826 } 1827 1828 /* 1829 ** This routine will drop an existing named index. This routine 1830 ** implements the DROP INDEX statement. 1831 */ 1832 void sqliteDropIndex(Parse *pParse, SrcList *pName){ 1833 Index *pIndex; 1834 Vdbe *v; 1835 sqlite *db = pParse->db; 1836 1837 if( pParse->nErr || sqlite_malloc_failed ) return; 1838 assert( pName->nSrc==1 ); 1839 pIndex = sqliteFindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 1840 if( pIndex==0 ){ 1841 sqliteErrorMsg(pParse, "no such index: %S", pName, 0); 1842 goto exit_drop_index; 1843 } 1844 if( pIndex->autoIndex ){ 1845 sqliteErrorMsg(pParse, "index associated with UNIQUE " 1846 "or PRIMARY KEY constraint cannot be dropped", 0); 1847 goto exit_drop_index; 1848 } 1849 if( pIndex->iDb>1 ){ 1850 sqliteErrorMsg(pParse, "cannot alter schema of attached " 1851 "databases", 0); 1852 goto exit_drop_index; 1853 } 1854 #ifndef SQLITE_OMIT_AUTHORIZATION 1855 { 1856 int code = SQLITE_DROP_INDEX; 1857 Table *pTab = pIndex->pTable; 1858 const char *zDb = db->aDb[pIndex->iDb].zName; 1859 const char *zTab = SCHEMA_TABLE(pIndex->iDb); 1860 if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 1861 goto exit_drop_index; 1862 } 1863 if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX; 1864 if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 1865 goto exit_drop_index; 1866 } 1867 } 1868 #endif 1869 1870 /* Generate code to remove the index and from the master table */ 1871 v = sqliteGetVdbe(pParse); 1872 if( v ){ 1873 static VdbeOp dropIndex[] = { 1874 { OP_Rewind, 0, ADDR(9), 0}, 1875 { OP_String, 0, 0, 0}, /* 1 */ 1876 { OP_MemStore, 1, 1, 0}, 1877 { OP_MemLoad, 1, 0, 0}, /* 3 */ 1878 { OP_Column, 0, 1, 0}, 1879 { OP_Eq, 0, ADDR(8), 0}, 1880 { OP_Next, 0, ADDR(3), 0}, 1881 { OP_Goto, 0, ADDR(9), 0}, 1882 { OP_Delete, 0, 0, 0}, /* 8 */ 1883 }; 1884 int base; 1885 1886 sqliteBeginWriteOperation(pParse, 0, pIndex->iDb); 1887 sqliteOpenMasterTable(v, pIndex->iDb); 1888 base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex); 1889 sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0); 1890 if( pIndex->iDb==0 ){ 1891 sqliteChangeCookie(db, v); 1892 } 1893 sqliteVdbeAddOp(v, OP_Close, 0, 0); 1894 sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb); 1895 sqliteEndWriteOperation(pParse); 1896 } 1897 1898 /* Delete the in-memory description of this index. 1899 */ 1900 if( !pParse->explain ){ 1901 sqliteUnlinkAndDeleteIndex(db, pIndex); 1902 db->flags |= SQLITE_InternChanges; 1903 } 1904 1905 exit_drop_index: 1906 sqliteSrcListDelete(pName); 1907 } 1908 1909 /* 1910 ** Append a new element to the given IdList. Create a new IdList if 1911 ** need be. 1912 ** 1913 ** A new IdList is returned, or NULL if malloc() fails. 1914 */ 1915 IdList *sqliteIdListAppend(IdList *pList, Token *pToken){ 1916 if( pList==0 ){ 1917 pList = sqliteMalloc( sizeof(IdList) ); 1918 if( pList==0 ) return 0; 1919 pList->nAlloc = 0; 1920 } 1921 if( pList->nId>=pList->nAlloc ){ 1922 struct IdList_item *a; 1923 pList->nAlloc = pList->nAlloc*2 + 5; 1924 a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) ); 1925 if( a==0 ){ 1926 sqliteIdListDelete(pList); 1927 return 0; 1928 } 1929 pList->a = a; 1930 } 1931 memset(&pList->a[pList->nId], 0, sizeof(pList->a[0])); 1932 if( pToken ){ 1933 char **pz = &pList->a[pList->nId].zName; 1934 sqliteSetNString(pz, pToken->z, pToken->n, 0); 1935 if( *pz==0 ){ 1936 sqliteIdListDelete(pList); 1937 return 0; 1938 }else{ 1939 sqliteDequote(*pz); 1940 } 1941 } 1942 pList->nId++; 1943 return pList; 1944 } 1945 1946 /* 1947 ** Append a new table name to the given SrcList. Create a new SrcList if 1948 ** need be. A new entry is created in the SrcList even if pToken is NULL. 1949 ** 1950 ** A new SrcList is returned, or NULL if malloc() fails. 1951 ** 1952 ** If pDatabase is not null, it means that the table has an optional 1953 ** database name prefix. Like this: "database.table". The pDatabase 1954 ** points to the table name and the pTable points to the database name. 1955 ** The SrcList.a[].zName field is filled with the table name which might 1956 ** come from pTable (if pDatabase is NULL) or from pDatabase. 1957 ** SrcList.a[].zDatabase is filled with the database name from pTable, 1958 ** or with NULL if no database is specified. 1959 ** 1960 ** In other words, if call like this: 1961 ** 1962 ** sqliteSrcListAppend(A,B,0); 1963 ** 1964 ** Then B is a table name and the database name is unspecified. If called 1965 ** like this: 1966 ** 1967 ** sqliteSrcListAppend(A,B,C); 1968 ** 1969 ** Then C is the table name and B is the database name. 1970 */ 1971 SrcList *sqliteSrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){ 1972 if( pList==0 ){ 1973 pList = sqliteMalloc( sizeof(SrcList) ); 1974 if( pList==0 ) return 0; 1975 pList->nAlloc = 1; 1976 } 1977 if( pList->nSrc>=pList->nAlloc ){ 1978 SrcList *pNew; 1979 pList->nAlloc *= 2; 1980 pNew = sqliteRealloc(pList, 1981 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) ); 1982 if( pNew==0 ){ 1983 sqliteSrcListDelete(pList); 1984 return 0; 1985 } 1986 pList = pNew; 1987 } 1988 memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0])); 1989 if( pDatabase && pDatabase->z==0 ){ 1990 pDatabase = 0; 1991 } 1992 if( pDatabase && pTable ){ 1993 Token *pTemp = pDatabase; 1994 pDatabase = pTable; 1995 pTable = pTemp; 1996 } 1997 if( pTable ){ 1998 char **pz = &pList->a[pList->nSrc].zName; 1999 sqliteSetNString(pz, pTable->z, pTable->n, 0); 2000 if( *pz==0 ){ 2001 sqliteSrcListDelete(pList); 2002 return 0; 2003 }else{ 2004 sqliteDequote(*pz); 2005 } 2006 } 2007 if( pDatabase ){ 2008 char **pz = &pList->a[pList->nSrc].zDatabase; 2009 sqliteSetNString(pz, pDatabase->z, pDatabase->n, 0); 2010 if( *pz==0 ){ 2011 sqliteSrcListDelete(pList); 2012 return 0; 2013 }else{ 2014 sqliteDequote(*pz); 2015 } 2016 } 2017 pList->a[pList->nSrc].iCursor = -1; 2018 pList->nSrc++; 2019 return pList; 2020 } 2021 2022 /* 2023 ** Assign cursors to all tables in a SrcList 2024 */ 2025 void sqliteSrcListAssignCursors(Parse *pParse, SrcList *pList){ 2026 int i; 2027 for(i=0; i<pList->nSrc; i++){ 2028 if( pList->a[i].iCursor<0 ){ 2029 pList->a[i].iCursor = pParse->nTab++; 2030 } 2031 } 2032 } 2033 2034 /* 2035 ** Add an alias to the last identifier on the given identifier list. 2036 */ 2037 void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){ 2038 if( pList && pList->nSrc>0 ){ 2039 int i = pList->nSrc - 1; 2040 sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0); 2041 sqliteDequote(pList->a[i].zAlias); 2042 } 2043 } 2044 2045 /* 2046 ** Delete an IdList. 2047 */ 2048 void sqliteIdListDelete(IdList *pList){ 2049 int i; 2050 if( pList==0 ) return; 2051 for(i=0; i<pList->nId; i++){ 2052 sqliteFree(pList->a[i].zName); 2053 } 2054 sqliteFree(pList->a); 2055 sqliteFree(pList); 2056 } 2057 2058 /* 2059 ** Return the index in pList of the identifier named zId. Return -1 2060 ** if not found. 2061 */ 2062 int sqliteIdListIndex(IdList *pList, const char *zName){ 2063 int i; 2064 if( pList==0 ) return -1; 2065 for(i=0; i<pList->nId; i++){ 2066 if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i; 2067 } 2068 return -1; 2069 } 2070 2071 /* 2072 ** Delete an entire SrcList including all its substructure. 2073 */ 2074 void sqliteSrcListDelete(SrcList *pList){ 2075 int i; 2076 if( pList==0 ) return; 2077 for(i=0; i<pList->nSrc; i++){ 2078 sqliteFree(pList->a[i].zDatabase); 2079 sqliteFree(pList->a[i].zName); 2080 sqliteFree(pList->a[i].zAlias); 2081 if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){ 2082 sqliteDeleteTable(0, pList->a[i].pTab); 2083 } 2084 sqliteSelectDelete(pList->a[i].pSelect); 2085 sqliteExprDelete(pList->a[i].pOn); 2086 sqliteIdListDelete(pList->a[i].pUsing); 2087 } 2088 sqliteFree(pList); 2089 } 2090 2091 /* 2092 ** Begin a transaction 2093 */ 2094 void sqliteBeginTransaction(Parse *pParse, int onError){ 2095 sqlite *db; 2096 2097 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2098 if( pParse->nErr || sqlite_malloc_failed ) return; 2099 if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return; 2100 if( db->flags & SQLITE_InTrans ){ 2101 sqliteErrorMsg(pParse, "cannot start a transaction within a transaction"); 2102 return; 2103 } 2104 sqliteBeginWriteOperation(pParse, 0, 0); 2105 db->flags |= SQLITE_InTrans; 2106 db->onError = onError; 2107 } 2108 2109 /* 2110 ** Commit a transaction 2111 */ 2112 void sqliteCommitTransaction(Parse *pParse){ 2113 sqlite *db; 2114 2115 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2116 if( pParse->nErr || sqlite_malloc_failed ) return; 2117 if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; 2118 if( (db->flags & SQLITE_InTrans)==0 ){ 2119 sqliteErrorMsg(pParse, "cannot commit - no transaction is active"); 2120 return; 2121 } 2122 db->flags &= ~SQLITE_InTrans; 2123 sqliteEndWriteOperation(pParse); 2124 db->onError = OE_Default; 2125 } 2126 2127 /* 2128 ** Rollback a transaction 2129 */ 2130 void sqliteRollbackTransaction(Parse *pParse){ 2131 sqlite *db; 2132 Vdbe *v; 2133 2134 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2135 if( pParse->nErr || sqlite_malloc_failed ) return; 2136 if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; 2137 if( (db->flags & SQLITE_InTrans)==0 ){ 2138 sqliteErrorMsg(pParse, "cannot rollback - no transaction is active"); 2139 return; 2140 } 2141 v = sqliteGetVdbe(pParse); 2142 if( v ){ 2143 sqliteVdbeAddOp(v, OP_Rollback, 0, 0); 2144 } 2145 db->flags &= ~SQLITE_InTrans; 2146 db->onError = OE_Default; 2147 } 2148 2149 /* 2150 ** Generate VDBE code that will verify the schema cookie for all 2151 ** named database files. 2152 */ 2153 void sqliteCodeVerifySchema(Parse *pParse, int iDb){ 2154 sqlite *db = pParse->db; 2155 Vdbe *v = sqliteGetVdbe(pParse); 2156 assert( iDb>=0 && iDb<db->nDb ); 2157 assert( db->aDb[iDb].pBt!=0 ); 2158 if( iDb!=1 && !DbHasProperty(db, iDb, DB_Cookie) ){ 2159 sqliteVdbeAddOp(v, OP_VerifyCookie, iDb, db->aDb[iDb].schema_cookie); 2160 DbSetProperty(db, iDb, DB_Cookie); 2161 } 2162 } 2163 2164 /* 2165 ** Generate VDBE code that prepares for doing an operation that 2166 ** might change the database. 2167 ** 2168 ** This routine starts a new transaction if we are not already within 2169 ** a transaction. If we are already within a transaction, then a checkpoint 2170 ** is set if the setCheckpoint parameter is true. A checkpoint should 2171 ** be set for operations that might fail (due to a constraint) part of 2172 ** the way through and which will need to undo some writes without having to 2173 ** rollback the whole transaction. For operations where all constraints 2174 ** can be checked before any changes are made to the database, it is never 2175 ** necessary to undo a write and the checkpoint should not be set. 2176 ** 2177 ** Only database iDb and the temp database are made writable by this call. 2178 ** If iDb==0, then the main and temp databases are made writable. If 2179 ** iDb==1 then only the temp database is made writable. If iDb>1 then the 2180 ** specified auxiliary database and the temp database are made writable. 2181 */ 2182 void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int iDb){ 2183 Vdbe *v; 2184 sqlite *db = pParse->db; 2185 if( DbHasProperty(db, iDb, DB_Locked) ) return; 2186 v = sqliteGetVdbe(pParse); 2187 if( v==0 ) return; 2188 if( !db->aDb[iDb].inTrans ){ 2189 sqliteVdbeAddOp(v, OP_Transaction, iDb, 0); 2190 DbSetProperty(db, iDb, DB_Locked); 2191 sqliteCodeVerifySchema(pParse, iDb); 2192 if( iDb!=1 ){ 2193 sqliteBeginWriteOperation(pParse, setCheckpoint, 1); 2194 } 2195 }else if( setCheckpoint ){ 2196 sqliteVdbeAddOp(v, OP_Checkpoint, iDb, 0); 2197 DbSetProperty(db, iDb, DB_Locked); 2198 } 2199 } 2200 2201 /* 2202 ** Generate code that concludes an operation that may have changed 2203 ** the database. If a statement transaction was started, then emit 2204 ** an OP_Commit that will cause the changes to be committed to disk. 2205 ** 2206 ** Note that checkpoints are automatically committed at the end of 2207 ** a statement. Note also that there can be multiple calls to 2208 ** sqliteBeginWriteOperation() but there should only be a single 2209 ** call to sqliteEndWriteOperation() at the conclusion of the statement. 2210 */ 2211 void sqliteEndWriteOperation(Parse *pParse){ 2212 Vdbe *v; 2213 sqlite *db = pParse->db; 2214 if( pParse->trigStack ) return; /* if this is in a trigger */ 2215 v = sqliteGetVdbe(pParse); 2216 if( v==0 ) return; 2217 if( db->flags & SQLITE_InTrans ){ 2218 /* A BEGIN has executed. Do not commit until we see an explicit 2219 ** COMMIT statement. */ 2220 }else{ 2221 sqliteVdbeAddOp(v, OP_Commit, 0, 0); 2222 } 2223 } 2224