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