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