1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** This file contains C code routines that are called by the SQLite parser 13 ** when syntax rules are reduced. The routines in this file handle the 14 ** following kinds of SQL syntax: 15 ** 16 ** CREATE TABLE 17 ** DROP TABLE 18 ** CREATE INDEX 19 ** DROP INDEX 20 ** creating ID lists 21 ** BEGIN TRANSACTION 22 ** COMMIT 23 ** ROLLBACK 24 ** 25 ** $Id: build.c,v 1.338 2005/07/28 16:51:51 drh Exp $ 26 */ 27 #include "sqliteInt.h" 28 #include <ctype.h> 29 30 /* 31 ** This routine is called when a new SQL statement is beginning to 32 ** be parsed. Initialize the pParse structure as needed. 33 */ 34 void sqlite3BeginParse(Parse *pParse, int explainFlag){ 35 pParse->explain = explainFlag; 36 pParse->nVar = 0; 37 } 38 39 /* 40 ** This routine is called after a single SQL statement has been 41 ** parsed and a VDBE program to execute that statement has been 42 ** prepared. This routine puts the finishing touches on the 43 ** VDBE program and resets the pParse structure for the next 44 ** parse. 45 ** 46 ** Note that if an error occurred, it might be the case that 47 ** no VDBE code was generated. 48 */ 49 void sqlite3FinishCoding(Parse *pParse){ 50 sqlite3 *db; 51 Vdbe *v; 52 53 if( sqlite3_malloc_failed ) return; 54 if( pParse->nested ) return; 55 if( !pParse->pVdbe ){ 56 if( pParse->rc==SQLITE_OK && pParse->nErr ){ 57 pParse->rc = SQLITE_ERROR; 58 } 59 return; 60 } 61 62 /* Begin by generating some termination code at the end of the 63 ** vdbe program 64 */ 65 db = pParse->db; 66 v = sqlite3GetVdbe(pParse); 67 if( v ){ 68 sqlite3VdbeAddOp(v, OP_Halt, 0, 0); 69 70 /* The cookie mask contains one bit for each database file open. 71 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 72 ** set for each database that is used. Generate code to start a 73 ** transaction on each used database and to verify the schema cookie 74 ** on each used database. 75 */ 76 if( pParse->cookieGoto>0 ){ 77 u32 mask; 78 int iDb; 79 sqlite3VdbeChangeP2(v, pParse->cookieGoto-1, sqlite3VdbeCurrentAddr(v)); 80 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ 81 if( (mask & pParse->cookieMask)==0 ) continue; 82 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0); 83 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); 84 } 85 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto); 86 } 87 88 /* Add a No-op that contains the complete text of the compiled SQL 89 ** statement as its P3 argument. This does not change the functionality 90 ** of the program. 91 ** 92 ** This is used to implement sqlite3_trace(). 93 */ 94 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql); 95 } 96 97 98 /* Get the VDBE program ready for execution 99 */ 100 if( v && pParse->nErr==0 ){ 101 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; 102 sqlite3VdbeTrace(v, trace); 103 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3, 104 pParse->nTab+3, pParse->nMaxDepth+1, pParse->explain); 105 pParse->rc = SQLITE_DONE; 106 pParse->colNamesSet = 0; 107 }else if( pParse->rc==SQLITE_OK ){ 108 pParse->rc = SQLITE_ERROR; 109 } 110 pParse->nTab = 0; 111 pParse->nMem = 0; 112 pParse->nSet = 0; 113 pParse->nVar = 0; 114 pParse->cookieMask = 0; 115 pParse->cookieGoto = 0; 116 } 117 118 /* 119 ** Run the parser and code generator recursively in order to generate 120 ** code for the SQL statement given onto the end of the pParse context 121 ** currently under construction. When the parser is run recursively 122 ** this way, the final OP_Halt is not appended and other initialization 123 ** and finalization steps are omitted because those are handling by the 124 ** outermost parser. 125 ** 126 ** Not everything is nestable. This facility is designed to permit 127 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 128 ** care if you decide to try to use this routine for some other purposes. 129 */ 130 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 131 va_list ap; 132 char *zSql; 133 int rc; 134 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) 135 char saveBuf[SAVE_SZ]; 136 137 if( pParse->nErr ) return; 138 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 139 va_start(ap, zFormat); 140 zSql = sqlite3VMPrintf(zFormat, ap); 141 va_end(ap); 142 if( zSql==0 ){ 143 return; /* A malloc must have failed */ 144 } 145 pParse->nested++; 146 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 147 memset(&pParse->nVar, 0, SAVE_SZ); 148 rc = sqlite3RunParser(pParse, zSql, 0); 149 sqliteFree(zSql); 150 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 151 pParse->nested--; 152 } 153 154 /* 155 ** Locate the in-memory structure that describes a particular database 156 ** table given the name of that table and (optionally) the name of the 157 ** database containing the table. Return NULL if not found. 158 ** 159 ** If zDatabase is 0, all databases are searched for the table and the 160 ** first matching table is returned. (No checking for duplicate table 161 ** names is done.) The search order is TEMP first, then MAIN, then any 162 ** auxiliary databases added using the ATTACH command. 163 ** 164 ** See also sqlite3LocateTable(). 165 */ 166 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 167 Table *p = 0; 168 int i; 169 assert( zName!=0 ); 170 assert( (db->flags & SQLITE_Initialized) || db->init.busy ); 171 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 172 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 173 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 174 p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1); 175 if( p ) break; 176 } 177 return p; 178 } 179 180 /* 181 ** Locate the in-memory structure that describes a particular database 182 ** table given the name of that table and (optionally) the name of the 183 ** database containing the table. Return NULL if not found. Also leave an 184 ** error message in pParse->zErrMsg. 185 ** 186 ** The difference between this routine and sqlite3FindTable() is that this 187 ** routine leaves an error message in pParse->zErrMsg where 188 ** sqlite3FindTable() does not. 189 */ 190 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){ 191 Table *p; 192 193 /* Read the database schema. If an error occurs, leave an error message 194 ** and code in pParse and return NULL. */ 195 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 196 return 0; 197 } 198 199 p = sqlite3FindTable(pParse->db, zName, zDbase); 200 if( p==0 ){ 201 if( zDbase ){ 202 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName); 203 }else if( sqlite3FindTable(pParse->db, zName, 0)!=0 ){ 204 sqlite3ErrorMsg(pParse, "table \"%s\" is not in database \"%s\"", 205 zName, zDbase); 206 }else{ 207 sqlite3ErrorMsg(pParse, "no such table: %s", zName); 208 } 209 pParse->checkSchema = 1; 210 } 211 return p; 212 } 213 214 /* 215 ** Locate the in-memory structure that describes 216 ** a particular index given the name of that index 217 ** and the name of the database that contains the index. 218 ** Return NULL if not found. 219 ** 220 ** If zDatabase is 0, all databases are searched for the 221 ** table and the first matching index is returned. (No checking 222 ** for duplicate index names is done.) The search order is 223 ** TEMP first, then MAIN, then any auxiliary databases added 224 ** using the ATTACH command. 225 */ 226 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 227 Index *p = 0; 228 int i; 229 assert( (db->flags & SQLITE_Initialized) || db->init.busy ); 230 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 231 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 232 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 233 p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1); 234 if( p ) break; 235 } 236 return p; 237 } 238 239 /* 240 ** Reclaim the memory used by an index 241 */ 242 static void freeIndex(Index *p){ 243 sqliteFree(p->zColAff); 244 sqliteFree(p); 245 } 246 247 /* 248 ** Remove the given index from the index hash table, and free 249 ** its memory structures. 250 ** 251 ** The index is removed from the database hash tables but 252 ** it is not unlinked from the Table that it indexes. 253 ** Unlinking from the Table must be done by the calling function. 254 */ 255 static void sqliteDeleteIndex(sqlite3 *db, Index *p){ 256 Index *pOld; 257 258 assert( db!=0 && p->zName!=0 ); 259 pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName, 260 strlen(p->zName)+1, 0); 261 if( pOld!=0 && pOld!=p ){ 262 sqlite3HashInsert(&db->aDb[p->iDb].idxHash, pOld->zName, 263 strlen(pOld->zName)+1, pOld); 264 } 265 freeIndex(p); 266 } 267 268 /* 269 ** For the index called zIdxName which is found in the database iDb, 270 ** unlike that index from its Table then remove the index from 271 ** the index hash table and free all memory structures associated 272 ** with the index. 273 */ 274 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 275 Index *pIndex; 276 int len; 277 278 len = strlen(zIdxName); 279 pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0); 280 if( pIndex ){ 281 if( pIndex->pTable->pIndex==pIndex ){ 282 pIndex->pTable->pIndex = pIndex->pNext; 283 }else{ 284 Index *p; 285 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){} 286 if( p && p->pNext==pIndex ){ 287 p->pNext = pIndex->pNext; 288 } 289 } 290 freeIndex(pIndex); 291 } 292 db->flags |= SQLITE_InternChanges; 293 } 294 295 /* 296 ** Erase all schema information from the in-memory hash tables of 297 ** a single database. This routine is called to reclaim memory 298 ** before the database closes. It is also called during a rollback 299 ** if there were schema changes during the transaction or if a 300 ** schema-cookie mismatch occurs. 301 ** 302 ** If iDb<=0 then reset the internal schema tables for all database 303 ** files. If iDb>=2 then reset the internal schema for only the 304 ** single file indicated. 305 */ 306 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ 307 HashElem *pElem; 308 Hash temp1; 309 Hash temp2; 310 int i, j; 311 312 assert( iDb>=0 && iDb<db->nDb ); 313 db->flags &= ~SQLITE_Initialized; 314 for(i=iDb; i<db->nDb; i++){ 315 Db *pDb = &db->aDb[i]; 316 temp1 = pDb->tblHash; 317 temp2 = pDb->trigHash; 318 sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0); 319 sqlite3HashClear(&pDb->aFKey); 320 sqlite3HashClear(&pDb->idxHash); 321 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ 322 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem)); 323 } 324 sqlite3HashClear(&temp2); 325 sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0); 326 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ 327 Table *pTab = sqliteHashData(pElem); 328 sqlite3DeleteTable(db, pTab); 329 } 330 sqlite3HashClear(&temp1); 331 pDb->pSeqTab = 0; 332 DbClearProperty(db, i, DB_SchemaLoaded); 333 if( iDb>0 ) return; 334 } 335 assert( iDb==0 ); 336 db->flags &= ~SQLITE_InternChanges; 337 338 /* If one or more of the auxiliary database files has been closed, 339 ** then remove then from the auxiliary database list. We take the 340 ** opportunity to do this here since we have just deleted all of the 341 ** schema hash tables and therefore do not have to make any changes 342 ** to any of those tables. 343 */ 344 for(i=0; i<db->nDb; i++){ 345 struct Db *pDb = &db->aDb[i]; 346 if( pDb->pBt==0 ){ 347 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux); 348 pDb->pAux = 0; 349 } 350 } 351 for(i=j=2; i<db->nDb; i++){ 352 struct Db *pDb = &db->aDb[i]; 353 if( pDb->pBt==0 ){ 354 sqliteFree(pDb->zName); 355 pDb->zName = 0; 356 continue; 357 } 358 if( j<i ){ 359 db->aDb[j] = db->aDb[i]; 360 } 361 j++; 362 } 363 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 364 db->nDb = j; 365 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 366 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 367 sqliteFree(db->aDb); 368 db->aDb = db->aDbStatic; 369 } 370 } 371 372 /* 373 ** This routine is called whenever a rollback occurs. If there were 374 ** schema changes during the transaction, then we have to reset the 375 ** internal hash tables and reload them from disk. 376 */ 377 void sqlite3RollbackInternalChanges(sqlite3 *db){ 378 if( db->flags & SQLITE_InternChanges ){ 379 sqlite3ResetInternalSchema(db, 0); 380 } 381 } 382 383 /* 384 ** This routine is called when a commit occurs. 385 */ 386 void sqlite3CommitInternalChanges(sqlite3 *db){ 387 db->flags &= ~SQLITE_InternChanges; 388 } 389 390 /* 391 ** Clear the column names from a table or view. 392 */ 393 static void sqliteResetColumnNames(Table *pTable){ 394 int i; 395 Column *pCol; 396 assert( pTable!=0 ); 397 if( (pCol = pTable->aCol)!=0 ){ 398 for(i=0; i<pTable->nCol; i++, pCol++){ 399 sqliteFree(pCol->zName); 400 sqlite3ExprDelete(pCol->pDflt); 401 sqliteFree(pCol->zType); 402 } 403 sqliteFree(pTable->aCol); 404 } 405 pTable->aCol = 0; 406 pTable->nCol = 0; 407 } 408 409 /* 410 ** Remove the memory data structures associated with the given 411 ** Table. No changes are made to disk by this routine. 412 ** 413 ** This routine just deletes the data structure. It does not unlink 414 ** the table data structure from the hash table. Nor does it remove 415 ** foreign keys from the sqlite.aFKey hash table. But it does destroy 416 ** memory structures of the indices and foreign keys associated with 417 ** the table. 418 ** 419 ** Indices associated with the table are unlinked from the "db" 420 ** data structure if db!=NULL. If db==NULL, indices attached to 421 ** the table are deleted, but it is assumed they have already been 422 ** unlinked. 423 */ 424 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ 425 Index *pIndex, *pNext; 426 FKey *pFKey, *pNextFKey; 427 428 if( pTable==0 ) return; 429 430 /* Do not delete the table until the reference count reaches zero. */ 431 pTable->nRef--; 432 if( pTable->nRef>0 ){ 433 return; 434 } 435 assert( pTable->nRef==0 ); 436 437 /* Delete all indices associated with this table 438 */ 439 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 440 pNext = pIndex->pNext; 441 assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) ); 442 sqliteDeleteIndex(db, pIndex); 443 } 444 445 #ifndef SQLITE_OMIT_FOREIGN_KEY 446 /* Delete all foreign keys associated with this table. The keys 447 ** should have already been unlinked from the db->aFKey hash table 448 */ 449 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ 450 pNextFKey = pFKey->pNextFrom; 451 assert( pTable->iDb<db->nDb ); 452 assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey, 453 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey ); 454 sqliteFree(pFKey); 455 } 456 #endif 457 458 /* Delete the Table structure itself. 459 */ 460 sqliteResetColumnNames(pTable); 461 sqliteFree(pTable->zName); 462 sqliteFree(pTable->zColAff); 463 sqlite3SelectDelete(pTable->pSelect); 464 sqliteFree(pTable); 465 } 466 467 /* 468 ** Unlink the given table from the hash tables and the delete the 469 ** table structure with all its indices and foreign keys. 470 */ 471 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 472 Table *p; 473 FKey *pF1, *pF2; 474 Db *pDb; 475 476 assert( db!=0 ); 477 assert( iDb>=0 && iDb<db->nDb ); 478 assert( zTabName && zTabName[0] ); 479 pDb = &db->aDb[iDb]; 480 p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0); 481 if( p ){ 482 #ifndef SQLITE_OMIT_FOREIGN_KEY 483 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){ 484 int nTo = strlen(pF1->zTo) + 1; 485 pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo); 486 if( pF2==pF1 ){ 487 sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo); 488 }else{ 489 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; } 490 if( pF2 ){ 491 pF2->pNextTo = pF1->pNextTo; 492 } 493 } 494 } 495 #endif 496 sqlite3DeleteTable(db, p); 497 } 498 db->flags |= SQLITE_InternChanges; 499 } 500 501 /* 502 ** Given a token, return a string that consists of the text of that 503 ** token with any quotations removed. Space to hold the returned string 504 ** is obtained from sqliteMalloc() and must be freed by the calling 505 ** function. 506 ** 507 ** Tokens are often just pointers into the original SQL text and so 508 ** are not \000 terminated and are not persistent. The returned string 509 ** is \000 terminated and is persistent. 510 */ 511 char *sqlite3NameFromToken(Token *pName){ 512 char *zName; 513 if( pName ){ 514 zName = sqliteStrNDup(pName->z, pName->n); 515 sqlite3Dequote(zName); 516 }else{ 517 zName = 0; 518 } 519 return zName; 520 } 521 522 /* 523 ** Open the sqlite_master table stored in database number iDb for 524 ** writing. The table is opened using cursor 0. 525 */ 526 void sqlite3OpenMasterTable(Vdbe *v, int iDb){ 527 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); 528 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT); 529 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */ 530 } 531 532 /* 533 ** The token *pName contains the name of a database (either "main" or 534 ** "temp" or the name of an attached db). This routine returns the 535 ** index of the named database in db->aDb[], or -1 if the named db 536 ** does not exist. 537 */ 538 int sqlite3FindDb(sqlite3 *db, Token *pName){ 539 int i = -1; /* Database number */ 540 int n; /* Number of characters in the name */ 541 Db *pDb; /* A database whose name space is being searched */ 542 char *zName; /* Name we are searching for */ 543 544 zName = sqlite3NameFromToken(pName); 545 if( zName ){ 546 n = strlen(zName); 547 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 548 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 549 0==sqlite3StrICmp(pDb->zName, zName) ){ 550 break; 551 } 552 } 553 sqliteFree(zName); 554 } 555 return i; 556 } 557 558 /* The table or view or trigger name is passed to this routine via tokens 559 ** pName1 and pName2. If the table name was fully qualified, for example: 560 ** 561 ** CREATE TABLE xxx.yyy (...); 562 ** 563 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 564 ** the table name is not fully qualified, i.e.: 565 ** 566 ** CREATE TABLE yyy(...); 567 ** 568 ** Then pName1 is set to "yyy" and pName2 is "". 569 ** 570 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 571 ** pName2) that stores the unqualified table name. The index of the 572 ** database "xxx" is returned. 573 */ 574 int sqlite3TwoPartName( 575 Parse *pParse, /* Parsing and code generating context */ 576 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 577 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 578 Token **pUnqual /* Write the unqualified object name here */ 579 ){ 580 int iDb; /* Database holding the object */ 581 sqlite3 *db = pParse->db; 582 583 if( pName2 && pName2->n>0 ){ 584 assert( !db->init.busy ); 585 *pUnqual = pName2; 586 iDb = sqlite3FindDb(db, pName1); 587 if( iDb<0 ){ 588 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 589 pParse->nErr++; 590 return -1; 591 } 592 }else{ 593 assert( db->init.iDb==0 || db->init.busy ); 594 iDb = db->init.iDb; 595 *pUnqual = pName1; 596 } 597 return iDb; 598 } 599 600 /* 601 ** This routine is used to check if the UTF-8 string zName is a legal 602 ** unqualified name for a new schema object (table, index, view or 603 ** trigger). All names are legal except those that begin with the string 604 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 605 ** is reserved for internal use. 606 */ 607 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 608 if( !pParse->db->init.busy && pParse->nested==0 609 && (pParse->db->flags & SQLITE_WriteSchema)==0 610 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 611 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 612 return SQLITE_ERROR; 613 } 614 return SQLITE_OK; 615 } 616 617 /* 618 ** Begin constructing a new table representation in memory. This is 619 ** the first of several action routines that get called in response 620 ** to a CREATE TABLE statement. In particular, this routine is called 621 ** after seeing tokens "CREATE" and "TABLE" and the table name. The 622 ** pStart token is the CREATE and pName is the table name. The isTemp 623 ** flag is true if the table should be stored in the auxiliary database 624 ** file instead of in the main database file. This is normally the case 625 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 626 ** CREATE and TABLE. 627 ** 628 ** The new table record is initialized and put in pParse->pNewTable. 629 ** As more of the CREATE TABLE statement is parsed, additional action 630 ** routines will be called to add more information to this record. 631 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 632 ** is called to complete the construction of the new table record. 633 */ 634 void sqlite3StartTable( 635 Parse *pParse, /* Parser context */ 636 Token *pStart, /* The "CREATE" token */ 637 Token *pName1, /* First part of the name of the table or view */ 638 Token *pName2, /* Second part of the name of the table or view */ 639 int isTemp, /* True if this is a TEMP table */ 640 int isView /* True if this is a VIEW */ 641 ){ 642 Table *pTable; 643 Index *pIdx; 644 char *zName = 0; /* The name of the new table */ 645 sqlite3 *db = pParse->db; 646 Vdbe *v; 647 int iDb; /* Database number to create the table in */ 648 Token *pName; /* Unqualified name of the table to create */ 649 650 /* The table or view name to create is passed to this routine via tokens 651 ** pName1 and pName2. If the table name was fully qualified, for example: 652 ** 653 ** CREATE TABLE xxx.yyy (...); 654 ** 655 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 656 ** the table name is not fully qualified, i.e.: 657 ** 658 ** CREATE TABLE yyy(...); 659 ** 660 ** Then pName1 is set to "yyy" and pName2 is "". 661 ** 662 ** The call below sets the pName pointer to point at the token (pName1 or 663 ** pName2) that stores the unqualified table name. The variable iDb is 664 ** set to the index of the database that the table or view is to be 665 ** created in. 666 */ 667 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 668 if( iDb<0 ) return; 669 if( !OMIT_TEMPDB && isTemp && iDb>1 ){ 670 /* If creating a temp table, the name may not be qualified */ 671 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 672 return; 673 } 674 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 675 676 pParse->sNameToken = *pName; 677 zName = sqlite3NameFromToken(pName); 678 if( zName==0 ) return; 679 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 680 goto begin_table_error; 681 } 682 if( db->init.iDb==1 ) isTemp = 1; 683 #ifndef SQLITE_OMIT_AUTHORIZATION 684 assert( (isTemp & 1)==isTemp ); 685 { 686 int code; 687 char *zDb = db->aDb[iDb].zName; 688 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 689 goto begin_table_error; 690 } 691 if( isView ){ 692 if( !OMIT_TEMPDB && isTemp ){ 693 code = SQLITE_CREATE_TEMP_VIEW; 694 }else{ 695 code = SQLITE_CREATE_VIEW; 696 } 697 }else{ 698 if( !OMIT_TEMPDB && isTemp ){ 699 code = SQLITE_CREATE_TEMP_TABLE; 700 }else{ 701 code = SQLITE_CREATE_TABLE; 702 } 703 } 704 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ 705 goto begin_table_error; 706 } 707 } 708 #endif 709 710 /* Make sure the new table name does not collide with an existing 711 ** index or table name in the same database. Issue an error message if 712 ** it does. 713 */ 714 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 715 goto begin_table_error; 716 } 717 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); 718 if( pTable ){ 719 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 720 goto begin_table_error; 721 } 722 if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 && 723 ( iDb==0 || !db->init.busy) ){ 724 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 725 goto begin_table_error; 726 } 727 pTable = sqliteMalloc( sizeof(Table) ); 728 if( pTable==0 ){ 729 pParse->rc = SQLITE_NOMEM; 730 pParse->nErr++; 731 goto begin_table_error; 732 } 733 pTable->zName = zName; 734 pTable->nCol = 0; 735 pTable->aCol = 0; 736 pTable->iPKey = -1; 737 pTable->pIndex = 0; 738 pTable->iDb = iDb; 739 pTable->nRef = 1; 740 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable); 741 pParse->pNewTable = pTable; 742 743 /* If this is the magic sqlite_sequence table used by autoincrement, 744 ** then record a pointer to this table in the main database structure 745 ** so that INSERT can find the table easily. 746 */ 747 #ifndef SQLITE_OMIT_AUTOINCREMENT 748 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 749 db->aDb[iDb].pSeqTab = pTable; 750 } 751 #endif 752 753 /* Begin generating the code that will insert the table record into 754 ** the SQLITE_MASTER table. Note in particular that we must go ahead 755 ** and allocate the record number for the table entry now. Before any 756 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 757 ** indices to be created and the table record must come before the 758 ** indices. Hence, the record number for the table must be allocated 759 ** now. 760 */ 761 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 762 int lbl; 763 sqlite3BeginWriteOperation(pParse, 0, iDb); 764 765 /* If the file format and encoding in the database have not been set, 766 ** set them now. 767 */ 768 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */ 769 lbl = sqlite3VdbeMakeLabel(v); 770 sqlite3VdbeAddOp(v, OP_If, 0, lbl); 771 sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0); 772 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); 773 sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0); 774 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4); 775 sqlite3VdbeResolveLabel(v, lbl); 776 777 /* This just creates a place-holder record in the sqlite_master table. 778 ** The record created does not contain anything yet. It will be replaced 779 ** by the real entry in code generated at sqlite3EndTable(). 780 ** 781 ** The rowid for the new entry is left on the top of the stack. 782 ** The rowid value is needed by the code that sqlite3EndTable will 783 ** generate. 784 */ 785 #ifndef SQLITE_OMIT_VIEW 786 if( isView ){ 787 sqlite3VdbeAddOp(v, OP_Integer, 0, 0); 788 }else 789 #endif 790 { 791 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0); 792 } 793 sqlite3OpenMasterTable(v, iDb); 794 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0); 795 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); 796 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 797 sqlite3VdbeAddOp(v, OP_Insert, 0, 0); 798 sqlite3VdbeAddOp(v, OP_Close, 0, 0); 799 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 800 } 801 802 /* Normal (non-error) return. */ 803 return; 804 805 /* If an error occurs, we jump here */ 806 begin_table_error: 807 sqliteFree(zName); 808 return; 809 } 810 811 /* 812 ** This macro is used to compare two strings in a case-insensitive manner. 813 ** It is slightly faster than calling sqlite3StrICmp() directly, but 814 ** produces larger code. 815 ** 816 ** WARNING: This macro is not compatible with the strcmp() family. It 817 ** returns true if the two strings are equal, otherwise false. 818 */ 819 #define STRICMP(x, y) (\ 820 sqlite3UpperToLower[*(unsigned char *)(x)]== \ 821 sqlite3UpperToLower[*(unsigned char *)(y)] \ 822 && sqlite3StrICmp((x)+1,(y)+1)==0 ) 823 824 /* 825 ** Add a new column to the table currently being constructed. 826 ** 827 ** The parser calls this routine once for each column declaration 828 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 829 ** first to get things going. Then this routine is called for each 830 ** column. 831 */ 832 void sqlite3AddColumn(Parse *pParse, Token *pName){ 833 Table *p; 834 int i; 835 char *z; 836 Column *pCol; 837 if( (p = pParse->pNewTable)==0 ) return; 838 z = sqlite3NameFromToken(pName); 839 if( z==0 ) return; 840 for(i=0; i<p->nCol; i++){ 841 if( STRICMP(z, p->aCol[i].zName) ){ 842 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 843 sqliteFree(z); 844 return; 845 } 846 } 847 if( (p->nCol & 0x7)==0 ){ 848 Column *aNew; 849 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0])); 850 if( aNew==0 ){ 851 sqliteFree(z); 852 return; 853 } 854 p->aCol = aNew; 855 } 856 pCol = &p->aCol[p->nCol]; 857 memset(pCol, 0, sizeof(p->aCol[0])); 858 pCol->zName = z; 859 860 /* If there is no type specified, columns have the default affinity 861 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will 862 ** be called next to set pCol->affinity correctly. 863 */ 864 pCol->affinity = SQLITE_AFF_NONE; 865 pCol->pColl = pParse->db->pDfltColl; 866 p->nCol++; 867 } 868 869 /* 870 ** This routine is called by the parser while in the middle of 871 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 872 ** been seen on a column. This routine sets the notNull flag on 873 ** the column currently under construction. 874 */ 875 void sqlite3AddNotNull(Parse *pParse, int onError){ 876 Table *p; 877 int i; 878 if( (p = pParse->pNewTable)==0 ) return; 879 i = p->nCol-1; 880 if( i>=0 ) p->aCol[i].notNull = onError; 881 } 882 883 /* 884 ** Scan the column type name zType (length nType) and return the 885 ** associated affinity type. 886 ** 887 ** This routine does a case-independent search of zType for the 888 ** substrings in the following table. If one of the substrings is 889 ** found, the corresponding affinity is returned. If zType contains 890 ** more than one of the substrings, entries toward the top of 891 ** the table take priority. For example, if zType is 'BLOBINT', 892 ** SQLITE_AFF_INTEGER is returned. 893 ** 894 ** Substring | Affinity 895 ** -------------------------------- 896 ** 'INT' | SQLITE_AFF_INTEGER 897 ** 'CHAR' | SQLITE_AFF_TEXT 898 ** 'CLOB' | SQLITE_AFF_TEXT 899 ** 'TEXT' | SQLITE_AFF_TEXT 900 ** 'BLOB' | SQLITE_AFF_NONE 901 ** 902 ** If none of the substrings in the above table are found, 903 ** SQLITE_AFF_NUMERIC is returned. 904 */ 905 char sqlite3AffinityType(const Token *pType){ 906 u32 h = 0; 907 char aff = SQLITE_AFF_NUMERIC; 908 const unsigned char *zIn = pType->z; 909 const unsigned char *zEnd = &pType->z[pType->n]; 910 911 while( zIn!=zEnd ){ 912 h = (h<<8) + sqlite3UpperToLower[*zIn]; 913 zIn++; 914 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 915 aff = SQLITE_AFF_TEXT; 916 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 917 aff = SQLITE_AFF_TEXT; 918 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 919 aff = SQLITE_AFF_TEXT; 920 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 921 && aff==SQLITE_AFF_NUMERIC ){ 922 aff = SQLITE_AFF_NONE; 923 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 924 aff = SQLITE_AFF_INTEGER; 925 break; 926 } 927 } 928 929 return aff; 930 } 931 932 /* 933 ** This routine is called by the parser while in the middle of 934 ** parsing a CREATE TABLE statement. The pFirst token is the first 935 ** token in the sequence of tokens that describe the type of the 936 ** column currently under construction. pLast is the last token 937 ** in the sequence. Use this information to construct a string 938 ** that contains the typename of the column and store that string 939 ** in zType. 940 */ 941 void sqlite3AddColumnType(Parse *pParse, Token *pType){ 942 Table *p; 943 int i; 944 Column *pCol; 945 946 if( (p = pParse->pNewTable)==0 ) return; 947 i = p->nCol-1; 948 if( i<0 ) return; 949 pCol = &p->aCol[i]; 950 assert( pCol->zType==0 ); 951 #if 0 952 z = pCol->zType = sqliteMallocRaw(n+1); 953 if( z==0 ) return; 954 for(i=j=0; i<n; i++){ 955 int c = zIn[i]; 956 if( isspace(c) ) continue; 957 z[j++] = c; 958 } 959 z[j] = 0; 960 #endif 961 pCol->zType = sqlite3NameFromToken(pType); 962 pCol->affinity = sqlite3AffinityType(pType); 963 } 964 965 /* 966 ** The expression is the default value for the most recently added column 967 ** of the table currently under construction. 968 ** 969 ** Default value expressions must be constant. Raise an exception if this 970 ** is not the case. 971 ** 972 ** This routine is called by the parser while in the middle of 973 ** parsing a CREATE TABLE statement. 974 */ 975 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){ 976 Table *p; 977 Column *pCol; 978 if( (p = pParse->pNewTable)==0 ) return; 979 pCol = &(p->aCol[p->nCol-1]); 980 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){ 981 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 982 pCol->zName); 983 }else{ 984 sqlite3ExprDelete(pCol->pDflt); 985 pCol->pDflt = sqlite3ExprDup(pExpr); 986 } 987 sqlite3ExprDelete(pExpr); 988 } 989 990 /* 991 ** Designate the PRIMARY KEY for the table. pList is a list of names 992 ** of columns that form the primary key. If pList is NULL, then the 993 ** most recently added column of the table is the primary key. 994 ** 995 ** A table can have at most one primary key. If the table already has 996 ** a primary key (and this is the second primary key) then create an 997 ** error. 998 ** 999 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 1000 ** then we will try to use that column as the rowid. Set the Table.iPKey 1001 ** field of the table under construction to be the index of the 1002 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 1003 ** no INTEGER PRIMARY KEY. 1004 ** 1005 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 1006 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 1007 */ 1008 void sqlite3AddPrimaryKey( 1009 Parse *pParse, /* Parsing context */ 1010 ExprList *pList, /* List of field names to be indexed */ 1011 int onError, /* What to do with a uniqueness conflict */ 1012 int autoInc /* True if the AUTOINCREMENT keyword is present */ 1013 ){ 1014 Table *pTab = pParse->pNewTable; 1015 char *zType = 0; 1016 int iCol = -1, i; 1017 if( pTab==0 ) goto primary_key_exit; 1018 if( pTab->hasPrimKey ){ 1019 sqlite3ErrorMsg(pParse, 1020 "table \"%s\" has more than one primary key", pTab->zName); 1021 goto primary_key_exit; 1022 } 1023 pTab->hasPrimKey = 1; 1024 if( pList==0 ){ 1025 iCol = pTab->nCol - 1; 1026 pTab->aCol[iCol].isPrimKey = 1; 1027 }else{ 1028 for(i=0; i<pList->nExpr; i++){ 1029 for(iCol=0; iCol<pTab->nCol; iCol++){ 1030 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ 1031 break; 1032 } 1033 } 1034 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1; 1035 } 1036 if( pList->nExpr>1 ) iCol = -1; 1037 } 1038 if( iCol>=0 && iCol<pTab->nCol ){ 1039 zType = pTab->aCol[iCol].zType; 1040 } 1041 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){ 1042 pTab->iPKey = iCol; 1043 pTab->keyConf = onError; 1044 pTab->autoInc = autoInc; 1045 }else if( autoInc ){ 1046 #ifndef SQLITE_OMIT_AUTOINCREMENT 1047 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1048 "INTEGER PRIMARY KEY"); 1049 #endif 1050 }else{ 1051 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0); 1052 pList = 0; 1053 } 1054 1055 primary_key_exit: 1056 sqlite3ExprListDelete(pList); 1057 return; 1058 } 1059 1060 /* 1061 ** Set the collation function of the most recently parsed table column 1062 ** to the CollSeq given. 1063 */ 1064 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){ 1065 Table *p; 1066 Index *pIdx; 1067 CollSeq *pColl; 1068 int i; 1069 1070 if( (p = pParse->pNewTable)==0 ) return; 1071 i = p->nCol-1; 1072 1073 pColl = sqlite3LocateCollSeq(pParse, zType, nType); 1074 p->aCol[i].pColl = pColl; 1075 1076 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1077 ** then an index may have been created on this column before the 1078 ** collation type was added. Correct this if it is the case. 1079 */ 1080 for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){ 1081 assert( pIdx->nColumn==1 ); 1082 if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl; 1083 } 1084 } 1085 1086 /* 1087 ** Call sqlite3CheckCollSeq() for all collating sequences in an index, 1088 ** in order to verify that all the necessary collating sequences are 1089 ** loaded. 1090 */ 1091 int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){ 1092 if( pIdx ){ 1093 int i; 1094 for(i=0; i<pIdx->nColumn; i++){ 1095 if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){ 1096 return SQLITE_ERROR; 1097 } 1098 } 1099 } 1100 return SQLITE_OK; 1101 } 1102 1103 /* 1104 ** This function returns the collation sequence for database native text 1105 ** encoding identified by the string zName, length nName. 1106 ** 1107 ** If the requested collation sequence is not available, or not available 1108 ** in the database native encoding, the collation factory is invoked to 1109 ** request it. If the collation factory does not supply such a sequence, 1110 ** and the sequence is available in another text encoding, then that is 1111 ** returned instead. 1112 ** 1113 ** If no versions of the requested collations sequence are available, or 1114 ** another error occurs, NULL is returned and an error message written into 1115 ** pParse. 1116 */ 1117 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){ 1118 sqlite3 *db = pParse->db; 1119 u8 enc = db->enc; 1120 u8 initbusy = db->init.busy; 1121 1122 CollSeq *pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy); 1123 if( !initbusy && (!pColl || !pColl->xCmp) ){ 1124 pColl = sqlite3GetCollSeq(db, pColl, zName, nName); 1125 if( !pColl ){ 1126 if( nName<0 ){ 1127 nName = strlen(zName); 1128 } 1129 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); 1130 pColl = 0; 1131 } 1132 } 1133 1134 return pColl; 1135 } 1136 1137 1138 /* 1139 ** Generate code that will increment the schema cookie. 1140 ** 1141 ** The schema cookie is used to determine when the schema for the 1142 ** database changes. After each schema change, the cookie value 1143 ** changes. When a process first reads the schema it records the 1144 ** cookie. Thereafter, whenever it goes to access the database, 1145 ** it checks the cookie to make sure the schema has not changed 1146 ** since it was last read. 1147 ** 1148 ** This plan is not completely bullet-proof. It is possible for 1149 ** the schema to change multiple times and for the cookie to be 1150 ** set back to prior value. But schema changes are infrequent 1151 ** and the probability of hitting the same cookie value is only 1152 ** 1 chance in 2^32. So we're safe enough. 1153 */ 1154 void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){ 1155 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0); 1156 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0); 1157 } 1158 1159 /* 1160 ** Measure the number of characters needed to output the given 1161 ** identifier. The number returned includes any quotes used 1162 ** but does not include the null terminator. 1163 ** 1164 ** The estimate is conservative. It might be larger that what is 1165 ** really needed. 1166 */ 1167 static int identLength(const char *z){ 1168 int n; 1169 for(n=0; *z; n++, z++){ 1170 if( *z=='"' ){ n++; } 1171 } 1172 return n + 2; 1173 } 1174 1175 /* 1176 ** Write an identifier onto the end of the given string. Add 1177 ** quote characters as needed. 1178 */ 1179 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 1180 unsigned char *zIdent = (unsigned char*)zSignedIdent; 1181 int i, j, needQuote; 1182 i = *pIdx; 1183 for(j=0; zIdent[j]; j++){ 1184 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 1185 } 1186 needQuote = zIdent[j]!=0 || isdigit(zIdent[0]) 1187 || sqlite3KeywordCode(zIdent, j)!=TK_ID; 1188 if( needQuote ) z[i++] = '"'; 1189 for(j=0; zIdent[j]; j++){ 1190 z[i++] = zIdent[j]; 1191 if( zIdent[j]=='"' ) z[i++] = '"'; 1192 } 1193 if( needQuote ) z[i++] = '"'; 1194 z[i] = 0; 1195 *pIdx = i; 1196 } 1197 1198 /* 1199 ** Generate a CREATE TABLE statement appropriate for the given 1200 ** table. Memory to hold the text of the statement is obtained 1201 ** from sqliteMalloc() and must be freed by the calling function. 1202 */ 1203 static char *createTableStmt(Table *p){ 1204 int i, k, n; 1205 char *zStmt; 1206 char *zSep, *zSep2, *zEnd, *z; 1207 Column *pCol; 1208 n = 0; 1209 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1210 n += identLength(pCol->zName); 1211 z = pCol->zType; 1212 if( z ){ 1213 n += (strlen(z) + 1); 1214 } 1215 } 1216 n += identLength(p->zName); 1217 if( n<50 ){ 1218 zSep = ""; 1219 zSep2 = ","; 1220 zEnd = ")"; 1221 }else{ 1222 zSep = "\n "; 1223 zSep2 = ",\n "; 1224 zEnd = "\n)"; 1225 } 1226 n += 35 + 6*p->nCol; 1227 zStmt = sqliteMallocRaw( n ); 1228 if( zStmt==0 ) return 0; 1229 strcpy(zStmt, !OMIT_TEMPDB&&p->iDb==1 ? "CREATE TEMP TABLE ":"CREATE TABLE "); 1230 k = strlen(zStmt); 1231 identPut(zStmt, &k, p->zName); 1232 zStmt[k++] = '('; 1233 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1234 strcpy(&zStmt[k], zSep); 1235 k += strlen(&zStmt[k]); 1236 zSep = zSep2; 1237 identPut(zStmt, &k, pCol->zName); 1238 if( (z = pCol->zType)!=0 ){ 1239 zStmt[k++] = ' '; 1240 strcpy(&zStmt[k], z); 1241 k += strlen(z); 1242 } 1243 } 1244 strcpy(&zStmt[k], zEnd); 1245 return zStmt; 1246 } 1247 1248 /* 1249 ** This routine is called to report the final ")" that terminates 1250 ** a CREATE TABLE statement. 1251 ** 1252 ** The table structure that other action routines have been building 1253 ** is added to the internal hash tables, assuming no errors have 1254 ** occurred. 1255 ** 1256 ** An entry for the table is made in the master table on disk, unless 1257 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1258 ** it means we are reading the sqlite_master table because we just 1259 ** connected to the database or because the sqlite_master table has 1260 ** recently changed, so the entry for this table already exists in 1261 ** the sqlite_master table. We do not want to create it again. 1262 ** 1263 ** If the pSelect argument is not NULL, it means that this routine 1264 ** was called to create a table generated from a 1265 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1266 ** the new table will match the result set of the SELECT. 1267 */ 1268 void sqlite3EndTable( 1269 Parse *pParse, /* Parse context */ 1270 Token *pCons, /* The ',' token after the last column defn. */ 1271 Token *pEnd, /* The final ')' token in the CREATE TABLE */ 1272 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 1273 ){ 1274 Table *p; 1275 sqlite3 *db = pParse->db; 1276 1277 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return; 1278 p = pParse->pNewTable; 1279 if( p==0 ) return; 1280 1281 assert( !db->init.busy || !pSelect ); 1282 1283 /* If the db->init.busy is 1 it means we are reading the SQL off the 1284 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1285 ** So do not write to the disk again. Extract the root page number 1286 ** for the table from the db->init.newTnum field. (The page number 1287 ** should have been put there by the sqliteOpenCb routine.) 1288 */ 1289 if( db->init.busy ){ 1290 p->tnum = db->init.newTnum; 1291 } 1292 1293 /* If not initializing, then create a record for the new table 1294 ** in the SQLITE_MASTER table of the database. The record number 1295 ** for the new table entry should already be on the stack. 1296 ** 1297 ** If this is a TEMPORARY table, write the entry into the auxiliary 1298 ** file instead of into the main database file. 1299 */ 1300 if( !db->init.busy ){ 1301 int n; 1302 Vdbe *v; 1303 char *zType; /* "view" or "table" */ 1304 char *zType2; /* "VIEW" or "TABLE" */ 1305 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 1306 1307 v = sqlite3GetVdbe(pParse); 1308 if( v==0 ) return; 1309 1310 sqlite3VdbeAddOp(v, OP_Close, 0, 0); 1311 1312 /* Create the rootpage for the new table and push it onto the stack. 1313 ** A view has no rootpage, so just push a zero onto the stack for 1314 ** views. Initialize zType at the same time. 1315 */ 1316 if( p->pSelect==0 ){ 1317 /* A regular table */ 1318 /* sqlite3VdbeAddOp(v, OP_CreateTable, p->iDb, 0); */ 1319 zType = "table"; 1320 zType2 = "TABLE"; 1321 #ifndef SQLITE_OMIT_VIEW 1322 }else{ 1323 /* A view */ 1324 /* sqlite3VdbeAddOp(v, OP_Integer, 0, 0); */ 1325 zType = "view"; 1326 zType2 = "VIEW"; 1327 #endif 1328 } 1329 1330 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 1331 ** statement to populate the new table. The root-page number for the 1332 ** new table is on the top of the vdbe stack. 1333 ** 1334 ** Once the SELECT has been coded by sqlite3Select(), it is in a 1335 ** suitable state to query for the column names and types to be used 1336 ** by the new table. 1337 */ 1338 if( pSelect ){ 1339 Table *pSelTab; 1340 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); 1341 sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0); 1342 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0); 1343 pParse->nTab = 2; 1344 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0); 1345 sqlite3VdbeAddOp(v, OP_Close, 1, 0); 1346 if( pParse->nErr==0 ){ 1347 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); 1348 if( pSelTab==0 ) return; 1349 assert( p->aCol==0 ); 1350 p->nCol = pSelTab->nCol; 1351 p->aCol = pSelTab->aCol; 1352 pSelTab->nCol = 0; 1353 pSelTab->aCol = 0; 1354 sqlite3DeleteTable(0, pSelTab); 1355 } 1356 } 1357 1358 /* Compute the complete text of the CREATE statement */ 1359 if( pSelect ){ 1360 zStmt = createTableStmt(p); 1361 }else{ 1362 n = pEnd->z - pParse->sNameToken.z + 1; 1363 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z); 1364 } 1365 1366 /* A slot for the record has already been allocated in the 1367 ** SQLITE_MASTER table. We just need to update that slot with all 1368 ** the information we've collected. The rowid for the preallocated 1369 ** slot is the 2nd item on the stack. The top of the stack is the 1370 ** root page for the new table (or a 0 if this is a view). 1371 */ 1372 sqlite3NestedParse(pParse, 1373 "UPDATE %Q.%s " 1374 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q " 1375 "WHERE rowid=#1", 1376 db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb), 1377 zType, 1378 p->zName, 1379 p->zName, 1380 zStmt 1381 ); 1382 sqliteFree(zStmt); 1383 sqlite3ChangeCookie(db, v, p->iDb); 1384 1385 #ifndef SQLITE_OMIT_AUTOINCREMENT 1386 /* Check to see if we need to create an sqlite_sequence table for 1387 ** keeping track of autoincrement keys. 1388 */ 1389 if( p->autoInc ){ 1390 Db *pDb = &db->aDb[p->iDb]; 1391 if( pDb->pSeqTab==0 ){ 1392 sqlite3NestedParse(pParse, 1393 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 1394 pDb->zName 1395 ); 1396 } 1397 } 1398 #endif 1399 1400 /* Reparse everything to update our internal data structures */ 1401 sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0, 1402 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC); 1403 } 1404 1405 1406 /* Add the table to the in-memory representation of the database. 1407 */ 1408 if( db->init.busy && pParse->nErr==0 ){ 1409 Table *pOld; 1410 FKey *pFKey; 1411 Db *pDb = &db->aDb[p->iDb]; 1412 pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p); 1413 if( pOld ){ 1414 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 1415 return; 1416 } 1417 #ifndef SQLITE_OMIT_FOREIGN_KEY 1418 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1419 int nTo = strlen(pFKey->zTo) + 1; 1420 pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo); 1421 sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey); 1422 } 1423 #endif 1424 pParse->pNewTable = 0; 1425 db->nTable++; 1426 db->flags |= SQLITE_InternChanges; 1427 1428 #ifndef SQLITE_OMIT_ALTERTABLE 1429 if( !p->pSelect ){ 1430 assert( !pSelect && pCons && pEnd ); 1431 if( pCons->z==0 ) pCons = pEnd; 1432 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z); 1433 } 1434 #endif 1435 } 1436 } 1437 1438 #ifndef SQLITE_OMIT_VIEW 1439 /* 1440 ** The parser calls this routine in order to create a new VIEW 1441 */ 1442 void sqlite3CreateView( 1443 Parse *pParse, /* The parsing context */ 1444 Token *pBegin, /* The CREATE token that begins the statement */ 1445 Token *pName1, /* The token that holds the name of the view */ 1446 Token *pName2, /* The token that holds the name of the view */ 1447 Select *pSelect, /* A SELECT statement that will become the new view */ 1448 int isTemp /* TRUE for a TEMPORARY view */ 1449 ){ 1450 Table *p; 1451 int n; 1452 const unsigned char *z; 1453 Token sEnd; 1454 DbFixer sFix; 1455 Token *pName; 1456 1457 if( pParse->nVar>0 ){ 1458 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 1459 sqlite3SelectDelete(pSelect); 1460 return; 1461 } 1462 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1); 1463 p = pParse->pNewTable; 1464 if( p==0 || pParse->nErr ){ 1465 sqlite3SelectDelete(pSelect); 1466 return; 1467 } 1468 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 1469 if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName) 1470 && sqlite3FixSelect(&sFix, pSelect) 1471 ){ 1472 sqlite3SelectDelete(pSelect); 1473 return; 1474 } 1475 1476 /* Make a copy of the entire SELECT statement that defines the view. 1477 ** This will force all the Expr.token.z values to be dynamically 1478 ** allocated rather than point to the input string - which means that 1479 ** they will persist after the current sqlite3_exec() call returns. 1480 */ 1481 p->pSelect = sqlite3SelectDup(pSelect); 1482 sqlite3SelectDelete(pSelect); 1483 if( !pParse->db->init.busy ){ 1484 sqlite3ViewGetColumnNames(pParse, p); 1485 } 1486 1487 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 1488 ** the end. 1489 */ 1490 sEnd = pParse->sLastToken; 1491 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ 1492 sEnd.z += sEnd.n; 1493 } 1494 sEnd.n = 0; 1495 n = sEnd.z - pBegin->z; 1496 z = (const unsigned char*)pBegin->z; 1497 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } 1498 sEnd.z = &z[n-1]; 1499 sEnd.n = 1; 1500 1501 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 1502 sqlite3EndTable(pParse, 0, &sEnd, 0); 1503 return; 1504 } 1505 #endif /* SQLITE_OMIT_VIEW */ 1506 1507 #ifndef SQLITE_OMIT_VIEW 1508 /* 1509 ** The Table structure pTable is really a VIEW. Fill in the names of 1510 ** the columns of the view in the pTable structure. Return the number 1511 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 1512 */ 1513 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 1514 Table *pSelTab; /* A fake table from which we get the result set */ 1515 Select *pSel; /* Copy of the SELECT that implements the view */ 1516 int nErr = 0; /* Number of errors encountered */ 1517 int n; /* Temporarily holds the number of cursors assigned */ 1518 1519 assert( pTable ); 1520 1521 /* A positive nCol means the columns names for this view are 1522 ** already known. 1523 */ 1524 if( pTable->nCol>0 ) return 0; 1525 1526 /* A negative nCol is a special marker meaning that we are currently 1527 ** trying to compute the column names. If we enter this routine with 1528 ** a negative nCol, it means two or more views form a loop, like this: 1529 ** 1530 ** CREATE VIEW one AS SELECT * FROM two; 1531 ** CREATE VIEW two AS SELECT * FROM one; 1532 ** 1533 ** Actually, this error is caught previously and so the following test 1534 ** should always fail. But we will leave it in place just to be safe. 1535 */ 1536 if( pTable->nCol<0 ){ 1537 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 1538 return 1; 1539 } 1540 1541 /* If we get this far, it means we need to compute the table names. 1542 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 1543 ** "*" elements in the results set of the view and will assign cursors 1544 ** to the elements of the FROM clause. But we do not want these changes 1545 ** to be permanent. So the computation is done on a copy of the SELECT 1546 ** statement that defines the view. 1547 */ 1548 assert( pTable->pSelect ); 1549 pSel = sqlite3SelectDup(pTable->pSelect); 1550 n = pParse->nTab; 1551 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 1552 pTable->nCol = -1; 1553 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel); 1554 pParse->nTab = n; 1555 if( pSelTab ){ 1556 assert( pTable->aCol==0 ); 1557 pTable->nCol = pSelTab->nCol; 1558 pTable->aCol = pSelTab->aCol; 1559 pSelTab->nCol = 0; 1560 pSelTab->aCol = 0; 1561 sqlite3DeleteTable(0, pSelTab); 1562 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews); 1563 }else{ 1564 pTable->nCol = 0; 1565 nErr++; 1566 } 1567 sqlite3SelectDelete(pSel); 1568 return nErr; 1569 } 1570 #endif /* SQLITE_OMIT_VIEW */ 1571 1572 #ifndef SQLITE_OMIT_VIEW 1573 /* 1574 ** Clear the column names from every VIEW in database idx. 1575 */ 1576 static void sqliteViewResetAll(sqlite3 *db, int idx){ 1577 HashElem *i; 1578 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 1579 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){ 1580 Table *pTab = sqliteHashData(i); 1581 if( pTab->pSelect ){ 1582 sqliteResetColumnNames(pTab); 1583 } 1584 } 1585 DbClearProperty(db, idx, DB_UnresetViews); 1586 } 1587 #else 1588 # define sqliteViewResetAll(A,B) 1589 #endif /* SQLITE_OMIT_VIEW */ 1590 1591 /* 1592 ** This function is called by the VDBE to adjust the internal schema 1593 ** used by SQLite when the btree layer moves a table root page. The 1594 ** root-page of a table or index in database iDb has changed from iFrom 1595 ** to iTo. 1596 */ 1597 #ifndef SQLITE_OMIT_AUTOVACUUM 1598 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ 1599 HashElem *pElem; 1600 1601 for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){ 1602 Table *pTab = sqliteHashData(pElem); 1603 if( pTab->tnum==iFrom ){ 1604 pTab->tnum = iTo; 1605 return; 1606 } 1607 } 1608 for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){ 1609 Index *pIdx = sqliteHashData(pElem); 1610 if( pIdx->tnum==iFrom ){ 1611 pIdx->tnum = iTo; 1612 return; 1613 } 1614 } 1615 assert(0); 1616 } 1617 #endif 1618 1619 /* 1620 ** Write code to erase the table with root-page iTable from database iDb. 1621 ** Also write code to modify the sqlite_master table and internal schema 1622 ** if a root-page of another table is moved by the btree-layer whilst 1623 ** erasing iTable (this can happen with an auto-vacuum database). 1624 */ 1625 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 1626 Vdbe *v = sqlite3GetVdbe(pParse); 1627 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb); 1628 #ifndef SQLITE_OMIT_AUTOVACUUM 1629 /* OP_Destroy pushes an integer onto the stack. If this integer 1630 ** is non-zero, then it is the root page number of a table moved to 1631 ** location iTable. The following code modifies the sqlite_master table to 1632 ** reflect this. 1633 ** 1634 ** The "#0" in the SQL is a special constant that means whatever value 1635 ** is on the top of the stack. See sqlite3RegisterExpr(). 1636 */ 1637 sqlite3NestedParse(pParse, 1638 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0", 1639 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable); 1640 #endif 1641 } 1642 1643 /* 1644 ** Write VDBE code to erase table pTab and all associated indices on disk. 1645 ** Code to update the sqlite_master tables and internal schema definitions 1646 ** in case a root-page belonging to another table is moved by the btree layer 1647 ** is also added (this can happen with an auto-vacuum database). 1648 */ 1649 static void destroyTable(Parse *pParse, Table *pTab){ 1650 #ifdef SQLITE_OMIT_AUTOVACUUM 1651 Index *pIdx; 1652 destroyRootPage(pParse, pTab->tnum, pTab->iDb); 1653 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1654 destroyRootPage(pParse, pIdx->tnum, pIdx->iDb); 1655 } 1656 #else 1657 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 1658 ** is not defined), then it is important to call OP_Destroy on the 1659 ** table and index root-pages in order, starting with the numerically 1660 ** largest root-page number. This guarantees that none of the root-pages 1661 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 1662 ** following were coded: 1663 ** 1664 ** OP_Destroy 4 0 1665 ** ... 1666 ** OP_Destroy 5 0 1667 ** 1668 ** and root page 5 happened to be the largest root-page number in the 1669 ** database, then root page 5 would be moved to page 4 by the 1670 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 1671 ** a free-list page. 1672 */ 1673 int iTab = pTab->tnum; 1674 int iDestroyed = 0; 1675 1676 while( 1 ){ 1677 Index *pIdx; 1678 int iLargest = 0; 1679 1680 if( iDestroyed==0 || iTab<iDestroyed ){ 1681 iLargest = iTab; 1682 } 1683 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1684 int iIdx = pIdx->tnum; 1685 assert( pIdx->iDb==pTab->iDb ); 1686 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 1687 iLargest = iIdx; 1688 } 1689 } 1690 if( iLargest==0 ) return; 1691 destroyRootPage(pParse, iLargest, pTab->iDb); 1692 iDestroyed = iLargest; 1693 } 1694 #endif 1695 } 1696 1697 /* 1698 ** This routine is called to do the work of a DROP TABLE statement. 1699 ** pName is the name of the table to be dropped. 1700 */ 1701 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){ 1702 Table *pTab; 1703 Vdbe *v; 1704 sqlite3 *db = pParse->db; 1705 int iDb; 1706 1707 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table; 1708 assert( pName->nSrc==1 ); 1709 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase); 1710 1711 if( pTab==0 ) goto exit_drop_table; 1712 iDb = pTab->iDb; 1713 assert( iDb>=0 && iDb<db->nDb ); 1714 #ifndef SQLITE_OMIT_AUTHORIZATION 1715 { 1716 int code; 1717 const char *zTab = SCHEMA_TABLE(pTab->iDb); 1718 const char *zDb = db->aDb[pTab->iDb].zName; 1719 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 1720 goto exit_drop_table; 1721 } 1722 if( isView ){ 1723 if( !OMIT_TEMPDB && iDb==1 ){ 1724 code = SQLITE_DROP_TEMP_VIEW; 1725 }else{ 1726 code = SQLITE_DROP_VIEW; 1727 } 1728 }else{ 1729 if( !OMIT_TEMPDB && iDb==1 ){ 1730 code = SQLITE_DROP_TEMP_TABLE; 1731 }else{ 1732 code = SQLITE_DROP_TABLE; 1733 } 1734 } 1735 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){ 1736 goto exit_drop_table; 1737 } 1738 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 1739 goto exit_drop_table; 1740 } 1741 } 1742 #endif 1743 if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){ 1744 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 1745 goto exit_drop_table; 1746 } 1747 1748 #ifndef SQLITE_OMIT_VIEW 1749 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 1750 ** on a table. 1751 */ 1752 if( isView && pTab->pSelect==0 ){ 1753 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 1754 goto exit_drop_table; 1755 } 1756 if( !isView && pTab->pSelect ){ 1757 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 1758 goto exit_drop_table; 1759 } 1760 #endif 1761 1762 /* Generate code to remove the table from the master table 1763 ** on disk. 1764 */ 1765 v = sqlite3GetVdbe(pParse); 1766 if( v ){ 1767 Trigger *pTrigger; 1768 int iDb = pTab->iDb; 1769 Db *pDb = &db->aDb[iDb]; 1770 sqlite3BeginWriteOperation(pParse, 0, iDb); 1771 1772 /* Drop all triggers associated with the table being dropped. Code 1773 ** is generated to remove entries from sqlite_master and/or 1774 ** sqlite_temp_master if required. 1775 */ 1776 pTrigger = pTab->pTrigger; 1777 while( pTrigger ){ 1778 assert( pTrigger->iDb==iDb || pTrigger->iDb==1 ); 1779 sqlite3DropTriggerPtr(pParse, pTrigger, 1); 1780 pTrigger = pTrigger->pNext; 1781 } 1782 1783 #ifndef SQLITE_OMIT_AUTOINCREMENT 1784 /* Remove any entries of the sqlite_sequence table associated with 1785 ** the table being dropped. This is done before the table is dropped 1786 ** at the btree level, in case the sqlite_sequence table needs to 1787 ** move as a result of the drop (can happen in auto-vacuum mode). 1788 */ 1789 if( pTab->autoInc ){ 1790 sqlite3NestedParse(pParse, 1791 "DELETE FROM %s.sqlite_sequence WHERE name=%Q", 1792 pDb->zName, pTab->zName 1793 ); 1794 } 1795 #endif 1796 1797 /* Drop all SQLITE_MASTER table and index entries that refer to the 1798 ** table. The program name loops through the master table and deletes 1799 ** every row that refers to a table of the same name as the one being 1800 ** dropped. Triggers are handled seperately because a trigger can be 1801 ** created in the temp database that refers to a table in another 1802 ** database. 1803 */ 1804 sqlite3NestedParse(pParse, 1805 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 1806 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 1807 if( !isView ){ 1808 destroyTable(pParse, pTab); 1809 } 1810 1811 /* Remove the table entry from SQLite's internal schema and modify 1812 ** the schema cookie. 1813 */ 1814 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); 1815 sqlite3ChangeCookie(db, v, iDb); 1816 } 1817 sqliteViewResetAll(db, iDb); 1818 1819 exit_drop_table: 1820 sqlite3SrcListDelete(pName); 1821 } 1822 1823 /* 1824 ** This routine is called to create a new foreign key on the table 1825 ** currently under construction. pFromCol determines which columns 1826 ** in the current table point to the foreign key. If pFromCol==0 then 1827 ** connect the key to the last column inserted. pTo is the name of 1828 ** the table referred to. pToCol is a list of tables in the other 1829 ** pTo table that the foreign key points to. flags contains all 1830 ** information about the conflict resolution algorithms specified 1831 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 1832 ** 1833 ** An FKey structure is created and added to the table currently 1834 ** under construction in the pParse->pNewTable field. The new FKey 1835 ** is not linked into db->aFKey at this point - that does not happen 1836 ** until sqlite3EndTable(). 1837 ** 1838 ** The foreign key is set for IMMEDIATE processing. A subsequent call 1839 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 1840 */ 1841 void sqlite3CreateForeignKey( 1842 Parse *pParse, /* Parsing context */ 1843 ExprList *pFromCol, /* Columns in this table that point to other table */ 1844 Token *pTo, /* Name of the other table */ 1845 ExprList *pToCol, /* Columns in the other table */ 1846 int flags /* Conflict resolution algorithms. */ 1847 ){ 1848 #ifndef SQLITE_OMIT_FOREIGN_KEY 1849 FKey *pFKey = 0; 1850 Table *p = pParse->pNewTable; 1851 int nByte; 1852 int i; 1853 int nCol; 1854 char *z; 1855 1856 assert( pTo!=0 ); 1857 if( p==0 || pParse->nErr ) goto fk_end; 1858 if( pFromCol==0 ){ 1859 int iCol = p->nCol-1; 1860 if( iCol<0 ) goto fk_end; 1861 if( pToCol && pToCol->nExpr!=1 ){ 1862 sqlite3ErrorMsg(pParse, "foreign key on %s" 1863 " should reference only one column of table %T", 1864 p->aCol[iCol].zName, pTo); 1865 goto fk_end; 1866 } 1867 nCol = 1; 1868 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 1869 sqlite3ErrorMsg(pParse, 1870 "number of columns in foreign key does not match the number of " 1871 "columns in the referenced table"); 1872 goto fk_end; 1873 }else{ 1874 nCol = pFromCol->nExpr; 1875 } 1876 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; 1877 if( pToCol ){ 1878 for(i=0; i<pToCol->nExpr; i++){ 1879 nByte += strlen(pToCol->a[i].zName) + 1; 1880 } 1881 } 1882 pFKey = sqliteMalloc( nByte ); 1883 if( pFKey==0 ) goto fk_end; 1884 pFKey->pFrom = p; 1885 pFKey->pNextFrom = p->pFKey; 1886 z = (char*)&pFKey[1]; 1887 pFKey->aCol = (struct sColMap*)z; 1888 z += sizeof(struct sColMap)*nCol; 1889 pFKey->zTo = z; 1890 memcpy(z, pTo->z, pTo->n); 1891 z[pTo->n] = 0; 1892 z += pTo->n+1; 1893 pFKey->pNextTo = 0; 1894 pFKey->nCol = nCol; 1895 if( pFromCol==0 ){ 1896 pFKey->aCol[0].iFrom = p->nCol-1; 1897 }else{ 1898 for(i=0; i<nCol; i++){ 1899 int j; 1900 for(j=0; j<p->nCol; j++){ 1901 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 1902 pFKey->aCol[i].iFrom = j; 1903 break; 1904 } 1905 } 1906 if( j>=p->nCol ){ 1907 sqlite3ErrorMsg(pParse, 1908 "unknown column \"%s\" in foreign key definition", 1909 pFromCol->a[i].zName); 1910 goto fk_end; 1911 } 1912 } 1913 } 1914 if( pToCol ){ 1915 for(i=0; i<nCol; i++){ 1916 int n = strlen(pToCol->a[i].zName); 1917 pFKey->aCol[i].zCol = z; 1918 memcpy(z, pToCol->a[i].zName, n); 1919 z[n] = 0; 1920 z += n+1; 1921 } 1922 } 1923 pFKey->isDeferred = 0; 1924 pFKey->deleteConf = flags & 0xff; 1925 pFKey->updateConf = (flags >> 8 ) & 0xff; 1926 pFKey->insertConf = (flags >> 16 ) & 0xff; 1927 1928 /* Link the foreign key to the table as the last step. 1929 */ 1930 p->pFKey = pFKey; 1931 pFKey = 0; 1932 1933 fk_end: 1934 sqliteFree(pFKey); 1935 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 1936 sqlite3ExprListDelete(pFromCol); 1937 sqlite3ExprListDelete(pToCol); 1938 } 1939 1940 /* 1941 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 1942 ** clause is seen as part of a foreign key definition. The isDeferred 1943 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 1944 ** The behavior of the most recently created foreign key is adjusted 1945 ** accordingly. 1946 */ 1947 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 1948 #ifndef SQLITE_OMIT_FOREIGN_KEY 1949 Table *pTab; 1950 FKey *pFKey; 1951 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 1952 pFKey->isDeferred = isDeferred; 1953 #endif 1954 } 1955 1956 /* 1957 ** Generate code that will erase and refill index *pIdx. This is 1958 ** used to initialize a newly created index or to recompute the 1959 ** content of an index in response to a REINDEX command. 1960 ** 1961 ** if memRootPage is not negative, it means that the index is newly 1962 ** created. The memory cell specified by memRootPage contains the 1963 ** root page number of the index. If memRootPage is negative, then 1964 ** the index already exists and must be cleared before being refilled and 1965 ** the root page number of the index is taken from pIndex->tnum. 1966 */ 1967 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 1968 Table *pTab = pIndex->pTable; /* The table that is indexed */ 1969 int iTab = pParse->nTab; /* Btree cursor used for pTab */ 1970 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */ 1971 int addr1; /* Address of top of loop */ 1972 int tnum; /* Root page of index */ 1973 Vdbe *v; /* Generate code into this virtual machine */ 1974 1975 #ifndef SQLITE_OMIT_AUTHORIZATION 1976 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 1977 pParse->db->aDb[pIndex->iDb].zName ) ){ 1978 return; 1979 } 1980 #endif 1981 1982 /* Ensure all the required collation sequences are available. This 1983 ** routine will invoke the collation-needed callback if necessary (and 1984 ** if one has been registered). 1985 */ 1986 if( sqlite3CheckIndexCollSeq(pParse, pIndex) ){ 1987 return; 1988 } 1989 1990 v = sqlite3GetVdbe(pParse); 1991 if( v==0 ) return; 1992 if( memRootPage>=0 ){ 1993 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0); 1994 tnum = 0; 1995 }else{ 1996 tnum = pIndex->tnum; 1997 sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb); 1998 } 1999 sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0); 2000 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, 2001 (char*)&pIndex->keyInfo, P3_KEYINFO); 2002 sqlite3OpenTableForReading(v, iTab, pTab); 2003 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); 2004 sqlite3GenerateIndexKey(v, pIndex, iTab); 2005 if( pIndex->onError!=OE_None ){ 2006 int curaddr = sqlite3VdbeCurrentAddr(v); 2007 int addr2 = curaddr+4; 2008 sqlite3VdbeChangeP2(v, curaddr-1, addr2); 2009 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0); 2010 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0); 2011 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2); 2012 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 2013 "indexed columns are not unique", P3_STATIC); 2014 assert( addr2==sqlite3VdbeCurrentAddr(v) ); 2015 } 2016 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0); 2017 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1); 2018 sqlite3VdbeChangeP2(v, addr1, sqlite3VdbeCurrentAddr(v)); 2019 sqlite3VdbeAddOp(v, OP_Close, iTab, 0); 2020 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 2021 } 2022 2023 /* 2024 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 2025 ** and pTblList is the name of the table that is to be indexed. Both will 2026 ** be NULL for a primary key or an index that is created to satisfy a 2027 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2028 ** as the table to be indexed. pParse->pNewTable is a table that is 2029 ** currently being constructed by a CREATE TABLE statement. 2030 ** 2031 ** pList is a list of columns to be indexed. pList will be NULL if this 2032 ** is a primary key or unique-constraint on the most recent column added 2033 ** to the table currently under construction. 2034 */ 2035 void sqlite3CreateIndex( 2036 Parse *pParse, /* All information about this parse */ 2037 Token *pName1, /* First part of index name. May be NULL */ 2038 Token *pName2, /* Second part of index name. May be NULL */ 2039 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 2040 ExprList *pList, /* A list of columns to be indexed */ 2041 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 2042 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */ 2043 Token *pEnd /* The ")" that closes the CREATE INDEX statement */ 2044 ){ 2045 Table *pTab = 0; /* Table to be indexed */ 2046 Index *pIndex = 0; /* The index to be created */ 2047 char *zName = 0; 2048 int i, j; 2049 Token nullId; /* Fake token for an empty ID list */ 2050 DbFixer sFix; /* For assigning database names to pTable */ 2051 sqlite3 *db = pParse->db; 2052 2053 int iDb; /* Index of the database that is being written */ 2054 Token *pName = 0; /* Unqualified name of the index to create */ 2055 2056 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index; 2057 2058 /* 2059 ** Find the table that is to be indexed. Return early if not found. 2060 */ 2061 if( pTblName!=0 ){ 2062 2063 /* Use the two-part index name to determine the database 2064 ** to search for the table. 'Fix' the table name to this db 2065 ** before looking up the table. 2066 */ 2067 assert( pName1 && pName2 ); 2068 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2069 if( iDb<0 ) goto exit_create_index; 2070 2071 #ifndef SQLITE_OMIT_TEMPDB 2072 /* If the index name was unqualified, check if the the table 2073 ** is a temp table. If so, set the database to 1. 2074 */ 2075 pTab = sqlite3SrcListLookup(pParse, pTblName); 2076 if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){ 2077 iDb = 1; 2078 } 2079 #endif 2080 2081 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && 2082 sqlite3FixSrcList(&sFix, pTblName) 2083 ){ 2084 goto exit_create_index; 2085 } 2086 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, 2087 pTblName->a[0].zDatabase); 2088 if( !pTab ) goto exit_create_index; 2089 assert( iDb==pTab->iDb ); 2090 }else{ 2091 assert( pName==0 ); 2092 pTab = pParse->pNewTable; 2093 iDb = pTab->iDb; 2094 } 2095 2096 if( pTab==0 || pParse->nErr ) goto exit_create_index; 2097 if( pTab->readOnly ){ 2098 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 2099 goto exit_create_index; 2100 } 2101 #ifndef SQLITE_OMIT_VIEW 2102 if( pTab->pSelect ){ 2103 sqlite3ErrorMsg(pParse, "views may not be indexed"); 2104 goto exit_create_index; 2105 } 2106 #endif 2107 2108 /* 2109 ** Find the name of the index. Make sure there is not already another 2110 ** index or table with the same name. 2111 ** 2112 ** Exception: If we are reading the names of permanent indices from the 2113 ** sqlite_master table (because some other process changed the schema) and 2114 ** one of the index names collides with the name of a temporary table or 2115 ** index, then we will continue to process this index. 2116 ** 2117 ** If pName==0 it means that we are 2118 ** dealing with a primary key or UNIQUE constraint. We have to invent our 2119 ** own name. 2120 */ 2121 if( pName ){ 2122 zName = sqlite3NameFromToken(pName); 2123 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 2124 if( zName==0 ) goto exit_create_index; 2125 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 2126 goto exit_create_index; 2127 } 2128 if( !db->init.busy ){ 2129 Index *pISameName; /* Another index with the same name */ 2130 Table *pTSameName; /* A table with same name as the index */ 2131 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index; 2132 if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName))!=0 ){ 2133 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 2134 goto exit_create_index; 2135 } 2136 if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 ){ 2137 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 2138 goto exit_create_index; 2139 } 2140 } 2141 }else{ 2142 char zBuf[30]; 2143 int n; 2144 Index *pLoop; 2145 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 2146 sprintf(zBuf,"_%d",n); 2147 zName = 0; 2148 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0); 2149 if( zName==0 ) goto exit_create_index; 2150 } 2151 2152 /* Check for authorization to create an index. 2153 */ 2154 #ifndef SQLITE_OMIT_AUTHORIZATION 2155 { 2156 const char *zDb = db->aDb[iDb].zName; 2157 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 2158 goto exit_create_index; 2159 } 2160 i = SQLITE_CREATE_INDEX; 2161 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 2162 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 2163 goto exit_create_index; 2164 } 2165 } 2166 #endif 2167 2168 /* If pList==0, it means this routine was called to make a primary 2169 ** key out of the last column added to the table under construction. 2170 ** So create a fake list to simulate this. 2171 */ 2172 if( pList==0 ){ 2173 nullId.z = pTab->aCol[pTab->nCol-1].zName; 2174 nullId.n = strlen(nullId.z); 2175 pList = sqlite3ExprListAppend(0, 0, &nullId); 2176 if( pList==0 ) goto exit_create_index; 2177 } 2178 2179 /* 2180 ** Allocate the index structure. 2181 */ 2182 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) + 2183 (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr ); 2184 if( sqlite3_malloc_failed ) goto exit_create_index; 2185 pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr]; 2186 pIndex->aiRowEst = &pIndex->aiColumn[pList->nExpr]; 2187 pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1]; 2188 strcpy(pIndex->zName, zName); 2189 pIndex->pTable = pTab; 2190 pIndex->nColumn = pList->nExpr; 2191 pIndex->onError = onError; 2192 pIndex->autoIndex = pName==0; 2193 pIndex->iDb = iDb; 2194 2195 /* Scan the names of the columns of the table to be indexed and 2196 ** load the column indices into the Index structure. Report an error 2197 ** if any column is not found. 2198 */ 2199 for(i=0; i<pList->nExpr; i++){ 2200 for(j=0; j<pTab->nCol; j++){ 2201 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break; 2202 } 2203 if( j>=pTab->nCol ){ 2204 sqlite3ErrorMsg(pParse, "table %s has no column named %s", 2205 pTab->zName, pList->a[i].zName); 2206 goto exit_create_index; 2207 } 2208 pIndex->aiColumn[i] = j; 2209 if( pList->a[i].pExpr ){ 2210 assert( pList->a[i].pExpr->pColl ); 2211 pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl; 2212 }else{ 2213 pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl; 2214 } 2215 assert( pIndex->keyInfo.aColl[i] ); 2216 if( !db->init.busy && 2217 sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i]) 2218 ){ 2219 goto exit_create_index; 2220 } 2221 } 2222 pIndex->keyInfo.nField = pList->nExpr; 2223 sqlite3DefaultRowEst(pIndex); 2224 2225 if( pTab==pParse->pNewTable ){ 2226 /* This routine has been called to create an automatic index as a 2227 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 2228 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 2229 ** i.e. one of: 2230 ** 2231 ** CREATE TABLE t(x PRIMARY KEY, y); 2232 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 2233 ** 2234 ** Either way, check to see if the table already has such an index. If 2235 ** so, don't bother creating this one. This only applies to 2236 ** automatically created indices. Users can do as they wish with 2237 ** explicit indices. 2238 */ 2239 Index *pIdx; 2240 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2241 int k; 2242 assert( pIdx->onError!=OE_None ); 2243 assert( pIdx->autoIndex ); 2244 assert( pIndex->onError!=OE_None ); 2245 2246 if( pIdx->nColumn!=pIndex->nColumn ) continue; 2247 for(k=0; k<pIdx->nColumn; k++){ 2248 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 2249 if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break; 2250 } 2251 if( k==pIdx->nColumn ){ 2252 if( pIdx->onError!=pIndex->onError ){ 2253 /* This constraint creates the same index as a previous 2254 ** constraint specified somewhere in the CREATE TABLE statement. 2255 ** However the ON CONFLICT clauses are different. If both this 2256 ** constraint and the previous equivalent constraint have explicit 2257 ** ON CONFLICT clauses this is an error. Otherwise, use the 2258 ** explicitly specified behaviour for the index. 2259 */ 2260 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 2261 sqlite3ErrorMsg(pParse, 2262 "conflicting ON CONFLICT clauses specified", 0); 2263 } 2264 if( pIdx->onError==OE_Default ){ 2265 pIdx->onError = pIndex->onError; 2266 } 2267 } 2268 goto exit_create_index; 2269 } 2270 } 2271 } 2272 2273 /* Link the new Index structure to its table and to the other 2274 ** in-memory database structures. 2275 */ 2276 if( db->init.busy ){ 2277 Index *p; 2278 p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash, 2279 pIndex->zName, strlen(pIndex->zName)+1, pIndex); 2280 if( p ){ 2281 assert( p==pIndex ); /* Malloc must have failed */ 2282 goto exit_create_index; 2283 } 2284 db->flags |= SQLITE_InternChanges; 2285 if( pTblName!=0 ){ 2286 pIndex->tnum = db->init.newTnum; 2287 } 2288 } 2289 2290 /* If the db->init.busy is 0 then create the index on disk. This 2291 ** involves writing the index into the master table and filling in the 2292 ** index with the current table contents. 2293 ** 2294 ** The db->init.busy is 0 when the user first enters a CREATE INDEX 2295 ** command. db->init.busy is 1 when a database is opened and 2296 ** CREATE INDEX statements are read out of the master table. In 2297 ** the latter case the index already exists on disk, which is why 2298 ** we don't want to recreate it. 2299 ** 2300 ** If pTblName==0 it means this index is generated as a primary key 2301 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table 2302 ** has just been created, it contains no data and the index initialization 2303 ** step can be skipped. 2304 */ 2305 else if( db->init.busy==0 ){ 2306 Vdbe *v; 2307 char *zStmt; 2308 int iMem = pParse->nMem++; 2309 2310 v = sqlite3GetVdbe(pParse); 2311 if( v==0 ) goto exit_create_index; 2312 2313 /* Create the rootpage for the index 2314 */ 2315 sqlite3BeginWriteOperation(pParse, 1, iDb); 2316 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0); 2317 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); 2318 2319 /* Gather the complete text of the CREATE INDEX statement into 2320 ** the zStmt variable 2321 */ 2322 if( pStart && pEnd ){ 2323 /* A named index with an explicit CREATE INDEX statement */ 2324 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s", 2325 onError==OE_None ? "" : " UNIQUE", 2326 pEnd->z - pName->z + 1, 2327 pName->z); 2328 }else{ 2329 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 2330 /* zStmt = sqlite3MPrintf(""); */ 2331 zStmt = 0; 2332 } 2333 2334 /* Add an entry in sqlite_master for this index 2335 */ 2336 sqlite3NestedParse(pParse, 2337 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);", 2338 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2339 pIndex->zName, 2340 pTab->zName, 2341 zStmt 2342 ); 2343 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 2344 sqliteFree(zStmt); 2345 2346 /* Fill the index with data and reparse the schema. Code an OP_Expire 2347 ** to invalidate all pre-compiled statements. 2348 */ 2349 if( pTblName ){ 2350 sqlite3RefillIndex(pParse, pIndex, iMem); 2351 sqlite3ChangeCookie(db, v, iDb); 2352 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, 2353 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC); 2354 sqlite3VdbeAddOp(v, OP_Expire, 0, 0); 2355 } 2356 } 2357 2358 /* When adding an index to the list of indices for a table, make 2359 ** sure all indices labeled OE_Replace come after all those labeled 2360 ** OE_Ignore. This is necessary for the correct operation of UPDATE 2361 ** and INSERT. 2362 */ 2363 if( db->init.busy || pTblName==0 ){ 2364 if( onError!=OE_Replace || pTab->pIndex==0 2365 || pTab->pIndex->onError==OE_Replace){ 2366 pIndex->pNext = pTab->pIndex; 2367 pTab->pIndex = pIndex; 2368 }else{ 2369 Index *pOther = pTab->pIndex; 2370 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 2371 pOther = pOther->pNext; 2372 } 2373 pIndex->pNext = pOther->pNext; 2374 pOther->pNext = pIndex; 2375 } 2376 pIndex = 0; 2377 } 2378 2379 /* Clean up before exiting */ 2380 exit_create_index: 2381 if( pIndex ){ 2382 freeIndex(pIndex); 2383 } 2384 sqlite3ExprListDelete(pList); 2385 sqlite3SrcListDelete(pTblName); 2386 sqliteFree(zName); 2387 return; 2388 } 2389 2390 /* 2391 ** Fill the Index.aiRowEst[] array with default information - information 2392 ** to be used when we have no ANALYZE command to run. 2393 ** 2394 ** aiRowEst[0] is suppose to contain the number of elements in the index. 2395 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 2396 ** number of rows in the table that match any particular value of the 2397 ** first column of the index. aiRowEst[2] is an estimate of the number 2398 ** of rows that match any particular combiniation of the first 2 columns 2399 ** of the index. And so forth. It must always be the case that 2400 * 2401 ** aiRowEst[N]<=aiRowEst[N-1] 2402 ** aiRowEst[N]>=1 2403 ** 2404 ** Apart from that, we have little to go on besides intuition as to 2405 ** how aiRowEst[] should be initialized. The numbers generated here 2406 ** are based on typical values found in actual indices. 2407 */ 2408 void sqlite3DefaultRowEst(Index *pIdx){ 2409 int *a = pIdx->aiRowEst; 2410 int i; 2411 assert( a!=0 ); 2412 a[0] = 1000000; 2413 for(i=pIdx->nColumn; i>=1; i--){ 2414 a[i] = 10; 2415 } 2416 if( pIdx->onError!=OE_None ){ 2417 a[pIdx->nColumn] = 1; 2418 } 2419 } 2420 2421 /* 2422 ** This routine will drop an existing named index. This routine 2423 ** implements the DROP INDEX statement. 2424 */ 2425 void sqlite3DropIndex(Parse *pParse, SrcList *pName){ 2426 Index *pIndex; 2427 Vdbe *v; 2428 sqlite3 *db = pParse->db; 2429 2430 if( pParse->nErr || sqlite3_malloc_failed ){ 2431 goto exit_drop_index; 2432 } 2433 assert( pName->nSrc==1 ); 2434 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2435 goto exit_drop_index; 2436 } 2437 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 2438 if( pIndex==0 ){ 2439 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 2440 pParse->checkSchema = 1; 2441 goto exit_drop_index; 2442 } 2443 if( pIndex->autoIndex ){ 2444 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 2445 "or PRIMARY KEY constraint cannot be dropped", 0); 2446 goto exit_drop_index; 2447 } 2448 #ifndef SQLITE_OMIT_AUTHORIZATION 2449 { 2450 int code = SQLITE_DROP_INDEX; 2451 Table *pTab = pIndex->pTable; 2452 const char *zDb = db->aDb[pIndex->iDb].zName; 2453 const char *zTab = SCHEMA_TABLE(pIndex->iDb); 2454 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 2455 goto exit_drop_index; 2456 } 2457 if( !OMIT_TEMPDB && pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX; 2458 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 2459 goto exit_drop_index; 2460 } 2461 } 2462 #endif 2463 2464 /* Generate code to remove the index and from the master table */ 2465 v = sqlite3GetVdbe(pParse); 2466 if( v ){ 2467 int iDb = pIndex->iDb; 2468 sqlite3NestedParse(pParse, 2469 "DELETE FROM %Q.%s WHERE name=%Q", 2470 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2471 pIndex->zName 2472 ); 2473 sqlite3ChangeCookie(db, v, iDb); 2474 destroyRootPage(pParse, pIndex->tnum, iDb); 2475 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0); 2476 } 2477 2478 exit_drop_index: 2479 sqlite3SrcListDelete(pName); 2480 } 2481 2482 /* 2483 ** Append a new element to the given IdList. Create a new IdList if 2484 ** need be. 2485 ** 2486 ** A new IdList is returned, or NULL if malloc() fails. 2487 */ 2488 IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){ 2489 if( pList==0 ){ 2490 pList = sqliteMalloc( sizeof(IdList) ); 2491 if( pList==0 ) return 0; 2492 pList->nAlloc = 0; 2493 } 2494 if( pList->nId>=pList->nAlloc ){ 2495 struct IdList_item *a; 2496 pList->nAlloc = pList->nAlloc*2 + 5; 2497 a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) ); 2498 if( a==0 ){ 2499 sqlite3IdListDelete(pList); 2500 return 0; 2501 } 2502 pList->a = a; 2503 } 2504 memset(&pList->a[pList->nId], 0, sizeof(pList->a[0])); 2505 pList->a[pList->nId].zName = sqlite3NameFromToken(pToken); 2506 pList->nId++; 2507 return pList; 2508 } 2509 2510 /* 2511 ** Delete an IdList. 2512 */ 2513 void sqlite3IdListDelete(IdList *pList){ 2514 int i; 2515 if( pList==0 ) return; 2516 for(i=0; i<pList->nId; i++){ 2517 sqliteFree(pList->a[i].zName); 2518 } 2519 sqliteFree(pList->a); 2520 sqliteFree(pList); 2521 } 2522 2523 /* 2524 ** Return the index in pList of the identifier named zId. Return -1 2525 ** if not found. 2526 */ 2527 int sqlite3IdListIndex(IdList *pList, const char *zName){ 2528 int i; 2529 if( pList==0 ) return -1; 2530 for(i=0; i<pList->nId; i++){ 2531 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 2532 } 2533 return -1; 2534 } 2535 2536 /* 2537 ** Append a new table name to the given SrcList. Create a new SrcList if 2538 ** need be. A new entry is created in the SrcList even if pToken is NULL. 2539 ** 2540 ** A new SrcList is returned, or NULL if malloc() fails. 2541 ** 2542 ** If pDatabase is not null, it means that the table has an optional 2543 ** database name prefix. Like this: "database.table". The pDatabase 2544 ** points to the table name and the pTable points to the database name. 2545 ** The SrcList.a[].zName field is filled with the table name which might 2546 ** come from pTable (if pDatabase is NULL) or from pDatabase. 2547 ** SrcList.a[].zDatabase is filled with the database name from pTable, 2548 ** or with NULL if no database is specified. 2549 ** 2550 ** In other words, if call like this: 2551 ** 2552 ** sqlite3SrcListAppend(A,B,0); 2553 ** 2554 ** Then B is a table name and the database name is unspecified. If called 2555 ** like this: 2556 ** 2557 ** sqlite3SrcListAppend(A,B,C); 2558 ** 2559 ** Then C is the table name and B is the database name. 2560 */ 2561 SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){ 2562 struct SrcList_item *pItem; 2563 if( pList==0 ){ 2564 pList = sqliteMalloc( sizeof(SrcList) ); 2565 if( pList==0 ) return 0; 2566 pList->nAlloc = 1; 2567 } 2568 if( pList->nSrc>=pList->nAlloc ){ 2569 SrcList *pNew; 2570 pList->nAlloc *= 2; 2571 pNew = sqliteRealloc(pList, 2572 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) ); 2573 if( pNew==0 ){ 2574 sqlite3SrcListDelete(pList); 2575 return 0; 2576 } 2577 pList = pNew; 2578 } 2579 pItem = &pList->a[pList->nSrc]; 2580 memset(pItem, 0, sizeof(pList->a[0])); 2581 if( pDatabase && pDatabase->z==0 ){ 2582 pDatabase = 0; 2583 } 2584 if( pDatabase && pTable ){ 2585 Token *pTemp = pDatabase; 2586 pDatabase = pTable; 2587 pTable = pTemp; 2588 } 2589 pItem->zName = sqlite3NameFromToken(pTable); 2590 pItem->zDatabase = sqlite3NameFromToken(pDatabase); 2591 pItem->iCursor = -1; 2592 pList->nSrc++; 2593 return pList; 2594 } 2595 2596 /* 2597 ** Assign cursors to all tables in a SrcList 2598 */ 2599 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 2600 int i; 2601 struct SrcList_item *pItem; 2602 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 2603 if( pItem->iCursor>=0 ) break; 2604 pItem->iCursor = pParse->nTab++; 2605 if( pItem->pSelect ){ 2606 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 2607 } 2608 } 2609 } 2610 2611 /* 2612 ** Add an alias to the last identifier on the given identifier list. 2613 */ 2614 void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){ 2615 if( pList && pList->nSrc>0 ){ 2616 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken); 2617 } 2618 } 2619 2620 /* 2621 ** Delete an entire SrcList including all its substructure. 2622 */ 2623 void sqlite3SrcListDelete(SrcList *pList){ 2624 int i; 2625 struct SrcList_item *pItem; 2626 if( pList==0 ) return; 2627 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 2628 sqliteFree(pItem->zDatabase); 2629 sqliteFree(pItem->zName); 2630 sqliteFree(pItem->zAlias); 2631 sqlite3DeleteTable(0, pItem->pTab); 2632 sqlite3SelectDelete(pItem->pSelect); 2633 sqlite3ExprDelete(pItem->pOn); 2634 sqlite3IdListDelete(pItem->pUsing); 2635 } 2636 sqliteFree(pList); 2637 } 2638 2639 /* 2640 ** Begin a transaction 2641 */ 2642 void sqlite3BeginTransaction(Parse *pParse, int type){ 2643 sqlite3 *db; 2644 Vdbe *v; 2645 int i; 2646 2647 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2648 if( pParse->nErr || sqlite3_malloc_failed ) return; 2649 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return; 2650 2651 v = sqlite3GetVdbe(pParse); 2652 if( !v ) return; 2653 if( type!=TK_DEFERRED ){ 2654 for(i=0; i<db->nDb; i++){ 2655 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 2656 } 2657 } 2658 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0); 2659 } 2660 2661 /* 2662 ** Commit a transaction 2663 */ 2664 void sqlite3CommitTransaction(Parse *pParse){ 2665 sqlite3 *db; 2666 Vdbe *v; 2667 2668 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2669 if( pParse->nErr || sqlite3_malloc_failed ) return; 2670 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; 2671 2672 v = sqlite3GetVdbe(pParse); 2673 if( v ){ 2674 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0); 2675 } 2676 } 2677 2678 /* 2679 ** Rollback a transaction 2680 */ 2681 void sqlite3RollbackTransaction(Parse *pParse){ 2682 sqlite3 *db; 2683 Vdbe *v; 2684 2685 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return; 2686 if( pParse->nErr || sqlite3_malloc_failed ) return; 2687 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; 2688 2689 v = sqlite3GetVdbe(pParse); 2690 if( v ){ 2691 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1); 2692 } 2693 } 2694 2695 /* 2696 ** Make sure the TEMP database is open and available for use. Return 2697 ** the number of errors. Leave any error messages in the pParse structure. 2698 */ 2699 static int sqlite3OpenTempDatabase(Parse *pParse){ 2700 sqlite3 *db = pParse->db; 2701 if( db->aDb[1].pBt==0 && !pParse->explain ){ 2702 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt); 2703 if( rc!=SQLITE_OK ){ 2704 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 2705 "file for storing temporary tables"); 2706 pParse->rc = rc; 2707 return 1; 2708 } 2709 if( db->flags & !db->autoCommit ){ 2710 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1); 2711 if( rc!=SQLITE_OK ){ 2712 sqlite3ErrorMsg(pParse, "unable to get a write lock on " 2713 "the temporary database file"); 2714 pParse->rc = rc; 2715 return 1; 2716 } 2717 } 2718 } 2719 return 0; 2720 } 2721 2722 /* 2723 ** Generate VDBE code that will verify the schema cookie and start 2724 ** a read-transaction for all named database files. 2725 ** 2726 ** It is important that all schema cookies be verified and all 2727 ** read transactions be started before anything else happens in 2728 ** the VDBE program. But this routine can be called after much other 2729 ** code has been generated. So here is what we do: 2730 ** 2731 ** The first time this routine is called, we code an OP_Goto that 2732 ** will jump to a subroutine at the end of the program. Then we 2733 ** record every database that needs its schema verified in the 2734 ** pParse->cookieMask field. Later, after all other code has been 2735 ** generated, the subroutine that does the cookie verifications and 2736 ** starts the transactions will be coded and the OP_Goto P2 value 2737 ** will be made to point to that subroutine. The generation of the 2738 ** cookie verification subroutine code happens in sqlite3FinishCoding(). 2739 ** 2740 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the 2741 ** schema on any databases. This can be used to position the OP_Goto 2742 ** early in the code, before we know if any database tables will be used. 2743 */ 2744 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 2745 sqlite3 *db; 2746 Vdbe *v; 2747 int mask; 2748 2749 v = sqlite3GetVdbe(pParse); 2750 if( v==0 ) return; /* This only happens if there was a prior error */ 2751 db = pParse->db; 2752 if( pParse->cookieGoto==0 ){ 2753 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1; 2754 } 2755 if( iDb>=0 ){ 2756 assert( iDb<db->nDb ); 2757 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 2758 assert( iDb<32 ); 2759 mask = 1<<iDb; 2760 if( (pParse->cookieMask & mask)==0 ){ 2761 pParse->cookieMask |= mask; 2762 pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie; 2763 if( !OMIT_TEMPDB && iDb==1 ){ 2764 sqlite3OpenTempDatabase(pParse); 2765 } 2766 } 2767 } 2768 } 2769 2770 /* 2771 ** Generate VDBE code that prepares for doing an operation that 2772 ** might change the database. 2773 ** 2774 ** This routine starts a new transaction if we are not already within 2775 ** a transaction. If we are already within a transaction, then a checkpoint 2776 ** is set if the setStatement parameter is true. A checkpoint should 2777 ** be set for operations that might fail (due to a constraint) part of 2778 ** the way through and which will need to undo some writes without having to 2779 ** rollback the whole transaction. For operations where all constraints 2780 ** can be checked before any changes are made to the database, it is never 2781 ** necessary to undo a write and the checkpoint should not be set. 2782 ** 2783 ** Only database iDb and the temp database are made writable by this call. 2784 ** If iDb==0, then the main and temp databases are made writable. If 2785 ** iDb==1 then only the temp database is made writable. If iDb>1 then the 2786 ** specified auxiliary database and the temp database are made writable. 2787 */ 2788 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 2789 Vdbe *v = sqlite3GetVdbe(pParse); 2790 if( v==0 ) return; 2791 sqlite3CodeVerifySchema(pParse, iDb); 2792 pParse->writeMask |= 1<<iDb; 2793 if( setStatement && pParse->nested==0 ){ 2794 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0); 2795 } 2796 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ 2797 sqlite3BeginWriteOperation(pParse, setStatement, 1); 2798 } 2799 } 2800 2801 /* 2802 ** Check to see if pIndex uses the collating sequence pColl. Return 2803 ** true if it does and false if it does not. 2804 */ 2805 #ifndef SQLITE_OMIT_REINDEX 2806 static int collationMatch(CollSeq *pColl, Index *pIndex){ 2807 int n = pIndex->keyInfo.nField; 2808 CollSeq **pp = pIndex->keyInfo.aColl; 2809 while( n-- ){ 2810 if( *pp==pColl ) return 1; 2811 pp++; 2812 } 2813 return 0; 2814 } 2815 #endif 2816 2817 /* 2818 ** Recompute all indices of pTab that use the collating sequence pColl. 2819 ** If pColl==0 then recompute all indices of pTab. 2820 */ 2821 #ifndef SQLITE_OMIT_REINDEX 2822 void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){ 2823 Index *pIndex; /* An index associated with pTab */ 2824 2825 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 2826 if( pColl==0 || collationMatch(pColl,pIndex) ){ 2827 sqlite3BeginWriteOperation(pParse, 0, pTab->iDb); 2828 sqlite3RefillIndex(pParse, pIndex, -1); 2829 } 2830 } 2831 } 2832 #endif 2833 2834 /* 2835 ** Recompute all indices of all tables in all databases where the 2836 ** indices use the collating sequence pColl. If pColl==0 then recompute 2837 ** all indices everywhere. 2838 */ 2839 #ifndef SQLITE_OMIT_REINDEX 2840 void reindexDatabases(Parse *pParse, CollSeq *pColl){ 2841 Db *pDb; /* A single database */ 2842 int iDb; /* The database index number */ 2843 sqlite3 *db = pParse->db; /* The database connection */ 2844 HashElem *k; /* For looping over tables in pDb */ 2845 Table *pTab; /* A table in the database */ 2846 2847 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 2848 if( pDb==0 ) continue; 2849 for(k=sqliteHashFirst(&pDb->tblHash); k; k=sqliteHashNext(k)){ 2850 pTab = (Table*)sqliteHashData(k); 2851 reindexTable(pParse, pTab, pColl); 2852 } 2853 } 2854 } 2855 #endif 2856 2857 /* 2858 ** Generate code for the REINDEX command. 2859 ** 2860 ** REINDEX -- 1 2861 ** REINDEX <collation> -- 2 2862 ** REINDEX ?<database>.?<tablename> -- 3 2863 ** REINDEX ?<database>.?<indexname> -- 4 2864 ** 2865 ** Form 1 causes all indices in all attached databases to be rebuilt. 2866 ** Form 2 rebuilds all indices in all databases that use the named 2867 ** collating function. Forms 3 and 4 rebuild the named index or all 2868 ** indices associated with the named table. 2869 */ 2870 #ifndef SQLITE_OMIT_REINDEX 2871 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 2872 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 2873 char *z; /* Name of a table or index */ 2874 const char *zDb; /* Name of the database */ 2875 Table *pTab; /* A table in the database */ 2876 Index *pIndex; /* An index associated with pTab */ 2877 int iDb; /* The database index number */ 2878 sqlite3 *db = pParse->db; /* The database connection */ 2879 Token *pObjName; /* Name of the table or index to be reindexed */ 2880 2881 /* Read the database schema. If an error occurs, leave an error message 2882 ** and code in pParse and return NULL. */ 2883 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2884 return; 2885 } 2886 2887 if( pName1==0 || pName1->z==0 ){ 2888 reindexDatabases(pParse, 0); 2889 return; 2890 }else if( pName2==0 || pName2->z==0 ){ 2891 pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0); 2892 if( pColl ){ 2893 reindexDatabases(pParse, pColl); 2894 return; 2895 } 2896 } 2897 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 2898 if( iDb<0 ) return; 2899 z = sqlite3NameFromToken(pObjName); 2900 zDb = db->aDb[iDb].zName; 2901 pTab = sqlite3FindTable(db, z, zDb); 2902 if( pTab ){ 2903 reindexTable(pParse, pTab, 0); 2904 sqliteFree(z); 2905 return; 2906 } 2907 pIndex = sqlite3FindIndex(db, z, zDb); 2908 sqliteFree(z); 2909 if( pIndex ){ 2910 sqlite3BeginWriteOperation(pParse, 0, iDb); 2911 sqlite3RefillIndex(pParse, pIndex, -1); 2912 return; 2913 } 2914 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 2915 } 2916 #endif 2917