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