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