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