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