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