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