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