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