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( !IsVirtual(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(IsVirtual(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( !IsVirtual(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( !IsVirtual(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, Token *pName){ 892 char *zName; 893 if( pName ){ 894 zName = sqlite3DbStrNDup(db, (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 = pCExpr->u.zToken; 1840 for(iCol=0; iCol<pTab->nCol; iCol++){ 1841 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){ 1842 pCol = &pTab->aCol[iCol]; 1843 makeColumnPartOfPrimaryKey(pParse, pCol); 1844 break; 1845 } 1846 } 1847 } 1848 } 1849 } 1850 if( nTerm==1 1851 && pCol 1852 && pCol->eCType==COLTYPE_INTEGER 1853 && sortOrder!=SQLITE_SO_DESC 1854 ){ 1855 if( IN_RENAME_OBJECT && pList ){ 1856 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr); 1857 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr); 1858 } 1859 pTab->iPKey = iCol; 1860 pTab->keyConf = (u8)onError; 1861 assert( autoInc==0 || autoInc==1 ); 1862 pTab->tabFlags |= autoInc*TF_Autoincrement; 1863 if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags; 1864 (void)sqlite3HasExplicitNulls(pParse, pList); 1865 }else if( autoInc ){ 1866 #ifndef SQLITE_OMIT_AUTOINCREMENT 1867 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " 1868 "INTEGER PRIMARY KEY"); 1869 #endif 1870 }else{ 1871 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 1872 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); 1873 pList = 0; 1874 } 1875 1876 primary_key_exit: 1877 sqlite3ExprListDelete(pParse->db, pList); 1878 return; 1879 } 1880 1881 /* 1882 ** Add a new CHECK constraint to the table currently under construction. 1883 */ 1884 void sqlite3AddCheckConstraint( 1885 Parse *pParse, /* Parsing context */ 1886 Expr *pCheckExpr, /* The check expression */ 1887 const char *zStart, /* Opening "(" */ 1888 const char *zEnd /* Closing ")" */ 1889 ){ 1890 #ifndef SQLITE_OMIT_CHECK 1891 Table *pTab = pParse->pNewTable; 1892 sqlite3 *db = pParse->db; 1893 if( pTab && !IN_DECLARE_VTAB 1894 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) 1895 ){ 1896 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); 1897 if( pParse->constraintName.n ){ 1898 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); 1899 }else{ 1900 Token t; 1901 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){} 1902 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; } 1903 t.z = zStart; 1904 t.n = (int)(zEnd - t.z); 1905 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1); 1906 } 1907 }else 1908 #endif 1909 { 1910 sqlite3ExprDelete(pParse->db, pCheckExpr); 1911 } 1912 } 1913 1914 /* 1915 ** Set the collation function of the most recently parsed table column 1916 ** to the CollSeq given. 1917 */ 1918 void sqlite3AddCollateType(Parse *pParse, Token *pToken){ 1919 Table *p; 1920 int i; 1921 char *zColl; /* Dequoted name of collation sequence */ 1922 sqlite3 *db; 1923 1924 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return; 1925 i = p->nCol-1; 1926 db = pParse->db; 1927 zColl = sqlite3NameFromToken(db, pToken); 1928 if( !zColl ) return; 1929 1930 if( sqlite3LocateCollSeq(pParse, zColl) ){ 1931 Index *pIdx; 1932 sqlite3ColumnSetColl(db, &p->aCol[i], zColl); 1933 1934 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", 1935 ** then an index may have been created on this column before the 1936 ** collation type was added. Correct this if it is the case. 1937 */ 1938 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 1939 assert( pIdx->nKeyCol==1 ); 1940 if( pIdx->aiColumn[0]==i ){ 1941 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]); 1942 } 1943 } 1944 } 1945 sqlite3DbFree(db, zColl); 1946 } 1947 1948 /* Change the most recently parsed column to be a GENERATED ALWAYS AS 1949 ** column. 1950 */ 1951 void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){ 1952 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1953 u8 eType = COLFLAG_VIRTUAL; 1954 Table *pTab = pParse->pNewTable; 1955 Column *pCol; 1956 if( pTab==0 ){ 1957 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */ 1958 goto generated_done; 1959 } 1960 pCol = &(pTab->aCol[pTab->nCol-1]); 1961 if( IN_DECLARE_VTAB ){ 1962 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns"); 1963 goto generated_done; 1964 } 1965 if( pCol->iDflt>0 ) goto generated_error; 1966 if( pType ){ 1967 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){ 1968 /* no-op */ 1969 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){ 1970 eType = COLFLAG_STORED; 1971 }else{ 1972 goto generated_error; 1973 } 1974 } 1975 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--; 1976 pCol->colFlags |= eType; 1977 assert( TF_HasVirtual==COLFLAG_VIRTUAL ); 1978 assert( TF_HasStored==COLFLAG_STORED ); 1979 pTab->tabFlags |= eType; 1980 if( pCol->colFlags & COLFLAG_PRIMKEY ){ 1981 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */ 1982 } 1983 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr); 1984 pExpr = 0; 1985 goto generated_done; 1986 1987 generated_error: 1988 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"", 1989 pCol->zCnName); 1990 generated_done: 1991 sqlite3ExprDelete(pParse->db, pExpr); 1992 #else 1993 /* Throw and error for the GENERATED ALWAYS AS clause if the 1994 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */ 1995 sqlite3ErrorMsg(pParse, "generated columns not supported"); 1996 sqlite3ExprDelete(pParse->db, pExpr); 1997 #endif 1998 } 1999 2000 /* 2001 ** Generate code that will increment the schema cookie. 2002 ** 2003 ** The schema cookie is used to determine when the schema for the 2004 ** database changes. After each schema change, the cookie value 2005 ** changes. When a process first reads the schema it records the 2006 ** cookie. Thereafter, whenever it goes to access the database, 2007 ** it checks the cookie to make sure the schema has not changed 2008 ** since it was last read. 2009 ** 2010 ** This plan is not completely bullet-proof. It is possible for 2011 ** the schema to change multiple times and for the cookie to be 2012 ** set back to prior value. But schema changes are infrequent 2013 ** and the probability of hitting the same cookie value is only 2014 ** 1 chance in 2^32. So we're safe enough. 2015 ** 2016 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments 2017 ** the schema-version whenever the schema changes. 2018 */ 2019 void sqlite3ChangeCookie(Parse *pParse, int iDb){ 2020 sqlite3 *db = pParse->db; 2021 Vdbe *v = pParse->pVdbe; 2022 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2023 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 2024 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie)); 2025 } 2026 2027 /* 2028 ** Measure the number of characters needed to output the given 2029 ** identifier. The number returned includes any quotes used 2030 ** but does not include the null terminator. 2031 ** 2032 ** The estimate is conservative. It might be larger that what is 2033 ** really needed. 2034 */ 2035 static int identLength(const char *z){ 2036 int n; 2037 for(n=0; *z; n++, z++){ 2038 if( *z=='"' ){ n++; } 2039 } 2040 return n + 2; 2041 } 2042 2043 /* 2044 ** The first parameter is a pointer to an output buffer. The second 2045 ** parameter is a pointer to an integer that contains the offset at 2046 ** which to write into the output buffer. This function copies the 2047 ** nul-terminated string pointed to by the third parameter, zSignedIdent, 2048 ** to the specified offset in the buffer and updates *pIdx to refer 2049 ** to the first byte after the last byte written before returning. 2050 ** 2051 ** If the string zSignedIdent consists entirely of alpha-numeric 2052 ** characters, does not begin with a digit and is not an SQL keyword, 2053 ** then it is copied to the output buffer exactly as it is. Otherwise, 2054 ** it is quoted using double-quotes. 2055 */ 2056 static void identPut(char *z, int *pIdx, char *zSignedIdent){ 2057 unsigned char *zIdent = (unsigned char*)zSignedIdent; 2058 int i, j, needQuote; 2059 i = *pIdx; 2060 2061 for(j=0; zIdent[j]; j++){ 2062 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; 2063 } 2064 needQuote = sqlite3Isdigit(zIdent[0]) 2065 || sqlite3KeywordCode(zIdent, j)!=TK_ID 2066 || zIdent[j]!=0 2067 || j==0; 2068 2069 if( needQuote ) z[i++] = '"'; 2070 for(j=0; zIdent[j]; j++){ 2071 z[i++] = zIdent[j]; 2072 if( zIdent[j]=='"' ) z[i++] = '"'; 2073 } 2074 if( needQuote ) z[i++] = '"'; 2075 z[i] = 0; 2076 *pIdx = i; 2077 } 2078 2079 /* 2080 ** Generate a CREATE TABLE statement appropriate for the given 2081 ** table. Memory to hold the text of the statement is obtained 2082 ** from sqliteMalloc() and must be freed by the calling function. 2083 */ 2084 static char *createTableStmt(sqlite3 *db, Table *p){ 2085 int i, k, n; 2086 char *zStmt; 2087 char *zSep, *zSep2, *zEnd; 2088 Column *pCol; 2089 n = 0; 2090 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){ 2091 n += identLength(pCol->zCnName) + 5; 2092 } 2093 n += identLength(p->zName); 2094 if( n<50 ){ 2095 zSep = ""; 2096 zSep2 = ","; 2097 zEnd = ")"; 2098 }else{ 2099 zSep = "\n "; 2100 zSep2 = ",\n "; 2101 zEnd = "\n)"; 2102 } 2103 n += 35 + 6*p->nCol; 2104 zStmt = sqlite3DbMallocRaw(0, n); 2105 if( zStmt==0 ){ 2106 sqlite3OomFault(db); 2107 return 0; 2108 } 2109 sqlite3_snprintf(n, zStmt, "CREATE TABLE "); 2110 k = sqlite3Strlen30(zStmt); 2111 identPut(zStmt, &k, p->zName); 2112 zStmt[k++] = '('; 2113 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ 2114 static const char * const azType[] = { 2115 /* SQLITE_AFF_BLOB */ "", 2116 /* SQLITE_AFF_TEXT */ " TEXT", 2117 /* SQLITE_AFF_NUMERIC */ " NUM", 2118 /* SQLITE_AFF_INTEGER */ " INT", 2119 /* SQLITE_AFF_REAL */ " REAL" 2120 }; 2121 int len; 2122 const char *zType; 2123 2124 sqlite3_snprintf(n-k, &zStmt[k], zSep); 2125 k += sqlite3Strlen30(&zStmt[k]); 2126 zSep = zSep2; 2127 identPut(zStmt, &k, pCol->zCnName); 2128 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); 2129 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); 2130 testcase( pCol->affinity==SQLITE_AFF_BLOB ); 2131 testcase( pCol->affinity==SQLITE_AFF_TEXT ); 2132 testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); 2133 testcase( pCol->affinity==SQLITE_AFF_INTEGER ); 2134 testcase( pCol->affinity==SQLITE_AFF_REAL ); 2135 2136 zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; 2137 len = sqlite3Strlen30(zType); 2138 assert( pCol->affinity==SQLITE_AFF_BLOB 2139 || pCol->affinity==sqlite3AffinityType(zType, 0) ); 2140 memcpy(&zStmt[k], zType, len); 2141 k += len; 2142 assert( k<=n ); 2143 } 2144 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); 2145 return zStmt; 2146 } 2147 2148 /* 2149 ** Resize an Index object to hold N columns total. Return SQLITE_OK 2150 ** on success and SQLITE_NOMEM on an OOM error. 2151 */ 2152 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ 2153 char *zExtra; 2154 int nByte; 2155 if( pIdx->nColumn>=N ) return SQLITE_OK; 2156 assert( pIdx->isResized==0 ); 2157 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N; 2158 zExtra = sqlite3DbMallocZero(db, nByte); 2159 if( zExtra==0 ) return SQLITE_NOMEM_BKPT; 2160 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); 2161 pIdx->azColl = (const char**)zExtra; 2162 zExtra += sizeof(char*)*N; 2163 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1)); 2164 pIdx->aiRowLogEst = (LogEst*)zExtra; 2165 zExtra += sizeof(LogEst)*N; 2166 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); 2167 pIdx->aiColumn = (i16*)zExtra; 2168 zExtra += sizeof(i16)*N; 2169 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); 2170 pIdx->aSortOrder = (u8*)zExtra; 2171 pIdx->nColumn = N; 2172 pIdx->isResized = 1; 2173 return SQLITE_OK; 2174 } 2175 2176 /* 2177 ** Estimate the total row width for a table. 2178 */ 2179 static void estimateTableWidth(Table *pTab){ 2180 unsigned wTable = 0; 2181 const Column *pTabCol; 2182 int i; 2183 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ 2184 wTable += pTabCol->szEst; 2185 } 2186 if( pTab->iPKey<0 ) wTable++; 2187 pTab->szTabRow = sqlite3LogEst(wTable*4); 2188 } 2189 2190 /* 2191 ** Estimate the average size of a row for an index. 2192 */ 2193 static void estimateIndexWidth(Index *pIdx){ 2194 unsigned wIndex = 0; 2195 int i; 2196 const Column *aCol = pIdx->pTable->aCol; 2197 for(i=0; i<pIdx->nColumn; i++){ 2198 i16 x = pIdx->aiColumn[i]; 2199 assert( x<pIdx->pTable->nCol ); 2200 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; 2201 } 2202 pIdx->szIdxRow = sqlite3LogEst(wIndex*4); 2203 } 2204 2205 /* Return true if column number x is any of the first nCol entries of aiCol[]. 2206 ** This is used to determine if the column number x appears in any of the 2207 ** first nCol entries of an index. 2208 */ 2209 static int hasColumn(const i16 *aiCol, int nCol, int x){ 2210 while( nCol-- > 0 ){ 2211 assert( aiCol[0]>=0 ); 2212 if( x==*(aiCol++) ){ 2213 return 1; 2214 } 2215 } 2216 return 0; 2217 } 2218 2219 /* 2220 ** Return true if any of the first nKey entries of index pIdx exactly 2221 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID 2222 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may 2223 ** or may not be the same index as pPk. 2224 ** 2225 ** The first nKey entries of pIdx are guaranteed to be ordinary columns, 2226 ** not a rowid or expression. 2227 ** 2228 ** This routine differs from hasColumn() in that both the column and the 2229 ** collating sequence must match for this routine, but for hasColumn() only 2230 ** the column name must match. 2231 */ 2232 static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){ 2233 int i, j; 2234 assert( nKey<=pIdx->nColumn ); 2235 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) ); 2236 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY ); 2237 assert( pPk->pTable->tabFlags & TF_WithoutRowid ); 2238 assert( pPk->pTable==pIdx->pTable ); 2239 testcase( pPk==pIdx ); 2240 j = pPk->aiColumn[iCol]; 2241 assert( j!=XN_ROWID && j!=XN_EXPR ); 2242 for(i=0; i<nKey; i++){ 2243 assert( pIdx->aiColumn[i]>=0 || j>=0 ); 2244 if( pIdx->aiColumn[i]==j 2245 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0 2246 ){ 2247 return 1; 2248 } 2249 } 2250 return 0; 2251 } 2252 2253 /* Recompute the colNotIdxed field of the Index. 2254 ** 2255 ** colNotIdxed is a bitmask that has a 0 bit representing each indexed 2256 ** columns that are within the first 63 columns of the table. The 2257 ** high-order bit of colNotIdxed is always 1. All unindexed columns 2258 ** of the table have a 1. 2259 ** 2260 ** 2019-10-24: For the purpose of this computation, virtual columns are 2261 ** not considered to be covered by the index, even if they are in the 2262 ** index, because we do not trust the logic in whereIndexExprTrans() to be 2263 ** able to find all instances of a reference to the indexed table column 2264 ** and convert them into references to the index. Hence we always want 2265 ** the actual table at hand in order to recompute the virtual column, if 2266 ** necessary. 2267 ** 2268 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask 2269 ** to determine if the index is covering index. 2270 */ 2271 static void recomputeColumnsNotIndexed(Index *pIdx){ 2272 Bitmask m = 0; 2273 int j; 2274 Table *pTab = pIdx->pTable; 2275 for(j=pIdx->nColumn-1; j>=0; j--){ 2276 int x = pIdx->aiColumn[j]; 2277 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){ 2278 testcase( x==BMS-1 ); 2279 testcase( x==BMS-2 ); 2280 if( x<BMS-1 ) m |= MASKBIT(x); 2281 } 2282 } 2283 pIdx->colNotIdxed = ~m; 2284 assert( (pIdx->colNotIdxed>>63)==1 ); 2285 } 2286 2287 /* 2288 ** This routine runs at the end of parsing a CREATE TABLE statement that 2289 ** has a WITHOUT ROWID clause. The job of this routine is to convert both 2290 ** internal schema data structures and the generated VDBE code so that they 2291 ** are appropriate for a WITHOUT ROWID table instead of a rowid table. 2292 ** Changes include: 2293 ** 2294 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. 2295 ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 2296 ** into BTREE_BLOBKEY. 2297 ** (3) Bypass the creation of the sqlite_schema table entry 2298 ** for the PRIMARY KEY as the primary key index is now 2299 ** identified by the sqlite_schema table entry of the table itself. 2300 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the 2301 ** schema to the rootpage from the main table. 2302 ** (5) Add all table columns to the PRIMARY KEY Index object 2303 ** so that the PRIMARY KEY is a covering index. The surplus 2304 ** columns are part of KeyInfo.nAllField and are not used for 2305 ** sorting or lookup or uniqueness checks. 2306 ** (6) Replace the rowid tail on all automatically generated UNIQUE 2307 ** indices with the PRIMARY KEY columns. 2308 ** 2309 ** For virtual tables, only (1) is performed. 2310 */ 2311 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ 2312 Index *pIdx; 2313 Index *pPk; 2314 int nPk; 2315 int nExtra; 2316 int i, j; 2317 sqlite3 *db = pParse->db; 2318 Vdbe *v = pParse->pVdbe; 2319 2320 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) 2321 */ 2322 if( !db->init.imposterTable ){ 2323 for(i=0; i<pTab->nCol; i++){ 2324 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 2325 && (pTab->aCol[i].notNull==OE_None) 2326 ){ 2327 pTab->aCol[i].notNull = OE_Abort; 2328 } 2329 } 2330 pTab->tabFlags |= TF_HasNotNull; 2331 } 2332 2333 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY 2334 ** into BTREE_BLOBKEY. 2335 */ 2336 assert( !pParse->bReturning ); 2337 if( pParse->u1.addrCrTab ){ 2338 assert( v ); 2339 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY); 2340 } 2341 2342 /* Locate the PRIMARY KEY index. Or, if this table was originally 2343 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 2344 */ 2345 if( pTab->iPKey>=0 ){ 2346 ExprList *pList; 2347 Token ipkToken; 2348 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName); 2349 pList = sqlite3ExprListAppend(pParse, 0, 2350 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); 2351 if( pList==0 ){ 2352 pTab->tabFlags &= ~TF_WithoutRowid; 2353 return; 2354 } 2355 if( IN_RENAME_OBJECT ){ 2356 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey); 2357 } 2358 pList->a[0].sortFlags = pParse->iPkSortOrder; 2359 assert( pParse->pNewTable==pTab ); 2360 pTab->iPKey = -1; 2361 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, 2362 SQLITE_IDXTYPE_PRIMARYKEY); 2363 if( db->mallocFailed || pParse->nErr ){ 2364 pTab->tabFlags &= ~TF_WithoutRowid; 2365 return; 2366 } 2367 pPk = sqlite3PrimaryKeyIndex(pTab); 2368 assert( pPk->nKeyCol==1 ); 2369 }else{ 2370 pPk = sqlite3PrimaryKeyIndex(pTab); 2371 assert( pPk!=0 ); 2372 2373 /* 2374 ** Remove all redundant columns from the PRIMARY KEY. For example, change 2375 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later 2376 ** code assumes the PRIMARY KEY contains no repeated columns. 2377 */ 2378 for(i=j=1; i<pPk->nKeyCol; i++){ 2379 if( isDupColumn(pPk, j, pPk, i) ){ 2380 pPk->nColumn--; 2381 }else{ 2382 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ); 2383 pPk->azColl[j] = pPk->azColl[i]; 2384 pPk->aSortOrder[j] = pPk->aSortOrder[i]; 2385 pPk->aiColumn[j++] = pPk->aiColumn[i]; 2386 } 2387 } 2388 pPk->nKeyCol = j; 2389 } 2390 assert( pPk!=0 ); 2391 pPk->isCovering = 1; 2392 if( !db->init.imposterTable ) pPk->uniqNotNull = 1; 2393 nPk = pPk->nColumn = pPk->nKeyCol; 2394 2395 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema 2396 ** table entry. This is only required if currently generating VDBE 2397 ** code for a CREATE TABLE (not when parsing one as part of reading 2398 ** a database schema). */ 2399 if( v && pPk->tnum>0 ){ 2400 assert( db->init.busy==0 ); 2401 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto); 2402 } 2403 2404 /* The root page of the PRIMARY KEY is the table root page */ 2405 pPk->tnum = pTab->tnum; 2406 2407 /* Update the in-memory representation of all UNIQUE indices by converting 2408 ** the final rowid column into one or more columns of the PRIMARY KEY. 2409 */ 2410 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 2411 int n; 2412 if( IsPrimaryKeyIndex(pIdx) ) continue; 2413 for(i=n=0; i<nPk; i++){ 2414 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2415 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 2416 n++; 2417 } 2418 } 2419 if( n==0 ){ 2420 /* This index is a superset of the primary key */ 2421 pIdx->nColumn = pIdx->nKeyCol; 2422 continue; 2423 } 2424 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; 2425 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ 2426 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ 2427 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); 2428 pIdx->aiColumn[j] = pPk->aiColumn[i]; 2429 pIdx->azColl[j] = pPk->azColl[i]; 2430 if( pPk->aSortOrder[i] ){ 2431 /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ 2432 pIdx->bAscKeyBug = 1; 2433 } 2434 j++; 2435 } 2436 } 2437 assert( pIdx->nColumn>=pIdx->nKeyCol+n ); 2438 assert( pIdx->nColumn>=j ); 2439 } 2440 2441 /* Add all table columns to the PRIMARY KEY index 2442 */ 2443 nExtra = 0; 2444 for(i=0; i<pTab->nCol; i++){ 2445 if( !hasColumn(pPk->aiColumn, nPk, i) 2446 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; 2447 } 2448 if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; 2449 for(i=0, j=nPk; i<pTab->nCol; i++){ 2450 if( !hasColumn(pPk->aiColumn, j, i) 2451 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 2452 ){ 2453 assert( j<pPk->nColumn ); 2454 pPk->aiColumn[j] = i; 2455 pPk->azColl[j] = sqlite3StrBINARY; 2456 j++; 2457 } 2458 } 2459 assert( pPk->nColumn==j ); 2460 assert( pTab->nNVCol<=j ); 2461 recomputeColumnsNotIndexed(pPk); 2462 } 2463 2464 2465 #ifndef SQLITE_OMIT_VIRTUALTABLE 2466 /* 2467 ** Return true if pTab is a virtual table and zName is a shadow table name 2468 ** for that virtual table. 2469 */ 2470 int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){ 2471 int nName; /* Length of zName */ 2472 Module *pMod; /* Module for the virtual table */ 2473 2474 if( !IsVirtual(pTab) ) return 0; 2475 nName = sqlite3Strlen30(pTab->zName); 2476 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0; 2477 if( zName[nName]!='_' ) return 0; 2478 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]); 2479 if( pMod==0 ) return 0; 2480 if( pMod->pModule->iVersion<3 ) return 0; 2481 if( pMod->pModule->xShadowName==0 ) return 0; 2482 return pMod->pModule->xShadowName(zName+nName+1); 2483 } 2484 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 2485 2486 #ifndef SQLITE_OMIT_VIRTUALTABLE 2487 /* 2488 ** Return true if zName is a shadow table name in the current database 2489 ** connection. 2490 ** 2491 ** zName is temporarily modified while this routine is running, but is 2492 ** restored to its original value prior to this routine returning. 2493 */ 2494 int sqlite3ShadowTableName(sqlite3 *db, const char *zName){ 2495 char *zTail; /* Pointer to the last "_" in zName */ 2496 Table *pTab; /* Table that zName is a shadow of */ 2497 zTail = strrchr(zName, '_'); 2498 if( zTail==0 ) return 0; 2499 *zTail = 0; 2500 pTab = sqlite3FindTable(db, zName, 0); 2501 *zTail = '_'; 2502 if( pTab==0 ) return 0; 2503 if( !IsVirtual(pTab) ) return 0; 2504 return sqlite3IsShadowTableOf(db, pTab, zName); 2505 } 2506 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 2507 2508 2509 #ifdef SQLITE_DEBUG 2510 /* 2511 ** Mark all nodes of an expression as EP_Immutable, indicating that 2512 ** they should not be changed. Expressions attached to a table or 2513 ** index definition are tagged this way to help ensure that we do 2514 ** not pass them into code generator routines by mistake. 2515 */ 2516 static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){ 2517 ExprSetVVAProperty(pExpr, EP_Immutable); 2518 return WRC_Continue; 2519 } 2520 static void markExprListImmutable(ExprList *pList){ 2521 if( pList ){ 2522 Walker w; 2523 memset(&w, 0, sizeof(w)); 2524 w.xExprCallback = markImmutableExprStep; 2525 w.xSelectCallback = sqlite3SelectWalkNoop; 2526 w.xSelectCallback2 = 0; 2527 sqlite3WalkExprList(&w, pList); 2528 } 2529 } 2530 #else 2531 #define markExprListImmutable(X) /* no-op */ 2532 #endif /* SQLITE_DEBUG */ 2533 2534 2535 /* 2536 ** This routine is called to report the final ")" that terminates 2537 ** a CREATE TABLE statement. 2538 ** 2539 ** The table structure that other action routines have been building 2540 ** is added to the internal hash tables, assuming no errors have 2541 ** occurred. 2542 ** 2543 ** An entry for the table is made in the schema table on disk, unless 2544 ** this is a temporary table or db->init.busy==1. When db->init.busy==1 2545 ** it means we are reading the sqlite_schema table because we just 2546 ** connected to the database or because the sqlite_schema table has 2547 ** recently changed, so the entry for this table already exists in 2548 ** the sqlite_schema table. We do not want to create it again. 2549 ** 2550 ** If the pSelect argument is not NULL, it means that this routine 2551 ** was called to create a table generated from a 2552 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of 2553 ** the new table will match the result set of the SELECT. 2554 */ 2555 void sqlite3EndTable( 2556 Parse *pParse, /* Parse context */ 2557 Token *pCons, /* The ',' token after the last column defn. */ 2558 Token *pEnd, /* The ')' before options in the CREATE TABLE */ 2559 u32 tabOpts, /* Extra table options. Usually 0. */ 2560 Select *pSelect /* Select from a "CREATE ... AS SELECT" */ 2561 ){ 2562 Table *p; /* The new table */ 2563 sqlite3 *db = pParse->db; /* The database connection */ 2564 int iDb; /* Database in which the table lives */ 2565 Index *pIdx; /* An implied index of the table */ 2566 2567 if( pEnd==0 && pSelect==0 ){ 2568 return; 2569 } 2570 p = pParse->pNewTable; 2571 if( p==0 ) return; 2572 2573 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){ 2574 p->tabFlags |= TF_Shadow; 2575 } 2576 2577 /* If the db->init.busy is 1 it means we are reading the SQL off the 2578 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk. 2579 ** So do not write to the disk again. Extract the root page number 2580 ** for the table from the db->init.newTnum field. (The page number 2581 ** should have been put there by the sqliteOpenCb routine.) 2582 ** 2583 ** If the root page number is 1, that means this is the sqlite_schema 2584 ** table itself. So mark it read-only. 2585 */ 2586 if( db->init.busy ){ 2587 if( pSelect ){ 2588 sqlite3ErrorMsg(pParse, ""); 2589 return; 2590 } 2591 p->tnum = db->init.newTnum; 2592 if( p->tnum==1 ) p->tabFlags |= TF_Readonly; 2593 } 2594 2595 /* Special processing for tables that include the STRICT keyword: 2596 ** 2597 ** * Do not allow custom column datatypes. Every column must have 2598 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB. 2599 ** 2600 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY, 2601 ** then all columns of the PRIMARY KEY must have a NOT NULL 2602 ** constraint. 2603 */ 2604 if( tabOpts & TF_Strict ){ 2605 int ii; 2606 p->tabFlags |= TF_Strict; 2607 for(ii=0; ii<p->nCol; ii++){ 2608 Column *pCol = &p->aCol[ii]; 2609 if( pCol->eCType==COLTYPE_CUSTOM ){ 2610 if( pCol->colFlags & COLFLAG_HASTYPE ){ 2611 sqlite3ErrorMsg(pParse, 2612 "unknown datatype for %s.%s: \"%s\"", 2613 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "") 2614 ); 2615 }else{ 2616 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s", 2617 p->zName, pCol->zCnName); 2618 } 2619 return; 2620 }else if( pCol->eCType==COLTYPE_ANY ){ 2621 pCol->affinity = SQLITE_AFF_BLOB; 2622 } 2623 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0 2624 && p->iPKey!=ii 2625 && pCol->notNull == OE_None 2626 ){ 2627 pCol->notNull = OE_Abort; 2628 p->tabFlags |= TF_HasNotNull; 2629 } 2630 } 2631 } 2632 2633 assert( (p->tabFlags & TF_HasPrimaryKey)==0 2634 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 ); 2635 assert( (p->tabFlags & TF_HasPrimaryKey)!=0 2636 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) ); 2637 2638 /* Special processing for WITHOUT ROWID Tables */ 2639 if( tabOpts & TF_WithoutRowid ){ 2640 if( (p->tabFlags & TF_Autoincrement) ){ 2641 sqlite3ErrorMsg(pParse, 2642 "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); 2643 return; 2644 } 2645 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ 2646 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); 2647 return; 2648 } 2649 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; 2650 convertToWithoutRowidTable(pParse, p); 2651 } 2652 iDb = sqlite3SchemaToIndex(db, p->pSchema); 2653 2654 #ifndef SQLITE_OMIT_CHECK 2655 /* Resolve names in all CHECK constraint expressions. 2656 */ 2657 if( p->pCheck ){ 2658 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); 2659 if( pParse->nErr ){ 2660 /* If errors are seen, delete the CHECK constraints now, else they might 2661 ** actually be used if PRAGMA writable_schema=ON is set. */ 2662 sqlite3ExprListDelete(db, p->pCheck); 2663 p->pCheck = 0; 2664 }else{ 2665 markExprListImmutable(p->pCheck); 2666 } 2667 } 2668 #endif /* !defined(SQLITE_OMIT_CHECK) */ 2669 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 2670 if( p->tabFlags & TF_HasGenerated ){ 2671 int ii, nNG = 0; 2672 testcase( p->tabFlags & TF_HasVirtual ); 2673 testcase( p->tabFlags & TF_HasStored ); 2674 for(ii=0; ii<p->nCol; ii++){ 2675 u32 colFlags = p->aCol[ii].colFlags; 2676 if( (colFlags & COLFLAG_GENERATED)!=0 ){ 2677 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]); 2678 testcase( colFlags & COLFLAG_VIRTUAL ); 2679 testcase( colFlags & COLFLAG_STORED ); 2680 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){ 2681 /* If there are errors in resolving the expression, change the 2682 ** expression to a NULL. This prevents code generators that operate 2683 ** on the expression from inserting extra parts into the expression 2684 ** tree that have been allocated from lookaside memory, which is 2685 ** illegal in a schema and will lead to errors or heap corruption 2686 ** when the database connection closes. */ 2687 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii], 2688 sqlite3ExprAlloc(db, TK_NULL, 0, 0)); 2689 } 2690 }else{ 2691 nNG++; 2692 } 2693 } 2694 if( nNG==0 ){ 2695 sqlite3ErrorMsg(pParse, "must have at least one non-generated column"); 2696 return; 2697 } 2698 } 2699 #endif 2700 2701 /* Estimate the average row size for the table and for all implied indices */ 2702 estimateTableWidth(p); 2703 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ 2704 estimateIndexWidth(pIdx); 2705 } 2706 2707 /* If not initializing, then create a record for the new table 2708 ** in the schema table of the database. 2709 ** 2710 ** If this is a TEMPORARY table, write the entry into the auxiliary 2711 ** file instead of into the main database file. 2712 */ 2713 if( !db->init.busy ){ 2714 int n; 2715 Vdbe *v; 2716 char *zType; /* "view" or "table" */ 2717 char *zType2; /* "VIEW" or "TABLE" */ 2718 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ 2719 2720 v = sqlite3GetVdbe(pParse); 2721 if( NEVER(v==0) ) return; 2722 2723 sqlite3VdbeAddOp1(v, OP_Close, 0); 2724 2725 /* 2726 ** Initialize zType for the new view or table. 2727 */ 2728 if( IsOrdinaryTable(p) ){ 2729 /* A regular table */ 2730 zType = "table"; 2731 zType2 = "TABLE"; 2732 #ifndef SQLITE_OMIT_VIEW 2733 }else{ 2734 /* A view */ 2735 zType = "view"; 2736 zType2 = "VIEW"; 2737 #endif 2738 } 2739 2740 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT 2741 ** statement to populate the new table. The root-page number for the 2742 ** new table is in register pParse->regRoot. 2743 ** 2744 ** Once the SELECT has been coded by sqlite3Select(), it is in a 2745 ** suitable state to query for the column names and types to be used 2746 ** by the new table. 2747 ** 2748 ** A shared-cache write-lock is not required to write to the new table, 2749 ** as a schema-lock must have already been obtained to create it. Since 2750 ** a schema-lock excludes all other database users, the write-lock would 2751 ** be redundant. 2752 */ 2753 if( pSelect ){ 2754 SelectDest dest; /* Where the SELECT should store results */ 2755 int regYield; /* Register holding co-routine entry-point */ 2756 int addrTop; /* Top of the co-routine */ 2757 int regRec; /* A record to be insert into the new table */ 2758 int regRowid; /* Rowid of the next row to insert */ 2759 int addrInsLoop; /* Top of the loop for inserting rows */ 2760 Table *pSelTab; /* A table that describes the SELECT results */ 2761 2762 regYield = ++pParse->nMem; 2763 regRec = ++pParse->nMem; 2764 regRowid = ++pParse->nMem; 2765 assert(pParse->nTab==1); 2766 sqlite3MayAbort(pParse); 2767 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); 2768 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); 2769 pParse->nTab = 2; 2770 addrTop = sqlite3VdbeCurrentAddr(v) + 1; 2771 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); 2772 if( pParse->nErr ) return; 2773 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB); 2774 if( pSelTab==0 ) return; 2775 assert( p->aCol==0 ); 2776 p->nCol = p->nNVCol = pSelTab->nCol; 2777 p->aCol = pSelTab->aCol; 2778 pSelTab->nCol = 0; 2779 pSelTab->aCol = 0; 2780 sqlite3DeleteTable(db, pSelTab); 2781 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); 2782 sqlite3Select(pParse, pSelect, &dest); 2783 if( pParse->nErr ) return; 2784 sqlite3VdbeEndCoroutine(v, regYield); 2785 sqlite3VdbeJumpHere(v, addrTop - 1); 2786 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); 2787 VdbeCoverage(v); 2788 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); 2789 sqlite3TableAffinity(v, p, 0); 2790 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); 2791 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); 2792 sqlite3VdbeGoto(v, addrInsLoop); 2793 sqlite3VdbeJumpHere(v, addrInsLoop); 2794 sqlite3VdbeAddOp1(v, OP_Close, 1); 2795 } 2796 2797 /* Compute the complete text of the CREATE statement */ 2798 if( pSelect ){ 2799 zStmt = createTableStmt(db, p); 2800 }else{ 2801 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; 2802 n = (int)(pEnd2->z - pParse->sNameToken.z); 2803 if( pEnd2->z[0]!=';' ) n += pEnd2->n; 2804 zStmt = sqlite3MPrintf(db, 2805 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z 2806 ); 2807 } 2808 2809 /* A slot for the record has already been allocated in the 2810 ** schema table. We just need to update that slot with all 2811 ** the information we've collected. 2812 */ 2813 sqlite3NestedParse(pParse, 2814 "UPDATE %Q." DFLT_SCHEMA_TABLE 2815 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q" 2816 " WHERE rowid=#%d", 2817 db->aDb[iDb].zDbSName, 2818 zType, 2819 p->zName, 2820 p->zName, 2821 pParse->regRoot, 2822 zStmt, 2823 pParse->regRowid 2824 ); 2825 sqlite3DbFree(db, zStmt); 2826 sqlite3ChangeCookie(pParse, iDb); 2827 2828 #ifndef SQLITE_OMIT_AUTOINCREMENT 2829 /* Check to see if we need to create an sqlite_sequence table for 2830 ** keeping track of autoincrement keys. 2831 */ 2832 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){ 2833 Db *pDb = &db->aDb[iDb]; 2834 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2835 if( pDb->pSchema->pSeqTab==0 ){ 2836 sqlite3NestedParse(pParse, 2837 "CREATE TABLE %Q.sqlite_sequence(name,seq)", 2838 pDb->zDbSName 2839 ); 2840 } 2841 } 2842 #endif 2843 2844 /* Reparse everything to update our internal data structures */ 2845 sqlite3VdbeAddParseSchemaOp(v, iDb, 2846 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0); 2847 } 2848 2849 /* Add the table to the in-memory representation of the database. 2850 */ 2851 if( db->init.busy ){ 2852 Table *pOld; 2853 Schema *pSchema = p->pSchema; 2854 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2855 assert( HasRowid(p) || p->iPKey<0 ); 2856 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); 2857 if( pOld ){ 2858 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ 2859 sqlite3OomFault(db); 2860 return; 2861 } 2862 pParse->pNewTable = 0; 2863 db->mDbFlags |= DBFLAG_SchemaChange; 2864 2865 /* If this is the magic sqlite_sequence table used by autoincrement, 2866 ** then record a pointer to this table in the main database structure 2867 ** so that INSERT can find the table easily. */ 2868 assert( !pParse->nested ); 2869 #ifndef SQLITE_OMIT_AUTOINCREMENT 2870 if( strcmp(p->zName, "sqlite_sequence")==0 ){ 2871 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 2872 p->pSchema->pSeqTab = p; 2873 } 2874 #endif 2875 } 2876 2877 #ifndef SQLITE_OMIT_ALTERTABLE 2878 if( !pSelect && IsOrdinaryTable(p) ){ 2879 assert( pCons && pEnd ); 2880 if( pCons->z==0 ){ 2881 pCons = pEnd; 2882 } 2883 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z); 2884 } 2885 #endif 2886 } 2887 2888 #ifndef SQLITE_OMIT_VIEW 2889 /* 2890 ** The parser calls this routine in order to create a new VIEW 2891 */ 2892 void sqlite3CreateView( 2893 Parse *pParse, /* The parsing context */ 2894 Token *pBegin, /* The CREATE token that begins the statement */ 2895 Token *pName1, /* The token that holds the name of the view */ 2896 Token *pName2, /* The token that holds the name of the view */ 2897 ExprList *pCNames, /* Optional list of view column names */ 2898 Select *pSelect, /* A SELECT statement that will become the new view */ 2899 int isTemp, /* TRUE for a TEMPORARY view */ 2900 int noErr /* Suppress error messages if VIEW already exists */ 2901 ){ 2902 Table *p; 2903 int n; 2904 const char *z; 2905 Token sEnd; 2906 DbFixer sFix; 2907 Token *pName = 0; 2908 int iDb; 2909 sqlite3 *db = pParse->db; 2910 2911 if( pParse->nVar>0 ){ 2912 sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); 2913 goto create_view_fail; 2914 } 2915 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); 2916 p = pParse->pNewTable; 2917 if( p==0 || pParse->nErr ) goto create_view_fail; 2918 2919 /* Legacy versions of SQLite allowed the use of the magic "rowid" column 2920 ** on a view, even though views do not have rowids. The following flag 2921 ** setting fixes this problem. But the fix can be disabled by compiling 2922 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that 2923 ** depend upon the old buggy behavior. */ 2924 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW 2925 p->tabFlags |= TF_NoVisibleRowid; 2926 #endif 2927 2928 sqlite3TwoPartName(pParse, pName1, pName2, &pName); 2929 iDb = sqlite3SchemaToIndex(db, p->pSchema); 2930 sqlite3FixInit(&sFix, pParse, iDb, "view", pName); 2931 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; 2932 2933 /* Make a copy of the entire SELECT statement that defines the view. 2934 ** This will force all the Expr.token.z values to be dynamically 2935 ** allocated rather than point to the input string - which means that 2936 ** they will persist after the current sqlite3_exec() call returns. 2937 */ 2938 pSelect->selFlags |= SF_View; 2939 if( IN_RENAME_OBJECT ){ 2940 p->u.view.pSelect = pSelect; 2941 pSelect = 0; 2942 }else{ 2943 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); 2944 } 2945 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); 2946 p->eTabType = TABTYP_VIEW; 2947 if( db->mallocFailed ) goto create_view_fail; 2948 2949 /* Locate the end of the CREATE VIEW statement. Make sEnd point to 2950 ** the end. 2951 */ 2952 sEnd = pParse->sLastToken; 2953 assert( sEnd.z[0]!=0 || sEnd.n==0 ); 2954 if( sEnd.z[0]!=';' ){ 2955 sEnd.z += sEnd.n; 2956 } 2957 sEnd.n = 0; 2958 n = (int)(sEnd.z - pBegin->z); 2959 assert( n>0 ); 2960 z = pBegin->z; 2961 while( sqlite3Isspace(z[n-1]) ){ n--; } 2962 sEnd.z = &z[n-1]; 2963 sEnd.n = 1; 2964 2965 /* Use sqlite3EndTable() to add the view to the schema table */ 2966 sqlite3EndTable(pParse, 0, &sEnd, 0, 0); 2967 2968 create_view_fail: 2969 sqlite3SelectDelete(db, pSelect); 2970 if( IN_RENAME_OBJECT ){ 2971 sqlite3RenameExprlistUnmap(pParse, pCNames); 2972 } 2973 sqlite3ExprListDelete(db, pCNames); 2974 return; 2975 } 2976 #endif /* SQLITE_OMIT_VIEW */ 2977 2978 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 2979 /* 2980 ** The Table structure pTable is really a VIEW. Fill in the names of 2981 ** the columns of the view in the pTable structure. Return the number 2982 ** of errors. If an error is seen leave an error message in pParse->zErrMsg. 2983 */ 2984 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ 2985 Table *pSelTab; /* A fake table from which we get the result set */ 2986 Select *pSel; /* Copy of the SELECT that implements the view */ 2987 int nErr = 0; /* Number of errors encountered */ 2988 int n; /* Temporarily holds the number of cursors assigned */ 2989 sqlite3 *db = pParse->db; /* Database connection for malloc errors */ 2990 #ifndef SQLITE_OMIT_VIRTUALTABLE 2991 int rc; 2992 #endif 2993 #ifndef SQLITE_OMIT_AUTHORIZATION 2994 sqlite3_xauth xAuth; /* Saved xAuth pointer */ 2995 #endif 2996 2997 assert( pTable ); 2998 2999 #ifndef SQLITE_OMIT_VIRTUALTABLE 3000 db->nSchemaLock++; 3001 rc = sqlite3VtabCallConnect(pParse, pTable); 3002 db->nSchemaLock--; 3003 if( rc ){ 3004 return 1; 3005 } 3006 if( IsVirtual(pTable) ) return 0; 3007 #endif 3008 3009 #ifndef SQLITE_OMIT_VIEW 3010 /* A positive nCol means the columns names for this view are 3011 ** already known. 3012 */ 3013 if( pTable->nCol>0 ) return 0; 3014 3015 /* A negative nCol is a special marker meaning that we are currently 3016 ** trying to compute the column names. If we enter this routine with 3017 ** a negative nCol, it means two or more views form a loop, like this: 3018 ** 3019 ** CREATE VIEW one AS SELECT * FROM two; 3020 ** CREATE VIEW two AS SELECT * FROM one; 3021 ** 3022 ** Actually, the error above is now caught prior to reaching this point. 3023 ** But the following test is still important as it does come up 3024 ** in the following: 3025 ** 3026 ** CREATE TABLE main.ex1(a); 3027 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; 3028 ** SELECT * FROM temp.ex1; 3029 */ 3030 if( pTable->nCol<0 ){ 3031 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); 3032 return 1; 3033 } 3034 assert( pTable->nCol>=0 ); 3035 3036 /* If we get this far, it means we need to compute the table names. 3037 ** Note that the call to sqlite3ResultSetOfSelect() will expand any 3038 ** "*" elements in the results set of the view and will assign cursors 3039 ** to the elements of the FROM clause. But we do not want these changes 3040 ** to be permanent. So the computation is done on a copy of the SELECT 3041 ** statement that defines the view. 3042 */ 3043 assert( IsView(pTable) ); 3044 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0); 3045 if( pSel ){ 3046 u8 eParseMode = pParse->eParseMode; 3047 pParse->eParseMode = PARSE_MODE_NORMAL; 3048 n = pParse->nTab; 3049 sqlite3SrcListAssignCursors(pParse, pSel->pSrc); 3050 pTable->nCol = -1; 3051 DisableLookaside; 3052 #ifndef SQLITE_OMIT_AUTHORIZATION 3053 xAuth = db->xAuth; 3054 db->xAuth = 0; 3055 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 3056 db->xAuth = xAuth; 3057 #else 3058 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); 3059 #endif 3060 pParse->nTab = n; 3061 if( pSelTab==0 ){ 3062 pTable->nCol = 0; 3063 nErr++; 3064 }else if( pTable->pCheck ){ 3065 /* CREATE VIEW name(arglist) AS ... 3066 ** The names of the columns in the table are taken from 3067 ** arglist which is stored in pTable->pCheck. The pCheck field 3068 ** normally holds CHECK constraints on an ordinary table, but for 3069 ** a VIEW it holds the list of column names. 3070 */ 3071 sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 3072 &pTable->nCol, &pTable->aCol); 3073 if( db->mallocFailed==0 3074 && pParse->nErr==0 3075 && pTable->nCol==pSel->pEList->nExpr 3076 ){ 3077 sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel, 3078 SQLITE_AFF_NONE); 3079 } 3080 }else{ 3081 /* CREATE VIEW name AS... without an argument list. Construct 3082 ** the column names from the SELECT statement that defines the view. 3083 */ 3084 assert( pTable->aCol==0 ); 3085 pTable->nCol = pSelTab->nCol; 3086 pTable->aCol = pSelTab->aCol; 3087 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT); 3088 pSelTab->nCol = 0; 3089 pSelTab->aCol = 0; 3090 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); 3091 } 3092 pTable->nNVCol = pTable->nCol; 3093 sqlite3DeleteTable(db, pSelTab); 3094 sqlite3SelectDelete(db, pSel); 3095 EnableLookaside; 3096 pParse->eParseMode = eParseMode; 3097 } else { 3098 nErr++; 3099 } 3100 pTable->pSchema->schemaFlags |= DB_UnresetViews; 3101 if( db->mallocFailed ){ 3102 sqlite3DeleteColumnNames(db, pTable); 3103 } 3104 #endif /* SQLITE_OMIT_VIEW */ 3105 return nErr; 3106 } 3107 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 3108 3109 #ifndef SQLITE_OMIT_VIEW 3110 /* 3111 ** Clear the column names from every VIEW in database idx. 3112 */ 3113 static void sqliteViewResetAll(sqlite3 *db, int idx){ 3114 HashElem *i; 3115 assert( sqlite3SchemaMutexHeld(db, idx, 0) ); 3116 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; 3117 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ 3118 Table *pTab = sqliteHashData(i); 3119 if( IsView(pTab) ){ 3120 sqlite3DeleteColumnNames(db, pTab); 3121 } 3122 } 3123 DbClearProperty(db, idx, DB_UnresetViews); 3124 } 3125 #else 3126 # define sqliteViewResetAll(A,B) 3127 #endif /* SQLITE_OMIT_VIEW */ 3128 3129 /* 3130 ** This function is called by the VDBE to adjust the internal schema 3131 ** used by SQLite when the btree layer moves a table root page. The 3132 ** root-page of a table or index in database iDb has changed from iFrom 3133 ** to iTo. 3134 ** 3135 ** Ticket #1728: The symbol table might still contain information 3136 ** on tables and/or indices that are the process of being deleted. 3137 ** If you are unlucky, one of those deleted indices or tables might 3138 ** have the same rootpage number as the real table or index that is 3139 ** being moved. So we cannot stop searching after the first match 3140 ** because the first match might be for one of the deleted indices 3141 ** or tables and not the table/index that is actually being moved. 3142 ** We must continue looping until all tables and indices with 3143 ** rootpage==iFrom have been converted to have a rootpage of iTo 3144 ** in order to be certain that we got the right one. 3145 */ 3146 #ifndef SQLITE_OMIT_AUTOVACUUM 3147 void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){ 3148 HashElem *pElem; 3149 Hash *pHash; 3150 Db *pDb; 3151 3152 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3153 pDb = &db->aDb[iDb]; 3154 pHash = &pDb->pSchema->tblHash; 3155 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 3156 Table *pTab = sqliteHashData(pElem); 3157 if( pTab->tnum==iFrom ){ 3158 pTab->tnum = iTo; 3159 } 3160 } 3161 pHash = &pDb->pSchema->idxHash; 3162 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ 3163 Index *pIdx = sqliteHashData(pElem); 3164 if( pIdx->tnum==iFrom ){ 3165 pIdx->tnum = iTo; 3166 } 3167 } 3168 } 3169 #endif 3170 3171 /* 3172 ** Write code to erase the table with root-page iTable from database iDb. 3173 ** Also write code to modify the sqlite_schema table and internal schema 3174 ** if a root-page of another table is moved by the btree-layer whilst 3175 ** erasing iTable (this can happen with an auto-vacuum database). 3176 */ 3177 static void destroyRootPage(Parse *pParse, int iTable, int iDb){ 3178 Vdbe *v = sqlite3GetVdbe(pParse); 3179 int r1 = sqlite3GetTempReg(pParse); 3180 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema"); 3181 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); 3182 sqlite3MayAbort(pParse); 3183 #ifndef SQLITE_OMIT_AUTOVACUUM 3184 /* OP_Destroy stores an in integer r1. If this integer 3185 ** is non-zero, then it is the root page number of a table moved to 3186 ** location iTable. The following code modifies the sqlite_schema table to 3187 ** reflect this. 3188 ** 3189 ** The "#NNN" in the SQL is a special constant that means whatever value 3190 ** is in register NNN. See grammar rules associated with the TK_REGISTER 3191 ** token for additional information. 3192 */ 3193 sqlite3NestedParse(pParse, 3194 "UPDATE %Q." DFLT_SCHEMA_TABLE 3195 " SET rootpage=%d WHERE #%d AND rootpage=#%d", 3196 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1); 3197 #endif 3198 sqlite3ReleaseTempReg(pParse, r1); 3199 } 3200 3201 /* 3202 ** Write VDBE code to erase table pTab and all associated indices on disk. 3203 ** Code to update the sqlite_schema tables and internal schema definitions 3204 ** in case a root-page belonging to another table is moved by the btree layer 3205 ** is also added (this can happen with an auto-vacuum database). 3206 */ 3207 static void destroyTable(Parse *pParse, Table *pTab){ 3208 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM 3209 ** is not defined), then it is important to call OP_Destroy on the 3210 ** table and index root-pages in order, starting with the numerically 3211 ** largest root-page number. This guarantees that none of the root-pages 3212 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the 3213 ** following were coded: 3214 ** 3215 ** OP_Destroy 4 0 3216 ** ... 3217 ** OP_Destroy 5 0 3218 ** 3219 ** and root page 5 happened to be the largest root-page number in the 3220 ** database, then root page 5 would be moved to page 4 by the 3221 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit 3222 ** a free-list page. 3223 */ 3224 Pgno iTab = pTab->tnum; 3225 Pgno iDestroyed = 0; 3226 3227 while( 1 ){ 3228 Index *pIdx; 3229 Pgno iLargest = 0; 3230 3231 if( iDestroyed==0 || iTab<iDestroyed ){ 3232 iLargest = iTab; 3233 } 3234 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 3235 Pgno iIdx = pIdx->tnum; 3236 assert( pIdx->pSchema==pTab->pSchema ); 3237 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){ 3238 iLargest = iIdx; 3239 } 3240 } 3241 if( iLargest==0 ){ 3242 return; 3243 }else{ 3244 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 3245 assert( iDb>=0 && iDb<pParse->db->nDb ); 3246 destroyRootPage(pParse, iLargest, iDb); 3247 iDestroyed = iLargest; 3248 } 3249 } 3250 } 3251 3252 /* 3253 ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) 3254 ** after a DROP INDEX or DROP TABLE command. 3255 */ 3256 static void sqlite3ClearStatTables( 3257 Parse *pParse, /* The parsing context */ 3258 int iDb, /* The database number */ 3259 const char *zType, /* "idx" or "tbl" */ 3260 const char *zName /* Name of index or table */ 3261 ){ 3262 int i; 3263 const char *zDbName = pParse->db->aDb[iDb].zDbSName; 3264 for(i=1; i<=4; i++){ 3265 char zTab[24]; 3266 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); 3267 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ 3268 sqlite3NestedParse(pParse, 3269 "DELETE FROM %Q.%s WHERE %s=%Q", 3270 zDbName, zTab, zType, zName 3271 ); 3272 } 3273 } 3274 } 3275 3276 /* 3277 ** Generate code to drop a table. 3278 */ 3279 void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ 3280 Vdbe *v; 3281 sqlite3 *db = pParse->db; 3282 Trigger *pTrigger; 3283 Db *pDb = &db->aDb[iDb]; 3284 3285 v = sqlite3GetVdbe(pParse); 3286 assert( v!=0 ); 3287 sqlite3BeginWriteOperation(pParse, 1, iDb); 3288 3289 #ifndef SQLITE_OMIT_VIRTUALTABLE 3290 if( IsVirtual(pTab) ){ 3291 sqlite3VdbeAddOp0(v, OP_VBegin); 3292 } 3293 #endif 3294 3295 /* Drop all triggers associated with the table being dropped. Code 3296 ** is generated to remove entries from sqlite_schema and/or 3297 ** sqlite_temp_schema if required. 3298 */ 3299 pTrigger = sqlite3TriggerList(pParse, pTab); 3300 while( pTrigger ){ 3301 assert( pTrigger->pSchema==pTab->pSchema || 3302 pTrigger->pSchema==db->aDb[1].pSchema ); 3303 sqlite3DropTriggerPtr(pParse, pTrigger); 3304 pTrigger = pTrigger->pNext; 3305 } 3306 3307 #ifndef SQLITE_OMIT_AUTOINCREMENT 3308 /* Remove any entries of the sqlite_sequence table associated with 3309 ** the table being dropped. This is done before the table is dropped 3310 ** at the btree level, in case the sqlite_sequence table needs to 3311 ** move as a result of the drop (can happen in auto-vacuum mode). 3312 */ 3313 if( pTab->tabFlags & TF_Autoincrement ){ 3314 sqlite3NestedParse(pParse, 3315 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", 3316 pDb->zDbSName, pTab->zName 3317 ); 3318 } 3319 #endif 3320 3321 /* Drop all entries in the schema table that refer to the 3322 ** table. The program name loops through the schema table and deletes 3323 ** every row that refers to a table of the same name as the one being 3324 ** dropped. Triggers are handled separately because a trigger can be 3325 ** created in the temp database that refers to a table in another 3326 ** database. 3327 */ 3328 sqlite3NestedParse(pParse, 3329 "DELETE FROM %Q." DFLT_SCHEMA_TABLE 3330 " WHERE tbl_name=%Q and type!='trigger'", 3331 pDb->zDbSName, pTab->zName); 3332 if( !isView && !IsVirtual(pTab) ){ 3333 destroyTable(pParse, pTab); 3334 } 3335 3336 /* Remove the table entry from SQLite's internal schema and modify 3337 ** the schema cookie. 3338 */ 3339 if( IsVirtual(pTab) ){ 3340 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); 3341 sqlite3MayAbort(pParse); 3342 } 3343 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); 3344 sqlite3ChangeCookie(pParse, iDb); 3345 sqliteViewResetAll(db, iDb); 3346 } 3347 3348 /* 3349 ** Return TRUE if shadow tables should be read-only in the current 3350 ** context. 3351 */ 3352 int sqlite3ReadOnlyShadowTables(sqlite3 *db){ 3353 #ifndef SQLITE_OMIT_VIRTUALTABLE 3354 if( (db->flags & SQLITE_Defensive)!=0 3355 && db->pVtabCtx==0 3356 && db->nVdbeExec==0 3357 && !sqlite3VtabInSync(db) 3358 ){ 3359 return 1; 3360 } 3361 #endif 3362 return 0; 3363 } 3364 3365 /* 3366 ** Return true if it is not allowed to drop the given table 3367 */ 3368 static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){ 3369 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ 3370 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0; 3371 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0; 3372 return 1; 3373 } 3374 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){ 3375 return 1; 3376 } 3377 return 0; 3378 } 3379 3380 /* 3381 ** This routine is called to do the work of a DROP TABLE statement. 3382 ** pName is the name of the table to be dropped. 3383 */ 3384 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ 3385 Table *pTab; 3386 Vdbe *v; 3387 sqlite3 *db = pParse->db; 3388 int iDb; 3389 3390 if( db->mallocFailed ){ 3391 goto exit_drop_table; 3392 } 3393 assert( pParse->nErr==0 ); 3394 assert( pName->nSrc==1 ); 3395 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; 3396 if( noErr ) db->suppressErr++; 3397 assert( isView==0 || isView==LOCATE_VIEW ); 3398 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); 3399 if( noErr ) db->suppressErr--; 3400 3401 if( pTab==0 ){ 3402 if( noErr ){ 3403 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 3404 sqlite3ForceNotReadOnly(pParse); 3405 } 3406 goto exit_drop_table; 3407 } 3408 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 3409 assert( iDb>=0 && iDb<db->nDb ); 3410 3411 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure 3412 ** it is initialized. 3413 */ 3414 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ 3415 goto exit_drop_table; 3416 } 3417 #ifndef SQLITE_OMIT_AUTHORIZATION 3418 { 3419 int code; 3420 const char *zTab = SCHEMA_TABLE(iDb); 3421 const char *zDb = db->aDb[iDb].zDbSName; 3422 const char *zArg2 = 0; 3423 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ 3424 goto exit_drop_table; 3425 } 3426 if( isView ){ 3427 if( !OMIT_TEMPDB && iDb==1 ){ 3428 code = SQLITE_DROP_TEMP_VIEW; 3429 }else{ 3430 code = SQLITE_DROP_VIEW; 3431 } 3432 #ifndef SQLITE_OMIT_VIRTUALTABLE 3433 }else if( IsVirtual(pTab) ){ 3434 code = SQLITE_DROP_VTABLE; 3435 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; 3436 #endif 3437 }else{ 3438 if( !OMIT_TEMPDB && iDb==1 ){ 3439 code = SQLITE_DROP_TEMP_TABLE; 3440 }else{ 3441 code = SQLITE_DROP_TABLE; 3442 } 3443 } 3444 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ 3445 goto exit_drop_table; 3446 } 3447 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ 3448 goto exit_drop_table; 3449 } 3450 } 3451 #endif 3452 if( tableMayNotBeDropped(db, pTab) ){ 3453 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); 3454 goto exit_drop_table; 3455 } 3456 3457 #ifndef SQLITE_OMIT_VIEW 3458 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used 3459 ** on a table. 3460 */ 3461 if( isView && !IsView(pTab) ){ 3462 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); 3463 goto exit_drop_table; 3464 } 3465 if( !isView && IsView(pTab) ){ 3466 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); 3467 goto exit_drop_table; 3468 } 3469 #endif 3470 3471 /* Generate code to remove the table from the schema table 3472 ** on disk. 3473 */ 3474 v = sqlite3GetVdbe(pParse); 3475 if( v ){ 3476 sqlite3BeginWriteOperation(pParse, 1, iDb); 3477 if( !isView ){ 3478 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); 3479 sqlite3FkDropTable(pParse, pName, pTab); 3480 } 3481 sqlite3CodeDropTable(pParse, pTab, iDb, isView); 3482 } 3483 3484 exit_drop_table: 3485 sqlite3SrcListDelete(db, pName); 3486 } 3487 3488 /* 3489 ** This routine is called to create a new foreign key on the table 3490 ** currently under construction. pFromCol determines which columns 3491 ** in the current table point to the foreign key. If pFromCol==0 then 3492 ** connect the key to the last column inserted. pTo is the name of 3493 ** the table referred to (a.k.a the "parent" table). pToCol is a list 3494 ** of tables in the parent pTo table. flags contains all 3495 ** information about the conflict resolution algorithms specified 3496 ** in the ON DELETE, ON UPDATE and ON INSERT clauses. 3497 ** 3498 ** An FKey structure is created and added to the table currently 3499 ** under construction in the pParse->pNewTable field. 3500 ** 3501 ** The foreign key is set for IMMEDIATE processing. A subsequent call 3502 ** to sqlite3DeferForeignKey() might change this to DEFERRED. 3503 */ 3504 void sqlite3CreateForeignKey( 3505 Parse *pParse, /* Parsing context */ 3506 ExprList *pFromCol, /* Columns in this table that point to other table */ 3507 Token *pTo, /* Name of the other table */ 3508 ExprList *pToCol, /* Columns in the other table */ 3509 int flags /* Conflict resolution algorithms. */ 3510 ){ 3511 sqlite3 *db = pParse->db; 3512 #ifndef SQLITE_OMIT_FOREIGN_KEY 3513 FKey *pFKey = 0; 3514 FKey *pNextTo; 3515 Table *p = pParse->pNewTable; 3516 int nByte; 3517 int i; 3518 int nCol; 3519 char *z; 3520 3521 assert( pTo!=0 ); 3522 if( p==0 || IN_DECLARE_VTAB ) goto fk_end; 3523 if( pFromCol==0 ){ 3524 int iCol = p->nCol-1; 3525 if( NEVER(iCol<0) ) goto fk_end; 3526 if( pToCol && pToCol->nExpr!=1 ){ 3527 sqlite3ErrorMsg(pParse, "foreign key on %s" 3528 " should reference only one column of table %T", 3529 p->aCol[iCol].zCnName, pTo); 3530 goto fk_end; 3531 } 3532 nCol = 1; 3533 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ 3534 sqlite3ErrorMsg(pParse, 3535 "number of columns in foreign key does not match the number of " 3536 "columns in the referenced table"); 3537 goto fk_end; 3538 }else{ 3539 nCol = pFromCol->nExpr; 3540 } 3541 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; 3542 if( pToCol ){ 3543 for(i=0; i<pToCol->nExpr; i++){ 3544 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1; 3545 } 3546 } 3547 pFKey = sqlite3DbMallocZero(db, nByte ); 3548 if( pFKey==0 ){ 3549 goto fk_end; 3550 } 3551 pFKey->pFrom = p; 3552 pFKey->pNextFrom = p->u.tab.pFKey; 3553 z = (char*)&pFKey->aCol[nCol]; 3554 pFKey->zTo = z; 3555 if( IN_RENAME_OBJECT ){ 3556 sqlite3RenameTokenMap(pParse, (void*)z, pTo); 3557 } 3558 memcpy(z, pTo->z, pTo->n); 3559 z[pTo->n] = 0; 3560 sqlite3Dequote(z); 3561 z += pTo->n+1; 3562 pFKey->nCol = nCol; 3563 if( pFromCol==0 ){ 3564 pFKey->aCol[0].iFrom = p->nCol-1; 3565 }else{ 3566 for(i=0; i<nCol; i++){ 3567 int j; 3568 for(j=0; j<p->nCol; j++){ 3569 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){ 3570 pFKey->aCol[i].iFrom = j; 3571 break; 3572 } 3573 } 3574 if( j>=p->nCol ){ 3575 sqlite3ErrorMsg(pParse, 3576 "unknown column \"%s\" in foreign key definition", 3577 pFromCol->a[i].zEName); 3578 goto fk_end; 3579 } 3580 if( IN_RENAME_OBJECT ){ 3581 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName); 3582 } 3583 } 3584 } 3585 if( pToCol ){ 3586 for(i=0; i<nCol; i++){ 3587 int n = sqlite3Strlen30(pToCol->a[i].zEName); 3588 pFKey->aCol[i].zCol = z; 3589 if( IN_RENAME_OBJECT ){ 3590 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName); 3591 } 3592 memcpy(z, pToCol->a[i].zEName, n); 3593 z[n] = 0; 3594 z += n+1; 3595 } 3596 } 3597 pFKey->isDeferred = 0; 3598 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ 3599 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ 3600 3601 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); 3602 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 3603 pFKey->zTo, (void *)pFKey 3604 ); 3605 if( pNextTo==pFKey ){ 3606 sqlite3OomFault(db); 3607 goto fk_end; 3608 } 3609 if( pNextTo ){ 3610 assert( pNextTo->pPrevTo==0 ); 3611 pFKey->pNextTo = pNextTo; 3612 pNextTo->pPrevTo = pFKey; 3613 } 3614 3615 /* Link the foreign key to the table as the last step. 3616 */ 3617 assert( !IsVirtual(p) ); 3618 p->u.tab.pFKey = pFKey; 3619 pFKey = 0; 3620 3621 fk_end: 3622 sqlite3DbFree(db, pFKey); 3623 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ 3624 sqlite3ExprListDelete(db, pFromCol); 3625 sqlite3ExprListDelete(db, pToCol); 3626 } 3627 3628 /* 3629 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED 3630 ** clause is seen as part of a foreign key definition. The isDeferred 3631 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. 3632 ** The behavior of the most recently created foreign key is adjusted 3633 ** accordingly. 3634 */ 3635 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ 3636 #ifndef SQLITE_OMIT_FOREIGN_KEY 3637 Table *pTab; 3638 FKey *pFKey; 3639 if( (pTab = pParse->pNewTable)==0 ) return; 3640 if( NEVER(IsVirtual(pTab)) ) return; 3641 if( (pFKey = pTab->u.tab.pFKey)==0 ) return; 3642 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ 3643 pFKey->isDeferred = (u8)isDeferred; 3644 #endif 3645 } 3646 3647 /* 3648 ** Generate code that will erase and refill index *pIdx. This is 3649 ** used to initialize a newly created index or to recompute the 3650 ** content of an index in response to a REINDEX command. 3651 ** 3652 ** if memRootPage is not negative, it means that the index is newly 3653 ** created. The register specified by memRootPage contains the 3654 ** root page number of the index. If memRootPage is negative, then 3655 ** the index already exists and must be cleared before being refilled and 3656 ** the root page number of the index is taken from pIndex->tnum. 3657 */ 3658 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ 3659 Table *pTab = pIndex->pTable; /* The table that is indexed */ 3660 int iTab = pParse->nTab++; /* Btree cursor used for pTab */ 3661 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ 3662 int iSorter; /* Cursor opened by OpenSorter (if in use) */ 3663 int addr1; /* Address of top of loop */ 3664 int addr2; /* Address to jump to for next iteration */ 3665 Pgno tnum; /* Root page of index */ 3666 int iPartIdxLabel; /* Jump to this label to skip a row */ 3667 Vdbe *v; /* Generate code into this virtual machine */ 3668 KeyInfo *pKey; /* KeyInfo for index */ 3669 int regRecord; /* Register holding assembled index record */ 3670 sqlite3 *db = pParse->db; /* The database connection */ 3671 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 3672 3673 #ifndef SQLITE_OMIT_AUTHORIZATION 3674 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, 3675 db->aDb[iDb].zDbSName ) ){ 3676 return; 3677 } 3678 #endif 3679 3680 /* Require a write-lock on the table to perform this operation */ 3681 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); 3682 3683 v = sqlite3GetVdbe(pParse); 3684 if( v==0 ) return; 3685 if( memRootPage>=0 ){ 3686 tnum = (Pgno)memRootPage; 3687 }else{ 3688 tnum = pIndex->tnum; 3689 } 3690 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); 3691 assert( pKey!=0 || db->mallocFailed || pParse->nErr ); 3692 3693 /* Open the sorter cursor if we are to use one. */ 3694 iSorter = pParse->nTab++; 3695 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) 3696 sqlite3KeyInfoRef(pKey), P4_KEYINFO); 3697 3698 /* Open the table. Loop through all rows of the table, inserting index 3699 ** records into the sorter. */ 3700 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 3701 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); 3702 regRecord = sqlite3GetTempReg(pParse); 3703 sqlite3MultiWrite(pParse); 3704 3705 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); 3706 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); 3707 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); 3708 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); 3709 sqlite3VdbeJumpHere(v, addr1); 3710 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); 3711 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb, 3712 (char *)pKey, P4_KEYINFO); 3713 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); 3714 3715 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); 3716 if( IsUniqueIndex(pIndex) ){ 3717 int j2 = sqlite3VdbeGoto(v, 1); 3718 addr2 = sqlite3VdbeCurrentAddr(v); 3719 sqlite3VdbeVerifyAbortable(v, OE_Abort); 3720 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, 3721 pIndex->nKeyCol); VdbeCoverage(v); 3722 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); 3723 sqlite3VdbeJumpHere(v, j2); 3724 }else{ 3725 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not 3726 ** abort. The exception is if one of the indexed expressions contains a 3727 ** user function that throws an exception when it is evaluated. But the 3728 ** overhead of adding a statement journal to a CREATE INDEX statement is 3729 ** very small (since most of the pages written do not contain content that 3730 ** needs to be restored if the statement aborts), so we call 3731 ** sqlite3MayAbort() for all CREATE INDEX statements. */ 3732 sqlite3MayAbort(pParse); 3733 addr2 = sqlite3VdbeCurrentAddr(v); 3734 } 3735 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); 3736 if( !pIndex->bAscKeyBug ){ 3737 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much 3738 ** faster by avoiding unnecessary seeks. But the optimization does 3739 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables 3740 ** with DESC primary keys, since those indexes have there keys in 3741 ** a different order from the main table. 3742 ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf 3743 */ 3744 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); 3745 } 3746 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); 3747 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 3748 sqlite3ReleaseTempReg(pParse, regRecord); 3749 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); 3750 sqlite3VdbeJumpHere(v, addr1); 3751 3752 sqlite3VdbeAddOp1(v, OP_Close, iTab); 3753 sqlite3VdbeAddOp1(v, OP_Close, iIdx); 3754 sqlite3VdbeAddOp1(v, OP_Close, iSorter); 3755 } 3756 3757 /* 3758 ** Allocate heap space to hold an Index object with nCol columns. 3759 ** 3760 ** Increase the allocation size to provide an extra nExtra bytes 3761 ** of 8-byte aligned space after the Index object and return a 3762 ** pointer to this extra space in *ppExtra. 3763 */ 3764 Index *sqlite3AllocateIndexObject( 3765 sqlite3 *db, /* Database connection */ 3766 i16 nCol, /* Total number of columns in the index */ 3767 int nExtra, /* Number of bytes of extra space to alloc */ 3768 char **ppExtra /* Pointer to the "extra" space */ 3769 ){ 3770 Index *p; /* Allocated index object */ 3771 int nByte; /* Bytes of space for Index object + arrays */ 3772 3773 nByte = ROUND8(sizeof(Index)) + /* Index structure */ 3774 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ 3775 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ 3776 sizeof(i16)*nCol + /* Index.aiColumn */ 3777 sizeof(u8)*nCol); /* Index.aSortOrder */ 3778 p = sqlite3DbMallocZero(db, nByte + nExtra); 3779 if( p ){ 3780 char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); 3781 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); 3782 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); 3783 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; 3784 p->aSortOrder = (u8*)pExtra; 3785 p->nColumn = nCol; 3786 p->nKeyCol = nCol - 1; 3787 *ppExtra = ((char*)p) + nByte; 3788 } 3789 return p; 3790 } 3791 3792 /* 3793 ** If expression list pList contains an expression that was parsed with 3794 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in 3795 ** pParse and return non-zero. Otherwise, return zero. 3796 */ 3797 int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){ 3798 if( pList ){ 3799 int i; 3800 for(i=0; i<pList->nExpr; i++){ 3801 if( pList->a[i].bNulls ){ 3802 u8 sf = pList->a[i].sortFlags; 3803 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", 3804 (sf==0 || sf==3) ? "FIRST" : "LAST" 3805 ); 3806 return 1; 3807 } 3808 } 3809 } 3810 return 0; 3811 } 3812 3813 /* 3814 ** Create a new index for an SQL table. pName1.pName2 is the name of the index 3815 ** and pTblList is the name of the table that is to be indexed. Both will 3816 ** be NULL for a primary key or an index that is created to satisfy a 3817 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable 3818 ** as the table to be indexed. pParse->pNewTable is a table that is 3819 ** currently being constructed by a CREATE TABLE statement. 3820 ** 3821 ** pList is a list of columns to be indexed. pList will be NULL if this 3822 ** is a primary key or unique-constraint on the most recent column added 3823 ** to the table currently under construction. 3824 */ 3825 void sqlite3CreateIndex( 3826 Parse *pParse, /* All information about this parse */ 3827 Token *pName1, /* First part of index name. May be NULL */ 3828 Token *pName2, /* Second part of index name. May be NULL */ 3829 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ 3830 ExprList *pList, /* A list of columns to be indexed */ 3831 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ 3832 Token *pStart, /* The CREATE token that begins this statement */ 3833 Expr *pPIWhere, /* WHERE clause for partial indices */ 3834 int sortOrder, /* Sort order of primary key when pList==NULL */ 3835 int ifNotExist, /* Omit error if index already exists */ 3836 u8 idxType /* The index type */ 3837 ){ 3838 Table *pTab = 0; /* Table to be indexed */ 3839 Index *pIndex = 0; /* The index to be created */ 3840 char *zName = 0; /* Name of the index */ 3841 int nName; /* Number of characters in zName */ 3842 int i, j; 3843 DbFixer sFix; /* For assigning database names to pTable */ 3844 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ 3845 sqlite3 *db = pParse->db; 3846 Db *pDb; /* The specific table containing the indexed database */ 3847 int iDb; /* Index of the database that is being written */ 3848 Token *pName = 0; /* Unqualified name of the index to create */ 3849 struct ExprList_item *pListItem; /* For looping over pList */ 3850 int nExtra = 0; /* Space allocated for zExtra[] */ 3851 int nExtraCol; /* Number of extra columns needed */ 3852 char *zExtra = 0; /* Extra space after the Index object */ 3853 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ 3854 3855 if( db->mallocFailed || pParse->nErr>0 ){ 3856 goto exit_create_index; 3857 } 3858 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ 3859 goto exit_create_index; 3860 } 3861 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 3862 goto exit_create_index; 3863 } 3864 if( sqlite3HasExplicitNulls(pParse, pList) ){ 3865 goto exit_create_index; 3866 } 3867 3868 /* 3869 ** Find the table that is to be indexed. Return early if not found. 3870 */ 3871 if( pTblName!=0 ){ 3872 3873 /* Use the two-part index name to determine the database 3874 ** to search for the table. 'Fix' the table name to this db 3875 ** before looking up the table. 3876 */ 3877 assert( pName1 && pName2 ); 3878 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); 3879 if( iDb<0 ) goto exit_create_index; 3880 assert( pName && pName->z ); 3881 3882 #ifndef SQLITE_OMIT_TEMPDB 3883 /* If the index name was unqualified, check if the table 3884 ** is a temp table. If so, set the database to 1. Do not do this 3885 ** if initialising a database schema. 3886 */ 3887 if( !db->init.busy ){ 3888 pTab = sqlite3SrcListLookup(pParse, pTblName); 3889 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ 3890 iDb = 1; 3891 } 3892 } 3893 #endif 3894 3895 sqlite3FixInit(&sFix, pParse, iDb, "index", pName); 3896 if( sqlite3FixSrcList(&sFix, pTblName) ){ 3897 /* Because the parser constructs pTblName from a single identifier, 3898 ** sqlite3FixSrcList can never fail. */ 3899 assert(0); 3900 } 3901 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); 3902 assert( db->mallocFailed==0 || pTab==0 ); 3903 if( pTab==0 ) goto exit_create_index; 3904 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ 3905 sqlite3ErrorMsg(pParse, 3906 "cannot create a TEMP index on non-TEMP table \"%s\"", 3907 pTab->zName); 3908 goto exit_create_index; 3909 } 3910 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); 3911 }else{ 3912 assert( pName==0 ); 3913 assert( pStart==0 ); 3914 pTab = pParse->pNewTable; 3915 if( !pTab ) goto exit_create_index; 3916 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 3917 } 3918 pDb = &db->aDb[iDb]; 3919 3920 assert( pTab!=0 ); 3921 assert( pParse->nErr==0 ); 3922 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 3923 && db->init.busy==0 3924 && pTblName!=0 3925 #if SQLITE_USER_AUTHENTICATION 3926 && sqlite3UserAuthTable(pTab->zName)==0 3927 #endif 3928 ){ 3929 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); 3930 goto exit_create_index; 3931 } 3932 #ifndef SQLITE_OMIT_VIEW 3933 if( IsView(pTab) ){ 3934 sqlite3ErrorMsg(pParse, "views may not be indexed"); 3935 goto exit_create_index; 3936 } 3937 #endif 3938 #ifndef SQLITE_OMIT_VIRTUALTABLE 3939 if( IsVirtual(pTab) ){ 3940 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); 3941 goto exit_create_index; 3942 } 3943 #endif 3944 3945 /* 3946 ** Find the name of the index. Make sure there is not already another 3947 ** index or table with the same name. 3948 ** 3949 ** Exception: If we are reading the names of permanent indices from the 3950 ** sqlite_schema table (because some other process changed the schema) and 3951 ** one of the index names collides with the name of a temporary table or 3952 ** index, then we will continue to process this index. 3953 ** 3954 ** If pName==0 it means that we are 3955 ** dealing with a primary key or UNIQUE constraint. We have to invent our 3956 ** own name. 3957 */ 3958 if( pName ){ 3959 zName = sqlite3NameFromToken(db, pName); 3960 if( zName==0 ) goto exit_create_index; 3961 assert( pName->z!=0 ); 3962 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){ 3963 goto exit_create_index; 3964 } 3965 if( !IN_RENAME_OBJECT ){ 3966 if( !db->init.busy ){ 3967 if( sqlite3FindTable(db, zName, 0)!=0 ){ 3968 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); 3969 goto exit_create_index; 3970 } 3971 } 3972 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ 3973 if( !ifNotExist ){ 3974 sqlite3ErrorMsg(pParse, "index %s already exists", zName); 3975 }else{ 3976 assert( !db->init.busy ); 3977 sqlite3CodeVerifySchema(pParse, iDb); 3978 sqlite3ForceNotReadOnly(pParse); 3979 } 3980 goto exit_create_index; 3981 } 3982 } 3983 }else{ 3984 int n; 3985 Index *pLoop; 3986 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} 3987 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); 3988 if( zName==0 ){ 3989 goto exit_create_index; 3990 } 3991 3992 /* Automatic index names generated from within sqlite3_declare_vtab() 3993 ** must have names that are distinct from normal automatic index names. 3994 ** The following statement converts "sqlite3_autoindex..." into 3995 ** "sqlite3_butoindex..." in order to make the names distinct. 3996 ** The "vtab_err.test" test demonstrates the need of this statement. */ 3997 if( IN_SPECIAL_PARSE ) zName[7]++; 3998 } 3999 4000 /* Check for authorization to create an index. 4001 */ 4002 #ifndef SQLITE_OMIT_AUTHORIZATION 4003 if( !IN_RENAME_OBJECT ){ 4004 const char *zDb = pDb->zDbSName; 4005 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ 4006 goto exit_create_index; 4007 } 4008 i = SQLITE_CREATE_INDEX; 4009 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; 4010 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ 4011 goto exit_create_index; 4012 } 4013 } 4014 #endif 4015 4016 /* If pList==0, it means this routine was called to make a primary 4017 ** key out of the last column added to the table under construction. 4018 ** So create a fake list to simulate this. 4019 */ 4020 if( pList==0 ){ 4021 Token prevCol; 4022 Column *pCol = &pTab->aCol[pTab->nCol-1]; 4023 pCol->colFlags |= COLFLAG_UNIQUE; 4024 sqlite3TokenInit(&prevCol, pCol->zCnName); 4025 pList = sqlite3ExprListAppend(pParse, 0, 4026 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); 4027 if( pList==0 ) goto exit_create_index; 4028 assert( pList->nExpr==1 ); 4029 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED); 4030 }else{ 4031 sqlite3ExprListCheckLength(pParse, pList, "index"); 4032 if( pParse->nErr ) goto exit_create_index; 4033 } 4034 4035 /* Figure out how many bytes of space are required to store explicitly 4036 ** specified collation sequence names. 4037 */ 4038 for(i=0; i<pList->nExpr; i++){ 4039 Expr *pExpr = pList->a[i].pExpr; 4040 assert( pExpr!=0 ); 4041 if( pExpr->op==TK_COLLATE ){ 4042 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); 4043 } 4044 } 4045 4046 /* 4047 ** Allocate the index structure. 4048 */ 4049 nName = sqlite3Strlen30(zName); 4050 nExtraCol = pPk ? pPk->nKeyCol : 1; 4051 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ ); 4052 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, 4053 nName + nExtra + 1, &zExtra); 4054 if( db->mallocFailed ){ 4055 goto exit_create_index; 4056 } 4057 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); 4058 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); 4059 pIndex->zName = zExtra; 4060 zExtra += nName + 1; 4061 memcpy(pIndex->zName, zName, nName+1); 4062 pIndex->pTable = pTab; 4063 pIndex->onError = (u8)onError; 4064 pIndex->uniqNotNull = onError!=OE_None; 4065 pIndex->idxType = idxType; 4066 pIndex->pSchema = db->aDb[iDb].pSchema; 4067 pIndex->nKeyCol = pList->nExpr; 4068 if( pPIWhere ){ 4069 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); 4070 pIndex->pPartIdxWhere = pPIWhere; 4071 pPIWhere = 0; 4072 } 4073 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 4074 4075 /* Check to see if we should honor DESC requests on index columns 4076 */ 4077 if( pDb->pSchema->file_format>=4 ){ 4078 sortOrderMask = -1; /* Honor DESC */ 4079 }else{ 4080 sortOrderMask = 0; /* Ignore DESC */ 4081 } 4082 4083 /* Analyze the list of expressions that form the terms of the index and 4084 ** report any errors. In the common case where the expression is exactly 4085 ** a table column, store that column in aiColumn[]. For general expressions, 4086 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. 4087 ** 4088 ** TODO: Issue a warning if two or more columns of the index are identical. 4089 ** TODO: Issue a warning if the table primary key is used as part of the 4090 ** index key. 4091 */ 4092 pListItem = pList->a; 4093 if( IN_RENAME_OBJECT ){ 4094 pIndex->aColExpr = pList; 4095 pList = 0; 4096 } 4097 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){ 4098 Expr *pCExpr; /* The i-th index expression */ 4099 int requestedSortOrder; /* ASC or DESC on the i-th expression */ 4100 const char *zColl; /* Collation sequence name */ 4101 4102 sqlite3StringToId(pListItem->pExpr); 4103 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); 4104 if( pParse->nErr ) goto exit_create_index; 4105 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); 4106 if( pCExpr->op!=TK_COLUMN ){ 4107 if( pTab==pParse->pNewTable ){ 4108 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " 4109 "UNIQUE constraints"); 4110 goto exit_create_index; 4111 } 4112 if( pIndex->aColExpr==0 ){ 4113 pIndex->aColExpr = pList; 4114 pList = 0; 4115 } 4116 j = XN_EXPR; 4117 pIndex->aiColumn[i] = XN_EXPR; 4118 pIndex->uniqNotNull = 0; 4119 }else{ 4120 j = pCExpr->iColumn; 4121 assert( j<=0x7fff ); 4122 if( j<0 ){ 4123 j = pTab->iPKey; 4124 }else{ 4125 if( pTab->aCol[j].notNull==0 ){ 4126 pIndex->uniqNotNull = 0; 4127 } 4128 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){ 4129 pIndex->bHasVCol = 1; 4130 } 4131 } 4132 pIndex->aiColumn[i] = (i16)j; 4133 } 4134 zColl = 0; 4135 if( pListItem->pExpr->op==TK_COLLATE ){ 4136 int nColl; 4137 zColl = pListItem->pExpr->u.zToken; 4138 nColl = sqlite3Strlen30(zColl) + 1; 4139 assert( nExtra>=nColl ); 4140 memcpy(zExtra, zColl, nColl); 4141 zColl = zExtra; 4142 zExtra += nColl; 4143 nExtra -= nColl; 4144 }else if( j>=0 ){ 4145 zColl = sqlite3ColumnColl(&pTab->aCol[j]); 4146 } 4147 if( !zColl ) zColl = sqlite3StrBINARY; 4148 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ 4149 goto exit_create_index; 4150 } 4151 pIndex->azColl[i] = zColl; 4152 requestedSortOrder = pListItem->sortFlags & sortOrderMask; 4153 pIndex->aSortOrder[i] = (u8)requestedSortOrder; 4154 } 4155 4156 /* Append the table key to the end of the index. For WITHOUT ROWID 4157 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For 4158 ** normal tables (when pPk==0) this will be the rowid. 4159 */ 4160 if( pPk ){ 4161 for(j=0; j<pPk->nKeyCol; j++){ 4162 int x = pPk->aiColumn[j]; 4163 assert( x>=0 ); 4164 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){ 4165 pIndex->nColumn--; 4166 }else{ 4167 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) ); 4168 pIndex->aiColumn[i] = x; 4169 pIndex->azColl[i] = pPk->azColl[j]; 4170 pIndex->aSortOrder[i] = pPk->aSortOrder[j]; 4171 i++; 4172 } 4173 } 4174 assert( i==pIndex->nColumn ); 4175 }else{ 4176 pIndex->aiColumn[i] = XN_ROWID; 4177 pIndex->azColl[i] = sqlite3StrBINARY; 4178 } 4179 sqlite3DefaultRowEst(pIndex); 4180 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); 4181 4182 /* If this index contains every column of its table, then mark 4183 ** it as a covering index */ 4184 assert( HasRowid(pTab) 4185 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 ); 4186 recomputeColumnsNotIndexed(pIndex); 4187 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ 4188 pIndex->isCovering = 1; 4189 for(j=0; j<pTab->nCol; j++){ 4190 if( j==pTab->iPKey ) continue; 4191 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue; 4192 pIndex->isCovering = 0; 4193 break; 4194 } 4195 } 4196 4197 if( pTab==pParse->pNewTable ){ 4198 /* This routine has been called to create an automatic index as a 4199 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or 4200 ** a PRIMARY KEY or UNIQUE clause following the column definitions. 4201 ** i.e. one of: 4202 ** 4203 ** CREATE TABLE t(x PRIMARY KEY, y); 4204 ** CREATE TABLE t(x, y, UNIQUE(x, y)); 4205 ** 4206 ** Either way, check to see if the table already has such an index. If 4207 ** so, don't bother creating this one. This only applies to 4208 ** automatically created indices. Users can do as they wish with 4209 ** explicit indices. 4210 ** 4211 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent 4212 ** (and thus suppressing the second one) even if they have different 4213 ** sort orders. 4214 ** 4215 ** If there are different collating sequences or if the columns of 4216 ** the constraint occur in different orders, then the constraints are 4217 ** considered distinct and both result in separate indices. 4218 */ 4219 Index *pIdx; 4220 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 4221 int k; 4222 assert( IsUniqueIndex(pIdx) ); 4223 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); 4224 assert( IsUniqueIndex(pIndex) ); 4225 4226 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; 4227 for(k=0; k<pIdx->nKeyCol; k++){ 4228 const char *z1; 4229 const char *z2; 4230 assert( pIdx->aiColumn[k]>=0 ); 4231 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; 4232 z1 = pIdx->azColl[k]; 4233 z2 = pIndex->azColl[k]; 4234 if( sqlite3StrICmp(z1, z2) ) break; 4235 } 4236 if( k==pIdx->nKeyCol ){ 4237 if( pIdx->onError!=pIndex->onError ){ 4238 /* This constraint creates the same index as a previous 4239 ** constraint specified somewhere in the CREATE TABLE statement. 4240 ** However the ON CONFLICT clauses are different. If both this 4241 ** constraint and the previous equivalent constraint have explicit 4242 ** ON CONFLICT clauses this is an error. Otherwise, use the 4243 ** explicitly specified behavior for the index. 4244 */ 4245 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ 4246 sqlite3ErrorMsg(pParse, 4247 "conflicting ON CONFLICT clauses specified", 0); 4248 } 4249 if( pIdx->onError==OE_Default ){ 4250 pIdx->onError = pIndex->onError; 4251 } 4252 } 4253 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; 4254 if( IN_RENAME_OBJECT ){ 4255 pIndex->pNext = pParse->pNewIndex; 4256 pParse->pNewIndex = pIndex; 4257 pIndex = 0; 4258 } 4259 goto exit_create_index; 4260 } 4261 } 4262 } 4263 4264 if( !IN_RENAME_OBJECT ){ 4265 4266 /* Link the new Index structure to its table and to the other 4267 ** in-memory database structures. 4268 */ 4269 assert( pParse->nErr==0 ); 4270 if( db->init.busy ){ 4271 Index *p; 4272 assert( !IN_SPECIAL_PARSE ); 4273 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); 4274 if( pTblName!=0 ){ 4275 pIndex->tnum = db->init.newTnum; 4276 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){ 4277 sqlite3ErrorMsg(pParse, "invalid rootpage"); 4278 pParse->rc = SQLITE_CORRUPT_BKPT; 4279 goto exit_create_index; 4280 } 4281 } 4282 p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 4283 pIndex->zName, pIndex); 4284 if( p ){ 4285 assert( p==pIndex ); /* Malloc must have failed */ 4286 sqlite3OomFault(db); 4287 goto exit_create_index; 4288 } 4289 db->mDbFlags |= DBFLAG_SchemaChange; 4290 } 4291 4292 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the 4293 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then 4294 ** emit code to allocate the index rootpage on disk and make an entry for 4295 ** the index in the sqlite_schema table and populate the index with 4296 ** content. But, do not do this if we are simply reading the sqlite_schema 4297 ** table to parse the schema, or if this index is the PRIMARY KEY index 4298 ** of a WITHOUT ROWID table. 4299 ** 4300 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY 4301 ** or UNIQUE index in a CREATE TABLE statement. Since the table 4302 ** has just been created, it contains no data and the index initialization 4303 ** step can be skipped. 4304 */ 4305 else if( HasRowid(pTab) || pTblName!=0 ){ 4306 Vdbe *v; 4307 char *zStmt; 4308 int iMem = ++pParse->nMem; 4309 4310 v = sqlite3GetVdbe(pParse); 4311 if( v==0 ) goto exit_create_index; 4312 4313 sqlite3BeginWriteOperation(pParse, 1, iDb); 4314 4315 /* Create the rootpage for the index using CreateIndex. But before 4316 ** doing so, code a Noop instruction and store its address in 4317 ** Index.tnum. This is required in case this index is actually a 4318 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 4319 ** that case the convertToWithoutRowidTable() routine will replace 4320 ** the Noop with a Goto to jump over the VDBE code generated below. */ 4321 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop); 4322 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY); 4323 4324 /* Gather the complete text of the CREATE INDEX statement into 4325 ** the zStmt variable 4326 */ 4327 assert( pName!=0 || pStart==0 ); 4328 if( pStart ){ 4329 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; 4330 if( pName->z[n-1]==';' ) n--; 4331 /* A named index with an explicit CREATE INDEX statement */ 4332 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", 4333 onError==OE_None ? "" : " UNIQUE", n, pName->z); 4334 }else{ 4335 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ 4336 /* zStmt = sqlite3MPrintf(""); */ 4337 zStmt = 0; 4338 } 4339 4340 /* Add an entry in sqlite_schema for this index 4341 */ 4342 sqlite3NestedParse(pParse, 4343 "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);", 4344 db->aDb[iDb].zDbSName, 4345 pIndex->zName, 4346 pTab->zName, 4347 iMem, 4348 zStmt 4349 ); 4350 sqlite3DbFree(db, zStmt); 4351 4352 /* Fill the index with data and reparse the schema. Code an OP_Expire 4353 ** to invalidate all pre-compiled statements. 4354 */ 4355 if( pTblName ){ 4356 sqlite3RefillIndex(pParse, pIndex, iMem); 4357 sqlite3ChangeCookie(pParse, iDb); 4358 sqlite3VdbeAddParseSchemaOp(v, iDb, 4359 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0); 4360 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1); 4361 } 4362 4363 sqlite3VdbeJumpHere(v, (int)pIndex->tnum); 4364 } 4365 } 4366 if( db->init.busy || pTblName==0 ){ 4367 pIndex->pNext = pTab->pIndex; 4368 pTab->pIndex = pIndex; 4369 pIndex = 0; 4370 } 4371 else if( IN_RENAME_OBJECT ){ 4372 assert( pParse->pNewIndex==0 ); 4373 pParse->pNewIndex = pIndex; 4374 pIndex = 0; 4375 } 4376 4377 /* Clean up before exiting */ 4378 exit_create_index: 4379 if( pIndex ) sqlite3FreeIndex(db, pIndex); 4380 if( pTab ){ 4381 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list. 4382 ** The list was already ordered when this routine was entered, so at this 4383 ** point at most a single index (the newly added index) will be out of 4384 ** order. So we have to reorder at most one index. */ 4385 Index **ppFrom = &pTab->pIndex; 4386 Index *pThis; 4387 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){ 4388 Index *pNext; 4389 if( pThis->onError!=OE_Replace ) continue; 4390 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){ 4391 *ppFrom = pNext; 4392 pThis->pNext = pNext->pNext; 4393 pNext->pNext = pThis; 4394 ppFrom = &pNext->pNext; 4395 } 4396 break; 4397 } 4398 #ifdef SQLITE_DEBUG 4399 /* Verify that all REPLACE indexes really are now at the end 4400 ** of the index list. In other words, no other index type ever 4401 ** comes after a REPLACE index on the list. */ 4402 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){ 4403 assert( pThis->onError!=OE_Replace 4404 || pThis->pNext==0 4405 || pThis->pNext->onError==OE_Replace ); 4406 } 4407 #endif 4408 } 4409 sqlite3ExprDelete(db, pPIWhere); 4410 sqlite3ExprListDelete(db, pList); 4411 sqlite3SrcListDelete(db, pTblName); 4412 sqlite3DbFree(db, zName); 4413 } 4414 4415 /* 4416 ** Fill the Index.aiRowEst[] array with default information - information 4417 ** to be used when we have not run the ANALYZE command. 4418 ** 4419 ** aiRowEst[0] is supposed to contain the number of elements in the index. 4420 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the 4421 ** number of rows in the table that match any particular value of the 4422 ** first column of the index. aiRowEst[2] is an estimate of the number 4423 ** of rows that match any particular combination of the first 2 columns 4424 ** of the index. And so forth. It must always be the case that 4425 * 4426 ** aiRowEst[N]<=aiRowEst[N-1] 4427 ** aiRowEst[N]>=1 4428 ** 4429 ** Apart from that, we have little to go on besides intuition as to 4430 ** how aiRowEst[] should be initialized. The numbers generated here 4431 ** are based on typical values found in actual indices. 4432 */ 4433 void sqlite3DefaultRowEst(Index *pIdx){ 4434 /* 10, 9, 8, 7, 6 */ 4435 static const LogEst aVal[] = { 33, 32, 30, 28, 26 }; 4436 LogEst *a = pIdx->aiRowLogEst; 4437 LogEst x; 4438 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); 4439 int i; 4440 4441 /* Indexes with default row estimates should not have stat1 data */ 4442 assert( !pIdx->hasStat1 ); 4443 4444 /* Set the first entry (number of rows in the index) to the estimated 4445 ** number of rows in the table, or half the number of rows in the table 4446 ** for a partial index. 4447 ** 4448 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1 4449 ** table but other parts we are having to guess at, then do not let the 4450 ** estimated number of rows in the table be less than 1000 (LogEst 99). 4451 ** Failure to do this can cause the indexes for which we do not have 4452 ** stat1 data to be ignored by the query planner. 4453 */ 4454 x = pIdx->pTable->nRowLogEst; 4455 assert( 99==sqlite3LogEst(1000) ); 4456 if( x<99 ){ 4457 pIdx->pTable->nRowLogEst = x = 99; 4458 } 4459 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); } 4460 a[0] = x; 4461 4462 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is 4463 ** 6 and each subsequent value (if any) is 5. */ 4464 memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); 4465 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ 4466 a[i] = 23; assert( 23==sqlite3LogEst(5) ); 4467 } 4468 4469 assert( 0==sqlite3LogEst(1) ); 4470 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; 4471 } 4472 4473 /* 4474 ** This routine will drop an existing named index. This routine 4475 ** implements the DROP INDEX statement. 4476 */ 4477 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ 4478 Index *pIndex; 4479 Vdbe *v; 4480 sqlite3 *db = pParse->db; 4481 int iDb; 4482 4483 assert( pParse->nErr==0 ); /* Never called with prior errors */ 4484 if( db->mallocFailed ){ 4485 goto exit_drop_index; 4486 } 4487 assert( pName->nSrc==1 ); 4488 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 4489 goto exit_drop_index; 4490 } 4491 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); 4492 if( pIndex==0 ){ 4493 if( !ifExists ){ 4494 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a); 4495 }else{ 4496 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); 4497 sqlite3ForceNotReadOnly(pParse); 4498 } 4499 pParse->checkSchema = 1; 4500 goto exit_drop_index; 4501 } 4502 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ 4503 sqlite3ErrorMsg(pParse, "index associated with UNIQUE " 4504 "or PRIMARY KEY constraint cannot be dropped", 0); 4505 goto exit_drop_index; 4506 } 4507 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); 4508 #ifndef SQLITE_OMIT_AUTHORIZATION 4509 { 4510 int code = SQLITE_DROP_INDEX; 4511 Table *pTab = pIndex->pTable; 4512 const char *zDb = db->aDb[iDb].zDbSName; 4513 const char *zTab = SCHEMA_TABLE(iDb); 4514 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ 4515 goto exit_drop_index; 4516 } 4517 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX; 4518 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ 4519 goto exit_drop_index; 4520 } 4521 } 4522 #endif 4523 4524 /* Generate code to remove the index and from the schema table */ 4525 v = sqlite3GetVdbe(pParse); 4526 if( v ){ 4527 sqlite3BeginWriteOperation(pParse, 1, iDb); 4528 sqlite3NestedParse(pParse, 4529 "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'", 4530 db->aDb[iDb].zDbSName, pIndex->zName 4531 ); 4532 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); 4533 sqlite3ChangeCookie(pParse, iDb); 4534 destroyRootPage(pParse, pIndex->tnum, iDb); 4535 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); 4536 } 4537 4538 exit_drop_index: 4539 sqlite3SrcListDelete(db, pName); 4540 } 4541 4542 /* 4543 ** pArray is a pointer to an array of objects. Each object in the 4544 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() 4545 ** to extend the array so that there is space for a new object at the end. 4546 ** 4547 ** When this function is called, *pnEntry contains the current size of 4548 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes 4549 ** in total). 4550 ** 4551 ** If the realloc() is successful (i.e. if no OOM condition occurs), the 4552 ** space allocated for the new object is zeroed, *pnEntry updated to 4553 ** reflect the new size of the array and a pointer to the new allocation 4554 ** returned. *pIdx is set to the index of the new array entry in this case. 4555 ** 4556 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains 4557 ** unchanged and a copy of pArray returned. 4558 */ 4559 void *sqlite3ArrayAllocate( 4560 sqlite3 *db, /* Connection to notify of malloc failures */ 4561 void *pArray, /* Array of objects. Might be reallocated */ 4562 int szEntry, /* Size of each object in the array */ 4563 int *pnEntry, /* Number of objects currently in use */ 4564 int *pIdx /* Write the index of a new slot here */ 4565 ){ 4566 char *z; 4567 sqlite3_int64 n = *pIdx = *pnEntry; 4568 if( (n & (n-1))==0 ){ 4569 sqlite3_int64 sz = (n==0) ? 1 : 2*n; 4570 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); 4571 if( pNew==0 ){ 4572 *pIdx = -1; 4573 return pArray; 4574 } 4575 pArray = pNew; 4576 } 4577 z = (char*)pArray; 4578 memset(&z[n * szEntry], 0, szEntry); 4579 ++*pnEntry; 4580 return pArray; 4581 } 4582 4583 /* 4584 ** Append a new element to the given IdList. Create a new IdList if 4585 ** need be. 4586 ** 4587 ** A new IdList is returned, or NULL if malloc() fails. 4588 */ 4589 IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){ 4590 sqlite3 *db = pParse->db; 4591 int i; 4592 if( pList==0 ){ 4593 pList = sqlite3DbMallocZero(db, sizeof(IdList) ); 4594 if( pList==0 ) return 0; 4595 } 4596 pList->a = sqlite3ArrayAllocate( 4597 db, 4598 pList->a, 4599 sizeof(pList->a[0]), 4600 &pList->nId, 4601 &i 4602 ); 4603 if( i<0 ){ 4604 sqlite3IdListDelete(db, pList); 4605 return 0; 4606 } 4607 pList->a[i].zName = sqlite3NameFromToken(db, pToken); 4608 if( IN_RENAME_OBJECT && pList->a[i].zName ){ 4609 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken); 4610 } 4611 return pList; 4612 } 4613 4614 /* 4615 ** Delete an IdList. 4616 */ 4617 void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ 4618 int i; 4619 if( pList==0 ) return; 4620 for(i=0; i<pList->nId; i++){ 4621 sqlite3DbFree(db, pList->a[i].zName); 4622 } 4623 sqlite3DbFree(db, pList->a); 4624 sqlite3DbFreeNN(db, pList); 4625 } 4626 4627 /* 4628 ** Return the index in pList of the identifier named zId. Return -1 4629 ** if not found. 4630 */ 4631 int sqlite3IdListIndex(IdList *pList, const char *zName){ 4632 int i; 4633 if( pList==0 ) return -1; 4634 for(i=0; i<pList->nId; i++){ 4635 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; 4636 } 4637 return -1; 4638 } 4639 4640 /* 4641 ** Maximum size of a SrcList object. 4642 ** The SrcList object is used to represent the FROM clause of a 4643 ** SELECT statement, and the query planner cannot deal with more 4644 ** than 64 tables in a join. So any value larger than 64 here 4645 ** is sufficient for most uses. Smaller values, like say 10, are 4646 ** appropriate for small and memory-limited applications. 4647 */ 4648 #ifndef SQLITE_MAX_SRCLIST 4649 # define SQLITE_MAX_SRCLIST 200 4650 #endif 4651 4652 /* 4653 ** Expand the space allocated for the given SrcList object by 4654 ** creating nExtra new slots beginning at iStart. iStart is zero based. 4655 ** New slots are zeroed. 4656 ** 4657 ** For example, suppose a SrcList initially contains two entries: A,B. 4658 ** To append 3 new entries onto the end, do this: 4659 ** 4660 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); 4661 ** 4662 ** After the call above it would contain: A, B, nil, nil, nil. 4663 ** If the iStart argument had been 1 instead of 2, then the result 4664 ** would have been: A, nil, nil, nil, B. To prepend the new slots, 4665 ** the iStart value would be 0. The result then would 4666 ** be: nil, nil, nil, A, B. 4667 ** 4668 ** If a memory allocation fails or the SrcList becomes too large, leave 4669 ** the original SrcList unchanged, return NULL, and leave an error message 4670 ** in pParse. 4671 */ 4672 SrcList *sqlite3SrcListEnlarge( 4673 Parse *pParse, /* Parsing context into which errors are reported */ 4674 SrcList *pSrc, /* The SrcList to be enlarged */ 4675 int nExtra, /* Number of new slots to add to pSrc->a[] */ 4676 int iStart /* Index in pSrc->a[] of first new slot */ 4677 ){ 4678 int i; 4679 4680 /* Sanity checking on calling parameters */ 4681 assert( iStart>=0 ); 4682 assert( nExtra>=1 ); 4683 assert( pSrc!=0 ); 4684 assert( iStart<=pSrc->nSrc ); 4685 4686 /* Allocate additional space if needed */ 4687 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ 4688 SrcList *pNew; 4689 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra; 4690 sqlite3 *db = pParse->db; 4691 4692 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ 4693 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d", 4694 SQLITE_MAX_SRCLIST); 4695 return 0; 4696 } 4697 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; 4698 pNew = sqlite3DbRealloc(db, pSrc, 4699 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); 4700 if( pNew==0 ){ 4701 assert( db->mallocFailed ); 4702 return 0; 4703 } 4704 pSrc = pNew; 4705 pSrc->nAlloc = nAlloc; 4706 } 4707 4708 /* Move existing slots that come after the newly inserted slots 4709 ** out of the way */ 4710 for(i=pSrc->nSrc-1; i>=iStart; i--){ 4711 pSrc->a[i+nExtra] = pSrc->a[i]; 4712 } 4713 pSrc->nSrc += nExtra; 4714 4715 /* Zero the newly allocated slots */ 4716 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); 4717 for(i=iStart; i<iStart+nExtra; i++){ 4718 pSrc->a[i].iCursor = -1; 4719 } 4720 4721 /* Return a pointer to the enlarged SrcList */ 4722 return pSrc; 4723 } 4724 4725 4726 /* 4727 ** Append a new table name to the given SrcList. Create a new SrcList if 4728 ** need be. A new entry is created in the SrcList even if pTable is NULL. 4729 ** 4730 ** A SrcList is returned, or NULL if there is an OOM error or if the 4731 ** SrcList grows to large. The returned 4732 ** SrcList might be the same as the SrcList that was input or it might be 4733 ** a new one. If an OOM error does occurs, then the prior value of pList 4734 ** that is input to this routine is automatically freed. 4735 ** 4736 ** If pDatabase is not null, it means that the table has an optional 4737 ** database name prefix. Like this: "database.table". The pDatabase 4738 ** points to the table name and the pTable points to the database name. 4739 ** The SrcList.a[].zName field is filled with the table name which might 4740 ** come from pTable (if pDatabase is NULL) or from pDatabase. 4741 ** SrcList.a[].zDatabase is filled with the database name from pTable, 4742 ** or with NULL if no database is specified. 4743 ** 4744 ** In other words, if call like this: 4745 ** 4746 ** sqlite3SrcListAppend(D,A,B,0); 4747 ** 4748 ** Then B is a table name and the database name is unspecified. If called 4749 ** like this: 4750 ** 4751 ** sqlite3SrcListAppend(D,A,B,C); 4752 ** 4753 ** Then C is the table name and B is the database name. If C is defined 4754 ** then so is B. In other words, we never have a case where: 4755 ** 4756 ** sqlite3SrcListAppend(D,A,0,C); 4757 ** 4758 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted 4759 ** before being added to the SrcList. 4760 */ 4761 SrcList *sqlite3SrcListAppend( 4762 Parse *pParse, /* Parsing context, in which errors are reported */ 4763 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ 4764 Token *pTable, /* Table to append */ 4765 Token *pDatabase /* Database of the table */ 4766 ){ 4767 SrcItem *pItem; 4768 sqlite3 *db; 4769 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ 4770 assert( pParse!=0 ); 4771 assert( pParse->db!=0 ); 4772 db = pParse->db; 4773 if( pList==0 ){ 4774 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); 4775 if( pList==0 ) return 0; 4776 pList->nAlloc = 1; 4777 pList->nSrc = 1; 4778 memset(&pList->a[0], 0, sizeof(pList->a[0])); 4779 pList->a[0].iCursor = -1; 4780 }else{ 4781 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc); 4782 if( pNew==0 ){ 4783 sqlite3SrcListDelete(db, pList); 4784 return 0; 4785 }else{ 4786 pList = pNew; 4787 } 4788 } 4789 pItem = &pList->a[pList->nSrc-1]; 4790 if( pDatabase && pDatabase->z==0 ){ 4791 pDatabase = 0; 4792 } 4793 if( pDatabase ){ 4794 pItem->zName = sqlite3NameFromToken(db, pDatabase); 4795 pItem->zDatabase = sqlite3NameFromToken(db, pTable); 4796 }else{ 4797 pItem->zName = sqlite3NameFromToken(db, pTable); 4798 pItem->zDatabase = 0; 4799 } 4800 return pList; 4801 } 4802 4803 /* 4804 ** Assign VdbeCursor index numbers to all tables in a SrcList 4805 */ 4806 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ 4807 int i; 4808 SrcItem *pItem; 4809 assert( pList || pParse->db->mallocFailed ); 4810 if( ALWAYS(pList) ){ 4811 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ 4812 if( pItem->iCursor>=0 ) continue; 4813 pItem->iCursor = pParse->nTab++; 4814 if( pItem->pSelect ){ 4815 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); 4816 } 4817 } 4818 } 4819 } 4820 4821 /* 4822 ** Delete an entire SrcList including all its substructure. 4823 */ 4824 void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ 4825 int i; 4826 SrcItem *pItem; 4827 if( pList==0 ) return; 4828 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ 4829 if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase); 4830 sqlite3DbFree(db, pItem->zName); 4831 if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias); 4832 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); 4833 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); 4834 sqlite3DeleteTable(db, pItem->pTab); 4835 if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect); 4836 if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn); 4837 if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing); 4838 } 4839 sqlite3DbFreeNN(db, pList); 4840 } 4841 4842 /* 4843 ** This routine is called by the parser to add a new term to the 4844 ** end of a growing FROM clause. The "p" parameter is the part of 4845 ** the FROM clause that has already been constructed. "p" is NULL 4846 ** if this is the first term of the FROM clause. pTable and pDatabase 4847 ** are the name of the table and database named in the FROM clause term. 4848 ** pDatabase is NULL if the database name qualifier is missing - the 4849 ** usual case. If the term has an alias, then pAlias points to the 4850 ** alias token. If the term is a subquery, then pSubquery is the 4851 ** SELECT statement that the subquery encodes. The pTable and 4852 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing 4853 ** parameters are the content of the ON and USING clauses. 4854 ** 4855 ** Return a new SrcList which encodes is the FROM with the new 4856 ** term added. 4857 */ 4858 SrcList *sqlite3SrcListAppendFromTerm( 4859 Parse *pParse, /* Parsing context */ 4860 SrcList *p, /* The left part of the FROM clause already seen */ 4861 Token *pTable, /* Name of the table to add to the FROM clause */ 4862 Token *pDatabase, /* Name of the database containing pTable */ 4863 Token *pAlias, /* The right-hand side of the AS subexpression */ 4864 Select *pSubquery, /* A subquery used in place of a table name */ 4865 Expr *pOn, /* The ON clause of a join */ 4866 IdList *pUsing /* The USING clause of a join */ 4867 ){ 4868 SrcItem *pItem; 4869 sqlite3 *db = pParse->db; 4870 if( !p && (pOn || pUsing) ){ 4871 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 4872 (pOn ? "ON" : "USING") 4873 ); 4874 goto append_from_error; 4875 } 4876 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase); 4877 if( p==0 ){ 4878 goto append_from_error; 4879 } 4880 assert( p->nSrc>0 ); 4881 pItem = &p->a[p->nSrc-1]; 4882 assert( (pTable==0)==(pDatabase==0) ); 4883 assert( pItem->zName==0 || pDatabase!=0 ); 4884 if( IN_RENAME_OBJECT && pItem->zName ){ 4885 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable; 4886 sqlite3RenameTokenMap(pParse, pItem->zName, pToken); 4887 } 4888 assert( pAlias!=0 ); 4889 if( pAlias->n ){ 4890 pItem->zAlias = sqlite3NameFromToken(db, pAlias); 4891 } 4892 pItem->pSelect = pSubquery; 4893 pItem->pOn = pOn; 4894 pItem->pUsing = pUsing; 4895 return p; 4896 4897 append_from_error: 4898 assert( p==0 ); 4899 sqlite3ExprDelete(db, pOn); 4900 sqlite3IdListDelete(db, pUsing); 4901 sqlite3SelectDelete(db, pSubquery); 4902 return 0; 4903 } 4904 4905 /* 4906 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 4907 ** element of the source-list passed as the second argument. 4908 */ 4909 void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ 4910 assert( pIndexedBy!=0 ); 4911 if( p && pIndexedBy->n>0 ){ 4912 SrcItem *pItem; 4913 assert( p->nSrc>0 ); 4914 pItem = &p->a[p->nSrc-1]; 4915 assert( pItem->fg.notIndexed==0 ); 4916 assert( pItem->fg.isIndexedBy==0 ); 4917 assert( pItem->fg.isTabFunc==0 ); 4918 if( pIndexedBy->n==1 && !pIndexedBy->z ){ 4919 /* A "NOT INDEXED" clause was supplied. See parse.y 4920 ** construct "indexed_opt" for details. */ 4921 pItem->fg.notIndexed = 1; 4922 }else{ 4923 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); 4924 pItem->fg.isIndexedBy = 1; 4925 } 4926 } 4927 } 4928 4929 /* 4930 ** Append the contents of SrcList p2 to SrcList p1 and return the resulting 4931 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2 4932 ** are deleted by this function. 4933 */ 4934 SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){ 4935 assert( p1 && p1->nSrc==1 ); 4936 if( p2 ){ 4937 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1); 4938 if( pNew==0 ){ 4939 sqlite3SrcListDelete(pParse->db, p2); 4940 }else{ 4941 p1 = pNew; 4942 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem)); 4943 sqlite3DbFree(pParse->db, p2); 4944 } 4945 } 4946 return p1; 4947 } 4948 4949 /* 4950 ** Add the list of function arguments to the SrcList entry for a 4951 ** table-valued-function. 4952 */ 4953 void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ 4954 if( p ){ 4955 SrcItem *pItem = &p->a[p->nSrc-1]; 4956 assert( pItem->fg.notIndexed==0 ); 4957 assert( pItem->fg.isIndexedBy==0 ); 4958 assert( pItem->fg.isTabFunc==0 ); 4959 pItem->u1.pFuncArg = pList; 4960 pItem->fg.isTabFunc = 1; 4961 }else{ 4962 sqlite3ExprListDelete(pParse->db, pList); 4963 } 4964 } 4965 4966 /* 4967 ** When building up a FROM clause in the parser, the join operator 4968 ** is initially attached to the left operand. But the code generator 4969 ** expects the join operator to be on the right operand. This routine 4970 ** Shifts all join operators from left to right for an entire FROM 4971 ** clause. 4972 ** 4973 ** Example: Suppose the join is like this: 4974 ** 4975 ** A natural cross join B 4976 ** 4977 ** The operator is "natural cross join". The A and B operands are stored 4978 ** in p->a[0] and p->a[1], respectively. The parser initially stores the 4979 ** operator with A. This routine shifts that operator over to B. 4980 */ 4981 void sqlite3SrcListShiftJoinType(SrcList *p){ 4982 if( p ){ 4983 int i; 4984 for(i=p->nSrc-1; i>0; i--){ 4985 p->a[i].fg.jointype = p->a[i-1].fg.jointype; 4986 } 4987 p->a[0].fg.jointype = 0; 4988 } 4989 } 4990 4991 /* 4992 ** Generate VDBE code for a BEGIN statement. 4993 */ 4994 void sqlite3BeginTransaction(Parse *pParse, int type){ 4995 sqlite3 *db; 4996 Vdbe *v; 4997 int i; 4998 4999 assert( pParse!=0 ); 5000 db = pParse->db; 5001 assert( db!=0 ); 5002 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ 5003 return; 5004 } 5005 v = sqlite3GetVdbe(pParse); 5006 if( !v ) return; 5007 if( type!=TK_DEFERRED ){ 5008 for(i=0; i<db->nDb; i++){ 5009 int eTxnType; 5010 Btree *pBt = db->aDb[i].pBt; 5011 if( pBt && sqlite3BtreeIsReadonly(pBt) ){ 5012 eTxnType = 0; /* Read txn */ 5013 }else if( type==TK_EXCLUSIVE ){ 5014 eTxnType = 2; /* Exclusive txn */ 5015 }else{ 5016 eTxnType = 1; /* Write txn */ 5017 } 5018 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType); 5019 sqlite3VdbeUsesBtree(v, i); 5020 } 5021 } 5022 sqlite3VdbeAddOp0(v, OP_AutoCommit); 5023 } 5024 5025 /* 5026 ** Generate VDBE code for a COMMIT or ROLLBACK statement. 5027 ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise 5028 ** code is generated for a COMMIT. 5029 */ 5030 void sqlite3EndTransaction(Parse *pParse, int eType){ 5031 Vdbe *v; 5032 int isRollback; 5033 5034 assert( pParse!=0 ); 5035 assert( pParse->db!=0 ); 5036 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK ); 5037 isRollback = eType==TK_ROLLBACK; 5038 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 5039 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){ 5040 return; 5041 } 5042 v = sqlite3GetVdbe(pParse); 5043 if( v ){ 5044 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback); 5045 } 5046 } 5047 5048 /* 5049 ** This function is called by the parser when it parses a command to create, 5050 ** release or rollback an SQL savepoint. 5051 */ 5052 void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ 5053 char *zName = sqlite3NameFromToken(pParse->db, pName); 5054 if( zName ){ 5055 Vdbe *v = sqlite3GetVdbe(pParse); 5056 #ifndef SQLITE_OMIT_AUTHORIZATION 5057 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; 5058 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); 5059 #endif 5060 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ 5061 sqlite3DbFree(pParse->db, zName); 5062 return; 5063 } 5064 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); 5065 } 5066 } 5067 5068 /* 5069 ** Make sure the TEMP database is open and available for use. Return 5070 ** the number of errors. Leave any error messages in the pParse structure. 5071 */ 5072 int sqlite3OpenTempDatabase(Parse *pParse){ 5073 sqlite3 *db = pParse->db; 5074 if( db->aDb[1].pBt==0 && !pParse->explain ){ 5075 int rc; 5076 Btree *pBt; 5077 static const int flags = 5078 SQLITE_OPEN_READWRITE | 5079 SQLITE_OPEN_CREATE | 5080 SQLITE_OPEN_EXCLUSIVE | 5081 SQLITE_OPEN_DELETEONCLOSE | 5082 SQLITE_OPEN_TEMP_DB; 5083 5084 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); 5085 if( rc!=SQLITE_OK ){ 5086 sqlite3ErrorMsg(pParse, "unable to open a temporary database " 5087 "file for storing temporary tables"); 5088 pParse->rc = rc; 5089 return 1; 5090 } 5091 db->aDb[1].pBt = pBt; 5092 assert( db->aDb[1].pSchema ); 5093 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){ 5094 sqlite3OomFault(db); 5095 return 1; 5096 } 5097 } 5098 return 0; 5099 } 5100 5101 /* 5102 ** Record the fact that the schema cookie will need to be verified 5103 ** for database iDb. The code to actually verify the schema cookie 5104 ** will occur at the end of the top-level VDBE and will be generated 5105 ** later, by sqlite3FinishCoding(). 5106 */ 5107 static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){ 5108 assert( iDb>=0 && iDb<pToplevel->db->nDb ); 5109 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 ); 5110 assert( iDb<SQLITE_MAX_DB ); 5111 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) ); 5112 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ 5113 DbMaskSet(pToplevel->cookieMask, iDb); 5114 if( !OMIT_TEMPDB && iDb==1 ){ 5115 sqlite3OpenTempDatabase(pToplevel); 5116 } 5117 } 5118 } 5119 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ 5120 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb); 5121 } 5122 5123 5124 /* 5125 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 5126 ** attached database. Otherwise, invoke it for the database named zDb only. 5127 */ 5128 void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ 5129 sqlite3 *db = pParse->db; 5130 int i; 5131 for(i=0; i<db->nDb; i++){ 5132 Db *pDb = &db->aDb[i]; 5133 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ 5134 sqlite3CodeVerifySchema(pParse, i); 5135 } 5136 } 5137 } 5138 5139 /* 5140 ** Generate VDBE code that prepares for doing an operation that 5141 ** might change the database. 5142 ** 5143 ** This routine starts a new transaction if we are not already within 5144 ** a transaction. If we are already within a transaction, then a checkpoint 5145 ** is set if the setStatement parameter is true. A checkpoint should 5146 ** be set for operations that might fail (due to a constraint) part of 5147 ** the way through and which will need to undo some writes without having to 5148 ** rollback the whole transaction. For operations where all constraints 5149 ** can be checked before any changes are made to the database, it is never 5150 ** necessary to undo a write and the checkpoint should not be set. 5151 */ 5152 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ 5153 Parse *pToplevel = sqlite3ParseToplevel(pParse); 5154 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb); 5155 DbMaskSet(pToplevel->writeMask, iDb); 5156 pToplevel->isMultiWrite |= setStatement; 5157 } 5158 5159 /* 5160 ** Indicate that the statement currently under construction might write 5161 ** more than one entry (example: deleting one row then inserting another, 5162 ** inserting multiple rows in a table, or inserting a row and index entries.) 5163 ** If an abort occurs after some of these writes have completed, then it will 5164 ** be necessary to undo the completed writes. 5165 */ 5166 void sqlite3MultiWrite(Parse *pParse){ 5167 Parse *pToplevel = sqlite3ParseToplevel(pParse); 5168 pToplevel->isMultiWrite = 1; 5169 } 5170 5171 /* 5172 ** The code generator calls this routine if is discovers that it is 5173 ** possible to abort a statement prior to completion. In order to 5174 ** perform this abort without corrupting the database, we need to make 5175 ** sure that the statement is protected by a statement transaction. 5176 ** 5177 ** Technically, we only need to set the mayAbort flag if the 5178 ** isMultiWrite flag was previously set. There is a time dependency 5179 ** such that the abort must occur after the multiwrite. This makes 5180 ** some statements involving the REPLACE conflict resolution algorithm 5181 ** go a little faster. But taking advantage of this time dependency 5182 ** makes it more difficult to prove that the code is correct (in 5183 ** particular, it prevents us from writing an effective 5184 ** implementation of sqlite3AssertMayAbort()) and so we have chosen 5185 ** to take the safe route and skip the optimization. 5186 */ 5187 void sqlite3MayAbort(Parse *pParse){ 5188 Parse *pToplevel = sqlite3ParseToplevel(pParse); 5189 pToplevel->mayAbort = 1; 5190 } 5191 5192 /* 5193 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT 5194 ** error. The onError parameter determines which (if any) of the statement 5195 ** and/or current transaction is rolled back. 5196 */ 5197 void sqlite3HaltConstraint( 5198 Parse *pParse, /* Parsing context */ 5199 int errCode, /* extended error code */ 5200 int onError, /* Constraint type */ 5201 char *p4, /* Error message */ 5202 i8 p4type, /* P4_STATIC or P4_TRANSIENT */ 5203 u8 p5Errmsg /* P5_ErrMsg type */ 5204 ){ 5205 Vdbe *v; 5206 assert( pParse->pVdbe!=0 ); 5207 v = sqlite3GetVdbe(pParse); 5208 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested ); 5209 if( onError==OE_Abort ){ 5210 sqlite3MayAbort(pParse); 5211 } 5212 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); 5213 sqlite3VdbeChangeP5(v, p5Errmsg); 5214 } 5215 5216 /* 5217 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. 5218 */ 5219 void sqlite3UniqueConstraint( 5220 Parse *pParse, /* Parsing context */ 5221 int onError, /* Constraint type */ 5222 Index *pIdx /* The index that triggers the constraint */ 5223 ){ 5224 char *zErr; 5225 int j; 5226 StrAccum errMsg; 5227 Table *pTab = pIdx->pTable; 5228 5229 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 5230 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]); 5231 if( pIdx->aColExpr ){ 5232 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName); 5233 }else{ 5234 for(j=0; j<pIdx->nKeyCol; j++){ 5235 char *zCol; 5236 assert( pIdx->aiColumn[j]>=0 ); 5237 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName; 5238 if( j ) sqlite3_str_append(&errMsg, ", ", 2); 5239 sqlite3_str_appendall(&errMsg, pTab->zName); 5240 sqlite3_str_append(&errMsg, ".", 1); 5241 sqlite3_str_appendall(&errMsg, zCol); 5242 } 5243 } 5244 zErr = sqlite3StrAccumFinish(&errMsg); 5245 sqlite3HaltConstraint(pParse, 5246 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 5247 : SQLITE_CONSTRAINT_UNIQUE, 5248 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); 5249 } 5250 5251 5252 /* 5253 ** Code an OP_Halt due to non-unique rowid. 5254 */ 5255 void sqlite3RowidConstraint( 5256 Parse *pParse, /* Parsing context */ 5257 int onError, /* Conflict resolution algorithm */ 5258 Table *pTab /* The table with the non-unique rowid */ 5259 ){ 5260 char *zMsg; 5261 int rc; 5262 if( pTab->iPKey>=0 ){ 5263 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, 5264 pTab->aCol[pTab->iPKey].zCnName); 5265 rc = SQLITE_CONSTRAINT_PRIMARYKEY; 5266 }else{ 5267 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); 5268 rc = SQLITE_CONSTRAINT_ROWID; 5269 } 5270 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, 5271 P5_ConstraintUnique); 5272 } 5273 5274 /* 5275 ** Check to see if pIndex uses the collating sequence pColl. Return 5276 ** true if it does and false if it does not. 5277 */ 5278 #ifndef SQLITE_OMIT_REINDEX 5279 static int collationMatch(const char *zColl, Index *pIndex){ 5280 int i; 5281 assert( zColl!=0 ); 5282 for(i=0; i<pIndex->nColumn; i++){ 5283 const char *z = pIndex->azColl[i]; 5284 assert( z!=0 || pIndex->aiColumn[i]<0 ); 5285 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ 5286 return 1; 5287 } 5288 } 5289 return 0; 5290 } 5291 #endif 5292 5293 /* 5294 ** Recompute all indices of pTab that use the collating sequence pColl. 5295 ** If pColl==0 then recompute all indices of pTab. 5296 */ 5297 #ifndef SQLITE_OMIT_REINDEX 5298 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ 5299 if( !IsVirtual(pTab) ){ 5300 Index *pIndex; /* An index associated with pTab */ 5301 5302 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ 5303 if( zColl==0 || collationMatch(zColl, pIndex) ){ 5304 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5305 sqlite3BeginWriteOperation(pParse, 0, iDb); 5306 sqlite3RefillIndex(pParse, pIndex, -1); 5307 } 5308 } 5309 } 5310 } 5311 #endif 5312 5313 /* 5314 ** Recompute all indices of all tables in all databases where the 5315 ** indices use the collating sequence pColl. If pColl==0 then recompute 5316 ** all indices everywhere. 5317 */ 5318 #ifndef SQLITE_OMIT_REINDEX 5319 static void reindexDatabases(Parse *pParse, char const *zColl){ 5320 Db *pDb; /* A single database */ 5321 int iDb; /* The database index number */ 5322 sqlite3 *db = pParse->db; /* The database connection */ 5323 HashElem *k; /* For looping over tables in pDb */ 5324 Table *pTab; /* A table in the database */ 5325 5326 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ 5327 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ 5328 assert( pDb!=0 ); 5329 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ 5330 pTab = (Table*)sqliteHashData(k); 5331 reindexTable(pParse, pTab, zColl); 5332 } 5333 } 5334 } 5335 #endif 5336 5337 /* 5338 ** Generate code for the REINDEX command. 5339 ** 5340 ** REINDEX -- 1 5341 ** REINDEX <collation> -- 2 5342 ** REINDEX ?<database>.?<tablename> -- 3 5343 ** REINDEX ?<database>.?<indexname> -- 4 5344 ** 5345 ** Form 1 causes all indices in all attached databases to be rebuilt. 5346 ** Form 2 rebuilds all indices in all databases that use the named 5347 ** collating function. Forms 3 and 4 rebuild the named index or all 5348 ** indices associated with the named table. 5349 */ 5350 #ifndef SQLITE_OMIT_REINDEX 5351 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ 5352 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ 5353 char *z; /* Name of a table or index */ 5354 const char *zDb; /* Name of the database */ 5355 Table *pTab; /* A table in the database */ 5356 Index *pIndex; /* An index associated with pTab */ 5357 int iDb; /* The database index number */ 5358 sqlite3 *db = pParse->db; /* The database connection */ 5359 Token *pObjName; /* Name of the table or index to be reindexed */ 5360 5361 /* Read the database schema. If an error occurs, leave an error message 5362 ** and code in pParse and return NULL. */ 5363 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ 5364 return; 5365 } 5366 5367 if( pName1==0 ){ 5368 reindexDatabases(pParse, 0); 5369 return; 5370 }else if( NEVER(pName2==0) || pName2->z==0 ){ 5371 char *zColl; 5372 assert( pName1->z ); 5373 zColl = sqlite3NameFromToken(pParse->db, pName1); 5374 if( !zColl ) return; 5375 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 5376 if( pColl ){ 5377 reindexDatabases(pParse, zColl); 5378 sqlite3DbFree(db, zColl); 5379 return; 5380 } 5381 sqlite3DbFree(db, zColl); 5382 } 5383 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); 5384 if( iDb<0 ) return; 5385 z = sqlite3NameFromToken(db, pObjName); 5386 if( z==0 ) return; 5387 zDb = db->aDb[iDb].zDbSName; 5388 pTab = sqlite3FindTable(db, z, zDb); 5389 if( pTab ){ 5390 reindexTable(pParse, pTab, 0); 5391 sqlite3DbFree(db, z); 5392 return; 5393 } 5394 pIndex = sqlite3FindIndex(db, z, zDb); 5395 sqlite3DbFree(db, z); 5396 if( pIndex ){ 5397 sqlite3BeginWriteOperation(pParse, 0, iDb); 5398 sqlite3RefillIndex(pParse, pIndex, -1); 5399 return; 5400 } 5401 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); 5402 } 5403 #endif 5404 5405 /* 5406 ** Return a KeyInfo structure that is appropriate for the given Index. 5407 ** 5408 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object 5409 ** when it has finished using it. 5410 */ 5411 KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ 5412 int i; 5413 int nCol = pIdx->nColumn; 5414 int nKey = pIdx->nKeyCol; 5415 KeyInfo *pKey; 5416 if( pParse->nErr ) return 0; 5417 if( pIdx->uniqNotNull ){ 5418 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); 5419 }else{ 5420 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); 5421 } 5422 if( pKey ){ 5423 assert( sqlite3KeyInfoIsWriteable(pKey) ); 5424 for(i=0; i<nCol; i++){ 5425 const char *zColl = pIdx->azColl[i]; 5426 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : 5427 sqlite3LocateCollSeq(pParse, zColl); 5428 pKey->aSortFlags[i] = pIdx->aSortOrder[i]; 5429 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) ); 5430 } 5431 if( pParse->nErr ){ 5432 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); 5433 if( pIdx->bNoQuery==0 ){ 5434 /* Deactivate the index because it contains an unknown collating 5435 ** sequence. The only way to reactive the index is to reload the 5436 ** schema. Adding the missing collating sequence later does not 5437 ** reactive the index. The application had the chance to register 5438 ** the missing index using the collation-needed callback. For 5439 ** simplicity, SQLite will not give the application a second chance. 5440 */ 5441 pIdx->bNoQuery = 1; 5442 pParse->rc = SQLITE_ERROR_RETRY; 5443 } 5444 sqlite3KeyInfoUnref(pKey); 5445 pKey = 0; 5446 } 5447 } 5448 return pKey; 5449 } 5450 5451 #ifndef SQLITE_OMIT_CTE 5452 /* 5453 ** Create a new CTE object 5454 */ 5455 Cte *sqlite3CteNew( 5456 Parse *pParse, /* Parsing context */ 5457 Token *pName, /* Name of the common-table */ 5458 ExprList *pArglist, /* Optional column name list for the table */ 5459 Select *pQuery, /* Query used to initialize the table */ 5460 u8 eM10d /* The MATERIALIZED flag */ 5461 ){ 5462 Cte *pNew; 5463 sqlite3 *db = pParse->db; 5464 5465 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)); 5466 assert( pNew!=0 || db->mallocFailed ); 5467 5468 if( db->mallocFailed ){ 5469 sqlite3ExprListDelete(db, pArglist); 5470 sqlite3SelectDelete(db, pQuery); 5471 }else{ 5472 pNew->pSelect = pQuery; 5473 pNew->pCols = pArglist; 5474 pNew->zName = sqlite3NameFromToken(pParse->db, pName); 5475 pNew->eM10d = eM10d; 5476 } 5477 return pNew; 5478 } 5479 5480 /* 5481 ** Clear information from a Cte object, but do not deallocate storage 5482 ** for the object itself. 5483 */ 5484 static void cteClear(sqlite3 *db, Cte *pCte){ 5485 assert( pCte!=0 ); 5486 sqlite3ExprListDelete(db, pCte->pCols); 5487 sqlite3SelectDelete(db, pCte->pSelect); 5488 sqlite3DbFree(db, pCte->zName); 5489 } 5490 5491 /* 5492 ** Free the contents of the CTE object passed as the second argument. 5493 */ 5494 void sqlite3CteDelete(sqlite3 *db, Cte *pCte){ 5495 assert( pCte!=0 ); 5496 cteClear(db, pCte); 5497 sqlite3DbFree(db, pCte); 5498 } 5499 5500 /* 5501 ** This routine is invoked once per CTE by the parser while parsing a 5502 ** WITH clause. The CTE described by teh third argument is added to 5503 ** the WITH clause of the second argument. If the second argument is 5504 ** NULL, then a new WITH argument is created. 5505 */ 5506 With *sqlite3WithAdd( 5507 Parse *pParse, /* Parsing context */ 5508 With *pWith, /* Existing WITH clause, or NULL */ 5509 Cte *pCte /* CTE to add to the WITH clause */ 5510 ){ 5511 sqlite3 *db = pParse->db; 5512 With *pNew; 5513 char *zName; 5514 5515 if( pCte==0 ){ 5516 return pWith; 5517 } 5518 5519 /* Check that the CTE name is unique within this WITH clause. If 5520 ** not, store an error in the Parse structure. */ 5521 zName = pCte->zName; 5522 if( zName && pWith ){ 5523 int i; 5524 for(i=0; i<pWith->nCte; i++){ 5525 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ 5526 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); 5527 } 5528 } 5529 } 5530 5531 if( pWith ){ 5532 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); 5533 pNew = sqlite3DbRealloc(db, pWith, nByte); 5534 }else{ 5535 pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); 5536 } 5537 assert( (pNew!=0 && zName!=0) || db->mallocFailed ); 5538 5539 if( db->mallocFailed ){ 5540 sqlite3CteDelete(db, pCte); 5541 pNew = pWith; 5542 }else{ 5543 pNew->a[pNew->nCte++] = *pCte; 5544 sqlite3DbFree(db, pCte); 5545 } 5546 5547 return pNew; 5548 } 5549 5550 /* 5551 ** Free the contents of the With object passed as the second argument. 5552 */ 5553 void sqlite3WithDelete(sqlite3 *db, With *pWith){ 5554 if( pWith ){ 5555 int i; 5556 for(i=0; i<pWith->nCte; i++){ 5557 cteClear(db, &pWith->a[i]); 5558 } 5559 sqlite3DbFree(db, pWith); 5560 } 5561 } 5562 #endif /* !defined(SQLITE_OMIT_CTE) */ 5563