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