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