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.556 2009/07/01 16:12:08 danielk1977 Exp $ 26 */ 27 #include "sqliteInt.h" 28 29 /* 30 ** This routine is called when a new SQL statement is beginning to 31 ** be parsed. Initialize the pParse structure as needed. 32 */ 33 void sqlite3BeginParse(Parse *pParse, int explainFlag){ 34 pParse->explain = (u8)explainFlag; 35 pParse->nVar = 0; 36 } 37 38 #ifndef SQLITE_OMIT_SHARED_CACHE 39 /* 40 ** The TableLock structure is only used by the sqlite3TableLock() and 41 ** codeTableLocks() functions. 42 */ 43 struct TableLock { 44 int iDb; /* The database containing the table to be locked */ 45 int iTab; /* The root page of the table to be locked */ 46 u8 isWriteLock; /* True for write lock. False for a read lock */ 47 const char *zName; /* Name of the table */ 48 }; 49 50 /* 51 ** Record the fact that we want to lock a table at run-time. 52 ** 53 ** The table to be locked has root page iTab and is found in database iDb. 54 ** A read or a write lock can be taken depending on isWritelock. 55 ** 56 ** This routine just records the fact that the lock is desired. The 57 ** code to make the lock occur is generated by a later call to 58 ** codeTableLocks() which occurs during sqlite3FinishCoding(). 59 */ 60 void sqlite3TableLock( 61 Parse *pParse, /* Parsing context */ 62 int iDb, /* Index of the database containing the table to lock */ 63 int iTab, /* Root page number of the table to be locked */ 64 u8 isWriteLock, /* True for a write lock */ 65 const char *zName /* Name of the table to be locked */ 66 ){ 67 int i; 68 int nBytes; 69 TableLock *p; 70 71 assert( iDb>=0 ); 72 for(i=0; i<pParse->nTableLock; i++){ 73 p = &pParse->aTableLock[i]; 74 if( p->iDb==iDb && p->iTab==iTab ){ 75 p->isWriteLock = (p->isWriteLock || isWriteLock); 76 return; 77 } 78 } 79 80 nBytes = sizeof(TableLock) * (pParse->nTableLock+1); 81 pParse->aTableLock = 82 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes); 83 if( pParse->aTableLock ){ 84 p = &pParse->aTableLock[pParse->nTableLock++]; 85 p->iDb = iDb; 86 p->iTab = iTab; 87 p->isWriteLock = isWriteLock; 88 p->zName = zName; 89 }else{ 90 pParse->nTableLock = 0; 91 pParse->db->mallocFailed = 1; 92 } 93 } 94 95 /* 96 ** Code an OP_TableLock instruction for each table locked by the 97 ** statement (configured by calls to sqlite3TableLock()). 98 */ 99 static void codeTableLocks(Parse *pParse){ 100 int i; 101 Vdbe *pVdbe; 102 103 pVdbe = sqlite3GetVdbe(pParse); 104 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ 105 106 for(i=0; i<pParse->nTableLock; i++){ 107 TableLock *p = &pParse->aTableLock[i]; 108 int p1 = p->iDb; 109 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, 110 p->zName, P4_STATIC); 111 } 112 } 113 #else 114 #define codeTableLocks(x) 115 #endif 116 117 /* 118 ** This routine is called after a single SQL statement has been 119 ** parsed and a VDBE program to execute that statement has been 120 ** prepared. This routine puts the finishing touches on the 121 ** VDBE program and resets the pParse structure for the next 122 ** parse. 123 ** 124 ** Note that if an error occurred, it might be the case that 125 ** no VDBE code was generated. 126 */ 127 void sqlite3FinishCoding(Parse *pParse){ 128 sqlite3 *db; 129 Vdbe *v; 130 131 db = pParse->db; 132 if( db->mallocFailed ) return; 133 if( pParse->nested ) return; 134 if( pParse->nErr ) return; 135 136 /* Begin by generating some termination code at the end of the 137 ** vdbe program 138 */ 139 v = sqlite3GetVdbe(pParse); 140 if( v ){ 141 sqlite3VdbeAddOp0(v, OP_Halt); 142 143 /* The cookie mask contains one bit for each database file open. 144 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are 145 ** set for each database that is used. Generate code to start a 146 ** transaction on each used database and to verify the schema cookie 147 ** on each used database. 148 */ 149 if( pParse->cookieGoto>0 ){ 150 u32 mask; 151 int iDb; 152 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); 153 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ 154 if( (mask & pParse->cookieMask)==0 ) continue; 155 sqlite3VdbeUsesBtree(v, iDb); 156 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); 157 if( db->init.busy==0 ){ 158 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); 159 } 160 } 161 #ifndef SQLITE_OMIT_VIRTUALTABLE 162 { 163 int i; 164 for(i=0; i<pParse->nVtabLock; i++){ 165 char *vtab = (char *)pParse->apVtabLock[i]->pVtab; 166 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); 167 } 168 pParse->nVtabLock = 0; 169 } 170 #endif 171 172 /* Once all the cookies have been verified and transactions opened, 173 ** obtain the required table-locks. This is a no-op unless the 174 ** shared-cache feature is enabled. 175 */ 176 codeTableLocks(pParse); 177 178 /* Initialize any AUTOINCREMENT data structures required. 179 */ 180 sqlite3AutoincrementBegin(pParse); 181 182 /* Finally, jump back to the beginning of the executable code. */ 183 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); 184 } 185 } 186 187 188 /* Get the VDBE program ready for execution 189 */ 190 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){ 191 #ifdef SQLITE_DEBUG 192 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; 193 sqlite3VdbeTrace(v, trace); 194 #endif 195 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ 196 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem, 197 pParse->nTab, pParse->explain); 198 pParse->rc = SQLITE_DONE; 199 pParse->colNamesSet = 0; 200 }else if( pParse->rc==SQLITE_OK ){ 201 pParse->rc = SQLITE_ERROR; 202 } 203 pParse->nTab = 0; 204 pParse->nMem = 0; 205 pParse->nSet = 0; 206 pParse->nVar = 0; 207 pParse->cookieMask = 0; 208 pParse->cookieGoto = 0; 209 } 210 211 /* 212 ** Run the parser and code generator recursively in order to generate 213 ** code for the SQL statement given onto the end of the pParse context 214 ** currently under construction. When the parser is run recursively 215 ** this way, the final OP_Halt is not appended and other initialization 216 ** and finalization steps are omitted because those are handling by the 217 ** outermost parser. 218 ** 219 ** Not everything is nestable. This facility is designed to permit 220 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use 221 ** care if you decide to try to use this routine for some other purposes. 222 */ 223 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ 224 va_list ap; 225 char *zSql; 226 char *zErrMsg = 0; 227 sqlite3 *db = pParse->db; 228 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) 229 char saveBuf[SAVE_SZ]; 230 231 if( pParse->nErr ) return; 232 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ 233 va_start(ap, zFormat); 234 zSql = sqlite3VMPrintf(db, zFormat, ap); 235 va_end(ap); 236 if( zSql==0 ){ 237 return; /* A malloc must have failed */ 238 } 239 pParse->nested++; 240 memcpy(saveBuf, &pParse->nVar, SAVE_SZ); 241 memset(&pParse->nVar, 0, SAVE_SZ); 242 sqlite3RunParser(pParse, zSql, &zErrMsg); 243 sqlite3DbFree(db, zErrMsg); 244 sqlite3DbFree(db, zSql); 245 memcpy(&pParse->nVar, saveBuf, SAVE_SZ); 246 pParse->nested--; 247 } 248 249 /* 250 ** Locate the in-memory structure that describes a particular database 251 ** table given the name of that table and (optionally) the name of the 252 ** database containing the table. Return NULL if not found. 253 ** 254 ** If zDatabase is 0, all databases are searched for the table and the 255 ** first matching table is returned. (No checking for duplicate table 256 ** names is done.) The search order is TEMP first, then MAIN, then any 257 ** auxiliary databases added using the ATTACH command. 258 ** 259 ** See also sqlite3LocateTable(). 260 */ 261 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ 262 Table *p = 0; 263 int i; 264 int nName; 265 assert( zName!=0 ); 266 nName = sqlite3Strlen30(zName); 267 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 268 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 269 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; 270 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); 271 if( p ) break; 272 } 273 return p; 274 } 275 276 /* 277 ** Locate the in-memory structure that describes a particular database 278 ** table given the name of that table and (optionally) the name of the 279 ** database containing the table. Return NULL if not found. Also leave an 280 ** error message in pParse->zErrMsg. 281 ** 282 ** The difference between this routine and sqlite3FindTable() is that this 283 ** routine leaves an error message in pParse->zErrMsg where 284 ** sqlite3FindTable() does not. 285 */ 286 Table *sqlite3LocateTable( 287 Parse *pParse, /* context in which to report errors */ 288 int isView, /* True if looking for a VIEW rather than a TABLE */ 289 const char *zName, /* Name of the table we are looking for */ 290 const char *zDbase /* Name of the database. Might be NULL */ 291 ){ 292 Table *p; 293 294 /* Read the database schema. If an error occurs, leave an error message 295 ** and code in pParse and return NULL. */ 296 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 297 return 0; 298 } 299 300 p = sqlite3FindTable(pParse->db, zName, zDbase); 301 if( p==0 ){ 302 const char *zMsg = isView ? "no such view" : "no such table"; 303 if( zDbase ){ 304 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); 305 }else{ 306 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); 307 } 308 pParse->checkSchema = 1; 309 } 310 return p; 311 } 312 313 /* 314 ** Locate the in-memory structure that describes 315 ** a particular index given the name of that index 316 ** and the name of the database that contains the index. 317 ** Return NULL if not found. 318 ** 319 ** If zDatabase is 0, all databases are searched for the 320 ** table and the first matching index is returned. (No checking 321 ** for duplicate index names is done.) The search order is 322 ** TEMP first, then MAIN, then any auxiliary databases added 323 ** using the ATTACH command. 324 */ 325 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ 326 Index *p = 0; 327 int i; 328 int nName = sqlite3Strlen30(zName); 329 for(i=OMIT_TEMPDB; i<db->nDb; i++){ 330 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ 331 Schema *pSchema = db->aDb[j].pSchema; 332 assert( pSchema ); 333 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; 334 p = sqlite3HashFind(&pSchema->idxHash, zName, nName); 335 if( p ) break; 336 } 337 return p; 338 } 339 340 /* 341 ** Reclaim the memory used by an index 342 */ 343 static void freeIndex(Index *p){ 344 sqlite3 *db = p->pTable->dbMem; 345 /* testcase( db==0 ); */ 346 sqlite3DbFree(db, p->zColAff); 347 sqlite3DbFree(db, p); 348 } 349 350 /* 351 ** Remove the given index from the index hash table, and free 352 ** its memory structures. 353 ** 354 ** The index is removed from the database hash tables but 355 ** it is not unlinked from the Table that it indexes. 356 ** Unlinking from the Table must be done by the calling function. 357 */ 358 static void sqlite3DeleteIndex(Index *p){ 359 Index *pOld; 360 const char *zName = p->zName; 361 362 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, 363 sqlite3Strlen30(zName), 0); 364 assert( pOld==0 || pOld==p ); 365 freeIndex(p); 366 } 367 368 /* 369 ** For the index called zIdxName which is found in the database iDb, 370 ** unlike that index from its Table then remove the index from 371 ** the index hash table and free all memory structures associated 372 ** with the index. 373 */ 374 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ 375 Index *pIndex; 376 int len; 377 Hash *pHash = &db->aDb[iDb].pSchema->idxHash; 378 379 len = sqlite3Strlen30(zIdxName); 380 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0); 381 if( pIndex ){ 382 if( pIndex->pTable->pIndex==pIndex ){ 383 pIndex->pTable->pIndex = pIndex->pNext; 384 }else{ 385 Index *p; 386 /* Justification of ALWAYS(); The index must be on the list of 387 ** indices. */ 388 p = pIndex->pTable->pIndex; 389 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } 390 if( ALWAYS(p && p->pNext==pIndex) ){ 391 p->pNext = pIndex->pNext; 392 } 393 } 394 freeIndex(pIndex); 395 } 396 db->flags |= SQLITE_InternChanges; 397 } 398 399 /* 400 ** Erase all schema information from the in-memory hash tables of 401 ** a single database. This routine is called to reclaim memory 402 ** before the database closes. It is also called during a rollback 403 ** if there were schema changes during the transaction or if a 404 ** schema-cookie mismatch occurs. 405 ** 406 ** If iDb==0 then reset the internal schema tables for all database 407 ** files. If iDb>=1 then reset the internal schema for only the 408 ** single file indicated. 409 */ 410 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ 411 int i, j; 412 assert( iDb>=0 && iDb<db->nDb ); 413 414 if( iDb==0 ){ 415 sqlite3BtreeEnterAll(db); 416 } 417 for(i=iDb; i<db->nDb; i++){ 418 Db *pDb = &db->aDb[i]; 419 if( pDb->pSchema ){ 420 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt))); 421 sqlite3SchemaFree(pDb->pSchema); 422 } 423 if( iDb>0 ) return; 424 } 425 assert( iDb==0 ); 426 db->flags &= ~SQLITE_InternChanges; 427 sqlite3BtreeLeaveAll(db); 428 429 /* If one or more of the auxiliary database files has been closed, 430 ** then remove them from the auxiliary database list. We take the 431 ** opportunity to do this here since we have just deleted all of the 432 ** schema hash tables and therefore do not have to make any changes 433 ** to any of those tables. 434 */ 435 for(i=j=2; i<db->nDb; i++){ 436 struct Db *pDb = &db->aDb[i]; 437 if( pDb->pBt==0 ){ 438 sqlite3DbFree(db, pDb->zName); 439 pDb->zName = 0; 440 continue; 441 } 442 if( j<i ){ 443 db->aDb[j] = db->aDb[i]; 444 } 445 j++; 446 } 447 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j])); 448 db->nDb = j; 449 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ 450 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); 451 sqlite3DbFree(db, db->aDb); 452 db->aDb = db->aDbStatic; 453 } 454 } 455 456 /* 457 ** This routine is called when a commit occurs. 458 */ 459 void sqlite3CommitInternalChanges(sqlite3 *db){ 460 db->flags &= ~SQLITE_InternChanges; 461 } 462 463 /* 464 ** Clear the column names from a table or view. 465 */ 466 static void sqliteResetColumnNames(Table *pTable){ 467 int i; 468 Column *pCol; 469 sqlite3 *db = pTable->dbMem; 470 testcase( db==0 ); 471 assert( pTable!=0 ); 472 if( (pCol = pTable->aCol)!=0 ){ 473 for(i=0; i<pTable->nCol; i++, pCol++){ 474 sqlite3DbFree(db, pCol->zName); 475 sqlite3ExprDelete(db, pCol->pDflt); 476 sqlite3DbFree(db, pCol->zDflt); 477 sqlite3DbFree(db, pCol->zType); 478 sqlite3DbFree(db, pCol->zColl); 479 } 480 sqlite3DbFree(db, pTable->aCol); 481 } 482 pTable->aCol = 0; 483 pTable->nCol = 0; 484 } 485 486 /* 487 ** Remove the memory data structures associated with the given 488 ** Table. No changes are made to disk by this routine. 489 ** 490 ** This routine just deletes the data structure. It does not unlink 491 ** the table data structure from the hash table. But it does destroy 492 ** memory structures of the indices and foreign keys associated with 493 ** the table. 494 */ 495 void sqlite3DeleteTable(Table *pTable){ 496 Index *pIndex, *pNext; 497 FKey *pFKey, *pNextFKey; 498 sqlite3 *db; 499 500 if( pTable==0 ) return; 501 db = pTable->dbMem; 502 testcase( db==0 ); 503 504 /* Do not delete the table until the reference count reaches zero. */ 505 pTable->nRef--; 506 if( pTable->nRef>0 ){ 507 return; 508 } 509 assert( pTable->nRef==0 ); 510 511 /* Delete all indices associated with this table 512 */ 513 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ 514 pNext = pIndex->pNext; 515 assert( pIndex->pSchema==pTable->pSchema ); 516 sqlite3DeleteIndex(pIndex); 517 } 518 519 #ifndef SQLITE_OMIT_FOREIGN_KEY 520 /* Delete all foreign keys associated with this table. */ 521 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ 522 pNextFKey = pFKey->pNextFrom; 523 sqlite3DbFree(db, pFKey); 524 } 525 #endif 526 527 /* Delete the Table structure itself. 528 */ 529 sqliteResetColumnNames(pTable); 530 sqlite3DbFree(db, pTable->zName); 531 sqlite3DbFree(db, pTable->zColAff); 532 sqlite3SelectDelete(db, pTable->pSelect); 533 #ifndef SQLITE_OMIT_CHECK 534 sqlite3ExprDelete(db, pTable->pCheck); 535 #endif 536 sqlite3VtabClear(pTable); 537 sqlite3DbFree(db, pTable); 538 } 539 540 /* 541 ** Unlink the given table from the hash tables and the delete the 542 ** table structure with all its indices and foreign keys. 543 */ 544 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ 545 Table *p; 546 Db *pDb; 547 548 assert( db!=0 ); 549 assert( iDb>=0 && iDb<db->nDb ); 550 assert( zTabName && zTabName[0] ); 551 pDb = &db->aDb[iDb]; 552 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 553 sqlite3Strlen30(zTabName),0); 554 sqlite3DeleteTable(p); 555 db->flags |= SQLITE_InternChanges; 556 } 557 558 /* 559 ** Given a token, return a string that consists of the text of that 560 ** token. Space to hold the returned string 561 ** is obtained from sqliteMalloc() and must be freed by the calling 562 ** function. 563 ** 564 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that 565 ** surround the body of the token are removed. 566 ** 567 ** Tokens are often just pointers into the original SQL text and so 568 ** are not \000 terminated and are not persistent. The returned string 569 ** is \000 terminated and is persistent. 570 */ 571 char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ 572 char *zName; 573 if( pName ){ 574 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); 575 sqlite3Dequote(zName); 576 }else{ 577 zName = 0; 578 } 579 return zName; 580 } 581 582 /* 583 ** Open the sqlite_master table stored in database number iDb for 584 ** writing. The table is opened using cursor 0. 585 */ 586 void sqlite3OpenMasterTable(Parse *p, int iDb){ 587 Vdbe *v = sqlite3GetVdbe(p); 588 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); 589 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); 590 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */ 591 if( p->nTab==0 ){ 592 p->nTab = 1; 593 } 594 } 595 596 /* 597 ** Parameter zName points to a nul-terminated buffer containing the name 598 ** of a database ("main", "temp" or the name of an attached db). This 599 ** function returns the index of the named database in db->aDb[], or 600 ** -1 if the named db cannot be found. 601 */ 602 int sqlite3FindDbName(sqlite3 *db, const char *zName){ 603 int i = -1; /* Database number */ 604 if( zName ){ 605 Db *pDb; 606 int n = sqlite3Strlen30(zName); 607 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ 608 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 609 0==sqlite3StrICmp(pDb->zName, zName) ){ 610 break; 611 } 612 } 613 } 614 return i; 615 } 616 617 /* 618 ** The token *pName contains the name of a database (either "main" or 619 ** "temp" or the name of an attached db). This routine returns the 620 ** index of the named database in db->aDb[], or -1 if the named db 621 ** does not exist. 622 */ 623 int sqlite3FindDb(sqlite3 *db, Token *pName){ 624 int i; /* Database number */ 625 char *zName; /* Name we are searching for */ 626 zName = sqlite3NameFromToken(db, pName); 627 i = sqlite3FindDbName(db, zName); 628 sqlite3DbFree(db, zName); 629 return i; 630 } 631 632 /* The table or view or trigger name is passed to this routine via tokens 633 ** pName1 and pName2. If the table name was fully qualified, for example: 634 ** 635 ** CREATE TABLE xxx.yyy (...); 636 ** 637 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 638 ** the table name is not fully qualified, i.e.: 639 ** 640 ** CREATE TABLE yyy(...); 641 ** 642 ** Then pName1 is set to "yyy" and pName2 is "". 643 ** 644 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or 645 ** pName2) that stores the unqualified table name. The index of the 646 ** database "xxx" is returned. 647 */ 648 int sqlite3TwoPartName( 649 Parse *pParse, /* Parsing and code generating context */ 650 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ 651 Token *pName2, /* The "yyy" in the name "xxx.yyy" */ 652 Token **pUnqual /* Write the unqualified object name here */ 653 ){ 654 int iDb; /* Database holding the object */ 655 sqlite3 *db = pParse->db; 656 657 if( ALWAYS(pName2!=0) && pName2->n>0 ){ 658 if( db->init.busy ) { 659 sqlite3ErrorMsg(pParse, "corrupt database"); 660 pParse->nErr++; 661 return -1; 662 } 663 *pUnqual = pName2; 664 iDb = sqlite3FindDb(db, pName1); 665 if( iDb<0 ){ 666 sqlite3ErrorMsg(pParse, "unknown database %T", pName1); 667 pParse->nErr++; 668 return -1; 669 } 670 }else{ 671 assert( db->init.iDb==0 || db->init.busy ); 672 iDb = db->init.iDb; 673 *pUnqual = pName1; 674 } 675 return iDb; 676 } 677 678 /* 679 ** This routine is used to check if the UTF-8 string zName is a legal 680 ** unqualified name for a new schema object (table, index, view or 681 ** trigger). All names are legal except those that begin with the string 682 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace 683 ** is reserved for internal use. 684 */ 685 int sqlite3CheckObjectName(Parse *pParse, const char *zName){ 686 if( !pParse->db->init.busy && pParse->nested==0 687 && (pParse->db->flags & SQLITE_WriteSchema)==0 688 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ 689 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); 690 return SQLITE_ERROR; 691 } 692 return SQLITE_OK; 693 } 694 695 /* 696 ** Begin constructing a new table representation in memory. This is 697 ** the first of several action routines that get called in response 698 ** to a CREATE TABLE statement. In particular, this routine is called 699 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp 700 ** flag is true if the table should be stored in the auxiliary database 701 ** file instead of in the main database file. This is normally the case 702 ** when the "TEMP" or "TEMPORARY" keyword occurs in between 703 ** CREATE and TABLE. 704 ** 705 ** The new table record is initialized and put in pParse->pNewTable. 706 ** As more of the CREATE TABLE statement is parsed, additional action 707 ** routines will be called to add more information to this record. 708 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine 709 ** is called to complete the construction of the new table record. 710 */ 711 void sqlite3StartTable( 712 Parse *pParse, /* Parser context */ 713 Token *pName1, /* First part of the name of the table or view */ 714 Token *pName2, /* Second part of the name of the table or view */ 715 int isTemp, /* True if this is a TEMP table */ 716 int isView, /* True if this is a VIEW */ 717 int isVirtual, /* True if this is a VIRTUAL table */ 718 int noErr /* Do nothing if table already exists */ 719 ){ 720 Table *pTable; 721 char *zName = 0; /* The name of the new table */ 722 sqlite3 *db = pParse->db; 723 Vdbe *v; 724 int iDb; /* Database number to create the table in */ 725 Token *pName; /* Unqualified name of the table to create */ 726 727 /* The table or view name to create is passed to this routine via tokens 728 ** pName1 and pName2. If the table name was fully qualified, for example: 729 ** 730 ** CREATE TABLE xxx.yyy (...); 731 ** 732 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if 733 ** the table name is not fully qualified, i.e.: 734 ** 735 ** CREATE TABLE yyy(...); 736 ** 737 ** Then pName1 is set to "yyy" and pName2 is "". 738 ** 739 ** The call below sets the pName pointer to point at the token (pName1 or 740 ** pName2) that stores the unqualified table name. The variable iDb is 741 ** set to the index of the database that the table or view is to be 742 ** created in. 743 */ 744 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 745 if( iDb<0 ) return; 746 if( !OMIT_TEMPDB && isTemp && iDb>1 ){ 747 /* If creating a temp table, the name may not be qualified */ 748 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); 749 return; 750 } 751 if( !OMIT_TEMPDB && isTemp ) iDb = 1; 752 753 pParse->sNameToken = *pName; 754 zName = sqlite3NameFromToken(db, pName); 755 if( zName==0 ) return; 756 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 757 goto begin_table_error; 758 } 759 if( db->init.iDb==1 ) isTemp = 1; 760 #ifndef SQLITE_OMIT_AUTHORIZATION 761 assert( (isTemp & 1)==isTemp ); 762 { 763 int code; 764 char *zDb = db->aDb[iDb].zName; 765 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ 766 goto begin_table_error; 767 } 768 if( isView ){ 769 if( !OMIT_TEMPDB && isTemp ){ 770 code = SQLITE_CREATE_TEMP_VIEW; 771 }else{ 772 code = SQLITE_CREATE_VIEW; 773 } 774 }else{ 775 if( !OMIT_TEMPDB && isTemp ){ 776 code = SQLITE_CREATE_TEMP_TABLE; 777 }else{ 778 code = SQLITE_CREATE_TABLE; 779 } 780 } 781 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ 782 goto begin_table_error; 783 } 784 } 785 #endif 786 787 /* Make sure the new table name does not collide with an existing 788 ** index or table name in the same database. Issue an error message if 789 ** it does. The exception is if the statement being parsed was passed 790 ** to an sqlite3_declare_vtab() call. In that case only the column names 791 ** and types will be used, so there is no need to test for namespace 792 ** collisions. 793 */ 794 if( !IN_DECLARE_VTAB ){ 795 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 796 goto begin_table_error; 797 } 798 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); 799 if( pTable ){ 800 if( !noErr ){ 801 sqlite3ErrorMsg(pParse, "table %T already exists", pName); 802 } 803 goto begin_table_error; 804 } 805 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){ 806 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); 807 goto begin_table_error; 808 } 809 } 810 811 pTable = sqlite3DbMallocZero(db, sizeof(Table)); 812 if( pTable==0 ){ 813 db->mallocFailed = 1; 814 pParse->rc = SQLITE_NOMEM; 815 pParse->nErr++; 816 goto begin_table_error; 817 } 818 pTable->zName = zName; 819 pTable->iPKey = -1; 820 pTable->pSchema = db->aDb[iDb].pSchema; 821 pTable->nRef = 1; 822 pTable->dbMem = 0; 823 assert( pParse->pNewTable==0 ); 824 pParse->pNewTable = pTable; 825 826 /* If this is the magic sqlite_sequence table used by autoincrement, 827 ** then record a pointer to this table in the main database structure 828 ** so that INSERT can find the table easily. 829 */ 830 #ifndef SQLITE_OMIT_AUTOINCREMENT 831 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ 832 pTable->pSchema->pSeqTab = pTable; 833 } 834 #endif 835 836 /* Begin generating the code that will insert the table record into 837 ** the SQLITE_MASTER table. Note in particular that we must go ahead 838 ** and allocate the record number for the table entry now. Before any 839 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause 840 ** indices to be created and the table record must come before the 841 ** indices. Hence, the record number for the table must be allocated 842 ** now. 843 */ 844 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ 845 int j1; 846 int fileFormat; 847 int reg1, reg2, reg3; 848 sqlite3BeginWriteOperation(pParse, 0, iDb); 849 850 #ifndef SQLITE_OMIT_VIRTUALTABLE 851 if( isVirtual ){ 852 sqlite3VdbeAddOp0(v, OP_VBegin); 853 } 854 #endif 855 856 /* If the file format and encoding in the database have not been set, 857 ** set them now. 858 */ 859 reg1 = pParse->regRowid = ++pParse->nMem; 860 reg2 = pParse->regRoot = ++pParse->nMem; 861 reg3 = ++pParse->nMem; 862 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); 863 sqlite3VdbeUsesBtree(v, iDb); 864 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); 865 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 866 1 : SQLITE_MAX_FILE_FORMAT; 867 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); 868 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3); 869 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); 870 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3); 871 sqlite3VdbeJumpHere(v, j1); 872 873 /* This just creates a place-holder record in the sqlite_master table. 874 ** The record created does not contain anything yet. It will be replaced 875 ** by the real entry in code generated at sqlite3EndTable(). 876 ** 877 ** The rowid for the new entry is left in register pParse->regRowid. 878 ** The root page number of the new table is left in reg pParse->regRoot. 879 ** The rowid and root page number values are needed by the code that 880 ** sqlite3EndTable will generate. 881 */ 882 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 883 if( isView || isVirtual ){ 884 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); 885 }else 886 #endif 887 { 888 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); 889 } 890 sqlite3OpenMasterTable(pParse, iDb); 891 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); 892 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); 893 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); 894 sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 895 sqlite3VdbeAddOp0(v, OP_Close); 896 } 897 898 /* Normal (non-error) return. */ 899 return; 900 901 /* If an error occurs, we jump here */ 902 begin_table_error: 903 sqlite3DbFree(db, zName); 904 return; 905 } 906 907 /* 908 ** This macro is used to compare two strings in a case-insensitive manner. 909 ** It is slightly faster than calling sqlite3StrICmp() directly, but 910 ** produces larger code. 911 ** 912 ** WARNING: This macro is not compatible with the strcmp() family. It 913 ** returns true if the two strings are equal, otherwise false. 914 */ 915 #define STRICMP(x, y) (\ 916 sqlite3UpperToLower[*(unsigned char *)(x)]== \ 917 sqlite3UpperToLower[*(unsigned char *)(y)] \ 918 && sqlite3StrICmp((x)+1,(y)+1)==0 ) 919 920 /* 921 ** Add a new column to the table currently being constructed. 922 ** 923 ** The parser calls this routine once for each column declaration 924 ** in a CREATE TABLE statement. sqlite3StartTable() gets called 925 ** first to get things going. Then this routine is called for each 926 ** column. 927 */ 928 void sqlite3AddColumn(Parse *pParse, Token *pName){ 929 Table *p; 930 int i; 931 char *z; 932 Column *pCol; 933 sqlite3 *db = pParse->db; 934 if( (p = pParse->pNewTable)==0 ) return; 935 #if SQLITE_MAX_COLUMN 936 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 937 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); 938 return; 939 } 940 #endif 941 z = sqlite3NameFromToken(db, pName); 942 if( z==0 ) return; 943 for(i=0; i<p->nCol; i++){ 944 if( STRICMP(z, p->aCol[i].zName) ){ 945 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); 946 sqlite3DbFree(db, z); 947 return; 948 } 949 } 950 if( (p->nCol & 0x7)==0 ){ 951 Column *aNew; 952 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); 953 if( aNew==0 ){ 954 sqlite3DbFree(db, z); 955 return; 956 } 957 p->aCol = aNew; 958 } 959 pCol = &p->aCol[p->nCol]; 960 memset(pCol, 0, sizeof(p->aCol[0])); 961 pCol->zName = z; 962 963 /* If there is no type specified, columns have the default affinity 964 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will 965 ** be called next to set pCol->affinity correctly. 966 */ 967 pCol->affinity = SQLITE_AFF_NONE; 968 p->nCol++; 969 } 970 971 /* 972 ** This routine is called by the parser while in the middle of 973 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has 974 ** been seen on a column. This routine sets the notNull flag on 975 ** the column currently under construction. 976 */ 977 void sqlite3AddNotNull(Parse *pParse, int onError){ 978 Table *p; 979 p = pParse->pNewTable; 980 if( p==0 || NEVER(p->nCol<1) ) return; 981 p->aCol[p->nCol-1].notNull = (u8)onError; 982 } 983 984 /* 985 ** Scan the column type name zType (length nType) and return the 986 ** associated affinity type. 987 ** 988 ** This routine does a case-independent search of zType for the 989 ** substrings in the following table. If one of the substrings is 990 ** found, the corresponding affinity is returned. If zType contains 991 ** more than one of the substrings, entries toward the top of 992 ** the table take priority. For example, if zType is 'BLOBINT', 993 ** SQLITE_AFF_INTEGER is returned. 994 ** 995 ** Substring | Affinity 996 ** -------------------------------- 997 ** 'INT' | SQLITE_AFF_INTEGER 998 ** 'CHAR' | SQLITE_AFF_TEXT 999 ** 'CLOB' | SQLITE_AFF_TEXT 1000 ** 'TEXT' | SQLITE_AFF_TEXT 1001 ** 'BLOB' | SQLITE_AFF_NONE 1002 ** 'REAL' | SQLITE_AFF_REAL 1003 ** 'FLOA' | SQLITE_AFF_REAL 1004 ** 'DOUB' | SQLITE_AFF_REAL 1005 ** 1006 ** If none of the substrings in the above table are found, 1007 ** SQLITE_AFF_NUMERIC is returned. 1008 */ 1009 char sqlite3AffinityType(const char *zIn){ 1010 u32 h = 0; 1011 char aff = SQLITE_AFF_NUMERIC; 1012 1013 if( zIn ) while( zIn[0] ){ 1014 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; 1015 zIn++; 1016 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ 1017 aff = SQLITE_AFF_TEXT; 1018 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ 1019 aff = SQLITE_AFF_TEXT; 1020 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ 1021 aff = SQLITE_AFF_TEXT; 1022 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ 1023 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ 1024 aff = SQLITE_AFF_NONE; 1025 #ifndef SQLITE_OMIT_FLOATING_POINT 1026 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ 1027 && aff==SQLITE_AFF_NUMERIC ){ 1028 aff = SQLITE_AFF_REAL; 1029 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ 1030 && aff==SQLITE_AFF_NUMERIC ){ 1031 aff = SQLITE_AFF_REAL; 1032 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ 1033 && aff==SQLITE_AFF_NUMERIC ){ 1034 aff = SQLITE_AFF_REAL; 1035 #endif 1036 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ 1037 aff = SQLITE_AFF_INTEGER; 1038 break; 1039 } 1040 } 1041 1042 return aff; 1043 } 1044 1045 /* 1046 ** This routine is called by the parser while in the middle of 1047 ** parsing a CREATE TABLE statement. The pFirst token is the first 1048 ** token in the sequence of tokens that describe the type of the 1049 ** column currently under construction. pLast is the last token 1050 ** in the sequence. Use this information to construct a string 1051 ** that contains the typename of the column and store that string 1052 ** in zType. 1053 */ 1054 void sqlite3AddColumnType(Parse *pParse, Token *pType){ 1055 Table *p; 1056 Column *pCol; 1057 1058 p = pParse->pNewTable; 1059 if( p==0 || NEVER(p->nCol<1) ) return; 1060 pCol = &p->aCol[p->nCol-1]; 1061 assert( pCol->zType==0 ); 1062 pCol->zType = sqlite3NameFromToken(pParse->db, pType); 1063 pCol->affinity = sqlite3AffinityType(pCol->zType); 1064 } 1065 1066 /* 1067 ** The expression is the default value for the most recently added column 1068 ** of the table currently under construction. 1069 ** 1070 ** Default value expressions must be constant. Raise an exception if this 1071 ** is not the case. 1072 ** 1073 ** This routine is called by the parser while in the middle of 1074 ** parsing a CREATE TABLE statement. 1075 */ 1076 void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ 1077 Table *p; 1078 Column *pCol; 1079 sqlite3 *db = pParse->db; 1080 p = pParse->pNewTable; 1081 if( p!=0 ){ 1082 pCol = &(p->aCol[p->nCol-1]); 1083 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){ 1084 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", 1085 pCol->zName); 1086 }else{ 1087 /* A copy of pExpr is used instead of the original, as pExpr contains 1088 ** tokens that point to volatile memory. The 'span' of the expression 1089 ** is required by pragma table_info. 1090 */ 1091 sqlite3ExprDelete(db, pCol->pDflt); 1092 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE); 1093 sqlite3DbFree(db, pCol->zDflt); 1094 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart, 1095 (int)(pSpan->zEnd - pSpan->zStart)); 1096 } 1097 } 1098 sqlite3ExprDelete(db, pSpan->pExpr); 1099 } 1100 1101 /* 1102 ** Designate the PRIMARY KEY for the table. pList is a list of names 1103 ** of columns that form the primary key. If pList is NULL, then the 1104 ** most recently added column of the table is the primary key. 1105 ** 1106 ** A table can have at most one primary key. If the table already has 1107 ** a primary key (and this is the second primary key) then create an 1108 ** error. 1109 ** 1110 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 1111 ** then we will try to use that column as the rowid. Set the Table.iPKey 1112 ** field of the table under construction to be the index of the 1113 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 1114 ** no INTEGER PRIMARY KEY. 1115 ** 1116 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 1117 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 1118 */ 1119 void sqlite3AddPrimaryKey( 1120 Parse *pParse, /* Parsing context */ 1121 ExprList *pList, /* List of field names to be indexed */ 1122 int onError, /* What to do with a uniqueness conflict */ 1123 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1124 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1125 ){ 1126 Table *pTab = pParse->pNewTable; 1127 char *zType = 0; 1128 int iCol = -1, i; 1129 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 1130 if( pTab->tabFlags & TF_HasPrimaryKey ){ 1131 sqlite3ErrorMsg(pParse, 1132 "table \"%s\" has more than one primary key", pTab->zName); 1133 goto primary_key_exit; 1134 } 1135 pTab->tabFlags |= TF_HasPrimaryKey; 1136 if( pList==0 ){ 1137 iCol = pTab->nCol - 1; 1138 pTab->aCol[iCol].isPrimKey = 1; 1139 }else{ 1140 for(i=0; i<pList->nExpr; i++){ 1141 for(iCol=0; iCol<pTab->nCol; iCol++){ 1142 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ 1143 break; 1144 } 1145 } 1146 if( iCol<pTab->nCol ){ 1147 pTab->aCol[iCol].isPrimKey = 1; 1148 } 1149 } 1150 if( pList->nExpr>1 ) iCol = -1; 1151 } 1152 if( iCol>=0 && iCol<pTab->nCol ){ 1153 zType = pTab->aCol[iCol].zType; 1154 } 1155 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 1156 && sortOrder==SQLITE_SO_ASC ){ 1157 pTab->iPKey = iCol; 1158 pTab->keyConf = (u8)onError; 1159 assert( autoInc==0 || autoInc==1 ); 1160 pTab->tabFlags |= autoInc*TF_Autoincrement; 1161 }else if( autoInc ){ 1162 #ifndef SQLITE_OMIT_AUTOINCREMENT 1163 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1164 "INTEGER PRIMARY KEY"); 1165 #endif 1166 }else{ 1167 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); 1168 pList = 0; 1169 } 1170 1171 primary_key_exit: 1172 sqlite3ExprListDelete(pParse->db, pList); 1173 return; 1174 } 1175 1176 /* 1177 ** Add a new CHECK constraint to the table currently under construction. 1178 */ 1179 void sqlite3AddCheckConstraint( 1180 Parse *pParse, /* Parsing context */ 1181 Expr *pCheckExpr /* The check expression */ 1182 ){ 1183 sqlite3 *db = pParse->db; 1184 #ifndef SQLITE_OMIT_CHECK 1185 Table *pTab = pParse->pNewTable; 1186 if( pTab && !IN_DECLARE_VTAB ){ 1187 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr); 1188 }else 1189 #endif 1190 { 1191 sqlite3ExprDelete(db, pCheckExpr); 1192 } 1193 } 1194 1195 /* 1196 ** Set the collation function of the most recently parsed table column 1197 ** to the CollSeq given. 1198 */ 1199 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 1200 Table *p; 1201 int i; 1202 char *zColl; /* Dequoted name of collation sequence */ 1203 sqlite3 *db; 1204 1205 if( (p = pParse->pNewTable)==0 ) return; 1206 i = p->nCol-1; 1207 db = pParse->db; 1208 zColl = sqlite3NameFromToken(db, pToken); 1209 if( !zColl ) return; 1210 1211 if( sqlite3LocateCollSeq(pParse, zColl) ){ 1212 Index *pIdx; 1213 p->aCol[i].zColl = zColl; 1214 1215 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1216 ** then an index may have been created on this column before the 1217 ** collation type was added. Correct this if it is the case. 1218 */ 1219 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1220 assert( pIdx->nColumn==1 ); 1221 if( pIdx->aiColumn[0]==i ){ 1222 pIdx->azColl[0] = p->aCol[i].zColl; 1223 } 1224 } 1225 }else{ 1226 sqlite3DbFree(db, zColl); 1227 } 1228 } 1229 1230 /* 1231 ** This function returns the collation sequence for database native text 1232 ** encoding identified by the string zName, length nName. 1233 ** 1234 ** If the requested collation sequence is not available, or not available 1235 ** in the database native encoding, the collation factory is invoked to 1236 ** request it. If the collation factory does not supply such a sequence, 1237 ** and the sequence is available in another text encoding, then that is 1238 ** returned instead. 1239 ** 1240 ** If no versions of the requested collations sequence are available, or 1241 ** another error occurs, NULL is returned and an error message written into 1242 ** pParse. 1243 ** 1244 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 1245 ** invokes the collation factory if the named collation cannot be found 1246 ** and generates an error message. 1247 ** 1248 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() 1249 */ 1250 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ 1251 sqlite3 *db = pParse->db; 1252 u8 enc = ENC(db); 1253 u8 initbusy = db->init.busy; 1254 CollSeq *pColl; 1255 1256 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); 1257 if( !initbusy && (!pColl || !pColl->xCmp) ){ 1258 pColl = sqlite3GetCollSeq(db, pColl, zName); 1259 if( !pColl ){ 1260 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); 1261 } 1262 } 1263 1264 return pColl; 1265 } 1266 1267 1268 /* 1269 ** Generate code that will increment the schema cookie. 1270 ** 1271 ** The schema cookie is used to determine when the schema for the 1272 ** database changes. After each schema change, the cookie value 1273 ** changes. When a process first reads the schema it records the 1274 ** cookie. Thereafter, whenever it goes to access the database, 1275 ** it checks the cookie to make sure the schema has not changed 1276 ** since it was last read. 1277 ** 1278 ** This plan is not completely bullet-proof. It is possible for 1279 ** the schema to change multiple times and for the cookie to be 1280 ** set back to prior value. But schema changes are infrequent 1281 ** and the probability of hitting the same cookie value is only 1282 ** 1 chance in 2^32. So we're safe enough. 1283 */ 1284 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 1285 int r1 = sqlite3GetTempReg(pParse); 1286 sqlite3 *db = pParse->db; 1287 Vdbe *v = pParse->pVdbe; 1288 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); 1289 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); 1290 sqlite3ReleaseTempReg(pParse, r1); 1291 } 1292 1293 /* 1294 ** Measure the number of characters needed to output the given 1295 ** identifier. The number returned includes any quotes used 1296 ** but does not include the null terminator. 1297 ** 1298 ** The estimate is conservative. It might be larger that what is 1299 ** really needed. 1300 */ 1301 static int identLength(const char *z){ 1302 int n; 1303 for(n=0; *z; n++, z++){ 1304 if( *z=='"' ){ n++; } 1305 } 1306 return n + 2; 1307 } 1308 1309 /* 1310 ** The first parameter is a pointer to an output buffer. The second 1311 ** parameter is a pointer to an integer that contains the offset at 1312 ** which to write into the output buffer. This function copies the 1313 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 1314 ** to the specified offset in the buffer and updates *pIdx to refer 1315 ** to the first byte after the last byte written before returning. 1316 ** 1317 ** If the string zSignedIdent consists entirely of alpha-numeric 1318 ** characters, does not begin with a digit and is not an SQL keyword, 1319 ** then it is copied to the output buffer exactly as it is. Otherwise, 1320 ** it is quoted using double-quotes. 1321 */ 1322 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 1323 unsigned char *zIdent = (unsigned char*)zSignedIdent; 1324 int i, j, needQuote; 1325 i = *pIdx; 1326 1327 for(j=0; zIdent[j]; j++){ 1328 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 1329 } 1330 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID; 1331 if( !needQuote ){ 1332 needQuote = zIdent[j]; 1333 } 1334 1335 if( needQuote ) z[i++] = '"'; 1336 for(j=0; zIdent[j]; j++){ 1337 z[i++] = zIdent[j]; 1338 if( zIdent[j]=='"' ) z[i++] = '"'; 1339 } 1340 if( needQuote ) z[i++] = '"'; 1341 z[i] = 0; 1342 *pIdx = i; 1343 } 1344 1345 /* 1346 ** Generate a CREATE TABLE statement appropriate for the given 1347 ** table. Memory to hold the text of the statement is obtained 1348 ** from sqliteMalloc() and must be freed by the calling function. 1349 */ 1350 static char *createTableStmt(sqlite3 *db, Table *p){ 1351 int i, k, n; 1352 char *zStmt; 1353 char *zSep, *zSep2, *zEnd; 1354 Column *pCol; 1355 n = 0; 1356 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1357 n += identLength(pCol->zName) + 5; 1358 } 1359 n += identLength(p->zName); 1360 if( n<50 ){ 1361 zSep = ""; 1362 zSep2 = ","; 1363 zEnd = ")"; 1364 }else{ 1365 zSep = "\n "; 1366 zSep2 = ",\n "; 1367 zEnd = "\n)"; 1368 } 1369 n += 35 + 6*p->nCol; 1370 zStmt = sqlite3Malloc( n ); 1371 if( zStmt==0 ){ 1372 db->mallocFailed = 1; 1373 return 0; 1374 } 1375 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 1376 k = sqlite3Strlen30(zStmt); 1377 identPut(zStmt, &k, p->zName); 1378 zStmt[k++] = '('; 1379 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1380 static const char * const azType[] = { 1381 /* SQLITE_AFF_TEXT */ " TEXT", 1382 /* SQLITE_AFF_NONE */ "", 1383 /* SQLITE_AFF_NUMERIC */ " NUM", 1384 /* SQLITE_AFF_INTEGER */ " INT", 1385 /* SQLITE_AFF_REAL */ " REAL" 1386 }; 1387 int len; 1388 const char *zType; 1389 1390 sqlite3_snprintf(n-k, &zStmt[k], zSep); 1391 k += sqlite3Strlen30(&zStmt[k]); 1392 zSep = zSep2; 1393 identPut(zStmt, &k, pCol->zName); 1394 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 ); 1395 assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) ); 1396 testcase( pCol->affinity==SQLITE_AFF_TEXT ); 1397 testcase( pCol->affinity==SQLITE_AFF_NONE ); 1398 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 1399 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 1400 testcase( pCol->affinity==SQLITE_AFF_REAL ); 1401 1402 zType = azType[pCol->affinity - SQLITE_AFF_TEXT]; 1403 len = sqlite3Strlen30(zType); 1404 assert( pCol->affinity==SQLITE_AFF_NONE 1405 || pCol->affinity==sqlite3AffinityType(zType) ); 1406 memcpy(&zStmt[k], zType, len); 1407 k += len; 1408 assert( k<=n ); 1409 } 1410 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 1411 return zStmt; 1412 } 1413 1414 /* 1415 ** This routine is called to report the final ")" that terminates 1416 ** a CREATE TABLE statement. 1417 ** 1418 ** The table structure that other action routines have been building 1419 ** is added to the internal hash tables, assuming no errors have 1420 ** occurred. 1421 ** 1422 ** An entry for the table is made in the master table on disk, unless 1423 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1424 ** it means we are reading the sqlite_master table because we just 1425 ** connected to the database or because the sqlite_master table has 1426 ** recently changed, so the entry for this table already exists in 1427 ** the sqlite_master table. We do not want to create it again. 1428 ** 1429 ** If the pSelect argument is not NULL, it means that this routine 1430 ** was called to create a table generated from a 1431 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1432 ** the new table will match the result set of the SELECT. 1433 */ 1434 void sqlite3EndTable( 1435 Parse *pParse, /* Parse context */ 1436 Token *pCons, /* The ',' token after the last column defn. */ 1437 Token *pEnd, /* The final ')' token in the CREATE TABLE */ 1438 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 1439 ){ 1440 Table *p; 1441 sqlite3 *db = pParse->db; 1442 int iDb; 1443 1444 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){ 1445 return; 1446 } 1447 p = pParse->pNewTable; 1448 if( p==0 ) return; 1449 1450 assert( !db->init.busy || !pSelect ); 1451 1452 iDb = sqlite3SchemaToIndex(db, p->pSchema); 1453 1454 #ifndef SQLITE_OMIT_CHECK 1455 /* Resolve names in all CHECK constraint expressions. 1456 */ 1457 if( p->pCheck ){ 1458 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 1459 NameContext sNC; /* Name context for pParse->pNewTable */ 1460 1461 memset(&sNC, 0, sizeof(sNC)); 1462 memset(&sSrc, 0, sizeof(sSrc)); 1463 sSrc.nSrc = 1; 1464 sSrc.a[0].zName = p->zName; 1465 sSrc.a[0].pTab = p; 1466 sSrc.a[0].iCursor = -1; 1467 sNC.pParse = pParse; 1468 sNC.pSrcList = &sSrc; 1469 sNC.isCheck = 1; 1470 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){ 1471 return; 1472 } 1473 } 1474 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1475 1476 /* If the db->init.busy is 1 it means we are reading the SQL off the 1477 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1478 ** So do not write to the disk again. Extract the root page number 1479 ** for the table from the db->init.newTnum field. (The page number 1480 ** should have been put there by the sqliteOpenCb routine.) 1481 */ 1482 if( db->init.busy ){ 1483 p->tnum = db->init.newTnum; 1484 } 1485 1486 /* If not initializing, then create a record for the new table 1487 ** in the SQLITE_MASTER table of the database. 1488 ** 1489 ** If this is a TEMPORARY table, write the entry into the auxiliary 1490 ** file instead of into the main database file. 1491 */ 1492 if( !db->init.busy ){ 1493 int n; 1494 Vdbe *v; 1495 char *zType; /* "view" or "table" */ 1496 char *zType2; /* "VIEW" or "TABLE" */ 1497 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 1498 1499 v = sqlite3GetVdbe(pParse); 1500 if( NEVER(v==0) ) return; 1501 1502 sqlite3VdbeAddOp1(v, OP_Close, 0); 1503 1504 /* 1505 ** Initialize zType for the new view or table. 1506 */ 1507 if( p->pSelect==0 ){ 1508 /* A regular table */ 1509 zType = "table"; 1510 zType2 = "TABLE"; 1511 #ifndef SQLITE_OMIT_VIEW 1512 }else{ 1513 /* A view */ 1514 zType = "view"; 1515 zType2 = "VIEW"; 1516 #endif 1517 } 1518 1519 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 1520 ** statement to populate the new table. The root-page number for the 1521 ** new table is in register pParse->regRoot. 1522 ** 1523 ** Once the SELECT has been coded by sqlite3Select(), it is in a 1524 ** suitable state to query for the column names and types to be used 1525 ** by the new table. 1526 ** 1527 ** A shared-cache write-lock is not required to write to the new table, 1528 ** as a schema-lock must have already been obtained to create it. Since 1529 ** a schema-lock excludes all other database users, the write-lock would 1530 ** be redundant. 1531 */ 1532 if( pSelect ){ 1533 SelectDest dest; 1534 Table *pSelTab; 1535 1536 assert(pParse->nTab==1); 1537 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 1538 sqlite3VdbeChangeP5(v, 1); 1539 pParse->nTab = 2; 1540 sqlite3SelectDestInit(&dest, SRT_Table, 1); 1541 sqlite3Select(pParse, pSelect, &dest); 1542 sqlite3VdbeAddOp1(v, OP_Close, 1); 1543 if( pParse->nErr==0 ){ 1544 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 1545 if( pSelTab==0 ) return; 1546 assert( p->aCol==0 ); 1547 p->nCol = pSelTab->nCol; 1548 p->aCol = pSelTab->aCol; 1549 pSelTab->nCol = 0; 1550 pSelTab->aCol = 0; 1551 sqlite3DeleteTable(pSelTab); 1552 } 1553 } 1554 1555 /* Compute the complete text of the CREATE statement */ 1556 if( pSelect ){ 1557 zStmt = createTableStmt(db, p); 1558 }else{ 1559 n = (int)(pEnd->z - pParse->sNameToken.z) + 1; 1560 zStmt = sqlite3MPrintf(db, 1561 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 1562 ); 1563 } 1564 1565 /* A slot for the record has already been allocated in the 1566 ** SQLITE_MASTER table. We just need to update that slot with all 1567 ** the information we've collected. 1568 */ 1569 sqlite3NestedParse(pParse, 1570 "UPDATE %Q.%s " 1571 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 1572 "WHERE rowid=#%d", 1573 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 1574 zType, 1575 p->zName, 1576 p->zName, 1577 pParse->regRoot, 1578 zStmt, 1579 pParse->regRowid 1580 ); 1581 sqlite3DbFree(db, zStmt); 1582 sqlite3ChangeCookie(pParse, iDb); 1583 1584 #ifndef SQLITE_OMIT_AUTOINCREMENT 1585 /* Check to see if we need to create an sqlite_sequence table for 1586 ** keeping track of autoincrement keys. 1587 */ 1588 if( p->tabFlags & TF_Autoincrement ){ 1589 Db *pDb = &db->aDb[iDb]; 1590 if( pDb->pSchema->pSeqTab==0 ){ 1591 sqlite3NestedParse(pParse, 1592 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 1593 pDb->zName 1594 ); 1595 } 1596 } 1597 #endif 1598 1599 /* Reparse everything to update our internal data structures */ 1600 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 1601 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); 1602 } 1603 1604 1605 /* Add the table to the in-memory representation of the database. 1606 */ 1607 if( db->init.busy ){ 1608 Table *pOld; 1609 Schema *pSchema = p->pSchema; 1610 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, 1611 sqlite3Strlen30(p->zName),p); 1612 if( pOld ){ 1613 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 1614 db->mallocFailed = 1; 1615 return; 1616 } 1617 pParse->pNewTable = 0; 1618 db->nTable++; 1619 db->flags |= SQLITE_InternChanges; 1620 1621 #ifndef SQLITE_OMIT_ALTERTABLE 1622 if( !p->pSelect ){ 1623 const char *zName = (const char *)pParse->sNameToken.z; 1624 int nName; 1625 assert( !pSelect && pCons && pEnd ); 1626 if( pCons->z==0 ){ 1627 pCons = pEnd; 1628 } 1629 nName = (int)((const char *)pCons->z - zName); 1630 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 1631 } 1632 #endif 1633 } 1634 } 1635 1636 #ifndef SQLITE_OMIT_VIEW 1637 /* 1638 ** The parser calls this routine in order to create a new VIEW 1639 */ 1640 void sqlite3CreateView( 1641 Parse *pParse, /* The parsing context */ 1642 Token *pBegin, /* The CREATE token that begins the statement */ 1643 Token *pName1, /* The token that holds the name of the view */ 1644 Token *pName2, /* The token that holds the name of the view */ 1645 Select *pSelect, /* A SELECT statement that will become the new view */ 1646 int isTemp, /* TRUE for a TEMPORARY view */ 1647 int noErr /* Suppress error messages if VIEW already exists */ 1648 ){ 1649 Table *p; 1650 int n; 1651 const char *z; 1652 Token sEnd; 1653 DbFixer sFix; 1654 Token *pName; 1655 int iDb; 1656 sqlite3 *db = pParse->db; 1657 1658 if( pParse->nVar>0 ){ 1659 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 1660 sqlite3SelectDelete(db, pSelect); 1661 return; 1662 } 1663 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 1664 p = pParse->pNewTable; 1665 if( p==0 ){ 1666 sqlite3SelectDelete(db, pSelect); 1667 return; 1668 } 1669 assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then 1670 ** there could not have been an error */ 1671 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 1672 iDb = sqlite3SchemaToIndex(db, p->pSchema); 1673 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) 1674 && sqlite3FixSelect(&sFix, pSelect) 1675 ){ 1676 sqlite3SelectDelete(db, pSelect); 1677 return; 1678 } 1679 1680 /* Make a copy of the entire SELECT statement that defines the view. 1681 ** This will force all the Expr.token.z values to be dynamically 1682 ** allocated rather than point to the input string - which means that 1683 ** they will persist after the current sqlite3_exec() call returns. 1684 */ 1685 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 1686 sqlite3SelectDelete(db, pSelect); 1687 if( db->mallocFailed ){ 1688 return; 1689 } 1690 if( !db->init.busy ){ 1691 sqlite3ViewGetColumnNames(pParse, p); 1692 } 1693 1694 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 1695 ** the end. 1696 */ 1697 sEnd = pParse->sLastToken; 1698 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){ 1699 sEnd.z += sEnd.n; 1700 } 1701 sEnd.n = 0; 1702 n = (int)(sEnd.z - pBegin->z); 1703 z = pBegin->z; 1704 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; } 1705 sEnd.z = &z[n-1]; 1706 sEnd.n = 1; 1707 1708 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 1709 sqlite3EndTable(pParse, 0, &sEnd, 0); 1710 return; 1711 } 1712 #endif /* SQLITE_OMIT_VIEW */ 1713 1714 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 1715 /* 1716 ** The Table structure pTable is really a VIEW. Fill in the names of 1717 ** the columns of the view in the pTable structure. Return the number 1718 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 1719 */ 1720 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 1721 Table *pSelTab; /* A fake table from which we get the result set */ 1722 Select *pSel; /* Copy of the SELECT that implements the view */ 1723 int nErr = 0; /* Number of errors encountered */ 1724 int n; /* Temporarily holds the number of cursors assigned */ 1725 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 1726 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); 1727 1728 assert( pTable ); 1729 1730 #ifndef SQLITE_OMIT_VIRTUALTABLE 1731 if( sqlite3VtabCallConnect(pParse, pTable) ){ 1732 return SQLITE_ERROR; 1733 } 1734 if( IsVirtual(pTable) ) return 0; 1735 #endif 1736 1737 #ifndef SQLITE_OMIT_VIEW 1738 /* A positive nCol means the columns names for this view are 1739 ** already known. 1740 */ 1741 if( pTable->nCol>0 ) return 0; 1742 1743 /* A negative nCol is a special marker meaning that we are currently 1744 ** trying to compute the column names. If we enter this routine with 1745 ** a negative nCol, it means two or more views form a loop, like this: 1746 ** 1747 ** CREATE VIEW one AS SELECT * FROM two; 1748 ** CREATE VIEW two AS SELECT * FROM one; 1749 ** 1750 ** Actually, the error above is now caught prior to reaching this point. 1751 ** But the following test is still important as it does come up 1752 ** in the following: 1753 ** 1754 ** CREATE TABLE main.ex1(a); 1755 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 1756 ** SELECT * FROM temp.ex1; 1757 */ 1758 if( pTable->nCol<0 ){ 1759 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 1760 return 1; 1761 } 1762 assert( pTable->nCol>=0 ); 1763 1764 /* If we get this far, it means we need to compute the table names. 1765 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 1766 ** "*" elements in the results set of the view and will assign cursors 1767 ** to the elements of the FROM clause. But we do not want these changes 1768 ** to be permanent. So the computation is done on a copy of the SELECT 1769 ** statement that defines the view. 1770 */ 1771 assert( pTable->pSelect ); 1772 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); 1773 if( pSel ){ 1774 u8 enableLookaside = db->lookaside.bEnabled; 1775 n = pParse->nTab; 1776 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 1777 pTable->nCol = -1; 1778 db->lookaside.bEnabled = 0; 1779 #ifndef SQLITE_OMIT_AUTHORIZATION 1780 xAuth = db->xAuth; 1781 db->xAuth = 0; 1782 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 1783 db->xAuth = xAuth; 1784 #else 1785 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 1786 #endif 1787 db->lookaside.bEnabled = enableLookaside; 1788 pParse->nTab = n; 1789 if( pSelTab ){ 1790 assert( pTable->aCol==0 ); 1791 pTable->nCol = pSelTab->nCol; 1792 pTable->aCol = pSelTab->aCol; 1793 pSelTab->nCol = 0; 1794 pSelTab->aCol = 0; 1795 sqlite3DeleteTable(pSelTab); 1796 pTable->pSchema->flags |= DB_UnresetViews; 1797 }else{ 1798 pTable->nCol = 0; 1799 nErr++; 1800 } 1801 sqlite3SelectDelete(db, pSel); 1802 } else { 1803 nErr++; 1804 } 1805 #endif /* SQLITE_OMIT_VIEW */ 1806 return nErr; 1807 } 1808 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 1809 1810 #ifndef SQLITE_OMIT_VIEW 1811 /* 1812 ** Clear the column names from every VIEW in database idx. 1813 */ 1814 static void sqliteViewResetAll(sqlite3 *db, int idx){ 1815 HashElem *i; 1816 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 1817 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 1818 Table *pTab = sqliteHashData(i); 1819 if( pTab->pSelect ){ 1820 sqliteResetColumnNames(pTab); 1821 } 1822 } 1823 DbClearProperty(db, idx, DB_UnresetViews); 1824 } 1825 #else 1826 # define sqliteViewResetAll(A,B) 1827 #endif /* SQLITE_OMIT_VIEW */ 1828 1829 /* 1830 ** This function is called by the VDBE to adjust the internal schema 1831 ** used by SQLite when the btree layer moves a table root page. The 1832 ** root-page of a table or index in database iDb has changed from iFrom 1833 ** to iTo. 1834 ** 1835 ** Ticket #1728: The symbol table might still contain information 1836 ** on tables and/or indices that are the process of being deleted. 1837 ** If you are unlucky, one of those deleted indices or tables might 1838 ** have the same rootpage number as the real table or index that is 1839 ** being moved. So we cannot stop searching after the first match 1840 ** because the first match might be for one of the deleted indices 1841 ** or tables and not the table/index that is actually being moved. 1842 ** We must continue looping until all tables and indices with 1843 ** rootpage==iFrom have been converted to have a rootpage of iTo 1844 ** in order to be certain that we got the right one. 1845 */ 1846 #ifndef SQLITE_OMIT_AUTOVACUUM 1847 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ 1848 HashElem *pElem; 1849 Hash *pHash; 1850 1851 pHash = &pDb->pSchema->tblHash; 1852 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 1853 Table *pTab = sqliteHashData(pElem); 1854 if( pTab->tnum==iFrom ){ 1855 pTab->tnum = iTo; 1856 } 1857 } 1858 pHash = &pDb->pSchema->idxHash; 1859 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 1860 Index *pIdx = sqliteHashData(pElem); 1861 if( pIdx->tnum==iFrom ){ 1862 pIdx->tnum = iTo; 1863 } 1864 } 1865 } 1866 #endif 1867 1868 /* 1869 ** Write code to erase the table with root-page iTable from database iDb. 1870 ** Also write code to modify the sqlite_master table and internal schema 1871 ** if a root-page of another table is moved by the btree-layer whilst 1872 ** erasing iTable (this can happen with an auto-vacuum database). 1873 */ 1874 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 1875 Vdbe *v = sqlite3GetVdbe(pParse); 1876 int r1 = sqlite3GetTempReg(pParse); 1877 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 1878 #ifndef SQLITE_OMIT_AUTOVACUUM 1879 /* OP_Destroy stores an in integer r1. If this integer 1880 ** is non-zero, then it is the root page number of a table moved to 1881 ** location iTable. The following code modifies the sqlite_master table to 1882 ** reflect this. 1883 ** 1884 ** The "#NNN" in the SQL is a special constant that means whatever value 1885 ** is in register NNN. See grammar rules associated with the TK_REGISTER 1886 ** token for additional information. 1887 */ 1888 sqlite3NestedParse(pParse, 1889 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 1890 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); 1891 #endif 1892 sqlite3ReleaseTempReg(pParse, r1); 1893 } 1894 1895 /* 1896 ** Write VDBE code to erase table pTab and all associated indices on disk. 1897 ** Code to update the sqlite_master tables and internal schema definitions 1898 ** in case a root-page belonging to another table is moved by the btree layer 1899 ** is also added (this can happen with an auto-vacuum database). 1900 */ 1901 static void destroyTable(Parse *pParse, Table *pTab){ 1902 #ifdef SQLITE_OMIT_AUTOVACUUM 1903 Index *pIdx; 1904 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1905 destroyRootPage(pParse, pTab->tnum, iDb); 1906 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1907 destroyRootPage(pParse, pIdx->tnum, iDb); 1908 } 1909 #else 1910 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 1911 ** is not defined), then it is important to call OP_Destroy on the 1912 ** table and index root-pages in order, starting with the numerically 1913 ** largest root-page number. This guarantees that none of the root-pages 1914 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 1915 ** following were coded: 1916 ** 1917 ** OP_Destroy 4 0 1918 ** ... 1919 ** OP_Destroy 5 0 1920 ** 1921 ** and root page 5 happened to be the largest root-page number in the 1922 ** database, then root page 5 would be moved to page 4 by the 1923 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 1924 ** a free-list page. 1925 */ 1926 int iTab = pTab->tnum; 1927 int iDestroyed = 0; 1928 1929 while( 1 ){ 1930 Index *pIdx; 1931 int iLargest = 0; 1932 1933 if( iDestroyed==0 || iTab<iDestroyed ){ 1934 iLargest = iTab; 1935 } 1936 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1937 int iIdx = pIdx->tnum; 1938 assert( pIdx->pSchema==pTab->pSchema ); 1939 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 1940 iLargest = iIdx; 1941 } 1942 } 1943 if( iLargest==0 ){ 1944 return; 1945 }else{ 1946 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 1947 destroyRootPage(pParse, iLargest, iDb); 1948 iDestroyed = iLargest; 1949 } 1950 } 1951 #endif 1952 } 1953 1954 /* 1955 ** This routine is called to do the work of a DROP TABLE statement. 1956 ** pName is the name of the table to be dropped. 1957 */ 1958 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 1959 Table *pTab; 1960 Vdbe *v; 1961 sqlite3 *db = pParse->db; 1962 int iDb; 1963 1964 if( db->mallocFailed ){ 1965 goto exit_drop_table; 1966 } 1967 assert( pParse->nErr==0 ); 1968 assert( pName->nSrc==1 ); 1969 pTab = sqlite3LocateTable(pParse, isView, 1970 pName->a[0].zName, pName->a[0].zDatabase); 1971 1972 if( pTab==0 ){ 1973 if( noErr ){ 1974 sqlite3ErrorClear(pParse); 1975 } 1976 goto exit_drop_table; 1977 } 1978 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1979 assert( iDb>=0 && iDb<db->nDb ); 1980 1981 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 1982 ** it is initialized. 1983 */ 1984 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 1985 goto exit_drop_table; 1986 } 1987 #ifndef SQLITE_OMIT_AUTHORIZATION 1988 { 1989 int code; 1990 const char *zTab = SCHEMA_TABLE(iDb); 1991 const char *zDb = db->aDb[iDb].zName; 1992 const char *zArg2 = 0; 1993 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 1994 goto exit_drop_table; 1995 } 1996 if( isView ){ 1997 if( !OMIT_TEMPDB && iDb==1 ){ 1998 code = SQLITE_DROP_TEMP_VIEW; 1999 }else{ 2000 code = SQLITE_DROP_VIEW; 2001 } 2002 #ifndef SQLITE_OMIT_VIRTUALTABLE 2003 }else if( IsVirtual(pTab) ){ 2004 code = SQLITE_DROP_VTABLE; 2005 zArg2 = pTab->pMod->zName; 2006 #endif 2007 }else{ 2008 if( !OMIT_TEMPDB && iDb==1 ){ 2009 code = SQLITE_DROP_TEMP_TABLE; 2010 }else{ 2011 code = SQLITE_DROP_TABLE; 2012 } 2013 } 2014 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 2015 goto exit_drop_table; 2016 } 2017 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 2018 goto exit_drop_table; 2019 } 2020 } 2021 #endif 2022 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 2023 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 2024 goto exit_drop_table; 2025 } 2026 2027 #ifndef SQLITE_OMIT_VIEW 2028 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 2029 ** on a table. 2030 */ 2031 if( isView && pTab->pSelect==0 ){ 2032 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 2033 goto exit_drop_table; 2034 } 2035 if( !isView && pTab->pSelect ){ 2036 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 2037 goto exit_drop_table; 2038 } 2039 #endif 2040 2041 /* Generate code to remove the table from the master table 2042 ** on disk. 2043 */ 2044 v = sqlite3GetVdbe(pParse); 2045 if( v ){ 2046 Trigger *pTrigger; 2047 Db *pDb = &db->aDb[iDb]; 2048 sqlite3BeginWriteOperation(pParse, 1, iDb); 2049 2050 #ifndef SQLITE_OMIT_VIRTUALTABLE 2051 if( IsVirtual(pTab) ){ 2052 sqlite3VdbeAddOp0(v, OP_VBegin); 2053 } 2054 #endif 2055 2056 /* Drop all triggers associated with the table being dropped. Code 2057 ** is generated to remove entries from sqlite_master and/or 2058 ** sqlite_temp_master if required. 2059 */ 2060 pTrigger = sqlite3TriggerList(pParse, pTab); 2061 while( pTrigger ){ 2062 assert( pTrigger->pSchema==pTab->pSchema || 2063 pTrigger->pSchema==db->aDb[1].pSchema ); 2064 sqlite3DropTriggerPtr(pParse, pTrigger); 2065 pTrigger = pTrigger->pNext; 2066 } 2067 2068 #ifndef SQLITE_OMIT_AUTOINCREMENT 2069 /* Remove any entries of the sqlite_sequence table associated with 2070 ** the table being dropped. This is done before the table is dropped 2071 ** at the btree level, in case the sqlite_sequence table needs to 2072 ** move as a result of the drop (can happen in auto-vacuum mode). 2073 */ 2074 if( pTab->tabFlags & TF_Autoincrement ){ 2075 sqlite3NestedParse(pParse, 2076 "DELETE FROM %s.sqlite_sequence WHERE name=%Q", 2077 pDb->zName, pTab->zName 2078 ); 2079 } 2080 #endif 2081 2082 /* Drop all SQLITE_MASTER table and index entries that refer to the 2083 ** table. The program name loops through the master table and deletes 2084 ** every row that refers to a table of the same name as the one being 2085 ** dropped. Triggers are handled seperately because a trigger can be 2086 ** created in the temp database that refers to a table in another 2087 ** database. 2088 */ 2089 sqlite3NestedParse(pParse, 2090 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 2091 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 2092 2093 /* Drop any statistics from the sqlite_stat1 table, if it exists */ 2094 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 2095 sqlite3NestedParse(pParse, 2096 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName 2097 ); 2098 } 2099 2100 if( !isView && !IsVirtual(pTab) ){ 2101 destroyTable(pParse, pTab); 2102 } 2103 2104 /* Remove the table entry from SQLite's internal schema and modify 2105 ** the schema cookie. 2106 */ 2107 if( IsVirtual(pTab) ){ 2108 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 2109 } 2110 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 2111 sqlite3ChangeCookie(pParse, iDb); 2112 } 2113 sqliteViewResetAll(db, iDb); 2114 2115 exit_drop_table: 2116 sqlite3SrcListDelete(db, pName); 2117 } 2118 2119 /* 2120 ** This routine is called to create a new foreign key on the table 2121 ** currently under construction. pFromCol determines which columns 2122 ** in the current table point to the foreign key. If pFromCol==0 then 2123 ** connect the key to the last column inserted. pTo is the name of 2124 ** the table referred to. pToCol is a list of tables in the other 2125 ** pTo table that the foreign key points to. flags contains all 2126 ** information about the conflict resolution algorithms specified 2127 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 2128 ** 2129 ** An FKey structure is created and added to the table currently 2130 ** under construction in the pParse->pNewTable field. 2131 ** 2132 ** The foreign key is set for IMMEDIATE processing. A subsequent call 2133 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 2134 */ 2135 void sqlite3CreateForeignKey( 2136 Parse *pParse, /* Parsing context */ 2137 ExprList *pFromCol, /* Columns in this table that point to other table */ 2138 Token *pTo, /* Name of the other table */ 2139 ExprList *pToCol, /* Columns in the other table */ 2140 int flags /* Conflict resolution algorithms. */ 2141 ){ 2142 sqlite3 *db = pParse->db; 2143 #ifndef SQLITE_OMIT_FOREIGN_KEY 2144 FKey *pFKey = 0; 2145 Table *p = pParse->pNewTable; 2146 int nByte; 2147 int i; 2148 int nCol; 2149 char *z; 2150 2151 assert( pTo!=0 ); 2152 if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 2153 if( pFromCol==0 ){ 2154 int iCol = p->nCol-1; 2155 if( NEVER(iCol<0) ) goto fk_end; 2156 if( pToCol && pToCol->nExpr!=1 ){ 2157 sqlite3ErrorMsg(pParse, "foreign key on %s" 2158 " should reference only one column of table %T", 2159 p->aCol[iCol].zName, pTo); 2160 goto fk_end; 2161 } 2162 nCol = 1; 2163 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 2164 sqlite3ErrorMsg(pParse, 2165 "number of columns in foreign key does not match the number of " 2166 "columns in the referenced table"); 2167 goto fk_end; 2168 }else{ 2169 nCol = pFromCol->nExpr; 2170 } 2171 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 2172 if( pToCol ){ 2173 for(i=0; i<pToCol->nExpr; i++){ 2174 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; 2175 } 2176 } 2177 pFKey = sqlite3DbMallocZero(db, nByte ); 2178 if( pFKey==0 ){ 2179 goto fk_end; 2180 } 2181 pFKey->pFrom = p; 2182 pFKey->pNextFrom = p->pFKey; 2183 z = (char*)&pFKey->aCol[nCol]; 2184 pFKey->zTo = z; 2185 memcpy(z, pTo->z, pTo->n); 2186 z[pTo->n] = 0; 2187 sqlite3Dequote(z); 2188 z += pTo->n+1; 2189 pFKey->nCol = nCol; 2190 if( pFromCol==0 ){ 2191 pFKey->aCol[0].iFrom = p->nCol-1; 2192 }else{ 2193 for(i=0; i<nCol; i++){ 2194 int j; 2195 for(j=0; j<p->nCol; j++){ 2196 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 2197 pFKey->aCol[i].iFrom = j; 2198 break; 2199 } 2200 } 2201 if( j>=p->nCol ){ 2202 sqlite3ErrorMsg(pParse, 2203 "unknown column \"%s\" in foreign key definition", 2204 pFromCol->a[i].zName); 2205 goto fk_end; 2206 } 2207 } 2208 } 2209 if( pToCol ){ 2210 for(i=0; i<nCol; i++){ 2211 int n = sqlite3Strlen30(pToCol->a[i].zName); 2212 pFKey->aCol[i].zCol = z; 2213 memcpy(z, pToCol->a[i].zName, n); 2214 z[n] = 0; 2215 z += n+1; 2216 } 2217 } 2218 pFKey->isDeferred = 0; 2219 pFKey->deleteConf = (u8)(flags & 0xff); 2220 pFKey->updateConf = (u8)((flags >> 8 ) & 0xff); 2221 pFKey->insertConf = (u8)((flags >> 16 ) & 0xff); 2222 2223 /* Link the foreign key to the table as the last step. 2224 */ 2225 p->pFKey = pFKey; 2226 pFKey = 0; 2227 2228 fk_end: 2229 sqlite3DbFree(db, pFKey); 2230 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 2231 sqlite3ExprListDelete(db, pFromCol); 2232 sqlite3ExprListDelete(db, pToCol); 2233 } 2234 2235 /* 2236 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 2237 ** clause is seen as part of a foreign key definition. The isDeferred 2238 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 2239 ** The behavior of the most recently created foreign key is adjusted 2240 ** accordingly. 2241 */ 2242 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 2243 #ifndef SQLITE_OMIT_FOREIGN_KEY 2244 Table *pTab; 2245 FKey *pFKey; 2246 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 2247 assert( isDeferred==0 || isDeferred==1 ); 2248 pFKey->isDeferred = (u8)isDeferred; 2249 #endif 2250 } 2251 2252 /* 2253 ** Generate code that will erase and refill index *pIdx. This is 2254 ** used to initialize a newly created index or to recompute the 2255 ** content of an index in response to a REINDEX command. 2256 ** 2257 ** if memRootPage is not negative, it means that the index is newly 2258 ** created. The register specified by memRootPage contains the 2259 ** root page number of the index. If memRootPage is negative, then 2260 ** the index already exists and must be cleared before being refilled and 2261 ** the root page number of the index is taken from pIndex->tnum. 2262 */ 2263 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 2264 Table *pTab = pIndex->pTable; /* The table that is indexed */ 2265 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 2266 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 2267 int addr1; /* Address of top of loop */ 2268 int tnum; /* Root page of index */ 2269 Vdbe *v; /* Generate code into this virtual machine */ 2270 KeyInfo *pKey; /* KeyInfo for index */ 2271 int regIdxKey; /* Registers containing the index key */ 2272 int regRecord; /* Register holding assemblied index record */ 2273 sqlite3 *db = pParse->db; /* The database connection */ 2274 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2275 2276 #ifndef SQLITE_OMIT_AUTHORIZATION 2277 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 2278 db->aDb[iDb].zName ) ){ 2279 return; 2280 } 2281 #endif 2282 2283 /* Require a write-lock on the table to perform this operation */ 2284 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 2285 2286 v = sqlite3GetVdbe(pParse); 2287 if( v==0 ) return; 2288 if( memRootPage>=0 ){ 2289 tnum = memRootPage; 2290 }else{ 2291 tnum = pIndex->tnum; 2292 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 2293 } 2294 pKey = sqlite3IndexKeyinfo(pParse, pIndex); 2295 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 2296 (char *)pKey, P4_KEYINFO_HANDOFF); 2297 if( memRootPage>=0 ){ 2298 sqlite3VdbeChangeP5(v, 1); 2299 } 2300 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2301 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); 2302 regRecord = sqlite3GetTempReg(pParse); 2303 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1); 2304 if( pIndex->onError!=OE_None ){ 2305 const int regRowid = regIdxKey + pIndex->nColumn; 2306 const int j2 = sqlite3VdbeCurrentAddr(v) + 2; 2307 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey); 2308 2309 /* The registers accessed by the OP_IsUnique opcode were allocated 2310 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey() 2311 ** call above. Just before that function was freed they were released 2312 ** (made available to the compiler for reuse) using 2313 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique 2314 ** opcode use the values stored within seems dangerous. However, since 2315 ** we can be sure that no other temp registers have been allocated 2316 ** since sqlite3ReleaseTempRange() was called, it is safe to do so. 2317 */ 2318 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32); 2319 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, 2320 "indexed columns are not unique", P4_STATIC); 2321 } 2322 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 2323 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 2324 sqlite3ReleaseTempReg(pParse, regRecord); 2325 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); 2326 sqlite3VdbeJumpHere(v, addr1); 2327 sqlite3VdbeAddOp1(v, OP_Close, iTab); 2328 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 2329 } 2330 2331 /* 2332 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 2333 ** and pTblList is the name of the table that is to be indexed. Both will 2334 ** be NULL for a primary key or an index that is created to satisfy a 2335 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2336 ** as the table to be indexed. pParse->pNewTable is a table that is 2337 ** currently being constructed by a CREATE TABLE statement. 2338 ** 2339 ** pList is a list of columns to be indexed. pList will be NULL if this 2340 ** is a primary key or unique-constraint on the most recent column added 2341 ** to the table currently under construction. 2342 */ 2343 void sqlite3CreateIndex( 2344 Parse *pParse, /* All information about this parse */ 2345 Token *pName1, /* First part of index name. May be NULL */ 2346 Token *pName2, /* Second part of index name. May be NULL */ 2347 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 2348 ExprList *pList, /* A list of columns to be indexed */ 2349 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 2350 Token *pStart, /* The CREATE token that begins this statement */ 2351 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ 2352 int sortOrder, /* Sort order of primary key when pList==NULL */ 2353 int ifNotExist /* Omit error if index already exists */ 2354 ){ 2355 Table *pTab = 0; /* Table to be indexed */ 2356 Index *pIndex = 0; /* The index to be created */ 2357 char *zName = 0; /* Name of the index */ 2358 int nName; /* Number of characters in zName */ 2359 int i, j; 2360 Token nullId; /* Fake token for an empty ID list */ 2361 DbFixer sFix; /* For assigning database names to pTable */ 2362 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 2363 sqlite3 *db = pParse->db; 2364 Db *pDb; /* The specific table containing the indexed database */ 2365 int iDb; /* Index of the database that is being written */ 2366 Token *pName = 0; /* Unqualified name of the index to create */ 2367 struct ExprList_item *pListItem; /* For looping over pList */ 2368 int nCol; 2369 int nExtra = 0; 2370 char *zExtra; 2371 2372 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */ 2373 assert( pParse->nErr==0 ); /* Never called with prior errors */ 2374 if( db->mallocFailed || IN_DECLARE_VTAB ){ 2375 goto exit_create_index; 2376 } 2377 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2378 goto exit_create_index; 2379 } 2380 2381 /* 2382 ** Find the table that is to be indexed. Return early if not found. 2383 */ 2384 if( pTblName!=0 ){ 2385 2386 /* Use the two-part index name to determine the database 2387 ** to search for the table. 'Fix' the table name to this db 2388 ** before looking up the table. 2389 */ 2390 assert( pName1 && pName2 ); 2391 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2392 if( iDb<0 ) goto exit_create_index; 2393 2394 #ifndef SQLITE_OMIT_TEMPDB 2395 /* If the index name was unqualified, check if the the table 2396 ** is a temp table. If so, set the database to 1. Do not do this 2397 ** if initialising a database schema. 2398 */ 2399 if( !db->init.busy ){ 2400 pTab = sqlite3SrcListLookup(pParse, pTblName); 2401 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 2402 iDb = 1; 2403 } 2404 } 2405 #endif 2406 2407 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && 2408 sqlite3FixSrcList(&sFix, pTblName) 2409 ){ 2410 /* Because the parser constructs pTblName from a single identifier, 2411 ** sqlite3FixSrcList can never fail. */ 2412 assert(0); 2413 } 2414 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 2415 pTblName->a[0].zDatabase); 2416 if( !pTab || db->mallocFailed ) goto exit_create_index; 2417 assert( db->aDb[iDb].pSchema==pTab->pSchema ); 2418 }else{ 2419 assert( pName==0 ); 2420 pTab = pParse->pNewTable; 2421 if( !pTab ) goto exit_create_index; 2422 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2423 } 2424 pDb = &db->aDb[iDb]; 2425 2426 assert( pTab!=0 ); 2427 assert( pParse->nErr==0 ); 2428 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 2429 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){ 2430 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 2431 goto exit_create_index; 2432 } 2433 #ifndef SQLITE_OMIT_VIEW 2434 if( pTab->pSelect ){ 2435 sqlite3ErrorMsg(pParse, "views may not be indexed"); 2436 goto exit_create_index; 2437 } 2438 #endif 2439 #ifndef SQLITE_OMIT_VIRTUALTABLE 2440 if( IsVirtual(pTab) ){ 2441 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 2442 goto exit_create_index; 2443 } 2444 #endif 2445 2446 /* 2447 ** Find the name of the index. Make sure there is not already another 2448 ** index or table with the same name. 2449 ** 2450 ** Exception: If we are reading the names of permanent indices from the 2451 ** sqlite_master table (because some other process changed the schema) and 2452 ** one of the index names collides with the name of a temporary table or 2453 ** index, then we will continue to process this index. 2454 ** 2455 ** If pName==0 it means that we are 2456 ** dealing with a primary key or UNIQUE constraint. We have to invent our 2457 ** own name. 2458 */ 2459 if( pName ){ 2460 zName = sqlite3NameFromToken(db, pName); 2461 if( zName==0 ) goto exit_create_index; 2462 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 2463 goto exit_create_index; 2464 } 2465 if( !db->init.busy ){ 2466 if( sqlite3FindTable(db, zName, 0)!=0 ){ 2467 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 2468 goto exit_create_index; 2469 } 2470 } 2471 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 2472 if( !ifNotExist ){ 2473 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 2474 } 2475 goto exit_create_index; 2476 } 2477 }else{ 2478 int n; 2479 Index *pLoop; 2480 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 2481 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 2482 if( zName==0 ){ 2483 goto exit_create_index; 2484 } 2485 } 2486 2487 /* Check for authorization to create an index. 2488 */ 2489 #ifndef SQLITE_OMIT_AUTHORIZATION 2490 { 2491 const char *zDb = pDb->zName; 2492 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 2493 goto exit_create_index; 2494 } 2495 i = SQLITE_CREATE_INDEX; 2496 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 2497 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 2498 goto exit_create_index; 2499 } 2500 } 2501 #endif 2502 2503 /* If pList==0, it means this routine was called to make a primary 2504 ** key out of the last column added to the table under construction. 2505 ** So create a fake list to simulate this. 2506 */ 2507 if( pList==0 ){ 2508 nullId.z = pTab->aCol[pTab->nCol-1].zName; 2509 nullId.n = sqlite3Strlen30((char*)nullId.z); 2510 pList = sqlite3ExprListAppend(pParse, 0, 0); 2511 if( pList==0 ) goto exit_create_index; 2512 sqlite3ExprListSetName(pParse, pList, &nullId, 0); 2513 pList->a[0].sortOrder = (u8)sortOrder; 2514 } 2515 2516 /* Figure out how many bytes of space are required to store explicitly 2517 ** specified collation sequence names. 2518 */ 2519 for(i=0; i<pList->nExpr; i++){ 2520 Expr *pExpr = pList->a[i].pExpr; 2521 if( pExpr ){ 2522 CollSeq *pColl = pExpr->pColl; 2523 /* Either pColl!=0 or there was an OOM failure. But if an OOM 2524 ** failure we have quit before reaching this point. */ 2525 if( ALWAYS(pColl) ){ 2526 nExtra += (1 + sqlite3Strlen30(pColl->zName)); 2527 } 2528 } 2529 } 2530 2531 /* 2532 ** Allocate the index structure. 2533 */ 2534 nName = sqlite3Strlen30(zName); 2535 nCol = pList->nExpr; 2536 pIndex = sqlite3DbMallocZero(db, 2537 sizeof(Index) + /* Index structure */ 2538 sizeof(int)*nCol + /* Index.aiColumn */ 2539 sizeof(int)*(nCol+1) + /* Index.aiRowEst */ 2540 sizeof(char *)*nCol + /* Index.azColl */ 2541 sizeof(u8)*nCol + /* Index.aSortOrder */ 2542 nName + 1 + /* Index.zName */ 2543 nExtra /* Collation sequence names */ 2544 ); 2545 if( db->mallocFailed ){ 2546 goto exit_create_index; 2547 } 2548 pIndex->azColl = (char**)(&pIndex[1]); 2549 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]); 2550 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]); 2551 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]); 2552 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]); 2553 zExtra = (char *)(&pIndex->zName[nName+1]); 2554 memcpy(pIndex->zName, zName, nName+1); 2555 pIndex->pTable = pTab; 2556 pIndex->nColumn = pList->nExpr; 2557 pIndex->onError = (u8)onError; 2558 pIndex->autoIndex = (u8)(pName==0); 2559 pIndex->pSchema = db->aDb[iDb].pSchema; 2560 2561 /* Check to see if we should honor DESC requests on index columns 2562 */ 2563 if( pDb->pSchema->file_format>=4 ){ 2564 sortOrderMask = -1; /* Honor DESC */ 2565 }else{ 2566 sortOrderMask = 0; /* Ignore DESC */ 2567 } 2568 2569 /* Scan the names of the columns of the table to be indexed and 2570 ** load the column indices into the Index structure. Report an error 2571 ** if any column is not found. 2572 ** 2573 ** TODO: Add a test to make sure that the same column is not named 2574 ** more than once within the same index. Only the first instance of 2575 ** the column will ever be used by the optimizer. Note that using the 2576 ** same column more than once cannot be an error because that would 2577 ** break backwards compatibility - it needs to be a warning. 2578 */ 2579 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 2580 const char *zColName = pListItem->zName; 2581 Column *pTabCol; 2582 int requestedSortOrder; 2583 char *zColl; /* Collation sequence name */ 2584 2585 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){ 2586 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break; 2587 } 2588 if( j>=pTab->nCol ){ 2589 sqlite3ErrorMsg(pParse, "table %s has no column named %s", 2590 pTab->zName, zColName); 2591 goto exit_create_index; 2592 } 2593 pIndex->aiColumn[i] = j; 2594 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of 2595 ** the way the "idxlist" non-terminal is constructed by the parser, 2596 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl 2597 ** must exist or else there must have been an OOM error. But if there 2598 ** was an OOM error, we would never reach this point. */ 2599 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){ 2600 int nColl; 2601 zColl = pListItem->pExpr->pColl->zName; 2602 nColl = sqlite3Strlen30(zColl) + 1; 2603 assert( nExtra>=nColl ); 2604 memcpy(zExtra, zColl, nColl); 2605 zColl = zExtra; 2606 zExtra += nColl; 2607 nExtra -= nColl; 2608 }else{ 2609 zColl = pTab->aCol[j].zColl; 2610 if( !zColl ){ 2611 zColl = db->pDfltColl->zName; 2612 } 2613 } 2614 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 2615 goto exit_create_index; 2616 } 2617 pIndex->azColl[i] = zColl; 2618 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 2619 pIndex->aSortOrder[i] = (u8)requestedSortOrder; 2620 } 2621 sqlite3DefaultRowEst(pIndex); 2622 2623 if( pTab==pParse->pNewTable ){ 2624 /* This routine has been called to create an automatic index as a 2625 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 2626 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 2627 ** i.e. one of: 2628 ** 2629 ** CREATE TABLE t(x PRIMARY KEY, y); 2630 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 2631 ** 2632 ** Either way, check to see if the table already has such an index. If 2633 ** so, don't bother creating this one. This only applies to 2634 ** automatically created indices. Users can do as they wish with 2635 ** explicit indices. 2636 ** 2637 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 2638 ** (and thus suppressing the second one) even if they have different 2639 ** sort orders. 2640 ** 2641 ** If there are different collating sequences or if the columns of 2642 ** the constraint occur in different orders, then the constraints are 2643 ** considered distinct and both result in separate indices. 2644 */ 2645 Index *pIdx; 2646 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2647 int k; 2648 assert( pIdx->onError!=OE_None ); 2649 assert( pIdx->autoIndex ); 2650 assert( pIndex->onError!=OE_None ); 2651 2652 if( pIdx->nColumn!=pIndex->nColumn ) continue; 2653 for(k=0; k<pIdx->nColumn; k++){ 2654 const char *z1; 2655 const char *z2; 2656 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 2657 z1 = pIdx->azColl[k]; 2658 z2 = pIndex->azColl[k]; 2659 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 2660 } 2661 if( k==pIdx->nColumn ){ 2662 if( pIdx->onError!=pIndex->onError ){ 2663 /* This constraint creates the same index as a previous 2664 ** constraint specified somewhere in the CREATE TABLE statement. 2665 ** However the ON CONFLICT clauses are different. If both this 2666 ** constraint and the previous equivalent constraint have explicit 2667 ** ON CONFLICT clauses this is an error. Otherwise, use the 2668 ** explicitly specified behaviour for the index. 2669 */ 2670 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 2671 sqlite3ErrorMsg(pParse, 2672 "conflicting ON CONFLICT clauses specified", 0); 2673 } 2674 if( pIdx->onError==OE_Default ){ 2675 pIdx->onError = pIndex->onError; 2676 } 2677 } 2678 goto exit_create_index; 2679 } 2680 } 2681 } 2682 2683 /* Link the new Index structure to its table and to the other 2684 ** in-memory database structures. 2685 */ 2686 if( db->init.busy ){ 2687 Index *p; 2688 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 2689 pIndex->zName, sqlite3Strlen30(pIndex->zName), 2690 pIndex); 2691 if( p ){ 2692 assert( p==pIndex ); /* Malloc must have failed */ 2693 db->mallocFailed = 1; 2694 goto exit_create_index; 2695 } 2696 db->flags |= SQLITE_InternChanges; 2697 if( pTblName!=0 ){ 2698 pIndex->tnum = db->init.newTnum; 2699 } 2700 } 2701 2702 /* If the db->init.busy is 0 then create the index on disk. This 2703 ** involves writing the index into the master table and filling in the 2704 ** index with the current table contents. 2705 ** 2706 ** The db->init.busy is 0 when the user first enters a CREATE INDEX 2707 ** command. db->init.busy is 1 when a database is opened and 2708 ** CREATE INDEX statements are read out of the master table. In 2709 ** the latter case the index already exists on disk, which is why 2710 ** we don't want to recreate it. 2711 ** 2712 ** If pTblName==0 it means this index is generated as a primary key 2713 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table 2714 ** has just been created, it contains no data and the index initialization 2715 ** step can be skipped. 2716 */ 2717 else{ /* if( db->init.busy==0 ) */ 2718 Vdbe *v; 2719 char *zStmt; 2720 int iMem = ++pParse->nMem; 2721 2722 v = sqlite3GetVdbe(pParse); 2723 if( v==0 ) goto exit_create_index; 2724 2725 2726 /* Create the rootpage for the index 2727 */ 2728 sqlite3BeginWriteOperation(pParse, 1, iDb); 2729 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 2730 2731 /* Gather the complete text of the CREATE INDEX statement into 2732 ** the zStmt variable 2733 */ 2734 if( pStart ){ 2735 assert( pEnd!=0 ); 2736 /* A named index with an explicit CREATE INDEX statement */ 2737 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 2738 onError==OE_None ? "" : " UNIQUE", 2739 pEnd->z - pName->z + 1, 2740 pName->z); 2741 }else{ 2742 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 2743 /* zStmt = sqlite3MPrintf(""); */ 2744 zStmt = 0; 2745 } 2746 2747 /* Add an entry in sqlite_master for this index 2748 */ 2749 sqlite3NestedParse(pParse, 2750 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 2751 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2752 pIndex->zName, 2753 pTab->zName, 2754 iMem, 2755 zStmt 2756 ); 2757 sqlite3DbFree(db, zStmt); 2758 2759 /* Fill the index with data and reparse the schema. Code an OP_Expire 2760 ** to invalidate all pre-compiled statements. 2761 */ 2762 if( pTblName ){ 2763 sqlite3RefillIndex(pParse, pIndex, iMem); 2764 sqlite3ChangeCookie(pParse, iDb); 2765 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, 2766 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC); 2767 sqlite3VdbeAddOp1(v, OP_Expire, 0); 2768 } 2769 } 2770 2771 /* When adding an index to the list of indices for a table, make 2772 ** sure all indices labeled OE_Replace come after all those labeled 2773 ** OE_Ignore. This is necessary for the correct constraint check 2774 ** processing (in sqlite3GenerateConstraintChecks()) as part of 2775 ** UPDATE and INSERT statements. 2776 */ 2777 if( db->init.busy || pTblName==0 ){ 2778 if( onError!=OE_Replace || pTab->pIndex==0 2779 || pTab->pIndex->onError==OE_Replace){ 2780 pIndex->pNext = pTab->pIndex; 2781 pTab->pIndex = pIndex; 2782 }else{ 2783 Index *pOther = pTab->pIndex; 2784 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 2785 pOther = pOther->pNext; 2786 } 2787 pIndex->pNext = pOther->pNext; 2788 pOther->pNext = pIndex; 2789 } 2790 pIndex = 0; 2791 } 2792 2793 /* Clean up before exiting */ 2794 exit_create_index: 2795 if( pIndex ){ 2796 sqlite3_free(pIndex->zColAff); 2797 sqlite3DbFree(db, pIndex); 2798 } 2799 sqlite3ExprListDelete(db, pList); 2800 sqlite3SrcListDelete(db, pTblName); 2801 sqlite3DbFree(db, zName); 2802 return; 2803 } 2804 2805 /* 2806 ** Fill the Index.aiRowEst[] array with default information - information 2807 ** to be used when we have not run the ANALYZE command. 2808 ** 2809 ** aiRowEst[0] is suppose to contain the number of elements in the index. 2810 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 2811 ** number of rows in the table that match any particular value of the 2812 ** first column of the index. aiRowEst[2] is an estimate of the number 2813 ** of rows that match any particular combiniation of the first 2 columns 2814 ** of the index. And so forth. It must always be the case that 2815 * 2816 ** aiRowEst[N]<=aiRowEst[N-1] 2817 ** aiRowEst[N]>=1 2818 ** 2819 ** Apart from that, we have little to go on besides intuition as to 2820 ** how aiRowEst[] should be initialized. The numbers generated here 2821 ** are based on typical values found in actual indices. 2822 */ 2823 void sqlite3DefaultRowEst(Index *pIdx){ 2824 unsigned *a = pIdx->aiRowEst; 2825 int i; 2826 assert( a!=0 ); 2827 a[0] = 1000000; 2828 for(i=pIdx->nColumn; i>=5; i--){ 2829 a[i] = 5; 2830 } 2831 while( i>=1 ){ 2832 a[i] = 11 - i; 2833 i--; 2834 } 2835 if( pIdx->onError!=OE_None ){ 2836 a[pIdx->nColumn] = 1; 2837 } 2838 } 2839 2840 /* 2841 ** This routine will drop an existing named index. This routine 2842 ** implements the DROP INDEX statement. 2843 */ 2844 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 2845 Index *pIndex; 2846 Vdbe *v; 2847 sqlite3 *db = pParse->db; 2848 int iDb; 2849 2850 assert( pParse->nErr==0 ); /* Never called with prior errors */ 2851 if( db->mallocFailed ){ 2852 goto exit_drop_index; 2853 } 2854 assert( pName->nSrc==1 ); 2855 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2856 goto exit_drop_index; 2857 } 2858 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 2859 if( pIndex==0 ){ 2860 if( !ifExists ){ 2861 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 2862 } 2863 pParse->checkSchema = 1; 2864 goto exit_drop_index; 2865 } 2866 if( pIndex->autoIndex ){ 2867 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 2868 "or PRIMARY KEY constraint cannot be dropped", 0); 2869 goto exit_drop_index; 2870 } 2871 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2872 #ifndef SQLITE_OMIT_AUTHORIZATION 2873 { 2874 int code = SQLITE_DROP_INDEX; 2875 Table *pTab = pIndex->pTable; 2876 const char *zDb = db->aDb[iDb].zName; 2877 const char *zTab = SCHEMA_TABLE(iDb); 2878 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 2879 goto exit_drop_index; 2880 } 2881 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 2882 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 2883 goto exit_drop_index; 2884 } 2885 } 2886 #endif 2887 2888 /* Generate code to remove the index and from the master table */ 2889 v = sqlite3GetVdbe(pParse); 2890 if( v ){ 2891 sqlite3BeginWriteOperation(pParse, 1, iDb); 2892 sqlite3NestedParse(pParse, 2893 "DELETE FROM %Q.%s WHERE name=%Q", 2894 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2895 pIndex->zName 2896 ); 2897 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ 2898 sqlite3NestedParse(pParse, 2899 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", 2900 db->aDb[iDb].zName, pIndex->zName 2901 ); 2902 } 2903 sqlite3ChangeCookie(pParse, iDb); 2904 destroyRootPage(pParse, pIndex->tnum, iDb); 2905 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 2906 } 2907 2908 exit_drop_index: 2909 sqlite3SrcListDelete(db, pName); 2910 } 2911 2912 /* 2913 ** pArray is a pointer to an array of objects. Each object in the 2914 ** array is szEntry bytes in size. This routine allocates a new 2915 ** object on the end of the array. 2916 ** 2917 ** *pnEntry is the number of entries already in use. *pnAlloc is 2918 ** the previously allocated size of the array. initSize is the 2919 ** suggested initial array size allocation. 2920 ** 2921 ** The index of the new entry is returned in *pIdx. 2922 ** 2923 ** This routine returns a pointer to the array of objects. This 2924 ** might be the same as the pArray parameter or it might be a different 2925 ** pointer if the array was resized. 2926 */ 2927 void *sqlite3ArrayAllocate( 2928 sqlite3 *db, /* Connection to notify of malloc failures */ 2929 void *pArray, /* Array of objects. Might be reallocated */ 2930 int szEntry, /* Size of each object in the array */ 2931 int initSize, /* Suggested initial allocation, in elements */ 2932 int *pnEntry, /* Number of objects currently in use */ 2933 int *pnAlloc, /* Current size of the allocation, in elements */ 2934 int *pIdx /* Write the index of a new slot here */ 2935 ){ 2936 char *z; 2937 if( *pnEntry >= *pnAlloc ){ 2938 void *pNew; 2939 int newSize; 2940 newSize = (*pnAlloc)*2 + initSize; 2941 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry); 2942 if( pNew==0 ){ 2943 *pIdx = -1; 2944 return pArray; 2945 } 2946 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry; 2947 pArray = pNew; 2948 } 2949 z = (char*)pArray; 2950 memset(&z[*pnEntry * szEntry], 0, szEntry); 2951 *pIdx = *pnEntry; 2952 ++*pnEntry; 2953 return pArray; 2954 } 2955 2956 /* 2957 ** Append a new element to the given IdList. Create a new IdList if 2958 ** need be. 2959 ** 2960 ** A new IdList is returned, or NULL if malloc() fails. 2961 */ 2962 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 2963 int i; 2964 if( pList==0 ){ 2965 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 2966 if( pList==0 ) return 0; 2967 pList->nAlloc = 0; 2968 } 2969 pList->a = sqlite3ArrayAllocate( 2970 db, 2971 pList->a, 2972 sizeof(pList->a[0]), 2973 5, 2974 &pList->nId, 2975 &pList->nAlloc, 2976 &i 2977 ); 2978 if( i<0 ){ 2979 sqlite3IdListDelete(db, pList); 2980 return 0; 2981 } 2982 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 2983 return pList; 2984 } 2985 2986 /* 2987 ** Delete an IdList. 2988 */ 2989 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 2990 int i; 2991 if( pList==0 ) return; 2992 for(i=0; i<pList->nId; i++){ 2993 sqlite3DbFree(db, pList->a[i].zName); 2994 } 2995 sqlite3DbFree(db, pList->a); 2996 sqlite3DbFree(db, pList); 2997 } 2998 2999 /* 3000 ** Return the index in pList of the identifier named zId. Return -1 3001 ** if not found. 3002 */ 3003 int sqlite3IdListIndex(IdList *pList, const char *zName){ 3004 int i; 3005 if( pList==0 ) return -1; 3006 for(i=0; i<pList->nId; i++){ 3007 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 3008 } 3009 return -1; 3010 } 3011 3012 /* 3013 ** Expand the space allocated for the given SrcList object by 3014 ** creating nExtra new slots beginning at iStart. iStart is zero based. 3015 ** New slots are zeroed. 3016 ** 3017 ** For example, suppose a SrcList initially contains two entries: A,B. 3018 ** To append 3 new entries onto the end, do this: 3019 ** 3020 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 3021 ** 3022 ** After the call above it would contain: A, B, nil, nil, nil. 3023 ** If the iStart argument had been 1 instead of 2, then the result 3024 ** would have been: A, nil, nil, nil, B. To prepend the new slots, 3025 ** the iStart value would be 0. The result then would 3026 ** be: nil, nil, nil, A, B. 3027 ** 3028 ** If a memory allocation fails the SrcList is unchanged. The 3029 ** db->mallocFailed flag will be set to true. 3030 */ 3031 SrcList *sqlite3SrcListEnlarge( 3032 sqlite3 *db, /* Database connection to notify of OOM errors */ 3033 SrcList *pSrc, /* The SrcList to be enlarged */ 3034 int nExtra, /* Number of new slots to add to pSrc->a[] */ 3035 int iStart /* Index in pSrc->a[] of first new slot */ 3036 ){ 3037 int i; 3038 3039 /* Sanity checking on calling parameters */ 3040 assert( iStart>=0 ); 3041 assert( nExtra>=1 ); 3042 assert( pSrc!=0 ); 3043 assert( iStart<=pSrc->nSrc ); 3044 3045 /* Allocate additional space if needed */ 3046 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){ 3047 SrcList *pNew; 3048 int nAlloc = pSrc->nSrc+nExtra; 3049 int nGot; 3050 pNew = sqlite3DbRealloc(db, pSrc, 3051 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 3052 if( pNew==0 ){ 3053 assert( db->mallocFailed ); 3054 return pSrc; 3055 } 3056 pSrc = pNew; 3057 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; 3058 pSrc->nAlloc = (u16)nGot; 3059 } 3060 3061 /* Move existing slots that come after the newly inserted slots 3062 ** out of the way */ 3063 for(i=pSrc->nSrc-1; i>=iStart; i--){ 3064 pSrc->a[i+nExtra] = pSrc->a[i]; 3065 } 3066 pSrc->nSrc += (i16)nExtra; 3067 3068 /* Zero the newly allocated slots */ 3069 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 3070 for(i=iStart; i<iStart+nExtra; i++){ 3071 pSrc->a[i].iCursor = -1; 3072 } 3073 3074 /* Return a pointer to the enlarged SrcList */ 3075 return pSrc; 3076 } 3077 3078 3079 /* 3080 ** Append a new table name to the given SrcList. Create a new SrcList if 3081 ** need be. A new entry is created in the SrcList even if pTable is NULL. 3082 ** 3083 ** A SrcList is returned, or NULL if there is an OOM error. The returned 3084 ** SrcList might be the same as the SrcList that was input or it might be 3085 ** a new one. If an OOM error does occurs, then the prior value of pList 3086 ** that is input to this routine is automatically freed. 3087 ** 3088 ** If pDatabase is not null, it means that the table has an optional 3089 ** database name prefix. Like this: "database.table". The pDatabase 3090 ** points to the table name and the pTable points to the database name. 3091 ** The SrcList.a[].zName field is filled with the table name which might 3092 ** come from pTable (if pDatabase is NULL) or from pDatabase. 3093 ** SrcList.a[].zDatabase is filled with the database name from pTable, 3094 ** or with NULL if no database is specified. 3095 ** 3096 ** In other words, if call like this: 3097 ** 3098 ** sqlite3SrcListAppend(D,A,B,0); 3099 ** 3100 ** Then B is a table name and the database name is unspecified. If called 3101 ** like this: 3102 ** 3103 ** sqlite3SrcListAppend(D,A,B,C); 3104 ** 3105 ** Then C is the table name and B is the database name. If C is defined 3106 ** then so is B. In other words, we never have a case where: 3107 ** 3108 ** sqlite3SrcListAppend(D,A,0,C); 3109 ** 3110 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 3111 ** before being added to the SrcList. 3112 */ 3113 SrcList *sqlite3SrcListAppend( 3114 sqlite3 *db, /* Connection to notify of malloc failures */ 3115 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 3116 Token *pTable, /* Table to append */ 3117 Token *pDatabase /* Database of the table */ 3118 ){ 3119 struct SrcList_item *pItem; 3120 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 3121 if( pList==0 ){ 3122 pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); 3123 if( pList==0 ) return 0; 3124 pList->nAlloc = 1; 3125 } 3126 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); 3127 if( db->mallocFailed ){ 3128 sqlite3SrcListDelete(db, pList); 3129 return 0; 3130 } 3131 pItem = &pList->a[pList->nSrc-1]; 3132 if( pDatabase && pDatabase->z==0 ){ 3133 pDatabase = 0; 3134 } 3135 if( pDatabase ){ 3136 Token *pTemp = pDatabase; 3137 pDatabase = pTable; 3138 pTable = pTemp; 3139 } 3140 pItem->zName = sqlite3NameFromToken(db, pTable); 3141 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 3142 return pList; 3143 } 3144 3145 /* 3146 ** Assign VdbeCursor index numbers to all tables in a SrcList 3147 */ 3148 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 3149 int i; 3150 struct SrcList_item *pItem; 3151 assert(pList || pParse->db->mallocFailed ); 3152 if( pList ){ 3153 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 3154 if( pItem->iCursor>=0 ) break; 3155 pItem->iCursor = pParse->nTab++; 3156 if( pItem->pSelect ){ 3157 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 3158 } 3159 } 3160 } 3161 } 3162 3163 /* 3164 ** Delete an entire SrcList including all its substructure. 3165 */ 3166 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 3167 int i; 3168 struct SrcList_item *pItem; 3169 if( pList==0 ) return; 3170 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 3171 sqlite3DbFree(db, pItem->zDatabase); 3172 sqlite3DbFree(db, pItem->zName); 3173 sqlite3DbFree(db, pItem->zAlias); 3174 sqlite3DbFree(db, pItem->zIndex); 3175 sqlite3DeleteTable(pItem->pTab); 3176 sqlite3SelectDelete(db, pItem->pSelect); 3177 sqlite3ExprDelete(db, pItem->pOn); 3178 sqlite3IdListDelete(db, pItem->pUsing); 3179 } 3180 sqlite3DbFree(db, pList); 3181 } 3182 3183 /* 3184 ** This routine is called by the parser to add a new term to the 3185 ** end of a growing FROM clause. The "p" parameter is the part of 3186 ** the FROM clause that has already been constructed. "p" is NULL 3187 ** if this is the first term of the FROM clause. pTable and pDatabase 3188 ** are the name of the table and database named in the FROM clause term. 3189 ** pDatabase is NULL if the database name qualifier is missing - the 3190 ** usual case. If the term has a alias, then pAlias points to the 3191 ** alias token. If the term is a subquery, then pSubquery is the 3192 ** SELECT statement that the subquery encodes. The pTable and 3193 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 3194 ** parameters are the content of the ON and USING clauses. 3195 ** 3196 ** Return a new SrcList which encodes is the FROM with the new 3197 ** term added. 3198 */ 3199 SrcList *sqlite3SrcListAppendFromTerm( 3200 Parse *pParse, /* Parsing context */ 3201 SrcList *p, /* The left part of the FROM clause already seen */ 3202 Token *pTable, /* Name of the table to add to the FROM clause */ 3203 Token *pDatabase, /* Name of the database containing pTable */ 3204 Token *pAlias, /* The right-hand side of the AS subexpression */ 3205 Select *pSubquery, /* A subquery used in place of a table name */ 3206 Expr *pOn, /* The ON clause of a join */ 3207 IdList *pUsing /* The USING clause of a join */ 3208 ){ 3209 struct SrcList_item *pItem; 3210 sqlite3 *db = pParse->db; 3211 if( !p && (pOn || pUsing) ){ 3212 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 3213 (pOn ? "ON" : "USING") 3214 ); 3215 goto append_from_error; 3216 } 3217 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 3218 if( p==0 || NEVER(p->nSrc==0) ){ 3219 goto append_from_error; 3220 } 3221 pItem = &p->a[p->nSrc-1]; 3222 assert( pAlias!=0 ); 3223 if( pAlias->n ){ 3224 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 3225 } 3226 pItem->pSelect = pSubquery; 3227 pItem->pOn = pOn; 3228 pItem->pUsing = pUsing; 3229 return p; 3230 3231 append_from_error: 3232 assert( p==0 ); 3233 sqlite3ExprDelete(db, pOn); 3234 sqlite3IdListDelete(db, pUsing); 3235 sqlite3SelectDelete(db, pSubquery); 3236 return 0; 3237 } 3238 3239 /* 3240 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 3241 ** element of the source-list passed as the second argument. 3242 */ 3243 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 3244 assert( pIndexedBy!=0 ); 3245 if( p && ALWAYS(p->nSrc>0) ){ 3246 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 3247 assert( pItem->notIndexed==0 && pItem->zIndex==0 ); 3248 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 3249 /* A "NOT INDEXED" clause was supplied. See parse.y 3250 ** construct "indexed_opt" for details. */ 3251 pItem->notIndexed = 1; 3252 }else{ 3253 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy); 3254 } 3255 } 3256 } 3257 3258 /* 3259 ** When building up a FROM clause in the parser, the join operator 3260 ** is initially attached to the left operand. But the code generator 3261 ** expects the join operator to be on the right operand. This routine 3262 ** Shifts all join operators from left to right for an entire FROM 3263 ** clause. 3264 ** 3265 ** Example: Suppose the join is like this: 3266 ** 3267 ** A natural cross join B 3268 ** 3269 ** The operator is "natural cross join". The A and B operands are stored 3270 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 3271 ** operator with A. This routine shifts that operator over to B. 3272 */ 3273 void sqlite3SrcListShiftJoinType(SrcList *p){ 3274 if( p && p->a ){ 3275 int i; 3276 for(i=p->nSrc-1; i>0; i--){ 3277 p->a[i].jointype = p->a[i-1].jointype; 3278 } 3279 p->a[0].jointype = 0; 3280 } 3281 } 3282 3283 /* 3284 ** Begin a transaction 3285 */ 3286 void sqlite3BeginTransaction(Parse *pParse, int type){ 3287 sqlite3 *db; 3288 Vdbe *v; 3289 int i; 3290 3291 assert( pParse!=0 ); 3292 db = pParse->db; 3293 assert( db!=0 ); 3294 /* if( db->aDb[0].pBt==0 ) return; */ 3295 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 3296 return; 3297 } 3298 v = sqlite3GetVdbe(pParse); 3299 if( !v ) return; 3300 if( type!=TK_DEFERRED ){ 3301 for(i=0; i<db->nDb; i++){ 3302 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 3303 sqlite3VdbeUsesBtree(v, i); 3304 } 3305 } 3306 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 3307 } 3308 3309 /* 3310 ** Commit a transaction 3311 */ 3312 void sqlite3CommitTransaction(Parse *pParse){ 3313 sqlite3 *db; 3314 Vdbe *v; 3315 3316 assert( pParse!=0 ); 3317 db = pParse->db; 3318 assert( db!=0 ); 3319 /* if( db->aDb[0].pBt==0 ) return; */ 3320 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ 3321 return; 3322 } 3323 v = sqlite3GetVdbe(pParse); 3324 if( v ){ 3325 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 3326 } 3327 } 3328 3329 /* 3330 ** Rollback a transaction 3331 */ 3332 void sqlite3RollbackTransaction(Parse *pParse){ 3333 sqlite3 *db; 3334 Vdbe *v; 3335 3336 assert( pParse!=0 ); 3337 db = pParse->db; 3338 assert( db!=0 ); 3339 /* if( db->aDb[0].pBt==0 ) return; */ 3340 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ 3341 return; 3342 } 3343 v = sqlite3GetVdbe(pParse); 3344 if( v ){ 3345 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 3346 } 3347 } 3348 3349 /* 3350 ** This function is called by the parser when it parses a command to create, 3351 ** release or rollback an SQL savepoint. 3352 */ 3353 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 3354 char *zName = sqlite3NameFromToken(pParse->db, pName); 3355 if( zName ){ 3356 Vdbe *v = sqlite3GetVdbe(pParse); 3357 #ifndef SQLITE_OMIT_AUTHORIZATION 3358 static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 3359 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 3360 #endif 3361 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 3362 sqlite3DbFree(pParse->db, zName); 3363 return; 3364 } 3365 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 3366 } 3367 } 3368 3369 /* 3370 ** Make sure the TEMP database is open and available for use. Return 3371 ** the number of errors. Leave any error messages in the pParse structure. 3372 */ 3373 int sqlite3OpenTempDatabase(Parse *pParse){ 3374 sqlite3 *db = pParse->db; 3375 if( db->aDb[1].pBt==0 && !pParse->explain ){ 3376 int rc; 3377 static const int flags = 3378 SQLITE_OPEN_READWRITE | 3379 SQLITE_OPEN_CREATE | 3380 SQLITE_OPEN_EXCLUSIVE | 3381 SQLITE_OPEN_DELETEONCLOSE | 3382 SQLITE_OPEN_TEMP_DB; 3383 3384 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, 3385 &db->aDb[1].pBt); 3386 if( rc!=SQLITE_OK ){ 3387 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 3388 "file for storing temporary tables"); 3389 pParse->rc = rc; 3390 return 1; 3391 } 3392 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit ); 3393 assert( db->aDb[1].pSchema ); 3394 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt), 3395 db->dfltJournalMode); 3396 } 3397 return 0; 3398 } 3399 3400 /* 3401 ** Generate VDBE code that will verify the schema cookie and start 3402 ** a read-transaction for all named database files. 3403 ** 3404 ** It is important that all schema cookies be verified and all 3405 ** read transactions be started before anything else happens in 3406 ** the VDBE program. But this routine can be called after much other 3407 ** code has been generated. So here is what we do: 3408 ** 3409 ** The first time this routine is called, we code an OP_Goto that 3410 ** will jump to a subroutine at the end of the program. Then we 3411 ** record every database that needs its schema verified in the 3412 ** pParse->cookieMask field. Later, after all other code has been 3413 ** generated, the subroutine that does the cookie verifications and 3414 ** starts the transactions will be coded and the OP_Goto P2 value 3415 ** will be made to point to that subroutine. The generation of the 3416 ** cookie verification subroutine code happens in sqlite3FinishCoding(). 3417 ** 3418 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the 3419 ** schema on any databases. This can be used to position the OP_Goto 3420 ** early in the code, before we know if any database tables will be used. 3421 */ 3422 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 3423 sqlite3 *db; 3424 Vdbe *v; 3425 int mask; 3426 3427 v = sqlite3GetVdbe(pParse); 3428 if( v==0 ) return; /* This only happens if there was a prior error */ 3429 db = pParse->db; 3430 if( pParse->cookieGoto==0 ){ 3431 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; 3432 } 3433 if( iDb>=0 ){ 3434 assert( iDb<db->nDb ); 3435 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 3436 assert( iDb<SQLITE_MAX_ATTACHED+2 ); 3437 mask = 1<<iDb; 3438 if( (pParse->cookieMask & mask)==0 ){ 3439 pParse->cookieMask |= mask; 3440 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; 3441 if( !OMIT_TEMPDB && iDb==1 ){ 3442 sqlite3OpenTempDatabase(pParse); 3443 } 3444 } 3445 } 3446 } 3447 3448 /* 3449 ** Generate VDBE code that prepares for doing an operation that 3450 ** might change the database. 3451 ** 3452 ** This routine starts a new transaction if we are not already within 3453 ** a transaction. If we are already within a transaction, then a checkpoint 3454 ** is set if the setStatement parameter is true. A checkpoint should 3455 ** be set for operations that might fail (due to a constraint) part of 3456 ** the way through and which will need to undo some writes without having to 3457 ** rollback the whole transaction. For operations where all constraints 3458 ** can be checked before any changes are made to the database, it is never 3459 ** necessary to undo a write and the checkpoint should not be set. 3460 */ 3461 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 3462 sqlite3CodeVerifySchema(pParse, iDb); 3463 pParse->writeMask |= 1<<iDb; 3464 if( setStatement && pParse->nested==0 ){ 3465 /* Every place where this routine is called with setStatement!=0 has 3466 ** already successfully created a VDBE. */ 3467 assert( pParse->pVdbe ); 3468 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Statement, iDb); 3469 } 3470 } 3471 3472 /* 3473 ** Check to see if pIndex uses the collating sequence pColl. Return 3474 ** true if it does and false if it does not. 3475 */ 3476 #ifndef SQLITE_OMIT_REINDEX 3477 static int collationMatch(const char *zColl, Index *pIndex){ 3478 int i; 3479 assert( zColl!=0 ); 3480 for(i=0; i<pIndex->nColumn; i++){ 3481 const char *z = pIndex->azColl[i]; 3482 assert( z!=0 ); 3483 if( 0==sqlite3StrICmp(z, zColl) ){ 3484 return 1; 3485 } 3486 } 3487 return 0; 3488 } 3489 #endif 3490 3491 /* 3492 ** Recompute all indices of pTab that use the collating sequence pColl. 3493 ** If pColl==0 then recompute all indices of pTab. 3494 */ 3495 #ifndef SQLITE_OMIT_REINDEX 3496 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 3497 Index *pIndex; /* An index associated with pTab */ 3498 3499 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 3500 if( zColl==0 || collationMatch(zColl, pIndex) ){ 3501 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 3502 sqlite3BeginWriteOperation(pParse, 0, iDb); 3503 sqlite3RefillIndex(pParse, pIndex, -1); 3504 } 3505 } 3506 } 3507 #endif 3508 3509 /* 3510 ** Recompute all indices of all tables in all databases where the 3511 ** indices use the collating sequence pColl. If pColl==0 then recompute 3512 ** all indices everywhere. 3513 */ 3514 #ifndef SQLITE_OMIT_REINDEX 3515 static void reindexDatabases(Parse *pParse, char const *zColl){ 3516 Db *pDb; /* A single database */ 3517 int iDb; /* The database index number */ 3518 sqlite3 *db = pParse->db; /* The database connection */ 3519 HashElem *k; /* For looping over tables in pDb */ 3520 Table *pTab; /* A table in the database */ 3521 3522 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 3523 assert( pDb!=0 ); 3524 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 3525 pTab = (Table*)sqliteHashData(k); 3526 reindexTable(pParse, pTab, zColl); 3527 } 3528 } 3529 } 3530 #endif 3531 3532 /* 3533 ** Generate code for the REINDEX command. 3534 ** 3535 ** REINDEX -- 1 3536 ** REINDEX <collation> -- 2 3537 ** REINDEX ?<database>.?<tablename> -- 3 3538 ** REINDEX ?<database>.?<indexname> -- 4 3539 ** 3540 ** Form 1 causes all indices in all attached databases to be rebuilt. 3541 ** Form 2 rebuilds all indices in all databases that use the named 3542 ** collating function. Forms 3 and 4 rebuild the named index or all 3543 ** indices associated with the named table. 3544 */ 3545 #ifndef SQLITE_OMIT_REINDEX 3546 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 3547 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 3548 char *z; /* Name of a table or index */ 3549 const char *zDb; /* Name of the database */ 3550 Table *pTab; /* A table in the database */ 3551 Index *pIndex; /* An index associated with pTab */ 3552 int iDb; /* The database index number */ 3553 sqlite3 *db = pParse->db; /* The database connection */ 3554 Token *pObjName; /* Name of the table or index to be reindexed */ 3555 3556 /* Read the database schema. If an error occurs, leave an error message 3557 ** and code in pParse and return NULL. */ 3558 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3559 return; 3560 } 3561 3562 if( pName1==0 ){ 3563 reindexDatabases(pParse, 0); 3564 return; 3565 }else if( NEVER(pName2==0) || pName2->z==0 ){ 3566 char *zColl; 3567 assert( pName1->z ); 3568 zColl = sqlite3NameFromToken(pParse->db, pName1); 3569 if( !zColl ) return; 3570 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 3571 if( pColl ){ 3572 reindexDatabases(pParse, zColl); 3573 sqlite3DbFree(db, zColl); 3574 return; 3575 } 3576 sqlite3DbFree(db, zColl); 3577 } 3578 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 3579 if( iDb<0 ) return; 3580 z = sqlite3NameFromToken(db, pObjName); 3581 if( z==0 ) return; 3582 zDb = db->aDb[iDb].zName; 3583 pTab = sqlite3FindTable(db, z, zDb); 3584 if( pTab ){ 3585 reindexTable(pParse, pTab, 0); 3586 sqlite3DbFree(db, z); 3587 return; 3588 } 3589 pIndex = sqlite3FindIndex(db, z, zDb); 3590 sqlite3DbFree(db, z); 3591 if( pIndex ){ 3592 sqlite3BeginWriteOperation(pParse, 0, iDb); 3593 sqlite3RefillIndex(pParse, pIndex, -1); 3594 return; 3595 } 3596 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 3597 } 3598 #endif 3599 3600 /* 3601 ** Return a dynamicly allocated KeyInfo structure that can be used 3602 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx. 3603 ** 3604 ** If successful, a pointer to the new structure is returned. In this case 3605 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 3606 ** pointer. If an error occurs (out of memory or missing collation 3607 ** sequence), NULL is returned and the state of pParse updated to reflect 3608 ** the error. 3609 */ 3610 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ 3611 int i; 3612 int nCol = pIdx->nColumn; 3613 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol; 3614 sqlite3 *db = pParse->db; 3615 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes); 3616 3617 if( pKey ){ 3618 pKey->db = pParse->db; 3619 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]); 3620 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) ); 3621 for(i=0; i<nCol; i++){ 3622 char *zColl = pIdx->azColl[i]; 3623 assert( zColl ); 3624 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl); 3625 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 3626 } 3627 pKey->nField = (u16)nCol; 3628 } 3629 3630 if( pParse->nErr ){ 3631 sqlite3DbFree(db, pKey); 3632 pKey = 0; 3633 } 3634 return pKey; 3635 } 3636