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 ** Backwards Compatibility Hack: 1276 ** 1277 ** Historical versions of SQLite accepted strings as column names in 1278 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: 1279 ** 1280 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) 1281 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); 1282 ** 1283 ** This is goofy. But to preserve backwards compatibility we continue to 1284 ** accept it. This routine does the necessary conversion. It converts 1285 ** the expression given in its argument from a TK_STRING into a TK_ID 1286 ** if the expression is just a TK_STRING with an optional COLLATE clause. 1287 ** If the epxression is anything other than TK_STRING, the expression is 1288 ** unchanged. 1289 */ 1290 static void sqlite3StringToId(Expr *p){ 1291 if( p->op==TK_STRING ){ 1292 p->op = TK_ID; 1293 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ 1294 p->pLeft->op = TK_ID; 1295 } 1296 } 1297 1298 /* 1299 ** Designate the PRIMARY KEY for the table. pList is a list of names 1300 ** of columns that form the primary key. If pList is NULL, then the 1301 ** most recently added column of the table is the primary key. 1302 ** 1303 ** A table can have at most one primary key. If the table already has 1304 ** a primary key (and this is the second primary key) then create an 1305 ** error. 1306 ** 1307 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, 1308 ** then we will try to use that column as the rowid. Set the Table.iPKey 1309 ** field of the table under construction to be the index of the 1310 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is 1311 ** no INTEGER PRIMARY KEY. 1312 ** 1313 ** If the key is not an INTEGER PRIMARY KEY, then create a unique 1314 ** index for the key. No index is created for INTEGER PRIMARY KEYs. 1315 */ 1316 void sqlite3AddPrimaryKey( 1317 Parse *pParse, /* Parsing context */ 1318 ExprList *pList, /* List of field names to be indexed */ 1319 int onError, /* What to do with a uniqueness conflict */ 1320 int autoInc, /* True if the AUTOINCREMENT keyword is present */ 1321 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 1322 ){ 1323 Table *pTab = pParse->pNewTable; 1324 char *zType = 0; 1325 int iCol = -1, i; 1326 int nTerm; 1327 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit; 1328 if( pTab->tabFlags & TF_HasPrimaryKey ){ 1329 sqlite3ErrorMsg(pParse, 1330 "table \"%s\" has more than one primary key", pTab->zName); 1331 goto primary_key_exit; 1332 } 1333 pTab->tabFlags |= TF_HasPrimaryKey; 1334 if( pList==0 ){ 1335 iCol = pTab->nCol - 1; 1336 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; 1337 zType = pTab->aCol[iCol].zType; 1338 nTerm = 1; 1339 }else{ 1340 nTerm = pList->nExpr; 1341 for(i=0; i<nTerm; i++){ 1342 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); 1343 assert( pCExpr!=0 ); 1344 sqlite3StringToId(pCExpr); 1345 if( pCExpr->op==TK_ID ){ 1346 const char *zCName = pCExpr->u.zToken; 1347 for(iCol=0; iCol<pTab->nCol; iCol++){ 1348 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ 1349 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY; 1350 zType = pTab->aCol[iCol].zType; 1351 break; 1352 } 1353 } 1354 } 1355 } 1356 } 1357 if( nTerm==1 1358 && zType && sqlite3StrICmp(zType, "INTEGER")==0 1359 && sortOrder!=SQLITE_SO_DESC 1360 ){ 1361 pTab->iPKey = iCol; 1362 pTab->keyConf = (u8)onError; 1363 assert( autoInc==0 || autoInc==1 ); 1364 pTab->tabFlags |= autoInc*TF_Autoincrement; 1365 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; 1366 }else if( autoInc ){ 1367 #ifndef SQLITE_OMIT_AUTOINCREMENT 1368 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1369 "INTEGER PRIMARY KEY"); 1370 #endif 1371 }else{ 1372 Index *p; 1373 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 1374 0, sortOrder, 0); 1375 if( p ){ 1376 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY; 1377 } 1378 pList = 0; 1379 } 1380 1381 primary_key_exit: 1382 sqlite3ExprListDelete(pParse->db, pList); 1383 return; 1384 } 1385 1386 /* 1387 ** Add a new CHECK constraint to the table currently under construction. 1388 */ 1389 void sqlite3AddCheckConstraint( 1390 Parse *pParse, /* Parsing context */ 1391 Expr *pCheckExpr /* The check expression */ 1392 ){ 1393 #ifndef SQLITE_OMIT_CHECK 1394 Table *pTab = pParse->pNewTable; 1395 sqlite3 *db = pParse->db; 1396 if( pTab && !IN_DECLARE_VTAB 1397 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 1398 ){ 1399 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 1400 if( pParse->constraintName.n ){ 1401 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 1402 } 1403 }else 1404 #endif 1405 { 1406 sqlite3ExprDelete(pParse->db, pCheckExpr); 1407 } 1408 } 1409 1410 /* 1411 ** Set the collation function of the most recently parsed table column 1412 ** to the CollSeq given. 1413 */ 1414 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 1415 Table *p; 1416 int i; 1417 char *zColl; /* Dequoted name of collation sequence */ 1418 sqlite3 *db; 1419 1420 if( (p = pParse->pNewTable)==0 ) return; 1421 i = p->nCol-1; 1422 db = pParse->db; 1423 zColl = sqlite3NameFromToken(db, pToken); 1424 if( !zColl ) return; 1425 1426 if( sqlite3LocateCollSeq(pParse, zColl) ){ 1427 Index *pIdx; 1428 sqlite3DbFree(db, p->aCol[i].zColl); 1429 p->aCol[i].zColl = zColl; 1430 1431 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1432 ** then an index may have been created on this column before the 1433 ** collation type was added. Correct this if it is the case. 1434 */ 1435 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1436 assert( pIdx->nKeyCol==1 ); 1437 if( pIdx->aiColumn[0]==i ){ 1438 pIdx->azColl[0] = p->aCol[i].zColl; 1439 } 1440 } 1441 }else{ 1442 sqlite3DbFree(db, zColl); 1443 } 1444 } 1445 1446 /* 1447 ** This function returns the collation sequence for database native text 1448 ** encoding identified by the string zName, length nName. 1449 ** 1450 ** If the requested collation sequence is not available, or not available 1451 ** in the database native encoding, the collation factory is invoked to 1452 ** request it. If the collation factory does not supply such a sequence, 1453 ** and the sequence is available in another text encoding, then that is 1454 ** returned instead. 1455 ** 1456 ** If no versions of the requested collations sequence are available, or 1457 ** another error occurs, NULL is returned and an error message written into 1458 ** pParse. 1459 ** 1460 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine 1461 ** invokes the collation factory if the named collation cannot be found 1462 ** and generates an error message. 1463 ** 1464 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() 1465 */ 1466 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ 1467 sqlite3 *db = pParse->db; 1468 u8 enc = ENC(db); 1469 u8 initbusy = db->init.busy; 1470 CollSeq *pColl; 1471 1472 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); 1473 if( !initbusy && (!pColl || !pColl->xCmp) ){ 1474 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); 1475 } 1476 1477 return pColl; 1478 } 1479 1480 1481 /* 1482 ** Generate code that will increment the schema cookie. 1483 ** 1484 ** The schema cookie is used to determine when the schema for the 1485 ** database changes. After each schema change, the cookie value 1486 ** changes. When a process first reads the schema it records the 1487 ** cookie. Thereafter, whenever it goes to access the database, 1488 ** it checks the cookie to make sure the schema has not changed 1489 ** since it was last read. 1490 ** 1491 ** This plan is not completely bullet-proof. It is possible for 1492 ** the schema to change multiple times and for the cookie to be 1493 ** set back to prior value. But schema changes are infrequent 1494 ** and the probability of hitting the same cookie value is only 1495 ** 1 chance in 2^32. So we're safe enough. 1496 */ 1497 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 1498 int r1 = sqlite3GetTempReg(pParse); 1499 sqlite3 *db = pParse->db; 1500 Vdbe *v = pParse->pVdbe; 1501 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 1502 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); 1503 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1); 1504 sqlite3ReleaseTempReg(pParse, r1); 1505 } 1506 1507 /* 1508 ** Measure the number of characters needed to output the given 1509 ** identifier. The number returned includes any quotes used 1510 ** but does not include the null terminator. 1511 ** 1512 ** The estimate is conservative. It might be larger that what is 1513 ** really needed. 1514 */ 1515 static int identLength(const char *z){ 1516 int n; 1517 for(n=0; *z; n++, z++){ 1518 if( *z=='"' ){ n++; } 1519 } 1520 return n + 2; 1521 } 1522 1523 /* 1524 ** The first parameter is a pointer to an output buffer. The second 1525 ** parameter is a pointer to an integer that contains the offset at 1526 ** which to write into the output buffer. This function copies the 1527 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 1528 ** to the specified offset in the buffer and updates *pIdx to refer 1529 ** to the first byte after the last byte written before returning. 1530 ** 1531 ** If the string zSignedIdent consists entirely of alpha-numeric 1532 ** characters, does not begin with a digit and is not an SQL keyword, 1533 ** then it is copied to the output buffer exactly as it is. Otherwise, 1534 ** it is quoted using double-quotes. 1535 */ 1536 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 1537 unsigned char *zIdent = (unsigned char*)zSignedIdent; 1538 int i, j, needQuote; 1539 i = *pIdx; 1540 1541 for(j=0; zIdent[j]; j++){ 1542 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 1543 } 1544 needQuote = sqlite3Isdigit(zIdent[0]) 1545 || sqlite3KeywordCode(zIdent, j)!=TK_ID 1546 || zIdent[j]!=0 1547 || j==0; 1548 1549 if( needQuote ) z[i++] = '"'; 1550 for(j=0; zIdent[j]; j++){ 1551 z[i++] = zIdent[j]; 1552 if( zIdent[j]=='"' ) z[i++] = '"'; 1553 } 1554 if( needQuote ) z[i++] = '"'; 1555 z[i] = 0; 1556 *pIdx = i; 1557 } 1558 1559 /* 1560 ** Generate a CREATE TABLE statement appropriate for the given 1561 ** table. Memory to hold the text of the statement is obtained 1562 ** from sqliteMalloc() and must be freed by the calling function. 1563 */ 1564 static char *createTableStmt(sqlite3 *db, Table *p){ 1565 int i, k, n; 1566 char *zStmt; 1567 char *zSep, *zSep2, *zEnd; 1568 Column *pCol; 1569 n = 0; 1570 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 1571 n += identLength(pCol->zName) + 5; 1572 } 1573 n += identLength(p->zName); 1574 if( n<50 ){ 1575 zSep = ""; 1576 zSep2 = ","; 1577 zEnd = ")"; 1578 }else{ 1579 zSep = "\n "; 1580 zSep2 = ",\n "; 1581 zEnd = "\n)"; 1582 } 1583 n += 35 + 6*p->nCol; 1584 zStmt = sqlite3DbMallocRaw(0, n); 1585 if( zStmt==0 ){ 1586 db->mallocFailed = 1; 1587 return 0; 1588 } 1589 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 1590 k = sqlite3Strlen30(zStmt); 1591 identPut(zStmt, &k, p->zName); 1592 zStmt[k++] = '('; 1593 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 1594 static const char * const azType[] = { 1595 /* SQLITE_AFF_BLOB */ "", 1596 /* SQLITE_AFF_TEXT */ " TEXT", 1597 /* SQLITE_AFF_NUMERIC */ " NUM", 1598 /* SQLITE_AFF_INTEGER */ " INT", 1599 /* SQLITE_AFF_REAL */ " REAL" 1600 }; 1601 int len; 1602 const char *zType; 1603 1604 sqlite3_snprintf(n-k, &zStmt[k], zSep); 1605 k += sqlite3Strlen30(&zStmt[k]); 1606 zSep = zSep2; 1607 identPut(zStmt, &k, pCol->zName); 1608 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 1609 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 1610 testcase( pCol->affinity==SQLITE_AFF_BLOB ); 1611 testcase( pCol->affinity==SQLITE_AFF_TEXT ); 1612 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 1613 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 1614 testcase( pCol->affinity==SQLITE_AFF_REAL ); 1615 1616 zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 1617 len = sqlite3Strlen30(zType); 1618 assert( pCol->affinity==SQLITE_AFF_BLOB 1619 || pCol->affinity==sqlite3AffinityType(zType, 0) ); 1620 memcpy(&zStmt[k], zType, len); 1621 k += len; 1622 assert( k<=n ); 1623 } 1624 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 1625 return zStmt; 1626 } 1627 1628 /* 1629 ** Resize an Index object to hold N columns total. Return SQLITE_OK 1630 ** on success and SQLITE_NOMEM on an OOM error. 1631 */ 1632 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 1633 char *zExtra; 1634 int nByte; 1635 if( pIdx->nColumn>=N ) return SQLITE_OK; 1636 assert( pIdx->isResized==0 ); 1637 nByte = (sizeof(char*) + sizeof(i16) + 1)*N; 1638 zExtra = sqlite3DbMallocZero(db, nByte); 1639 if( zExtra==0 ) return SQLITE_NOMEM; 1640 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 1641 pIdx->azColl = (char**)zExtra; 1642 zExtra += sizeof(char*)*N; 1643 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 1644 pIdx->aiColumn = (i16*)zExtra; 1645 zExtra += sizeof(i16)*N; 1646 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 1647 pIdx->aSortOrder = (u8*)zExtra; 1648 pIdx->nColumn = N; 1649 pIdx->isResized = 1; 1650 return SQLITE_OK; 1651 } 1652 1653 /* 1654 ** Estimate the total row width for a table. 1655 */ 1656 static void estimateTableWidth(Table *pTab){ 1657 unsigned wTable = 0; 1658 const Column *pTabCol; 1659 int i; 1660 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 1661 wTable += pTabCol->szEst; 1662 } 1663 if( pTab->iPKey<0 ) wTable++; 1664 pTab->szTabRow = sqlite3LogEst(wTable*4); 1665 } 1666 1667 /* 1668 ** Estimate the average size of a row for an index. 1669 */ 1670 static void estimateIndexWidth(Index *pIdx){ 1671 unsigned wIndex = 0; 1672 int i; 1673 const Column *aCol = pIdx->pTable->aCol; 1674 for(i=0; i<pIdx->nColumn; i++){ 1675 i16 x = pIdx->aiColumn[i]; 1676 assert( x<pIdx->pTable->nCol ); 1677 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 1678 } 1679 pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 1680 } 1681 1682 /* Return true if value x is found any of the first nCol entries of aiCol[] 1683 */ 1684 static int hasColumn(const i16 *aiCol, int nCol, int x){ 1685 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; 1686 return 0; 1687 } 1688 1689 /* 1690 ** This routine runs at the end of parsing a CREATE TABLE statement that 1691 ** has a WITHOUT ROWID clause. The job of this routine is to convert both 1692 ** internal schema data structures and the generated VDBE code so that they 1693 ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 1694 ** Changes include: 1695 ** 1696 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is 1697 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical 1698 ** data storage is a covering index btree. 1699 ** (2) Bypass the creation of the sqlite_master table entry 1700 ** for the PRIMARY KEY as the primary key index is now 1701 ** identified by the sqlite_master table entry of the table itself. 1702 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the 1703 ** schema to the rootpage from the main table. 1704 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 1705 ** (5) Add all table columns to the PRIMARY KEY Index object 1706 ** so that the PRIMARY KEY is a covering index. The surplus 1707 ** columns are part of KeyInfo.nXField and are not used for 1708 ** sorting or lookup or uniqueness checks. 1709 ** (6) Replace the rowid tail on all automatically generated UNIQUE 1710 ** indices with the PRIMARY KEY columns. 1711 */ 1712 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 1713 Index *pIdx; 1714 Index *pPk; 1715 int nPk; 1716 int i, j; 1717 sqlite3 *db = pParse->db; 1718 Vdbe *v = pParse->pVdbe; 1719 1720 /* Convert the OP_CreateTable opcode that would normally create the 1721 ** root-page for the table into an OP_CreateIndex opcode. The index 1722 ** created will become the PRIMARY KEY index. 1723 */ 1724 if( pParse->addrCrTab ){ 1725 assert( v ); 1726 sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); 1727 } 1728 1729 /* Locate the PRIMARY KEY index. Or, if this table was originally 1730 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 1731 */ 1732 if( pTab->iPKey>=0 ){ 1733 ExprList *pList; 1734 Token ipkToken; 1735 ipkToken.z = pTab->aCol[pTab->iPKey].zName; 1736 ipkToken.n = sqlite3Strlen30(ipkToken.z); 1737 pList = sqlite3ExprListAppend(pParse, 0, 1738 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 1739 if( pList==0 ) return; 1740 pList->a[0].sortOrder = pParse->iPkSortOrder; 1741 assert( pParse->pNewTable==pTab ); 1742 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0); 1743 if( pPk==0 ) return; 1744 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY; 1745 pTab->iPKey = -1; 1746 }else{ 1747 pPk = sqlite3PrimaryKeyIndex(pTab); 1748 1749 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master 1750 ** table entry. This is only required if currently generating VDBE 1751 ** code for a CREATE TABLE (not when parsing one as part of reading 1752 ** a database schema). */ 1753 if( v ){ 1754 assert( db->init.busy==0 ); 1755 sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); 1756 } 1757 1758 /* 1759 ** Remove all redundant columns from the PRIMARY KEY. For example, change 1760 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 1761 ** code assumes the PRIMARY KEY contains no repeated columns. 1762 */ 1763 for(i=j=1; i<pPk->nKeyCol; i++){ 1764 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ 1765 pPk->nColumn--; 1766 }else{ 1767 pPk->aiColumn[j++] = pPk->aiColumn[i]; 1768 } 1769 } 1770 pPk->nKeyCol = j; 1771 } 1772 pPk->isCovering = 1; 1773 assert( pPk!=0 ); 1774 nPk = pPk->nKeyCol; 1775 1776 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except, 1777 ** do not enforce this for imposter tables.) */ 1778 if( !db->init.imposterTable ){ 1779 for(i=0; i<nPk; i++){ 1780 pTab->aCol[pPk->aiColumn[i]].notNull = 1; 1781 } 1782 pPk->uniqNotNull = 1; 1783 } 1784 1785 /* The root page of the PRIMARY KEY is the table root page */ 1786 pPk->tnum = pTab->tnum; 1787 1788 /* Update the in-memory representation of all UNIQUE indices by converting 1789 ** the final rowid column into one or more columns of the PRIMARY KEY. 1790 */ 1791 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 1792 int n; 1793 if( IsPrimaryKeyIndex(pIdx) ) continue; 1794 for(i=n=0; i<nPk; i++){ 1795 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; 1796 } 1797 if( n==0 ){ 1798 /* This index is a superset of the primary key */ 1799 pIdx->nColumn = pIdx->nKeyCol; 1800 continue; 1801 } 1802 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 1803 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 1804 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ 1805 pIdx->aiColumn[j] = pPk->aiColumn[i]; 1806 pIdx->azColl[j] = pPk->azColl[i]; 1807 j++; 1808 } 1809 } 1810 assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 1811 assert( pIdx->nColumn>=j ); 1812 } 1813 1814 /* Add all table columns to the PRIMARY KEY index 1815 */ 1816 if( nPk<pTab->nCol ){ 1817 if( resizeIndexObject(db, pPk, pTab->nCol) ) return; 1818 for(i=0, j=nPk; i<pTab->nCol; i++){ 1819 if( !hasColumn(pPk->aiColumn, j, i) ){ 1820 assert( j<pPk->nColumn ); 1821 pPk->aiColumn[j] = i; 1822 pPk->azColl[j] = "BINARY"; 1823 j++; 1824 } 1825 } 1826 assert( pPk->nColumn==j ); 1827 assert( pTab->nCol==j ); 1828 }else{ 1829 pPk->nColumn = pTab->nCol; 1830 } 1831 } 1832 1833 /* 1834 ** This routine is called to report the final ")" that terminates 1835 ** a CREATE TABLE statement. 1836 ** 1837 ** The table structure that other action routines have been building 1838 ** is added to the internal hash tables, assuming no errors have 1839 ** occurred. 1840 ** 1841 ** An entry for the table is made in the master table on disk, unless 1842 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 1843 ** it means we are reading the sqlite_master table because we just 1844 ** connected to the database or because the sqlite_master table has 1845 ** recently changed, so the entry for this table already exists in 1846 ** the sqlite_master table. We do not want to create it again. 1847 ** 1848 ** If the pSelect argument is not NULL, it means that this routine 1849 ** was called to create a table generated from a 1850 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 1851 ** the new table will match the result set of the SELECT. 1852 */ 1853 void sqlite3EndTable( 1854 Parse *pParse, /* Parse context */ 1855 Token *pCons, /* The ',' token after the last column defn. */ 1856 Token *pEnd, /* The ')' before options in the CREATE TABLE */ 1857 u8 tabOpts, /* Extra table options. Usually 0. */ 1858 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 1859 ){ 1860 Table *p; /* The new table */ 1861 sqlite3 *db = pParse->db; /* The database connection */ 1862 int iDb; /* Database in which the table lives */ 1863 Index *pIdx; /* An implied index of the table */ 1864 1865 if( pEnd==0 && pSelect==0 ){ 1866 return; 1867 } 1868 assert( !db->mallocFailed ); 1869 p = pParse->pNewTable; 1870 if( p==0 ) return; 1871 1872 assert( !db->init.busy || !pSelect ); 1873 1874 /* If the db->init.busy is 1 it means we are reading the SQL off the 1875 ** "sqlite_master" or "sqlite_temp_master" table on the disk. 1876 ** So do not write to the disk again. Extract the root page number 1877 ** for the table from the db->init.newTnum field. (The page number 1878 ** should have been put there by the sqliteOpenCb routine.) 1879 */ 1880 if( db->init.busy ){ 1881 p->tnum = db->init.newTnum; 1882 } 1883 1884 /* Special processing for WITHOUT ROWID Tables */ 1885 if( tabOpts & TF_WithoutRowid ){ 1886 if( (p->tabFlags & TF_Autoincrement) ){ 1887 sqlite3ErrorMsg(pParse, 1888 "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 1889 return; 1890 } 1891 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 1892 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 1893 }else{ 1894 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 1895 convertToWithoutRowidTable(pParse, p); 1896 } 1897 } 1898 1899 iDb = sqlite3SchemaToIndex(db, p->pSchema); 1900 1901 #ifndef SQLITE_OMIT_CHECK 1902 /* Resolve names in all CHECK constraint expressions. 1903 */ 1904 if( p->pCheck ){ 1905 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 1906 } 1907 #endif /* !defined(SQLITE_OMIT_CHECK) */ 1908 1909 /* Estimate the average row size for the table and for all implied indices */ 1910 estimateTableWidth(p); 1911 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1912 estimateIndexWidth(pIdx); 1913 } 1914 1915 /* If not initializing, then create a record for the new table 1916 ** in the SQLITE_MASTER table of the database. 1917 ** 1918 ** If this is a TEMPORARY table, write the entry into the auxiliary 1919 ** file instead of into the main database file. 1920 */ 1921 if( !db->init.busy ){ 1922 int n; 1923 Vdbe *v; 1924 char *zType; /* "view" or "table" */ 1925 char *zType2; /* "VIEW" or "TABLE" */ 1926 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 1927 1928 v = sqlite3GetVdbe(pParse); 1929 if( NEVER(v==0) ) return; 1930 1931 sqlite3VdbeAddOp1(v, OP_Close, 0); 1932 1933 /* 1934 ** Initialize zType for the new view or table. 1935 */ 1936 if( p->pSelect==0 ){ 1937 /* A regular table */ 1938 zType = "table"; 1939 zType2 = "TABLE"; 1940 #ifndef SQLITE_OMIT_VIEW 1941 }else{ 1942 /* A view */ 1943 zType = "view"; 1944 zType2 = "VIEW"; 1945 #endif 1946 } 1947 1948 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 1949 ** statement to populate the new table. The root-page number for the 1950 ** new table is in register pParse->regRoot. 1951 ** 1952 ** Once the SELECT has been coded by sqlite3Select(), it is in a 1953 ** suitable state to query for the column names and types to be used 1954 ** by the new table. 1955 ** 1956 ** A shared-cache write-lock is not required to write to the new table, 1957 ** as a schema-lock must have already been obtained to create it. Since 1958 ** a schema-lock excludes all other database users, the write-lock would 1959 ** be redundant. 1960 */ 1961 if( pSelect ){ 1962 SelectDest dest; /* Where the SELECT should store results */ 1963 int regYield; /* Register holding co-routine entry-point */ 1964 int addrTop; /* Top of the co-routine */ 1965 int regRec; /* A record to be insert into the new table */ 1966 int regRowid; /* Rowid of the next row to insert */ 1967 int addrInsLoop; /* Top of the loop for inserting rows */ 1968 Table *pSelTab; /* A table that describes the SELECT results */ 1969 1970 regYield = ++pParse->nMem; 1971 regRec = ++pParse->nMem; 1972 regRowid = ++pParse->nMem; 1973 assert(pParse->nTab==1); 1974 sqlite3MayAbort(pParse); 1975 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 1976 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 1977 pParse->nTab = 2; 1978 addrTop = sqlite3VdbeCurrentAddr(v) + 1; 1979 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 1980 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 1981 sqlite3Select(pParse, pSelect, &dest); 1982 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); 1983 sqlite3VdbeJumpHere(v, addrTop - 1); 1984 if( pParse->nErr ) return; 1985 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); 1986 if( pSelTab==0 ) return; 1987 assert( p->aCol==0 ); 1988 p->nCol = pSelTab->nCol; 1989 p->aCol = pSelTab->aCol; 1990 pSelTab->nCol = 0; 1991 pSelTab->aCol = 0; 1992 sqlite3DeleteTable(db, pSelTab); 1993 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 1994 VdbeCoverage(v); 1995 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 1996 sqlite3TableAffinity(v, p, 0); 1997 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 1998 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 1999 sqlite3VdbeGoto(v, addrInsLoop); 2000 sqlite3VdbeJumpHere(v, addrInsLoop); 2001 sqlite3VdbeAddOp1(v, OP_Close, 1); 2002 } 2003 2004 /* Compute the complete text of the CREATE statement */ 2005 if( pSelect ){ 2006 zStmt = createTableStmt(db, p); 2007 }else{ 2008 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 2009 n = (int)(pEnd2->z - pParse->sNameToken.z); 2010 if( pEnd2->z[0]!=';' ) n += pEnd2->n; 2011 zStmt = sqlite3MPrintf(db, 2012 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 2013 ); 2014 } 2015 2016 /* A slot for the record has already been allocated in the 2017 ** SQLITE_MASTER table. We just need to update that slot with all 2018 ** the information we've collected. 2019 */ 2020 sqlite3NestedParse(pParse, 2021 "UPDATE %Q.%s " 2022 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " 2023 "WHERE rowid=#%d", 2024 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 2025 zType, 2026 p->zName, 2027 p->zName, 2028 pParse->regRoot, 2029 zStmt, 2030 pParse->regRowid 2031 ); 2032 sqlite3DbFree(db, zStmt); 2033 sqlite3ChangeCookie(pParse, iDb); 2034 2035 #ifndef SQLITE_OMIT_AUTOINCREMENT 2036 /* Check to see if we need to create an sqlite_sequence table for 2037 ** keeping track of autoincrement keys. 2038 */ 2039 if( p->tabFlags & TF_Autoincrement ){ 2040 Db *pDb = &db->aDb[iDb]; 2041 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2042 if( pDb->pSchema->pSeqTab==0 ){ 2043 sqlite3NestedParse(pParse, 2044 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 2045 pDb->zName 2046 ); 2047 } 2048 } 2049 #endif 2050 2051 /* Reparse everything to update our internal data structures */ 2052 sqlite3VdbeAddParseSchemaOp(v, iDb, 2053 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); 2054 } 2055 2056 2057 /* Add the table to the in-memory representation of the database. 2058 */ 2059 if( db->init.busy ){ 2060 Table *pOld; 2061 Schema *pSchema = p->pSchema; 2062 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2063 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 2064 if( pOld ){ 2065 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 2066 db->mallocFailed = 1; 2067 return; 2068 } 2069 pParse->pNewTable = 0; 2070 db->flags |= SQLITE_InternChanges; 2071 2072 #ifndef SQLITE_OMIT_ALTERTABLE 2073 if( !p->pSelect ){ 2074 const char *zName = (const char *)pParse->sNameToken.z; 2075 int nName; 2076 assert( !pSelect && pCons && pEnd ); 2077 if( pCons->z==0 ){ 2078 pCons = pEnd; 2079 } 2080 nName = (int)((const char *)pCons->z - zName); 2081 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); 2082 } 2083 #endif 2084 } 2085 } 2086 2087 #ifndef SQLITE_OMIT_VIEW 2088 /* 2089 ** The parser calls this routine in order to create a new VIEW 2090 */ 2091 void sqlite3CreateView( 2092 Parse *pParse, /* The parsing context */ 2093 Token *pBegin, /* The CREATE token that begins the statement */ 2094 Token *pName1, /* The token that holds the name of the view */ 2095 Token *pName2, /* The token that holds the name of the view */ 2096 ExprList *pCNames, /* Optional list of view column names */ 2097 Select *pSelect, /* A SELECT statement that will become the new view */ 2098 int isTemp, /* TRUE for a TEMPORARY view */ 2099 int noErr /* Suppress error messages if VIEW already exists */ 2100 ){ 2101 Table *p; 2102 int n; 2103 const char *z; 2104 Token sEnd; 2105 DbFixer sFix; 2106 Token *pName = 0; 2107 int iDb; 2108 sqlite3 *db = pParse->db; 2109 2110 if( pParse->nVar>0 ){ 2111 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 2112 goto create_view_fail; 2113 } 2114 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2115 p = pParse->pNewTable; 2116 if( p==0 || pParse->nErr ) goto create_view_fail; 2117 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2118 iDb = sqlite3SchemaToIndex(db, p->pSchema); 2119 sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 2120 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 2121 2122 /* Make a copy of the entire SELECT statement that defines the view. 2123 ** This will force all the Expr.token.z values to be dynamically 2124 ** allocated rather than point to the input string - which means that 2125 ** they will persist after the current sqlite3_exec() call returns. 2126 */ 2127 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 2128 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 2129 if( db->mallocFailed ) goto create_view_fail; 2130 2131 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 2132 ** the end. 2133 */ 2134 sEnd = pParse->sLastToken; 2135 assert( sEnd.z[0]!=0 ); 2136 if( sEnd.z[0]!=';' ){ 2137 sEnd.z += sEnd.n; 2138 } 2139 sEnd.n = 0; 2140 n = (int)(sEnd.z - pBegin->z); 2141 assert( n>0 ); 2142 z = pBegin->z; 2143 while( sqlite3Isspace(z[n-1]) ){ n--; } 2144 sEnd.z = &z[n-1]; 2145 sEnd.n = 1; 2146 2147 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ 2148 sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 2149 2150 create_view_fail: 2151 sqlite3SelectDelete(db, pSelect); 2152 sqlite3ExprListDelete(db, pCNames); 2153 return; 2154 } 2155 #endif /* SQLITE_OMIT_VIEW */ 2156 2157 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 2158 /* 2159 ** The Table structure pTable is really a VIEW. Fill in the names of 2160 ** the columns of the view in the pTable structure. Return the number 2161 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 2162 */ 2163 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 2164 Table *pSelTab; /* A fake table from which we get the result set */ 2165 Select *pSel; /* Copy of the SELECT that implements the view */ 2166 int nErr = 0; /* Number of errors encountered */ 2167 int n; /* Temporarily holds the number of cursors assigned */ 2168 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 2169 sqlite3_xauth xAuth; /* Saved xAuth pointer */ 2170 u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */ 2171 2172 assert( pTable ); 2173 2174 #ifndef SQLITE_OMIT_VIRTUALTABLE 2175 if( sqlite3VtabCallConnect(pParse, pTable) ){ 2176 return SQLITE_ERROR; 2177 } 2178 if( IsVirtual(pTable) ) return 0; 2179 #endif 2180 2181 #ifndef SQLITE_OMIT_VIEW 2182 /* A positive nCol means the columns names for this view are 2183 ** already known. 2184 */ 2185 if( pTable->nCol>0 ) return 0; 2186 2187 /* A negative nCol is a special marker meaning that we are currently 2188 ** trying to compute the column names. If we enter this routine with 2189 ** a negative nCol, it means two or more views form a loop, like this: 2190 ** 2191 ** CREATE VIEW one AS SELECT * FROM two; 2192 ** CREATE VIEW two AS SELECT * FROM one; 2193 ** 2194 ** Actually, the error above is now caught prior to reaching this point. 2195 ** But the following test is still important as it does come up 2196 ** in the following: 2197 ** 2198 ** CREATE TABLE main.ex1(a); 2199 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 2200 ** SELECT * FROM temp.ex1; 2201 */ 2202 if( pTable->nCol<0 ){ 2203 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 2204 return 1; 2205 } 2206 assert( pTable->nCol>=0 ); 2207 2208 /* If we get this far, it means we need to compute the table names. 2209 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 2210 ** "*" elements in the results set of the view and will assign cursors 2211 ** to the elements of the FROM clause. But we do not want these changes 2212 ** to be permanent. So the computation is done on a copy of the SELECT 2213 ** statement that defines the view. 2214 */ 2215 assert( pTable->pSelect ); 2216 bEnabledLA = db->lookaside.bEnabled; 2217 if( pTable->pCheck ){ 2218 db->lookaside.bEnabled = 0; 2219 sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 2220 &pTable->nCol, &pTable->aCol); 2221 }else{ 2222 pSel = sqlite3SelectDup(db, pTable->pSelect, 0); 2223 if( pSel ){ 2224 n = pParse->nTab; 2225 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 2226 pTable->nCol = -1; 2227 db->lookaside.bEnabled = 0; 2228 #ifndef SQLITE_OMIT_AUTHORIZATION 2229 xAuth = db->xAuth; 2230 db->xAuth = 0; 2231 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 2232 db->xAuth = xAuth; 2233 #else 2234 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); 2235 #endif 2236 pParse->nTab = n; 2237 if( pSelTab ){ 2238 assert( pTable->aCol==0 ); 2239 pTable->nCol = pSelTab->nCol; 2240 pTable->aCol = pSelTab->aCol; 2241 pSelTab->nCol = 0; 2242 pSelTab->aCol = 0; 2243 sqlite3DeleteTable(db, pSelTab); 2244 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 2245 }else{ 2246 pTable->nCol = 0; 2247 nErr++; 2248 } 2249 sqlite3SelectDelete(db, pSel); 2250 } else { 2251 nErr++; 2252 } 2253 } 2254 db->lookaside.bEnabled = bEnabledLA; 2255 pTable->pSchema->schemaFlags |= DB_UnresetViews; 2256 #endif /* SQLITE_OMIT_VIEW */ 2257 return nErr; 2258 } 2259 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 2260 2261 #ifndef SQLITE_OMIT_VIEW 2262 /* 2263 ** Clear the column names from every VIEW in database idx. 2264 */ 2265 static void sqliteViewResetAll(sqlite3 *db, int idx){ 2266 HashElem *i; 2267 assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 2268 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 2269 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 2270 Table *pTab = sqliteHashData(i); 2271 if( pTab->pSelect ){ 2272 sqlite3DeleteColumnNames(db, pTab); 2273 pTab->aCol = 0; 2274 pTab->nCol = 0; 2275 } 2276 } 2277 DbClearProperty(db, idx, DB_UnresetViews); 2278 } 2279 #else 2280 # define sqliteViewResetAll(A,B) 2281 #endif /* SQLITE_OMIT_VIEW */ 2282 2283 /* 2284 ** This function is called by the VDBE to adjust the internal schema 2285 ** used by SQLite when the btree layer moves a table root page. The 2286 ** root-page of a table or index in database iDb has changed from iFrom 2287 ** to iTo. 2288 ** 2289 ** Ticket #1728: The symbol table might still contain information 2290 ** on tables and/or indices that are the process of being deleted. 2291 ** If you are unlucky, one of those deleted indices or tables might 2292 ** have the same rootpage number as the real table or index that is 2293 ** being moved. So we cannot stop searching after the first match 2294 ** because the first match might be for one of the deleted indices 2295 ** or tables and not the table/index that is actually being moved. 2296 ** We must continue looping until all tables and indices with 2297 ** rootpage==iFrom have been converted to have a rootpage of iTo 2298 ** in order to be certain that we got the right one. 2299 */ 2300 #ifndef SQLITE_OMIT_AUTOVACUUM 2301 void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ 2302 HashElem *pElem; 2303 Hash *pHash; 2304 Db *pDb; 2305 2306 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2307 pDb = &db->aDb[iDb]; 2308 pHash = &pDb->pSchema->tblHash; 2309 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2310 Table *pTab = sqliteHashData(pElem); 2311 if( pTab->tnum==iFrom ){ 2312 pTab->tnum = iTo; 2313 } 2314 } 2315 pHash = &pDb->pSchema->idxHash; 2316 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 2317 Index *pIdx = sqliteHashData(pElem); 2318 if( pIdx->tnum==iFrom ){ 2319 pIdx->tnum = iTo; 2320 } 2321 } 2322 } 2323 #endif 2324 2325 /* 2326 ** Write code to erase the table with root-page iTable from database iDb. 2327 ** Also write code to modify the sqlite_master table and internal schema 2328 ** if a root-page of another table is moved by the btree-layer whilst 2329 ** erasing iTable (this can happen with an auto-vacuum database). 2330 */ 2331 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 2332 Vdbe *v = sqlite3GetVdbe(pParse); 2333 int r1 = sqlite3GetTempReg(pParse); 2334 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 2335 sqlite3MayAbort(pParse); 2336 #ifndef SQLITE_OMIT_AUTOVACUUM 2337 /* OP_Destroy stores an in integer r1. If this integer 2338 ** is non-zero, then it is the root page number of a table moved to 2339 ** location iTable. The following code modifies the sqlite_master table to 2340 ** reflect this. 2341 ** 2342 ** The "#NNN" in the SQL is a special constant that means whatever value 2343 ** is in register NNN. See grammar rules associated with the TK_REGISTER 2344 ** token for additional information. 2345 */ 2346 sqlite3NestedParse(pParse, 2347 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", 2348 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); 2349 #endif 2350 sqlite3ReleaseTempReg(pParse, r1); 2351 } 2352 2353 /* 2354 ** Write VDBE code to erase table pTab and all associated indices on disk. 2355 ** Code to update the sqlite_master tables and internal schema definitions 2356 ** in case a root-page belonging to another table is moved by the btree layer 2357 ** is also added (this can happen with an auto-vacuum database). 2358 */ 2359 static void destroyTable(Parse *pParse, Table *pTab){ 2360 #ifdef SQLITE_OMIT_AUTOVACUUM 2361 Index *pIdx; 2362 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2363 destroyRootPage(pParse, pTab->tnum, iDb); 2364 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2365 destroyRootPage(pParse, pIdx->tnum, iDb); 2366 } 2367 #else 2368 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 2369 ** is not defined), then it is important to call OP_Destroy on the 2370 ** table and index root-pages in order, starting with the numerically 2371 ** largest root-page number. This guarantees that none of the root-pages 2372 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 2373 ** following were coded: 2374 ** 2375 ** OP_Destroy 4 0 2376 ** ... 2377 ** OP_Destroy 5 0 2378 ** 2379 ** and root page 5 happened to be the largest root-page number in the 2380 ** database, then root page 5 would be moved to page 4 by the 2381 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 2382 ** a free-list page. 2383 */ 2384 int iTab = pTab->tnum; 2385 int iDestroyed = 0; 2386 2387 while( 1 ){ 2388 Index *pIdx; 2389 int iLargest = 0; 2390 2391 if( iDestroyed==0 || iTab<iDestroyed ){ 2392 iLargest = iTab; 2393 } 2394 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2395 int iIdx = pIdx->tnum; 2396 assert( pIdx->pSchema==pTab->pSchema ); 2397 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 2398 iLargest = iIdx; 2399 } 2400 } 2401 if( iLargest==0 ){ 2402 return; 2403 }else{ 2404 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 2405 assert( iDb>=0 && iDb<pParse->db->nDb ); 2406 destroyRootPage(pParse, iLargest, iDb); 2407 iDestroyed = iLargest; 2408 } 2409 } 2410 #endif 2411 } 2412 2413 /* 2414 ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 2415 ** after a DROP INDEX or DROP TABLE command. 2416 */ 2417 static void sqlite3ClearStatTables( 2418 Parse *pParse, /* The parsing context */ 2419 int iDb, /* The database number */ 2420 const char *zType, /* "idx" or "tbl" */ 2421 const char *zName /* Name of index or table */ 2422 ){ 2423 int i; 2424 const char *zDbName = pParse->db->aDb[iDb].zName; 2425 for(i=1; i<=4; i++){ 2426 char zTab[24]; 2427 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 2428 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 2429 sqlite3NestedParse(pParse, 2430 "DELETE FROM %Q.%s WHERE %s=%Q", 2431 zDbName, zTab, zType, zName 2432 ); 2433 } 2434 } 2435 } 2436 2437 /* 2438 ** Generate code to drop a table. 2439 */ 2440 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 2441 Vdbe *v; 2442 sqlite3 *db = pParse->db; 2443 Trigger *pTrigger; 2444 Db *pDb = &db->aDb[iDb]; 2445 2446 v = sqlite3GetVdbe(pParse); 2447 assert( v!=0 ); 2448 sqlite3BeginWriteOperation(pParse, 1, iDb); 2449 2450 #ifndef SQLITE_OMIT_VIRTUALTABLE 2451 if( IsVirtual(pTab) ){ 2452 sqlite3VdbeAddOp0(v, OP_VBegin); 2453 } 2454 #endif 2455 2456 /* Drop all triggers associated with the table being dropped. Code 2457 ** is generated to remove entries from sqlite_master and/or 2458 ** sqlite_temp_master if required. 2459 */ 2460 pTrigger = sqlite3TriggerList(pParse, pTab); 2461 while( pTrigger ){ 2462 assert( pTrigger->pSchema==pTab->pSchema || 2463 pTrigger->pSchema==db->aDb[1].pSchema ); 2464 sqlite3DropTriggerPtr(pParse, pTrigger); 2465 pTrigger = pTrigger->pNext; 2466 } 2467 2468 #ifndef SQLITE_OMIT_AUTOINCREMENT 2469 /* Remove any entries of the sqlite_sequence table associated with 2470 ** the table being dropped. This is done before the table is dropped 2471 ** at the btree level, in case the sqlite_sequence table needs to 2472 ** move as a result of the drop (can happen in auto-vacuum mode). 2473 */ 2474 if( pTab->tabFlags & TF_Autoincrement ){ 2475 sqlite3NestedParse(pParse, 2476 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 2477 pDb->zName, pTab->zName 2478 ); 2479 } 2480 #endif 2481 2482 /* Drop all SQLITE_MASTER table and index entries that refer to the 2483 ** table. The program name loops through the master table and deletes 2484 ** every row that refers to a table of the same name as the one being 2485 ** dropped. Triggers are handled separately because a trigger can be 2486 ** created in the temp database that refers to a table in another 2487 ** database. 2488 */ 2489 sqlite3NestedParse(pParse, 2490 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", 2491 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); 2492 if( !isView && !IsVirtual(pTab) ){ 2493 destroyTable(pParse, pTab); 2494 } 2495 2496 /* Remove the table entry from SQLite's internal schema and modify 2497 ** the schema cookie. 2498 */ 2499 if( IsVirtual(pTab) ){ 2500 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 2501 } 2502 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 2503 sqlite3ChangeCookie(pParse, iDb); 2504 sqliteViewResetAll(db, iDb); 2505 } 2506 2507 /* 2508 ** This routine is called to do the work of a DROP TABLE statement. 2509 ** pName is the name of the table to be dropped. 2510 */ 2511 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 2512 Table *pTab; 2513 Vdbe *v; 2514 sqlite3 *db = pParse->db; 2515 int iDb; 2516 2517 if( db->mallocFailed ){ 2518 goto exit_drop_table; 2519 } 2520 assert( pParse->nErr==0 ); 2521 assert( pName->nSrc==1 ); 2522 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 2523 if( noErr ) db->suppressErr++; 2524 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 2525 if( noErr ) db->suppressErr--; 2526 2527 if( pTab==0 ){ 2528 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 2529 goto exit_drop_table; 2530 } 2531 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2532 assert( iDb>=0 && iDb<db->nDb ); 2533 2534 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 2535 ** it is initialized. 2536 */ 2537 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 2538 goto exit_drop_table; 2539 } 2540 #ifndef SQLITE_OMIT_AUTHORIZATION 2541 { 2542 int code; 2543 const char *zTab = SCHEMA_TABLE(iDb); 2544 const char *zDb = db->aDb[iDb].zName; 2545 const char *zArg2 = 0; 2546 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 2547 goto exit_drop_table; 2548 } 2549 if( isView ){ 2550 if( !OMIT_TEMPDB && iDb==1 ){ 2551 code = SQLITE_DROP_TEMP_VIEW; 2552 }else{ 2553 code = SQLITE_DROP_VIEW; 2554 } 2555 #ifndef SQLITE_OMIT_VIRTUALTABLE 2556 }else if( IsVirtual(pTab) ){ 2557 code = SQLITE_DROP_VTABLE; 2558 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 2559 #endif 2560 }else{ 2561 if( !OMIT_TEMPDB && iDb==1 ){ 2562 code = SQLITE_DROP_TEMP_TABLE; 2563 }else{ 2564 code = SQLITE_DROP_TABLE; 2565 } 2566 } 2567 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 2568 goto exit_drop_table; 2569 } 2570 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 2571 goto exit_drop_table; 2572 } 2573 } 2574 #endif 2575 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 2576 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ 2577 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 2578 goto exit_drop_table; 2579 } 2580 2581 #ifndef SQLITE_OMIT_VIEW 2582 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 2583 ** on a table. 2584 */ 2585 if( isView && pTab->pSelect==0 ){ 2586 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 2587 goto exit_drop_table; 2588 } 2589 if( !isView && pTab->pSelect ){ 2590 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 2591 goto exit_drop_table; 2592 } 2593 #endif 2594 2595 /* Generate code to remove the table from the master table 2596 ** on disk. 2597 */ 2598 v = sqlite3GetVdbe(pParse); 2599 if( v ){ 2600 sqlite3BeginWriteOperation(pParse, 1, iDb); 2601 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 2602 sqlite3FkDropTable(pParse, pName, pTab); 2603 sqlite3CodeDropTable(pParse, pTab, iDb, isView); 2604 } 2605 2606 exit_drop_table: 2607 sqlite3SrcListDelete(db, pName); 2608 } 2609 2610 /* 2611 ** This routine is called to create a new foreign key on the table 2612 ** currently under construction. pFromCol determines which columns 2613 ** in the current table point to the foreign key. If pFromCol==0 then 2614 ** connect the key to the last column inserted. pTo is the name of 2615 ** the table referred to (a.k.a the "parent" table). pToCol is a list 2616 ** of tables in the parent pTo table. flags contains all 2617 ** information about the conflict resolution algorithms specified 2618 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 2619 ** 2620 ** An FKey structure is created and added to the table currently 2621 ** under construction in the pParse->pNewTable field. 2622 ** 2623 ** The foreign key is set for IMMEDIATE processing. A subsequent call 2624 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 2625 */ 2626 void sqlite3CreateForeignKey( 2627 Parse *pParse, /* Parsing context */ 2628 ExprList *pFromCol, /* Columns in this table that point to other table */ 2629 Token *pTo, /* Name of the other table */ 2630 ExprList *pToCol, /* Columns in the other table */ 2631 int flags /* Conflict resolution algorithms. */ 2632 ){ 2633 sqlite3 *db = pParse->db; 2634 #ifndef SQLITE_OMIT_FOREIGN_KEY 2635 FKey *pFKey = 0; 2636 FKey *pNextTo; 2637 Table *p = pParse->pNewTable; 2638 int nByte; 2639 int i; 2640 int nCol; 2641 char *z; 2642 2643 assert( pTo!=0 ); 2644 if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 2645 if( pFromCol==0 ){ 2646 int iCol = p->nCol-1; 2647 if( NEVER(iCol<0) ) goto fk_end; 2648 if( pToCol && pToCol->nExpr!=1 ){ 2649 sqlite3ErrorMsg(pParse, "foreign key on %s" 2650 " should reference only one column of table %T", 2651 p->aCol[iCol].zName, pTo); 2652 goto fk_end; 2653 } 2654 nCol = 1; 2655 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 2656 sqlite3ErrorMsg(pParse, 2657 "number of columns in foreign key does not match the number of " 2658 "columns in the referenced table"); 2659 goto fk_end; 2660 }else{ 2661 nCol = pFromCol->nExpr; 2662 } 2663 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 2664 if( pToCol ){ 2665 for(i=0; i<pToCol->nExpr; i++){ 2666 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; 2667 } 2668 } 2669 pFKey = sqlite3DbMallocZero(db, nByte ); 2670 if( pFKey==0 ){ 2671 goto fk_end; 2672 } 2673 pFKey->pFrom = p; 2674 pFKey->pNextFrom = p->pFKey; 2675 z = (char*)&pFKey->aCol[nCol]; 2676 pFKey->zTo = z; 2677 memcpy(z, pTo->z, pTo->n); 2678 z[pTo->n] = 0; 2679 sqlite3Dequote(z); 2680 z += pTo->n+1; 2681 pFKey->nCol = nCol; 2682 if( pFromCol==0 ){ 2683 pFKey->aCol[0].iFrom = p->nCol-1; 2684 }else{ 2685 for(i=0; i<nCol; i++){ 2686 int j; 2687 for(j=0; j<p->nCol; j++){ 2688 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ 2689 pFKey->aCol[i].iFrom = j; 2690 break; 2691 } 2692 } 2693 if( j>=p->nCol ){ 2694 sqlite3ErrorMsg(pParse, 2695 "unknown column \"%s\" in foreign key definition", 2696 pFromCol->a[i].zName); 2697 goto fk_end; 2698 } 2699 } 2700 } 2701 if( pToCol ){ 2702 for(i=0; i<nCol; i++){ 2703 int n = sqlite3Strlen30(pToCol->a[i].zName); 2704 pFKey->aCol[i].zCol = z; 2705 memcpy(z, pToCol->a[i].zName, n); 2706 z[n] = 0; 2707 z += n+1; 2708 } 2709 } 2710 pFKey->isDeferred = 0; 2711 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 2712 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 2713 2714 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 2715 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 2716 pFKey->zTo, (void *)pFKey 2717 ); 2718 if( pNextTo==pFKey ){ 2719 db->mallocFailed = 1; 2720 goto fk_end; 2721 } 2722 if( pNextTo ){ 2723 assert( pNextTo->pPrevTo==0 ); 2724 pFKey->pNextTo = pNextTo; 2725 pNextTo->pPrevTo = pFKey; 2726 } 2727 2728 /* Link the foreign key to the table as the last step. 2729 */ 2730 p->pFKey = pFKey; 2731 pFKey = 0; 2732 2733 fk_end: 2734 sqlite3DbFree(db, pFKey); 2735 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 2736 sqlite3ExprListDelete(db, pFromCol); 2737 sqlite3ExprListDelete(db, pToCol); 2738 } 2739 2740 /* 2741 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 2742 ** clause is seen as part of a foreign key definition. The isDeferred 2743 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 2744 ** The behavior of the most recently created foreign key is adjusted 2745 ** accordingly. 2746 */ 2747 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 2748 #ifndef SQLITE_OMIT_FOREIGN_KEY 2749 Table *pTab; 2750 FKey *pFKey; 2751 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; 2752 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 2753 pFKey->isDeferred = (u8)isDeferred; 2754 #endif 2755 } 2756 2757 /* 2758 ** Generate code that will erase and refill index *pIdx. This is 2759 ** used to initialize a newly created index or to recompute the 2760 ** content of an index in response to a REINDEX command. 2761 ** 2762 ** if memRootPage is not negative, it means that the index is newly 2763 ** created. The register specified by memRootPage contains the 2764 ** root page number of the index. If memRootPage is negative, then 2765 ** the index already exists and must be cleared before being refilled and 2766 ** the root page number of the index is taken from pIndex->tnum. 2767 */ 2768 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 2769 Table *pTab = pIndex->pTable; /* The table that is indexed */ 2770 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 2771 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 2772 int iSorter; /* Cursor opened by OpenSorter (if in use) */ 2773 int addr1; /* Address of top of loop */ 2774 int addr2; /* Address to jump to for next iteration */ 2775 int tnum; /* Root page of index */ 2776 int iPartIdxLabel; /* Jump to this label to skip a row */ 2777 Vdbe *v; /* Generate code into this virtual machine */ 2778 KeyInfo *pKey; /* KeyInfo for index */ 2779 int regRecord; /* Register holding assembled index record */ 2780 sqlite3 *db = pParse->db; /* The database connection */ 2781 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 2782 2783 #ifndef SQLITE_OMIT_AUTHORIZATION 2784 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 2785 db->aDb[iDb].zName ) ){ 2786 return; 2787 } 2788 #endif 2789 2790 /* Require a write-lock on the table to perform this operation */ 2791 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 2792 2793 v = sqlite3GetVdbe(pParse); 2794 if( v==0 ) return; 2795 if( memRootPage>=0 ){ 2796 tnum = memRootPage; 2797 }else{ 2798 tnum = pIndex->tnum; 2799 } 2800 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 2801 2802 /* Open the sorter cursor if we are to use one. */ 2803 iSorter = pParse->nTab++; 2804 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 2805 sqlite3KeyInfoRef(pKey), P4_KEYINFO); 2806 2807 /* Open the table. Loop through all rows of the table, inserting index 2808 ** records into the sorter. */ 2809 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2810 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 2811 regRecord = sqlite3GetTempReg(pParse); 2812 2813 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 2814 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 2815 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 2816 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 2817 sqlite3VdbeJumpHere(v, addr1); 2818 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 2819 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 2820 (char *)pKey, P4_KEYINFO); 2821 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 2822 2823 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 2824 assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 2825 if( IsUniqueIndex(pIndex) && pKey!=0 ){ 2826 int j2 = sqlite3VdbeCurrentAddr(v) + 3; 2827 sqlite3VdbeGoto(v, j2); 2828 addr2 = sqlite3VdbeCurrentAddr(v); 2829 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 2830 pIndex->nKeyCol); VdbeCoverage(v); 2831 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 2832 }else{ 2833 addr2 = sqlite3VdbeCurrentAddr(v); 2834 } 2835 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 2836 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); 2837 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0); 2838 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 2839 sqlite3ReleaseTempReg(pParse, regRecord); 2840 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 2841 sqlite3VdbeJumpHere(v, addr1); 2842 2843 sqlite3VdbeAddOp1(v, OP_Close, iTab); 2844 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 2845 sqlite3VdbeAddOp1(v, OP_Close, iSorter); 2846 } 2847 2848 /* 2849 ** Allocate heap space to hold an Index object with nCol columns. 2850 ** 2851 ** Increase the allocation size to provide an extra nExtra bytes 2852 ** of 8-byte aligned space after the Index object and return a 2853 ** pointer to this extra space in *ppExtra. 2854 */ 2855 Index *sqlite3AllocateIndexObject( 2856 sqlite3 *db, /* Database connection */ 2857 i16 nCol, /* Total number of columns in the index */ 2858 int nExtra, /* Number of bytes of extra space to alloc */ 2859 char **ppExtra /* Pointer to the "extra" space */ 2860 ){ 2861 Index *p; /* Allocated index object */ 2862 int nByte; /* Bytes of space for Index object + arrays */ 2863 2864 nByte = ROUND8(sizeof(Index)) + /* Index structure */ 2865 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 2866 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 2867 sizeof(i16)*nCol + /* Index.aiColumn */ 2868 sizeof(u8)*nCol); /* Index.aSortOrder */ 2869 p = sqlite3DbMallocZero(db, nByte + nExtra); 2870 if( p ){ 2871 char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 2872 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 2873 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 2874 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 2875 p->aSortOrder = (u8*)pExtra; 2876 p->nColumn = nCol; 2877 p->nKeyCol = nCol - 1; 2878 *ppExtra = ((char*)p) + nByte; 2879 } 2880 return p; 2881 } 2882 2883 /* 2884 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 2885 ** and pTblList is the name of the table that is to be indexed. Both will 2886 ** be NULL for a primary key or an index that is created to satisfy a 2887 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 2888 ** as the table to be indexed. pParse->pNewTable is a table that is 2889 ** currently being constructed by a CREATE TABLE statement. 2890 ** 2891 ** pList is a list of columns to be indexed. pList will be NULL if this 2892 ** is a primary key or unique-constraint on the most recent column added 2893 ** to the table currently under construction. 2894 ** 2895 ** If the index is created successfully, return a pointer to the new Index 2896 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index 2897 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY) 2898 */ 2899 Index *sqlite3CreateIndex( 2900 Parse *pParse, /* All information about this parse */ 2901 Token *pName1, /* First part of index name. May be NULL */ 2902 Token *pName2, /* Second part of index name. May be NULL */ 2903 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 2904 ExprList *pList, /* A list of columns to be indexed */ 2905 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 2906 Token *pStart, /* The CREATE token that begins this statement */ 2907 Expr *pPIWhere, /* WHERE clause for partial indices */ 2908 int sortOrder, /* Sort order of primary key when pList==NULL */ 2909 int ifNotExist /* Omit error if index already exists */ 2910 ){ 2911 Index *pRet = 0; /* Pointer to return */ 2912 Table *pTab = 0; /* Table to be indexed */ 2913 Index *pIndex = 0; /* The index to be created */ 2914 char *zName = 0; /* Name of the index */ 2915 int nName; /* Number of characters in zName */ 2916 int i, j; 2917 DbFixer sFix; /* For assigning database names to pTable */ 2918 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 2919 sqlite3 *db = pParse->db; 2920 Db *pDb; /* The specific table containing the indexed database */ 2921 int iDb; /* Index of the database that is being written */ 2922 Token *pName = 0; /* Unqualified name of the index to create */ 2923 struct ExprList_item *pListItem; /* For looping over pList */ 2924 int nExtra = 0; /* Space allocated for zExtra[] */ 2925 int nExtraCol; /* Number of extra columns needed */ 2926 char *zExtra = 0; /* Extra space after the Index object */ 2927 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 2928 2929 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){ 2930 goto exit_create_index; 2931 } 2932 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 2933 goto exit_create_index; 2934 } 2935 2936 /* 2937 ** Find the table that is to be indexed. Return early if not found. 2938 */ 2939 if( pTblName!=0 ){ 2940 2941 /* Use the two-part index name to determine the database 2942 ** to search for the table. 'Fix' the table name to this db 2943 ** before looking up the table. 2944 */ 2945 assert( pName1 && pName2 ); 2946 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2947 if( iDb<0 ) goto exit_create_index; 2948 assert( pName && pName->z ); 2949 2950 #ifndef SQLITE_OMIT_TEMPDB 2951 /* If the index name was unqualified, check if the table 2952 ** is a temp table. If so, set the database to 1. Do not do this 2953 ** if initialising a database schema. 2954 */ 2955 if( !db->init.busy ){ 2956 pTab = sqlite3SrcListLookup(pParse, pTblName); 2957 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 2958 iDb = 1; 2959 } 2960 } 2961 #endif 2962 2963 sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 2964 if( sqlite3FixSrcList(&sFix, pTblName) ){ 2965 /* Because the parser constructs pTblName from a single identifier, 2966 ** sqlite3FixSrcList can never fail. */ 2967 assert(0); 2968 } 2969 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 2970 assert( db->mallocFailed==0 || pTab==0 ); 2971 if( pTab==0 ) goto exit_create_index; 2972 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 2973 sqlite3ErrorMsg(pParse, 2974 "cannot create a TEMP index on non-TEMP table \"%s\"", 2975 pTab->zName); 2976 goto exit_create_index; 2977 } 2978 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 2979 }else{ 2980 assert( pName==0 ); 2981 assert( pStart==0 ); 2982 pTab = pParse->pNewTable; 2983 if( !pTab ) goto exit_create_index; 2984 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2985 } 2986 pDb = &db->aDb[iDb]; 2987 2988 assert( pTab!=0 ); 2989 assert( pParse->nErr==0 ); 2990 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 2991 && db->init.busy==0 2992 #if SQLITE_USER_AUTHENTICATION 2993 && sqlite3UserAuthTable(pTab->zName)==0 2994 #endif 2995 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ 2996 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 2997 goto exit_create_index; 2998 } 2999 #ifndef SQLITE_OMIT_VIEW 3000 if( pTab->pSelect ){ 3001 sqlite3ErrorMsg(pParse, "views may not be indexed"); 3002 goto exit_create_index; 3003 } 3004 #endif 3005 #ifndef SQLITE_OMIT_VIRTUALTABLE 3006 if( IsVirtual(pTab) ){ 3007 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 3008 goto exit_create_index; 3009 } 3010 #endif 3011 3012 /* 3013 ** Find the name of the index. Make sure there is not already another 3014 ** index or table with the same name. 3015 ** 3016 ** Exception: If we are reading the names of permanent indices from the 3017 ** sqlite_master table (because some other process changed the schema) and 3018 ** one of the index names collides with the name of a temporary table or 3019 ** index, then we will continue to process this index. 3020 ** 3021 ** If pName==0 it means that we are 3022 ** dealing with a primary key or UNIQUE constraint. We have to invent our 3023 ** own name. 3024 */ 3025 if( pName ){ 3026 zName = sqlite3NameFromToken(db, pName); 3027 if( zName==0 ) goto exit_create_index; 3028 assert( pName->z!=0 ); 3029 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ 3030 goto exit_create_index; 3031 } 3032 if( !db->init.busy ){ 3033 if( sqlite3FindTable(db, zName, 0)!=0 ){ 3034 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 3035 goto exit_create_index; 3036 } 3037 } 3038 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){ 3039 if( !ifNotExist ){ 3040 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 3041 }else{ 3042 assert( !db->init.busy ); 3043 sqlite3CodeVerifySchema(pParse, iDb); 3044 } 3045 goto exit_create_index; 3046 } 3047 }else{ 3048 int n; 3049 Index *pLoop; 3050 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 3051 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 3052 if( zName==0 ){ 3053 goto exit_create_index; 3054 } 3055 } 3056 3057 /* Check for authorization to create an index. 3058 */ 3059 #ifndef SQLITE_OMIT_AUTHORIZATION 3060 { 3061 const char *zDb = pDb->zName; 3062 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 3063 goto exit_create_index; 3064 } 3065 i = SQLITE_CREATE_INDEX; 3066 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 3067 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 3068 goto exit_create_index; 3069 } 3070 } 3071 #endif 3072 3073 /* If pList==0, it means this routine was called to make a primary 3074 ** key out of the last column added to the table under construction. 3075 ** So create a fake list to simulate this. 3076 */ 3077 if( pList==0 ){ 3078 Token prevCol; 3079 prevCol.z = pTab->aCol[pTab->nCol-1].zName; 3080 prevCol.n = sqlite3Strlen30(prevCol.z); 3081 pList = sqlite3ExprListAppend(pParse, 0, 3082 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 3083 if( pList==0 ) goto exit_create_index; 3084 assert( pList->nExpr==1 ); 3085 sqlite3ExprListSetSortOrder(pList, sortOrder); 3086 }else{ 3087 sqlite3ExprListCheckLength(pParse, pList, "index"); 3088 } 3089 3090 /* Figure out how many bytes of space are required to store explicitly 3091 ** specified collation sequence names. 3092 */ 3093 for(i=0; i<pList->nExpr; i++){ 3094 Expr *pExpr = pList->a[i].pExpr; 3095 assert( pExpr!=0 ); 3096 if( pExpr->op==TK_COLLATE ){ 3097 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 3098 } 3099 } 3100 3101 /* 3102 ** Allocate the index structure. 3103 */ 3104 nName = sqlite3Strlen30(zName); 3105 nExtraCol = pPk ? pPk->nKeyCol : 1; 3106 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 3107 nName + nExtra + 1, &zExtra); 3108 if( db->mallocFailed ){ 3109 goto exit_create_index; 3110 } 3111 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 3112 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 3113 pIndex->zName = zExtra; 3114 zExtra += nName + 1; 3115 memcpy(pIndex->zName, zName, nName+1); 3116 pIndex->pTable = pTab; 3117 pIndex->onError = (u8)onError; 3118 pIndex->uniqNotNull = onError!=OE_None; 3119 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE; 3120 pIndex->pSchema = db->aDb[iDb].pSchema; 3121 pIndex->nKeyCol = pList->nExpr; 3122 if( pPIWhere ){ 3123 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 3124 pIndex->pPartIdxWhere = pPIWhere; 3125 pPIWhere = 0; 3126 } 3127 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3128 3129 /* Check to see if we should honor DESC requests on index columns 3130 */ 3131 if( pDb->pSchema->file_format>=4 ){ 3132 sortOrderMask = -1; /* Honor DESC */ 3133 }else{ 3134 sortOrderMask = 0; /* Ignore DESC */ 3135 } 3136 3137 /* Analyze the list of expressions that form the terms of the index and 3138 ** report any errors. In the common case where the expression is exactly 3139 ** a table column, store that column in aiColumn[]. For general expressions, 3140 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. 3141 ** 3142 ** TODO: Issue a warning if two or more columns of the index are identical. 3143 ** TODO: Issue a warning if the table primary key is used as part of the 3144 ** index key. 3145 */ 3146 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ 3147 Expr *pCExpr; /* The i-th index expression */ 3148 int requestedSortOrder; /* ASC or DESC on the i-th expression */ 3149 char *zColl; /* Collation sequence name */ 3150 3151 sqlite3StringToId(pListItem->pExpr); 3152 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 3153 if( pParse->nErr ) goto exit_create_index; 3154 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 3155 if( pCExpr->op!=TK_COLUMN ){ 3156 if( pTab==pParse->pNewTable ){ 3157 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " 3158 "UNIQUE constraints"); 3159 goto exit_create_index; 3160 } 3161 if( pIndex->aColExpr==0 ){ 3162 ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); 3163 pIndex->aColExpr = pCopy; 3164 if( !db->mallocFailed ){ 3165 assert( pCopy!=0 ); 3166 pListItem = &pCopy->a[i]; 3167 } 3168 } 3169 j = XN_EXPR; 3170 pIndex->aiColumn[i] = XN_EXPR; 3171 pIndex->uniqNotNull = 0; 3172 }else{ 3173 j = pCExpr->iColumn; 3174 assert( j<=0x7fff ); 3175 if( j<0 ){ 3176 j = pTab->iPKey; 3177 }else if( pTab->aCol[j].notNull==0 ){ 3178 pIndex->uniqNotNull = 0; 3179 } 3180 pIndex->aiColumn[i] = (i16)j; 3181 } 3182 zColl = 0; 3183 if( pListItem->pExpr->op==TK_COLLATE ){ 3184 int nColl; 3185 zColl = pListItem->pExpr->u.zToken; 3186 nColl = sqlite3Strlen30(zColl) + 1; 3187 assert( nExtra>=nColl ); 3188 memcpy(zExtra, zColl, nColl); 3189 zColl = zExtra; 3190 zExtra += nColl; 3191 nExtra -= nColl; 3192 }else if( j>=0 ){ 3193 zColl = pTab->aCol[j].zColl; 3194 } 3195 if( !zColl ) zColl = "BINARY"; 3196 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 3197 goto exit_create_index; 3198 } 3199 pIndex->azColl[i] = zColl; 3200 requestedSortOrder = pListItem->sortOrder & sortOrderMask; 3201 pIndex->aSortOrder[i] = (u8)requestedSortOrder; 3202 } 3203 3204 /* Append the table key to the end of the index. For WITHOUT ROWID 3205 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For 3206 ** normal tables (when pPk==0) this will be the rowid. 3207 */ 3208 if( pPk ){ 3209 for(j=0; j<pPk->nKeyCol; j++){ 3210 int x = pPk->aiColumn[j]; 3211 assert( x>=0 ); 3212 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ 3213 pIndex->nColumn--; 3214 }else{ 3215 pIndex->aiColumn[i] = x; 3216 pIndex->azColl[i] = pPk->azColl[j]; 3217 pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 3218 i++; 3219 } 3220 } 3221 assert( i==pIndex->nColumn ); 3222 }else{ 3223 pIndex->aiColumn[i] = XN_ROWID; 3224 pIndex->azColl[i] = "BINARY"; 3225 } 3226 sqlite3DefaultRowEst(pIndex); 3227 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 3228 3229 if( pTab==pParse->pNewTable ){ 3230 /* This routine has been called to create an automatic index as a 3231 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 3232 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 3233 ** i.e. one of: 3234 ** 3235 ** CREATE TABLE t(x PRIMARY KEY, y); 3236 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 3237 ** 3238 ** Either way, check to see if the table already has such an index. If 3239 ** so, don't bother creating this one. This only applies to 3240 ** automatically created indices. Users can do as they wish with 3241 ** explicit indices. 3242 ** 3243 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 3244 ** (and thus suppressing the second one) even if they have different 3245 ** sort orders. 3246 ** 3247 ** If there are different collating sequences or if the columns of 3248 ** the constraint occur in different orders, then the constraints are 3249 ** considered distinct and both result in separate indices. 3250 */ 3251 Index *pIdx; 3252 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3253 int k; 3254 assert( IsUniqueIndex(pIdx) ); 3255 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 3256 assert( IsUniqueIndex(pIndex) ); 3257 3258 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 3259 for(k=0; k<pIdx->nKeyCol; k++){ 3260 const char *z1; 3261 const char *z2; 3262 assert( pIdx->aiColumn[k]>=0 ); 3263 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 3264 z1 = pIdx->azColl[k]; 3265 z2 = pIndex->azColl[k]; 3266 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break; 3267 } 3268 if( k==pIdx->nKeyCol ){ 3269 if( pIdx->onError!=pIndex->onError ){ 3270 /* This constraint creates the same index as a previous 3271 ** constraint specified somewhere in the CREATE TABLE statement. 3272 ** However the ON CONFLICT clauses are different. If both this 3273 ** constraint and the previous equivalent constraint have explicit 3274 ** ON CONFLICT clauses this is an error. Otherwise, use the 3275 ** explicitly specified behavior for the index. 3276 */ 3277 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 3278 sqlite3ErrorMsg(pParse, 3279 "conflicting ON CONFLICT clauses specified", 0); 3280 } 3281 if( pIdx->onError==OE_Default ){ 3282 pIdx->onError = pIndex->onError; 3283 } 3284 } 3285 pRet = pIdx; 3286 goto exit_create_index; 3287 } 3288 } 3289 } 3290 3291 /* Link the new Index structure to its table and to the other 3292 ** in-memory database structures. 3293 */ 3294 assert( pParse->nErr==0 ); 3295 if( db->init.busy ){ 3296 Index *p; 3297 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 3298 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 3299 pIndex->zName, pIndex); 3300 if( p ){ 3301 assert( p==pIndex ); /* Malloc must have failed */ 3302 db->mallocFailed = 1; 3303 goto exit_create_index; 3304 } 3305 db->flags |= SQLITE_InternChanges; 3306 if( pTblName!=0 ){ 3307 pIndex->tnum = db->init.newTnum; 3308 } 3309 } 3310 3311 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 3312 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 3313 ** emit code to allocate the index rootpage on disk and make an entry for 3314 ** the index in the sqlite_master table and populate the index with 3315 ** content. But, do not do this if we are simply reading the sqlite_master 3316 ** table to parse the schema, or if this index is the PRIMARY KEY index 3317 ** of a WITHOUT ROWID table. 3318 ** 3319 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 3320 ** or UNIQUE index in a CREATE TABLE statement. Since the table 3321 ** has just been created, it contains no data and the index initialization 3322 ** step can be skipped. 3323 */ 3324 else if( HasRowid(pTab) || pTblName!=0 ){ 3325 Vdbe *v; 3326 char *zStmt; 3327 int iMem = ++pParse->nMem; 3328 3329 v = sqlite3GetVdbe(pParse); 3330 if( v==0 ) goto exit_create_index; 3331 3332 sqlite3BeginWriteOperation(pParse, 1, iDb); 3333 3334 /* Create the rootpage for the index using CreateIndex. But before 3335 ** doing so, code a Noop instruction and store its address in 3336 ** Index.tnum. This is required in case this index is actually a 3337 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 3338 ** that case the convertToWithoutRowidTable() routine will replace 3339 ** the Noop with a Goto to jump over the VDBE code generated below. */ 3340 pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); 3341 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); 3342 3343 /* Gather the complete text of the CREATE INDEX statement into 3344 ** the zStmt variable 3345 */ 3346 if( pStart ){ 3347 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 3348 if( pName->z[n-1]==';' ) n--; 3349 /* A named index with an explicit CREATE INDEX statement */ 3350 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 3351 onError==OE_None ? "" : " UNIQUE", n, pName->z); 3352 }else{ 3353 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 3354 /* zStmt = sqlite3MPrintf(""); */ 3355 zStmt = 0; 3356 } 3357 3358 /* Add an entry in sqlite_master for this index 3359 */ 3360 sqlite3NestedParse(pParse, 3361 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", 3362 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), 3363 pIndex->zName, 3364 pTab->zName, 3365 iMem, 3366 zStmt 3367 ); 3368 sqlite3DbFree(db, zStmt); 3369 3370 /* Fill the index with data and reparse the schema. Code an OP_Expire 3371 ** to invalidate all pre-compiled statements. 3372 */ 3373 if( pTblName ){ 3374 sqlite3RefillIndex(pParse, pIndex, iMem); 3375 sqlite3ChangeCookie(pParse, iDb); 3376 sqlite3VdbeAddParseSchemaOp(v, iDb, 3377 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); 3378 sqlite3VdbeAddOp1(v, OP_Expire, 0); 3379 } 3380 3381 sqlite3VdbeJumpHere(v, pIndex->tnum); 3382 } 3383 3384 /* When adding an index to the list of indices for a table, make 3385 ** sure all indices labeled OE_Replace come after all those labeled 3386 ** OE_Ignore. This is necessary for the correct constraint check 3387 ** processing (in sqlite3GenerateConstraintChecks()) as part of 3388 ** UPDATE and INSERT statements. 3389 */ 3390 if( db->init.busy || pTblName==0 ){ 3391 if( onError!=OE_Replace || pTab->pIndex==0 3392 || pTab->pIndex->onError==OE_Replace){ 3393 pIndex->pNext = pTab->pIndex; 3394 pTab->pIndex = pIndex; 3395 }else{ 3396 Index *pOther = pTab->pIndex; 3397 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ 3398 pOther = pOther->pNext; 3399 } 3400 pIndex->pNext = pOther->pNext; 3401 pOther->pNext = pIndex; 3402 } 3403 pRet = pIndex; 3404 pIndex = 0; 3405 } 3406 3407 /* Clean up before exiting */ 3408 exit_create_index: 3409 if( pIndex ) freeIndex(db, pIndex); 3410 sqlite3ExprDelete(db, pPIWhere); 3411 sqlite3ExprListDelete(db, pList); 3412 sqlite3SrcListDelete(db, pTblName); 3413 sqlite3DbFree(db, zName); 3414 return pRet; 3415 } 3416 3417 /* 3418 ** Fill the Index.aiRowEst[] array with default information - information 3419 ** to be used when we have not run the ANALYZE command. 3420 ** 3421 ** aiRowEst[0] is supposed to contain the number of elements in the index. 3422 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 3423 ** number of rows in the table that match any particular value of the 3424 ** first column of the index. aiRowEst[2] is an estimate of the number 3425 ** of rows that match any particular combination of the first 2 columns 3426 ** of the index. And so forth. It must always be the case that 3427 * 3428 ** aiRowEst[N]<=aiRowEst[N-1] 3429 ** aiRowEst[N]>=1 3430 ** 3431 ** Apart from that, we have little to go on besides intuition as to 3432 ** how aiRowEst[] should be initialized. The numbers generated here 3433 ** are based on typical values found in actual indices. 3434 */ 3435 void sqlite3DefaultRowEst(Index *pIdx){ 3436 /* 10, 9, 8, 7, 6 */ 3437 LogEst aVal[] = { 33, 32, 30, 28, 26 }; 3438 LogEst *a = pIdx->aiRowLogEst; 3439 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 3440 int i; 3441 3442 /* Set the first entry (number of rows in the index) to the estimated 3443 ** number of rows in the table. Or 10, if the estimated number of rows 3444 ** in the table is less than that. */ 3445 a[0] = pIdx->pTable->nRowLogEst; 3446 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); 3447 3448 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 3449 ** 6 and each subsequent value (if any) is 5. */ 3450 memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 3451 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 3452 a[i] = 23; assert( 23==sqlite3LogEst(5) ); 3453 } 3454 3455 assert( 0==sqlite3LogEst(1) ); 3456 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 3457 } 3458 3459 /* 3460 ** This routine will drop an existing named index. This routine 3461 ** implements the DROP INDEX statement. 3462 */ 3463 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 3464 Index *pIndex; 3465 Vdbe *v; 3466 sqlite3 *db = pParse->db; 3467 int iDb; 3468 3469 assert( pParse->nErr==0 ); /* Never called with prior errors */ 3470 if( db->mallocFailed ){ 3471 goto exit_drop_index; 3472 } 3473 assert( pName->nSrc==1 ); 3474 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3475 goto exit_drop_index; 3476 } 3477 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 3478 if( pIndex==0 ){ 3479 if( !ifExists ){ 3480 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); 3481 }else{ 3482 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 3483 } 3484 pParse->checkSchema = 1; 3485 goto exit_drop_index; 3486 } 3487 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 3488 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 3489 "or PRIMARY KEY constraint cannot be dropped", 0); 3490 goto exit_drop_index; 3491 } 3492 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3493 #ifndef SQLITE_OMIT_AUTHORIZATION 3494 { 3495 int code = SQLITE_DROP_INDEX; 3496 Table *pTab = pIndex->pTable; 3497 const char *zDb = db->aDb[iDb].zName; 3498 const char *zTab = SCHEMA_TABLE(iDb); 3499 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 3500 goto exit_drop_index; 3501 } 3502 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; 3503 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 3504 goto exit_drop_index; 3505 } 3506 } 3507 #endif 3508 3509 /* Generate code to remove the index and from the master table */ 3510 v = sqlite3GetVdbe(pParse); 3511 if( v ){ 3512 sqlite3BeginWriteOperation(pParse, 1, iDb); 3513 sqlite3NestedParse(pParse, 3514 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", 3515 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName 3516 ); 3517 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 3518 sqlite3ChangeCookie(pParse, iDb); 3519 destroyRootPage(pParse, pIndex->tnum, iDb); 3520 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 3521 } 3522 3523 exit_drop_index: 3524 sqlite3SrcListDelete(db, pName); 3525 } 3526 3527 /* 3528 ** pArray is a pointer to an array of objects. Each object in the 3529 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 3530 ** to extend the array so that there is space for a new object at the end. 3531 ** 3532 ** When this function is called, *pnEntry contains the current size of 3533 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 3534 ** in total). 3535 ** 3536 ** If the realloc() is successful (i.e. if no OOM condition occurs), the 3537 ** space allocated for the new object is zeroed, *pnEntry updated to 3538 ** reflect the new size of the array and a pointer to the new allocation 3539 ** returned. *pIdx is set to the index of the new array entry in this case. 3540 ** 3541 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 3542 ** unchanged and a copy of pArray returned. 3543 */ 3544 void *sqlite3ArrayAllocate( 3545 sqlite3 *db, /* Connection to notify of malloc failures */ 3546 void *pArray, /* Array of objects. Might be reallocated */ 3547 int szEntry, /* Size of each object in the array */ 3548 int *pnEntry, /* Number of objects currently in use */ 3549 int *pIdx /* Write the index of a new slot here */ 3550 ){ 3551 char *z; 3552 int n = *pnEntry; 3553 if( (n & (n-1))==0 ){ 3554 int sz = (n==0) ? 1 : 2*n; 3555 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 3556 if( pNew==0 ){ 3557 *pIdx = -1; 3558 return pArray; 3559 } 3560 pArray = pNew; 3561 } 3562 z = (char*)pArray; 3563 memset(&z[n * szEntry], 0, szEntry); 3564 *pIdx = n; 3565 ++*pnEntry; 3566 return pArray; 3567 } 3568 3569 /* 3570 ** Append a new element to the given IdList. Create a new IdList if 3571 ** need be. 3572 ** 3573 ** A new IdList is returned, or NULL if malloc() fails. 3574 */ 3575 IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ 3576 int i; 3577 if( pList==0 ){ 3578 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 3579 if( pList==0 ) return 0; 3580 } 3581 pList->a = sqlite3ArrayAllocate( 3582 db, 3583 pList->a, 3584 sizeof(pList->a[0]), 3585 &pList->nId, 3586 &i 3587 ); 3588 if( i<0 ){ 3589 sqlite3IdListDelete(db, pList); 3590 return 0; 3591 } 3592 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 3593 return pList; 3594 } 3595 3596 /* 3597 ** Delete an IdList. 3598 */ 3599 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 3600 int i; 3601 if( pList==0 ) return; 3602 for(i=0; i<pList->nId; i++){ 3603 sqlite3DbFree(db, pList->a[i].zName); 3604 } 3605 sqlite3DbFree(db, pList->a); 3606 sqlite3DbFree(db, pList); 3607 } 3608 3609 /* 3610 ** Return the index in pList of the identifier named zId. Return -1 3611 ** if not found. 3612 */ 3613 int sqlite3IdListIndex(IdList *pList, const char *zName){ 3614 int i; 3615 if( pList==0 ) return -1; 3616 for(i=0; i<pList->nId; i++){ 3617 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 3618 } 3619 return -1; 3620 } 3621 3622 /* 3623 ** Expand the space allocated for the given SrcList object by 3624 ** creating nExtra new slots beginning at iStart. iStart is zero based. 3625 ** New slots are zeroed. 3626 ** 3627 ** For example, suppose a SrcList initially contains two entries: A,B. 3628 ** To append 3 new entries onto the end, do this: 3629 ** 3630 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 3631 ** 3632 ** After the call above it would contain: A, B, nil, nil, nil. 3633 ** If the iStart argument had been 1 instead of 2, then the result 3634 ** would have been: A, nil, nil, nil, B. To prepend the new slots, 3635 ** the iStart value would be 0. The result then would 3636 ** be: nil, nil, nil, A, B. 3637 ** 3638 ** If a memory allocation fails the SrcList is unchanged. The 3639 ** db->mallocFailed flag will be set to true. 3640 */ 3641 SrcList *sqlite3SrcListEnlarge( 3642 sqlite3 *db, /* Database connection to notify of OOM errors */ 3643 SrcList *pSrc, /* The SrcList to be enlarged */ 3644 int nExtra, /* Number of new slots to add to pSrc->a[] */ 3645 int iStart /* Index in pSrc->a[] of first new slot */ 3646 ){ 3647 int i; 3648 3649 /* Sanity checking on calling parameters */ 3650 assert( iStart>=0 ); 3651 assert( nExtra>=1 ); 3652 assert( pSrc!=0 ); 3653 assert( iStart<=pSrc->nSrc ); 3654 3655 /* Allocate additional space if needed */ 3656 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 3657 SrcList *pNew; 3658 int nAlloc = pSrc->nSrc+nExtra; 3659 int nGot; 3660 pNew = sqlite3DbRealloc(db, pSrc, 3661 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 3662 if( pNew==0 ){ 3663 assert( db->mallocFailed ); 3664 return pSrc; 3665 } 3666 pSrc = pNew; 3667 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; 3668 pSrc->nAlloc = nGot; 3669 } 3670 3671 /* Move existing slots that come after the newly inserted slots 3672 ** out of the way */ 3673 for(i=pSrc->nSrc-1; i>=iStart; i--){ 3674 pSrc->a[i+nExtra] = pSrc->a[i]; 3675 } 3676 pSrc->nSrc += nExtra; 3677 3678 /* Zero the newly allocated slots */ 3679 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 3680 for(i=iStart; i<iStart+nExtra; i++){ 3681 pSrc->a[i].iCursor = -1; 3682 } 3683 3684 /* Return a pointer to the enlarged SrcList */ 3685 return pSrc; 3686 } 3687 3688 3689 /* 3690 ** Append a new table name to the given SrcList. Create a new SrcList if 3691 ** need be. A new entry is created in the SrcList even if pTable is NULL. 3692 ** 3693 ** A SrcList is returned, or NULL if there is an OOM error. The returned 3694 ** SrcList might be the same as the SrcList that was input or it might be 3695 ** a new one. If an OOM error does occurs, then the prior value of pList 3696 ** that is input to this routine is automatically freed. 3697 ** 3698 ** If pDatabase is not null, it means that the table has an optional 3699 ** database name prefix. Like this: "database.table". The pDatabase 3700 ** points to the table name and the pTable points to the database name. 3701 ** The SrcList.a[].zName field is filled with the table name which might 3702 ** come from pTable (if pDatabase is NULL) or from pDatabase. 3703 ** SrcList.a[].zDatabase is filled with the database name from pTable, 3704 ** or with NULL if no database is specified. 3705 ** 3706 ** In other words, if call like this: 3707 ** 3708 ** sqlite3SrcListAppend(D,A,B,0); 3709 ** 3710 ** Then B is a table name and the database name is unspecified. If called 3711 ** like this: 3712 ** 3713 ** sqlite3SrcListAppend(D,A,B,C); 3714 ** 3715 ** Then C is the table name and B is the database name. If C is defined 3716 ** then so is B. In other words, we never have a case where: 3717 ** 3718 ** sqlite3SrcListAppend(D,A,0,C); 3719 ** 3720 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 3721 ** before being added to the SrcList. 3722 */ 3723 SrcList *sqlite3SrcListAppend( 3724 sqlite3 *db, /* Connection to notify of malloc failures */ 3725 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 3726 Token *pTable, /* Table to append */ 3727 Token *pDatabase /* Database of the table */ 3728 ){ 3729 struct SrcList_item *pItem; 3730 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 3731 if( pList==0 ){ 3732 pList = sqlite3DbMallocZero(db, sizeof(SrcList) ); 3733 if( pList==0 ) return 0; 3734 pList->nAlloc = 1; 3735 } 3736 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); 3737 if( db->mallocFailed ){ 3738 sqlite3SrcListDelete(db, pList); 3739 return 0; 3740 } 3741 pItem = &pList->a[pList->nSrc-1]; 3742 if( pDatabase && pDatabase->z==0 ){ 3743 pDatabase = 0; 3744 } 3745 if( pDatabase ){ 3746 Token *pTemp = pDatabase; 3747 pDatabase = pTable; 3748 pTable = pTemp; 3749 } 3750 pItem->zName = sqlite3NameFromToken(db, pTable); 3751 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); 3752 return pList; 3753 } 3754 3755 /* 3756 ** Assign VdbeCursor index numbers to all tables in a SrcList 3757 */ 3758 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 3759 int i; 3760 struct SrcList_item *pItem; 3761 assert(pList || pParse->db->mallocFailed ); 3762 if( pList ){ 3763 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 3764 if( pItem->iCursor>=0 ) break; 3765 pItem->iCursor = pParse->nTab++; 3766 if( pItem->pSelect ){ 3767 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 3768 } 3769 } 3770 } 3771 } 3772 3773 /* 3774 ** Delete an entire SrcList including all its substructure. 3775 */ 3776 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 3777 int i; 3778 struct SrcList_item *pItem; 3779 if( pList==0 ) return; 3780 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 3781 sqlite3DbFree(db, pItem->zDatabase); 3782 sqlite3DbFree(db, pItem->zName); 3783 sqlite3DbFree(db, pItem->zAlias); 3784 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 3785 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 3786 sqlite3DeleteTable(db, pItem->pTab); 3787 sqlite3SelectDelete(db, pItem->pSelect); 3788 sqlite3ExprDelete(db, pItem->pOn); 3789 sqlite3IdListDelete(db, pItem->pUsing); 3790 } 3791 sqlite3DbFree(db, pList); 3792 } 3793 3794 /* 3795 ** This routine is called by the parser to add a new term to the 3796 ** end of a growing FROM clause. The "p" parameter is the part of 3797 ** the FROM clause that has already been constructed. "p" is NULL 3798 ** if this is the first term of the FROM clause. pTable and pDatabase 3799 ** are the name of the table and database named in the FROM clause term. 3800 ** pDatabase is NULL if the database name qualifier is missing - the 3801 ** usual case. If the term has an alias, then pAlias points to the 3802 ** alias token. If the term is a subquery, then pSubquery is the 3803 ** SELECT statement that the subquery encodes. The pTable and 3804 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 3805 ** parameters are the content of the ON and USING clauses. 3806 ** 3807 ** Return a new SrcList which encodes is the FROM with the new 3808 ** term added. 3809 */ 3810 SrcList *sqlite3SrcListAppendFromTerm( 3811 Parse *pParse, /* Parsing context */ 3812 SrcList *p, /* The left part of the FROM clause already seen */ 3813 Token *pTable, /* Name of the table to add to the FROM clause */ 3814 Token *pDatabase, /* Name of the database containing pTable */ 3815 Token *pAlias, /* The right-hand side of the AS subexpression */ 3816 Select *pSubquery, /* A subquery used in place of a table name */ 3817 Expr *pOn, /* The ON clause of a join */ 3818 IdList *pUsing /* The USING clause of a join */ 3819 ){ 3820 struct SrcList_item *pItem; 3821 sqlite3 *db = pParse->db; 3822 if( !p && (pOn || pUsing) ){ 3823 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 3824 (pOn ? "ON" : "USING") 3825 ); 3826 goto append_from_error; 3827 } 3828 p = sqlite3SrcListAppend(db, p, pTable, pDatabase); 3829 if( p==0 || NEVER(p->nSrc==0) ){ 3830 goto append_from_error; 3831 } 3832 pItem = &p->a[p->nSrc-1]; 3833 assert( pAlias!=0 ); 3834 if( pAlias->n ){ 3835 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 3836 } 3837 pItem->pSelect = pSubquery; 3838 pItem->pOn = pOn; 3839 pItem->pUsing = pUsing; 3840 return p; 3841 3842 append_from_error: 3843 assert( p==0 ); 3844 sqlite3ExprDelete(db, pOn); 3845 sqlite3IdListDelete(db, pUsing); 3846 sqlite3SelectDelete(db, pSubquery); 3847 return 0; 3848 } 3849 3850 /* 3851 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 3852 ** element of the source-list passed as the second argument. 3853 */ 3854 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 3855 assert( pIndexedBy!=0 ); 3856 if( p && ALWAYS(p->nSrc>0) ){ 3857 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 3858 assert( pItem->fg.notIndexed==0 ); 3859 assert( pItem->fg.isIndexedBy==0 ); 3860 assert( pItem->fg.isTabFunc==0 ); 3861 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 3862 /* A "NOT INDEXED" clause was supplied. See parse.y 3863 ** construct "indexed_opt" for details. */ 3864 pItem->fg.notIndexed = 1; 3865 }else{ 3866 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 3867 pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); 3868 } 3869 } 3870 } 3871 3872 /* 3873 ** Add the list of function arguments to the SrcList entry for a 3874 ** table-valued-function. 3875 */ 3876 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 3877 if( p && pList ){ 3878 struct SrcList_item *pItem = &p->a[p->nSrc-1]; 3879 assert( pItem->fg.notIndexed==0 ); 3880 assert( pItem->fg.isIndexedBy==0 ); 3881 assert( pItem->fg.isTabFunc==0 ); 3882 pItem->u1.pFuncArg = pList; 3883 pItem->fg.isTabFunc = 1; 3884 }else{ 3885 sqlite3ExprListDelete(pParse->db, pList); 3886 } 3887 } 3888 3889 /* 3890 ** When building up a FROM clause in the parser, the join operator 3891 ** is initially attached to the left operand. But the code generator 3892 ** expects the join operator to be on the right operand. This routine 3893 ** Shifts all join operators from left to right for an entire FROM 3894 ** clause. 3895 ** 3896 ** Example: Suppose the join is like this: 3897 ** 3898 ** A natural cross join B 3899 ** 3900 ** The operator is "natural cross join". The A and B operands are stored 3901 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 3902 ** operator with A. This routine shifts that operator over to B. 3903 */ 3904 void sqlite3SrcListShiftJoinType(SrcList *p){ 3905 if( p ){ 3906 int i; 3907 for(i=p->nSrc-1; i>0; i--){ 3908 p->a[i].fg.jointype = p->a[i-1].fg.jointype; 3909 } 3910 p->a[0].fg.jointype = 0; 3911 } 3912 } 3913 3914 /* 3915 ** Begin a transaction 3916 */ 3917 void sqlite3BeginTransaction(Parse *pParse, int type){ 3918 sqlite3 *db; 3919 Vdbe *v; 3920 int i; 3921 3922 assert( pParse!=0 ); 3923 db = pParse->db; 3924 assert( db!=0 ); 3925 /* if( db->aDb[0].pBt==0 ) return; */ 3926 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 3927 return; 3928 } 3929 v = sqlite3GetVdbe(pParse); 3930 if( !v ) return; 3931 if( type!=TK_DEFERRED ){ 3932 for(i=0; i<db->nDb; i++){ 3933 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); 3934 sqlite3VdbeUsesBtree(v, i); 3935 } 3936 } 3937 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); 3938 } 3939 3940 /* 3941 ** Commit a transaction 3942 */ 3943 void sqlite3CommitTransaction(Parse *pParse){ 3944 Vdbe *v; 3945 3946 assert( pParse!=0 ); 3947 assert( pParse->db!=0 ); 3948 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ 3949 return; 3950 } 3951 v = sqlite3GetVdbe(pParse); 3952 if( v ){ 3953 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); 3954 } 3955 } 3956 3957 /* 3958 ** Rollback a transaction 3959 */ 3960 void sqlite3RollbackTransaction(Parse *pParse){ 3961 Vdbe *v; 3962 3963 assert( pParse!=0 ); 3964 assert( pParse->db!=0 ); 3965 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ 3966 return; 3967 } 3968 v = sqlite3GetVdbe(pParse); 3969 if( v ){ 3970 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); 3971 } 3972 } 3973 3974 /* 3975 ** This function is called by the parser when it parses a command to create, 3976 ** release or rollback an SQL savepoint. 3977 */ 3978 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 3979 char *zName = sqlite3NameFromToken(pParse->db, pName); 3980 if( zName ){ 3981 Vdbe *v = sqlite3GetVdbe(pParse); 3982 #ifndef SQLITE_OMIT_AUTHORIZATION 3983 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 3984 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 3985 #endif 3986 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 3987 sqlite3DbFree(pParse->db, zName); 3988 return; 3989 } 3990 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 3991 } 3992 } 3993 3994 /* 3995 ** Make sure the TEMP database is open and available for use. Return 3996 ** the number of errors. Leave any error messages in the pParse structure. 3997 */ 3998 int sqlite3OpenTempDatabase(Parse *pParse){ 3999 sqlite3 *db = pParse->db; 4000 if( db->aDb[1].pBt==0 && !pParse->explain ){ 4001 int rc; 4002 Btree *pBt; 4003 static const int flags = 4004 SQLITE_OPEN_READWRITE | 4005 SQLITE_OPEN_CREATE | 4006 SQLITE_OPEN_EXCLUSIVE | 4007 SQLITE_OPEN_DELETEONCLOSE | 4008 SQLITE_OPEN_TEMP_DB; 4009 4010 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 4011 if( rc!=SQLITE_OK ){ 4012 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 4013 "file for storing temporary tables"); 4014 pParse->rc = rc; 4015 return 1; 4016 } 4017 db->aDb[1].pBt = pBt; 4018 assert( db->aDb[1].pSchema ); 4019 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ 4020 db->mallocFailed = 1; 4021 return 1; 4022 } 4023 } 4024 return 0; 4025 } 4026 4027 /* 4028 ** Record the fact that the schema cookie will need to be verified 4029 ** for database iDb. The code to actually verify the schema cookie 4030 ** will occur at the end of the top-level VDBE and will be generated 4031 ** later, by sqlite3FinishCoding(). 4032 */ 4033 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 4034 Parse *pToplevel = sqlite3ParseToplevel(pParse); 4035 sqlite3 *db = pToplevel->db; 4036 4037 assert( iDb>=0 && iDb<db->nDb ); 4038 assert( db->aDb[iDb].pBt!=0 || iDb==1 ); 4039 assert( iDb<SQLITE_MAX_ATTACHED+2 ); 4040 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 4041 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 4042 DbMaskSet(pToplevel->cookieMask, iDb); 4043 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie; 4044 if( !OMIT_TEMPDB && iDb==1 ){ 4045 sqlite3OpenTempDatabase(pToplevel); 4046 } 4047 } 4048 } 4049 4050 /* 4051 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 4052 ** attached database. Otherwise, invoke it for the database named zDb only. 4053 */ 4054 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 4055 sqlite3 *db = pParse->db; 4056 int i; 4057 for(i=0; i<db->nDb; i++){ 4058 Db *pDb = &db->aDb[i]; 4059 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){ 4060 sqlite3CodeVerifySchema(pParse, i); 4061 } 4062 } 4063 } 4064 4065 /* 4066 ** Generate VDBE code that prepares for doing an operation that 4067 ** might change the database. 4068 ** 4069 ** This routine starts a new transaction if we are not already within 4070 ** a transaction. If we are already within a transaction, then a checkpoint 4071 ** is set if the setStatement parameter is true. A checkpoint should 4072 ** be set for operations that might fail (due to a constraint) part of 4073 ** the way through and which will need to undo some writes without having to 4074 ** rollback the whole transaction. For operations where all constraints 4075 ** can be checked before any changes are made to the database, it is never 4076 ** necessary to undo a write and the checkpoint should not be set. 4077 */ 4078 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 4079 Parse *pToplevel = sqlite3ParseToplevel(pParse); 4080 sqlite3CodeVerifySchema(pParse, iDb); 4081 DbMaskSet(pToplevel->writeMask, iDb); 4082 pToplevel->isMultiWrite |= setStatement; 4083 } 4084 4085 /* 4086 ** Indicate that the statement currently under construction might write 4087 ** more than one entry (example: deleting one row then inserting another, 4088 ** inserting multiple rows in a table, or inserting a row and index entries.) 4089 ** If an abort occurs after some of these writes have completed, then it will 4090 ** be necessary to undo the completed writes. 4091 */ 4092 void sqlite3MultiWrite(Parse *pParse){ 4093 Parse *pToplevel = sqlite3ParseToplevel(pParse); 4094 pToplevel->isMultiWrite = 1; 4095 } 4096 4097 /* 4098 ** The code generator calls this routine if is discovers that it is 4099 ** possible to abort a statement prior to completion. In order to 4100 ** perform this abort without corrupting the database, we need to make 4101 ** sure that the statement is protected by a statement transaction. 4102 ** 4103 ** Technically, we only need to set the mayAbort flag if the 4104 ** isMultiWrite flag was previously set. There is a time dependency 4105 ** such that the abort must occur after the multiwrite. This makes 4106 ** some statements involving the REPLACE conflict resolution algorithm 4107 ** go a little faster. But taking advantage of this time dependency 4108 ** makes it more difficult to prove that the code is correct (in 4109 ** particular, it prevents us from writing an effective 4110 ** implementation of sqlite3AssertMayAbort()) and so we have chosen 4111 ** to take the safe route and skip the optimization. 4112 */ 4113 void sqlite3MayAbort(Parse *pParse){ 4114 Parse *pToplevel = sqlite3ParseToplevel(pParse); 4115 pToplevel->mayAbort = 1; 4116 } 4117 4118 /* 4119 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 4120 ** error. The onError parameter determines which (if any) of the statement 4121 ** and/or current transaction is rolled back. 4122 */ 4123 void sqlite3HaltConstraint( 4124 Parse *pParse, /* Parsing context */ 4125 int errCode, /* extended error code */ 4126 int onError, /* Constraint type */ 4127 char *p4, /* Error message */ 4128 i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 4129 u8 p5Errmsg /* P5_ErrMsg type */ 4130 ){ 4131 Vdbe *v = sqlite3GetVdbe(pParse); 4132 assert( (errCode&0xff)==SQLITE_CONSTRAINT ); 4133 if( onError==OE_Abort ){ 4134 sqlite3MayAbort(pParse); 4135 } 4136 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 4137 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg); 4138 } 4139 4140 /* 4141 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 4142 */ 4143 void sqlite3UniqueConstraint( 4144 Parse *pParse, /* Parsing context */ 4145 int onError, /* Constraint type */ 4146 Index *pIdx /* The index that triggers the constraint */ 4147 ){ 4148 char *zErr; 4149 int j; 4150 StrAccum errMsg; 4151 Table *pTab = pIdx->pTable; 4152 4153 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); 4154 if( pIdx->aColExpr ){ 4155 sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName); 4156 }else{ 4157 for(j=0; j<pIdx->nKeyCol; j++){ 4158 char *zCol; 4159 assert( pIdx->aiColumn[j]>=0 ); 4160 zCol = pTab->aCol[pIdx->aiColumn[j]].zName; 4161 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); 4162 sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol); 4163 } 4164 } 4165 zErr = sqlite3StrAccumFinish(&errMsg); 4166 sqlite3HaltConstraint(pParse, 4167 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 4168 : SQLITE_CONSTRAINT_UNIQUE, 4169 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 4170 } 4171 4172 4173 /* 4174 ** Code an OP_Halt due to non-unique rowid. 4175 */ 4176 void sqlite3RowidConstraint( 4177 Parse *pParse, /* Parsing context */ 4178 int onError, /* Conflict resolution algorithm */ 4179 Table *pTab /* The table with the non-unique rowid */ 4180 ){ 4181 char *zMsg; 4182 int rc; 4183 if( pTab->iPKey>=0 ){ 4184 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 4185 pTab->aCol[pTab->iPKey].zName); 4186 rc = SQLITE_CONSTRAINT_PRIMARYKEY; 4187 }else{ 4188 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 4189 rc = SQLITE_CONSTRAINT_ROWID; 4190 } 4191 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 4192 P5_ConstraintUnique); 4193 } 4194 4195 /* 4196 ** Check to see if pIndex uses the collating sequence pColl. Return 4197 ** true if it does and false if it does not. 4198 */ 4199 #ifndef SQLITE_OMIT_REINDEX 4200 static int collationMatch(const char *zColl, Index *pIndex){ 4201 int i; 4202 assert( zColl!=0 ); 4203 for(i=0; i<pIndex->nColumn; i++){ 4204 const char *z = pIndex->azColl[i]; 4205 assert( z!=0 || pIndex->aiColumn[i]<0 ); 4206 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 4207 return 1; 4208 } 4209 } 4210 return 0; 4211 } 4212 #endif 4213 4214 /* 4215 ** Recompute all indices of pTab that use the collating sequence pColl. 4216 ** If pColl==0 then recompute all indices of pTab. 4217 */ 4218 #ifndef SQLITE_OMIT_REINDEX 4219 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 4220 Index *pIndex; /* An index associated with pTab */ 4221 4222 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 4223 if( zColl==0 || collationMatch(zColl, pIndex) ){ 4224 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 4225 sqlite3BeginWriteOperation(pParse, 0, iDb); 4226 sqlite3RefillIndex(pParse, pIndex, -1); 4227 } 4228 } 4229 } 4230 #endif 4231 4232 /* 4233 ** Recompute all indices of all tables in all databases where the 4234 ** indices use the collating sequence pColl. If pColl==0 then recompute 4235 ** all indices everywhere. 4236 */ 4237 #ifndef SQLITE_OMIT_REINDEX 4238 static void reindexDatabases(Parse *pParse, char const *zColl){ 4239 Db *pDb; /* A single database */ 4240 int iDb; /* The database index number */ 4241 sqlite3 *db = pParse->db; /* The database connection */ 4242 HashElem *k; /* For looping over tables in pDb */ 4243 Table *pTab; /* A table in the database */ 4244 4245 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 4246 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 4247 assert( pDb!=0 ); 4248 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 4249 pTab = (Table*)sqliteHashData(k); 4250 reindexTable(pParse, pTab, zColl); 4251 } 4252 } 4253 } 4254 #endif 4255 4256 /* 4257 ** Generate code for the REINDEX command. 4258 ** 4259 ** REINDEX -- 1 4260 ** REINDEX <collation> -- 2 4261 ** REINDEX ?<database>.?<tablename> -- 3 4262 ** REINDEX ?<database>.?<indexname> -- 4 4263 ** 4264 ** Form 1 causes all indices in all attached databases to be rebuilt. 4265 ** Form 2 rebuilds all indices in all databases that use the named 4266 ** collating function. Forms 3 and 4 rebuild the named index or all 4267 ** indices associated with the named table. 4268 */ 4269 #ifndef SQLITE_OMIT_REINDEX 4270 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 4271 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 4272 char *z; /* Name of a table or index */ 4273 const char *zDb; /* Name of the database */ 4274 Table *pTab; /* A table in the database */ 4275 Index *pIndex; /* An index associated with pTab */ 4276 int iDb; /* The database index number */ 4277 sqlite3 *db = pParse->db; /* The database connection */ 4278 Token *pObjName; /* Name of the table or index to be reindexed */ 4279 4280 /* Read the database schema. If an error occurs, leave an error message 4281 ** and code in pParse and return NULL. */ 4282 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 4283 return; 4284 } 4285 4286 if( pName1==0 ){ 4287 reindexDatabases(pParse, 0); 4288 return; 4289 }else if( NEVER(pName2==0) || pName2->z==0 ){ 4290 char *zColl; 4291 assert( pName1->z ); 4292 zColl = sqlite3NameFromToken(pParse->db, pName1); 4293 if( !zColl ) return; 4294 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 4295 if( pColl ){ 4296 reindexDatabases(pParse, zColl); 4297 sqlite3DbFree(db, zColl); 4298 return; 4299 } 4300 sqlite3DbFree(db, zColl); 4301 } 4302 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 4303 if( iDb<0 ) return; 4304 z = sqlite3NameFromToken(db, pObjName); 4305 if( z==0 ) return; 4306 zDb = db->aDb[iDb].zName; 4307 pTab = sqlite3FindTable(db, z, zDb); 4308 if( pTab ){ 4309 reindexTable(pParse, pTab, 0); 4310 sqlite3DbFree(db, z); 4311 return; 4312 } 4313 pIndex = sqlite3FindIndex(db, z, zDb); 4314 sqlite3DbFree(db, z); 4315 if( pIndex ){ 4316 sqlite3BeginWriteOperation(pParse, 0, iDb); 4317 sqlite3RefillIndex(pParse, pIndex, -1); 4318 return; 4319 } 4320 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 4321 } 4322 #endif 4323 4324 /* 4325 ** Return a KeyInfo structure that is appropriate for the given Index. 4326 ** 4327 ** The KeyInfo structure for an index is cached in the Index object. 4328 ** So there might be multiple references to the returned pointer. The 4329 ** caller should not try to modify the KeyInfo object. 4330 ** 4331 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 4332 ** when it has finished using it. 4333 */ 4334 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 4335 int i; 4336 int nCol = pIdx->nColumn; 4337 int nKey = pIdx->nKeyCol; 4338 KeyInfo *pKey; 4339 if( pParse->nErr ) return 0; 4340 if( pIdx->uniqNotNull ){ 4341 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 4342 }else{ 4343 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 4344 } 4345 if( pKey ){ 4346 assert( sqlite3KeyInfoIsWriteable(pKey) ); 4347 for(i=0; i<nCol; i++){ 4348 char *zColl = pIdx->azColl[i]; 4349 assert( zColl!=0 ); 4350 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 : 4351 sqlite3LocateCollSeq(pParse, zColl); 4352 pKey->aSortOrder[i] = pIdx->aSortOrder[i]; 4353 } 4354 if( pParse->nErr ){ 4355 sqlite3KeyInfoUnref(pKey); 4356 pKey = 0; 4357 } 4358 } 4359 return pKey; 4360 } 4361 4362 #ifndef SQLITE_OMIT_CTE 4363 /* 4364 ** This routine is invoked once per CTE by the parser while parsing a 4365 ** WITH clause. 4366 */ 4367 With *sqlite3WithAdd( 4368 Parse *pParse, /* Parsing context */ 4369 With *pWith, /* Existing WITH clause, or NULL */ 4370 Token *pName, /* Name of the common-table */ 4371 ExprList *pArglist, /* Optional column name list for the table */ 4372 Select *pQuery /* Query used to initialize the table */ 4373 ){ 4374 sqlite3 *db = pParse->db; 4375 With *pNew; 4376 char *zName; 4377 4378 /* Check that the CTE name is unique within this WITH clause. If 4379 ** not, store an error in the Parse structure. */ 4380 zName = sqlite3NameFromToken(pParse->db, pName); 4381 if( zName && pWith ){ 4382 int i; 4383 for(i=0; i<pWith->nCte; i++){ 4384 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 4385 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 4386 } 4387 } 4388 } 4389 4390 if( pWith ){ 4391 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 4392 pNew = sqlite3DbRealloc(db, pWith, nByte); 4393 }else{ 4394 pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 4395 } 4396 assert( zName!=0 || pNew==0 ); 4397 assert( db->mallocFailed==0 || pNew==0 ); 4398 4399 if( pNew==0 ){ 4400 sqlite3ExprListDelete(db, pArglist); 4401 sqlite3SelectDelete(db, pQuery); 4402 sqlite3DbFree(db, zName); 4403 pNew = pWith; 4404 }else{ 4405 pNew->a[pNew->nCte].pSelect = pQuery; 4406 pNew->a[pNew->nCte].pCols = pArglist; 4407 pNew->a[pNew->nCte].zName = zName; 4408 pNew->a[pNew->nCte].zCteErr = 0; 4409 pNew->nCte++; 4410 } 4411 4412 return pNew; 4413 } 4414 4415 /* 4416 ** Free the contents of the With object passed as the second argument. 4417 */ 4418 void sqlite3WithDelete(sqlite3 *db, With *pWith){ 4419 if( pWith ){ 4420 int i; 4421 for(i=0; i<pWith->nCte; i++){ 4422 struct Cte *pCte = &pWith->a[i]; 4423 sqlite3ExprListDelete(db, pCte->pCols); 4424 sqlite3SelectDelete(db, pCte->pSelect); 4425 sqlite3DbFree(db, pCte->zName); 4426 } 4427 sqlite3DbFree(db, pWith); 4428 } 4429 } 4430 #endif /* !defined(SQLITE_OMIT_CTE) */ 4431