1 /* 2 ** 2005 May 25 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 the implementation of the sqlite3_prepare() 13 ** interface, and routines that contribute to loading the database schema 14 ** from disk. 15 */ 16 #include "sqliteInt.h" 17 18 /* 19 ** Fill the InitData structure with an error message that indicates 20 ** that the database is corrupt. 21 */ 22 static void corruptSchema( 23 InitData *pData, /* Initialization context */ 24 const char *zObj, /* Object being parsed at the point of error */ 25 const char *zExtra /* Error information */ 26 ){ 27 sqlite3 *db = pData->db; 28 if( db->mallocFailed ){ 29 pData->rc = SQLITE_NOMEM_BKPT; 30 }else if( pData->pzErrMsg[0]!=0 ){ 31 /* A error message has already been generated. Do not overwrite it */ 32 }else if( pData->mInitFlags & INITFLAG_AlterTable ){ 33 *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra); 34 pData->rc = SQLITE_ERROR; 35 }else if( db->flags & SQLITE_WriteSchema ){ 36 pData->rc = SQLITE_CORRUPT_BKPT; 37 }else{ 38 char *z; 39 if( zObj==0 ) zObj = "?"; 40 z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); 41 if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); 42 *pData->pzErrMsg = z; 43 pData->rc = SQLITE_CORRUPT_BKPT; 44 } 45 } 46 47 /* 48 ** Check to see if any sibling index (another index on the same table) 49 ** of pIndex has the same root page number, and if it does, return true. 50 ** This would indicate a corrupt schema. 51 */ 52 int sqlite3IndexHasDuplicateRootPage(Index *pIndex){ 53 Index *p; 54 for(p=pIndex->pTable->pIndex; p; p=p->pNext){ 55 if( p->tnum==pIndex->tnum && p!=pIndex ) return 1; 56 } 57 return 0; 58 } 59 60 /* forward declaration */ 61 static int sqlite3Prepare( 62 sqlite3 *db, /* Database handle. */ 63 const char *zSql, /* UTF-8 encoded SQL statement. */ 64 int nBytes, /* Length of zSql in bytes. */ 65 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 66 Vdbe *pReprepare, /* VM being reprepared */ 67 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 68 const char **pzTail /* OUT: End of parsed string */ 69 ); 70 71 72 /* 73 ** This is the callback routine for the code that initializes the 74 ** database. See sqlite3Init() below for additional information. 75 ** This routine is also called from the OP_ParseSchema opcode of the VDBE. 76 ** 77 ** Each callback contains the following information: 78 ** 79 ** argv[0] = type of object: "table", "index", "trigger", or "view". 80 ** argv[1] = name of thing being created 81 ** argv[2] = associated table if an index or trigger 82 ** argv[3] = root page number for table or index. 0 for trigger or view. 83 ** argv[4] = SQL text for the CREATE statement. 84 ** 85 */ 86 int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ 87 InitData *pData = (InitData*)pInit; 88 sqlite3 *db = pData->db; 89 int iDb = pData->iDb; 90 91 assert( argc==5 ); 92 UNUSED_PARAMETER2(NotUsed, argc); 93 assert( sqlite3_mutex_held(db->mutex) ); 94 db->mDbFlags |= DBFLAG_EncodingFixed; 95 pData->nInitRow++; 96 if( db->mallocFailed ){ 97 corruptSchema(pData, argv[1], 0); 98 return 1; 99 } 100 101 assert( iDb>=0 && iDb<db->nDb ); 102 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ 103 if( argv[3]==0 ){ 104 corruptSchema(pData, argv[1], 0); 105 }else if( argv[4] 106 && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]] 107 && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){ 108 /* Call the parser to process a CREATE TABLE, INDEX or VIEW. 109 ** But because db->init.busy is set to 1, no VDBE code is generated 110 ** or executed. All the parser does is build the internal data 111 ** structures that describe the table, index, or view. 112 ** 113 ** No other valid SQL statement, other than the variable CREATE statements, 114 ** can begin with the letters "C" and "R". Thus, it is not possible run 115 ** any other kind of statement while parsing the schema, even a corrupt 116 ** schema. 117 */ 118 int rc; 119 u8 saved_iDb = db->init.iDb; 120 sqlite3_stmt *pStmt; 121 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ 122 123 assert( db->init.busy ); 124 db->init.iDb = iDb; 125 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0 126 || (db->init.newTnum>pData->mxPage && pData->mxPage>0) 127 ){ 128 if( sqlite3Config.bExtraSchemaChecks ){ 129 corruptSchema(pData, argv[1], "invalid rootpage"); 130 } 131 } 132 db->init.orphanTrigger = 0; 133 db->init.azInit = argv; 134 pStmt = 0; 135 TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0); 136 rc = db->errCode; 137 assert( (rc&0xFF)==(rcp&0xFF) ); 138 db->init.iDb = saved_iDb; 139 /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */ 140 if( SQLITE_OK!=rc ){ 141 if( db->init.orphanTrigger ){ 142 assert( iDb==1 ); 143 }else{ 144 if( rc > pData->rc ) pData->rc = rc; 145 if( rc==SQLITE_NOMEM ){ 146 sqlite3OomFault(db); 147 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ 148 corruptSchema(pData, argv[1], sqlite3_errmsg(db)); 149 } 150 } 151 } 152 sqlite3_finalize(pStmt); 153 }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){ 154 corruptSchema(pData, argv[1], 0); 155 }else{ 156 /* If the SQL column is blank it means this is an index that 157 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE 158 ** constraint for a CREATE TABLE. The index should have already 159 ** been created when we processed the CREATE TABLE. All we have 160 ** to do here is record the root page number for that index. 161 */ 162 Index *pIndex; 163 pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName); 164 if( pIndex==0 ){ 165 corruptSchema(pData, argv[1], "orphan index"); 166 }else 167 if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0 168 || pIndex->tnum<2 169 || pIndex->tnum>pData->mxPage 170 || sqlite3IndexHasDuplicateRootPage(pIndex) 171 ){ 172 if( sqlite3Config.bExtraSchemaChecks ){ 173 corruptSchema(pData, argv[1], "invalid rootpage"); 174 } 175 } 176 } 177 return 0; 178 } 179 180 /* 181 ** Attempt to read the database schema and initialize internal 182 ** data structures for a single database file. The index of the 183 ** database file is given by iDb. iDb==0 is used for the main 184 ** database. iDb==1 should never be used. iDb>=2 is used for 185 ** auxiliary databases. Return one of the SQLITE_ error codes to 186 ** indicate success or failure. 187 */ 188 int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){ 189 int rc; 190 int i; 191 #ifndef SQLITE_OMIT_DEPRECATED 192 int size; 193 #endif 194 Db *pDb; 195 char const *azArg[6]; 196 int meta[5]; 197 InitData initData; 198 const char *zSchemaTabName; 199 int openedTransaction = 0; 200 int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed); 201 202 assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ); 203 assert( iDb>=0 && iDb<db->nDb ); 204 assert( db->aDb[iDb].pSchema ); 205 assert( sqlite3_mutex_held(db->mutex) ); 206 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); 207 208 db->init.busy = 1; 209 210 /* Construct the in-memory representation schema tables (sqlite_schema or 211 ** sqlite_temp_schema) by invoking the parser directly. The appropriate 212 ** table name will be inserted automatically by the parser so we can just 213 ** use the abbreviation "x" here. The parser will also automatically tag 214 ** the schema table as read-only. */ 215 azArg[0] = "table"; 216 azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb); 217 azArg[2] = azArg[1]; 218 azArg[3] = "1"; 219 azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text," 220 "rootpage int,sql text)"; 221 azArg[5] = 0; 222 initData.db = db; 223 initData.iDb = iDb; 224 initData.rc = SQLITE_OK; 225 initData.pzErrMsg = pzErrMsg; 226 initData.mInitFlags = mFlags; 227 initData.nInitRow = 0; 228 initData.mxPage = 0; 229 sqlite3InitCallback(&initData, 5, (char **)azArg, 0); 230 db->mDbFlags &= mask; 231 if( initData.rc ){ 232 rc = initData.rc; 233 goto error_out; 234 } 235 236 /* Create a cursor to hold the database open 237 */ 238 pDb = &db->aDb[iDb]; 239 if( pDb->pBt==0 ){ 240 assert( iDb==1 ); 241 DbSetProperty(db, 1, DB_SchemaLoaded); 242 rc = SQLITE_OK; 243 goto error_out; 244 } 245 246 /* If there is not already a read-only (or read-write) transaction opened 247 ** on the b-tree database, open one now. If a transaction is opened, it 248 ** will be closed before this function returns. */ 249 sqlite3BtreeEnter(pDb->pBt); 250 if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){ 251 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0); 252 if( rc!=SQLITE_OK ){ 253 sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc)); 254 goto initone_error_out; 255 } 256 openedTransaction = 1; 257 } 258 259 /* Get the database meta information. 260 ** 261 ** Meta values are as follows: 262 ** meta[0] Schema cookie. Changes with each schema change. 263 ** meta[1] File format of schema layer. 264 ** meta[2] Size of the page cache. 265 ** meta[3] Largest rootpage (auto/incr_vacuum mode) 266 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE 267 ** meta[5] User version 268 ** meta[6] Incremental vacuum mode 269 ** meta[7] unused 270 ** meta[8] unused 271 ** meta[9] unused 272 ** 273 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to 274 ** the possible values of meta[4]. 275 */ 276 for(i=0; i<ArraySize(meta); i++){ 277 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]); 278 } 279 if( (db->flags & SQLITE_ResetDatabase)!=0 ){ 280 memset(meta, 0, sizeof(meta)); 281 } 282 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; 283 284 /* If opening a non-empty database, check the text encoding. For the 285 ** main database, set sqlite3.enc to the encoding of the main database. 286 ** For an attached db, it is an error if the encoding is not the same 287 ** as sqlite3.enc. 288 */ 289 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ 290 if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){ 291 u8 encoding; 292 #ifndef SQLITE_OMIT_UTF16 293 /* If opening the main database, set ENC(db). */ 294 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; 295 if( encoding==0 ) encoding = SQLITE_UTF8; 296 #else 297 encoding = SQLITE_UTF8; 298 #endif 299 sqlite3SetTextEncoding(db, encoding); 300 }else{ 301 /* If opening an attached database, the encoding much match ENC(db) */ 302 if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){ 303 sqlite3SetString(pzErrMsg, db, "attached databases must use the same" 304 " text encoding as main database"); 305 rc = SQLITE_ERROR; 306 goto initone_error_out; 307 } 308 } 309 } 310 pDb->pSchema->enc = ENC(db); 311 312 if( pDb->pSchema->cache_size==0 ){ 313 #ifndef SQLITE_OMIT_DEPRECATED 314 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); 315 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } 316 pDb->pSchema->cache_size = size; 317 #else 318 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; 319 #endif 320 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); 321 } 322 323 /* 324 ** file_format==1 Version 3.0.0. 325 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN 326 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults 327 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants 328 */ 329 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; 330 if( pDb->pSchema->file_format==0 ){ 331 pDb->pSchema->file_format = 1; 332 } 333 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ 334 sqlite3SetString(pzErrMsg, db, "unsupported file format"); 335 rc = SQLITE_ERROR; 336 goto initone_error_out; 337 } 338 339 /* Ticket #2804: When we open a database in the newer file format, 340 ** clear the legacy_file_format pragma flag so that a VACUUM will 341 ** not downgrade the database and thus invalidate any descending 342 ** indices that the user might have created. 343 */ 344 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ 345 db->flags &= ~(u64)SQLITE_LegacyFileFmt; 346 } 347 348 /* Read the schema information out of the schema tables 349 */ 350 assert( db->init.busy ); 351 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt); 352 { 353 char *zSql; 354 zSql = sqlite3MPrintf(db, 355 "SELECT*FROM\"%w\".%s ORDER BY rowid", 356 db->aDb[iDb].zDbSName, zSchemaTabName); 357 #ifndef SQLITE_OMIT_AUTHORIZATION 358 { 359 sqlite3_xauth xAuth; 360 xAuth = db->xAuth; 361 db->xAuth = 0; 362 #endif 363 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); 364 #ifndef SQLITE_OMIT_AUTHORIZATION 365 db->xAuth = xAuth; 366 } 367 #endif 368 if( rc==SQLITE_OK ) rc = initData.rc; 369 sqlite3DbFree(db, zSql); 370 #ifndef SQLITE_OMIT_ANALYZE 371 if( rc==SQLITE_OK ){ 372 sqlite3AnalysisLoad(db, iDb); 373 } 374 #endif 375 } 376 if( db->mallocFailed ){ 377 rc = SQLITE_NOMEM_BKPT; 378 sqlite3ResetAllSchemasOfConnection(db); 379 } 380 if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){ 381 /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider 382 ** the schema loaded, even if errors occurred. In this situation the 383 ** current sqlite3_prepare() operation will fail, but the following one 384 ** will attempt to compile the supplied statement against whatever subset 385 ** of the schema was loaded before the error occurred. The primary 386 ** purpose of this is to allow access to the sqlite_schema table 387 ** even when its contents have been corrupted. 388 */ 389 DbSetProperty(db, iDb, DB_SchemaLoaded); 390 rc = SQLITE_OK; 391 } 392 393 /* Jump here for an error that occurs after successfully allocating 394 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs 395 ** before that point, jump to error_out. 396 */ 397 initone_error_out: 398 if( openedTransaction ){ 399 sqlite3BtreeCommit(pDb->pBt); 400 } 401 sqlite3BtreeLeave(pDb->pBt); 402 403 error_out: 404 if( rc ){ 405 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ 406 sqlite3OomFault(db); 407 } 408 sqlite3ResetOneSchema(db, iDb); 409 } 410 db->init.busy = 0; 411 return rc; 412 } 413 414 /* 415 ** Initialize all database files - the main database file, the file 416 ** used to store temporary tables, and any additional database files 417 ** created using ATTACH statements. Return a success code. If an 418 ** error occurs, write an error message into *pzErrMsg. 419 ** 420 ** After a database is initialized, the DB_SchemaLoaded bit is set 421 ** bit is set in the flags field of the Db structure. 422 */ 423 int sqlite3Init(sqlite3 *db, char **pzErrMsg){ 424 int i, rc; 425 int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange); 426 427 assert( sqlite3_mutex_held(db->mutex) ); 428 assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); 429 assert( db->init.busy==0 ); 430 ENC(db) = SCHEMA_ENC(db); 431 assert( db->nDb>0 ); 432 /* Do the main schema first */ 433 if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){ 434 rc = sqlite3InitOne(db, 0, pzErrMsg, 0); 435 if( rc ) return rc; 436 } 437 /* All other schemas after the main schema. The "temp" schema must be last */ 438 for(i=db->nDb-1; i>0; i--){ 439 assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) ); 440 if( !DbHasProperty(db, i, DB_SchemaLoaded) ){ 441 rc = sqlite3InitOne(db, i, pzErrMsg, 0); 442 if( rc ) return rc; 443 } 444 } 445 if( commit_internal ){ 446 sqlite3CommitInternalChanges(db); 447 } 448 return SQLITE_OK; 449 } 450 451 /* 452 ** This routine is a no-op if the database schema is already initialized. 453 ** Otherwise, the schema is loaded. An error code is returned. 454 */ 455 int sqlite3ReadSchema(Parse *pParse){ 456 int rc = SQLITE_OK; 457 sqlite3 *db = pParse->db; 458 assert( sqlite3_mutex_held(db->mutex) ); 459 if( !db->init.busy ){ 460 rc = sqlite3Init(db, &pParse->zErrMsg); 461 if( rc!=SQLITE_OK ){ 462 pParse->rc = rc; 463 pParse->nErr++; 464 }else if( db->noSharedCache ){ 465 db->mDbFlags |= DBFLAG_SchemaKnownOk; 466 } 467 } 468 return rc; 469 } 470 471 472 /* 473 ** Check schema cookies in all databases. If any cookie is out 474 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies 475 ** make no changes to pParse->rc. 476 */ 477 static void schemaIsValid(Parse *pParse){ 478 sqlite3 *db = pParse->db; 479 int iDb; 480 int rc; 481 int cookie; 482 483 assert( pParse->checkSchema ); 484 assert( sqlite3_mutex_held(db->mutex) ); 485 for(iDb=0; iDb<db->nDb; iDb++){ 486 int openedTransaction = 0; /* True if a transaction is opened */ 487 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ 488 if( pBt==0 ) continue; 489 490 /* If there is not already a read-only (or read-write) transaction opened 491 ** on the b-tree database, open one now. If a transaction is opened, it 492 ** will be closed immediately after reading the meta-value. */ 493 if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){ 494 rc = sqlite3BtreeBeginTrans(pBt, 0, 0); 495 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ 496 sqlite3OomFault(db); 497 } 498 if( rc!=SQLITE_OK ) return; 499 openedTransaction = 1; 500 } 501 502 /* Read the schema cookie from the database. If it does not match the 503 ** value stored as part of the in-memory schema representation, 504 ** set Parse.rc to SQLITE_SCHEMA. */ 505 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); 506 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 507 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ 508 sqlite3ResetOneSchema(db, iDb); 509 pParse->rc = SQLITE_SCHEMA; 510 } 511 512 /* Close the transaction, if one was opened. */ 513 if( openedTransaction ){ 514 sqlite3BtreeCommit(pBt); 515 } 516 } 517 } 518 519 /* 520 ** Convert a schema pointer into the iDb index that indicates 521 ** which database file in db->aDb[] the schema refers to. 522 ** 523 ** If the same database is attached more than once, the first 524 ** attached database is returned. 525 */ 526 int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ 527 int i = -32768; 528 529 /* If pSchema is NULL, then return -32768. This happens when code in 530 ** expr.c is trying to resolve a reference to a transient table (i.e. one 531 ** created by a sub-select). In this case the return value of this 532 ** function should never be used. 533 ** 534 ** We return -32768 instead of the more usual -1 simply because using 535 ** -32768 as the incorrect index into db->aDb[] is much 536 ** more likely to cause a segfault than -1 (of course there are assert() 537 ** statements too, but it never hurts to play the odds) and 538 ** -32768 will still fit into a 16-bit signed integer. 539 */ 540 assert( sqlite3_mutex_held(db->mutex) ); 541 if( pSchema ){ 542 for(i=0; 1; i++){ 543 assert( i<db->nDb ); 544 if( db->aDb[i].pSchema==pSchema ){ 545 break; 546 } 547 } 548 assert( i>=0 && i<db->nDb ); 549 } 550 return i; 551 } 552 553 /* 554 ** Free all memory allocations in the pParse object 555 */ 556 void sqlite3ParserReset(Parse *pParse){ 557 sqlite3 *db = pParse->db; 558 while( pParse->pCleanup ){ 559 ParseCleanup *pCleanup = pParse->pCleanup; 560 pParse->pCleanup = pCleanup->pNext; 561 pCleanup->xCleanup(db, pCleanup->pPtr); 562 sqlite3DbFreeNN(db, pCleanup); 563 } 564 sqlite3DbFree(db, pParse->aLabel); 565 if( pParse->pConstExpr ){ 566 sqlite3ExprListDelete(db, pParse->pConstExpr); 567 } 568 if( db ){ 569 assert( db->lookaside.bDisable >= pParse->disableLookaside ); 570 db->lookaside.bDisable -= pParse->disableLookaside; 571 db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue; 572 } 573 pParse->disableLookaside = 0; 574 } 575 576 /* 577 ** Add a new cleanup operation to a Parser. The cleanup should happen when 578 ** the parser object is destroyed. But, beware: the cleanup might happen 579 ** immediately. 580 ** 581 ** Use this mechanism for uncommon cleanups. There is a higher setup 582 ** cost for this mechansim (an extra malloc), so it should not be used 583 ** for common cleanups that happen on most calls. But for less 584 ** common cleanups, we save a single NULL-pointer comparison in 585 ** sqlite3ParserReset(), which reduces the total CPU cycle count. 586 ** 587 ** If a memory allocation error occurs, then the cleanup happens immediately. 588 ** When eithr SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the 589 ** pParse->earlyCleanup flag is set in that case. Calling code show verify 590 ** that test cases exist for which this happens, to guard against possible 591 ** use-after-free errors following an OOM. The preferred way to do this is 592 ** to immediately follow the call to this routine with: 593 ** 594 ** testcase( pParse->earlyCleanup ); 595 */ 596 void sqlite3ParserAddCleanup( 597 Parse *pParse, /* Destroy when this Parser finishes */ 598 void (*xCleanup)(sqlite3*,void*), /* The cleanup routine */ 599 void *pPtr /* Pointer to object to be cleaned up */ 600 ){ 601 ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup)); 602 if( pCleanup ){ 603 pCleanup->pNext = pParse->pCleanup; 604 pParse->pCleanup = pCleanup; 605 pCleanup->pPtr = pPtr; 606 pCleanup->xCleanup = xCleanup; 607 }else{ 608 xCleanup(pParse->db, pPtr); 609 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) 610 pParse->earlyCleanup = 1; 611 #endif 612 } 613 } 614 615 /* 616 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. 617 */ 618 static int sqlite3Prepare( 619 sqlite3 *db, /* Database handle. */ 620 const char *zSql, /* UTF-8 encoded SQL statement. */ 621 int nBytes, /* Length of zSql in bytes. */ 622 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 623 Vdbe *pReprepare, /* VM being reprepared */ 624 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 625 const char **pzTail /* OUT: End of parsed string */ 626 ){ 627 char *zErrMsg = 0; /* Error message */ 628 int rc = SQLITE_OK; /* Result code */ 629 int i; /* Loop counter */ 630 Parse sParse; /* Parsing context */ 631 632 memset(&sParse, 0, PARSE_HDR_SZ); 633 memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ); 634 sParse.pReprepare = pReprepare; 635 assert( ppStmt && *ppStmt==0 ); 636 /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */ 637 assert( sqlite3_mutex_held(db->mutex) ); 638 639 /* For a long-term use prepared statement avoid the use of 640 ** lookaside memory. 641 */ 642 if( prepFlags & SQLITE_PREPARE_PERSISTENT ){ 643 sParse.disableLookaside++; 644 DisableLookaside; 645 } 646 sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0; 647 648 /* Check to verify that it is possible to get a read lock on all 649 ** database schemas. The inability to get a read lock indicates that 650 ** some other database connection is holding a write-lock, which in 651 ** turn means that the other connection has made uncommitted changes 652 ** to the schema. 653 ** 654 ** Were we to proceed and prepare the statement against the uncommitted 655 ** schema changes and if those schema changes are subsequently rolled 656 ** back and different changes are made in their place, then when this 657 ** prepared statement goes to run the schema cookie would fail to detect 658 ** the schema change. Disaster would follow. 659 ** 660 ** This thread is currently holding mutexes on all Btrees (because 661 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it 662 ** is not possible for another thread to start a new schema change 663 ** while this routine is running. Hence, we do not need to hold 664 ** locks on the schema, we just need to make sure nobody else is 665 ** holding them. 666 ** 667 ** Note that setting READ_UNCOMMITTED overrides most lock detection, 668 ** but it does *not* override schema lock detection, so this all still 669 ** works even if READ_UNCOMMITTED is set. 670 */ 671 if( !db->noSharedCache ){ 672 for(i=0; i<db->nDb; i++) { 673 Btree *pBt = db->aDb[i].pBt; 674 if( pBt ){ 675 assert( sqlite3BtreeHoldsMutex(pBt) ); 676 rc = sqlite3BtreeSchemaLocked(pBt); 677 if( rc ){ 678 const char *zDb = db->aDb[i].zDbSName; 679 sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); 680 testcase( db->flags & SQLITE_ReadUncommit ); 681 goto end_prepare; 682 } 683 } 684 } 685 } 686 687 sqlite3VtabUnlockList(db); 688 689 sParse.db = db; 690 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ 691 char *zSqlCopy; 692 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; 693 testcase( nBytes==mxLen ); 694 testcase( nBytes==mxLen+1 ); 695 if( nBytes>mxLen ){ 696 sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); 697 rc = sqlite3ApiExit(db, SQLITE_TOOBIG); 698 goto end_prepare; 699 } 700 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); 701 if( zSqlCopy ){ 702 sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); 703 sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; 704 sqlite3DbFree(db, zSqlCopy); 705 }else{ 706 sParse.zTail = &zSql[nBytes]; 707 } 708 }else{ 709 sqlite3RunParser(&sParse, zSql, &zErrMsg); 710 } 711 assert( 0==sParse.nQueryLoop ); 712 713 if( pzTail ){ 714 *pzTail = sParse.zTail; 715 } 716 717 if( db->init.busy==0 ){ 718 sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags); 719 } 720 if( db->mallocFailed ){ 721 sParse.rc = SQLITE_NOMEM_BKPT; 722 } 723 if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){ 724 if( sParse.checkSchema ){ 725 schemaIsValid(&sParse); 726 } 727 if( sParse.pVdbe ){ 728 sqlite3VdbeFinalize(sParse.pVdbe); 729 } 730 assert( 0==(*ppStmt) ); 731 rc = sParse.rc; 732 if( zErrMsg ){ 733 sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); 734 sqlite3DbFree(db, zErrMsg); 735 }else{ 736 sqlite3Error(db, rc); 737 } 738 }else{ 739 assert( zErrMsg==0 ); 740 *ppStmt = (sqlite3_stmt*)sParse.pVdbe; 741 rc = SQLITE_OK; 742 sqlite3ErrorClear(db); 743 } 744 745 746 /* Delete any TriggerPrg structures allocated while parsing this statement. */ 747 while( sParse.pTriggerPrg ){ 748 TriggerPrg *pT = sParse.pTriggerPrg; 749 sParse.pTriggerPrg = pT->pNext; 750 sqlite3DbFree(db, pT); 751 } 752 753 end_prepare: 754 755 sqlite3ParserReset(&sParse); 756 return rc; 757 } 758 static int sqlite3LockAndPrepare( 759 sqlite3 *db, /* Database handle. */ 760 const char *zSql, /* UTF-8 encoded SQL statement. */ 761 int nBytes, /* Length of zSql in bytes. */ 762 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 763 Vdbe *pOld, /* VM being reprepared */ 764 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 765 const char **pzTail /* OUT: End of parsed string */ 766 ){ 767 int rc; 768 int cnt = 0; 769 770 #ifdef SQLITE_ENABLE_API_ARMOR 771 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; 772 #endif 773 *ppStmt = 0; 774 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ 775 return SQLITE_MISUSE_BKPT; 776 } 777 sqlite3_mutex_enter(db->mutex); 778 sqlite3BtreeEnterAll(db); 779 do{ 780 /* Make multiple attempts to compile the SQL, until it either succeeds 781 ** or encounters a permanent error. A schema problem after one schema 782 ** reset is considered a permanent error. */ 783 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); 784 assert( rc==SQLITE_OK || *ppStmt==0 ); 785 }while( rc==SQLITE_ERROR_RETRY 786 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) ); 787 sqlite3BtreeLeaveAll(db); 788 rc = sqlite3ApiExit(db, rc); 789 assert( (rc&db->errMask)==rc ); 790 db->busyHandler.nBusy = 0; 791 sqlite3_mutex_leave(db->mutex); 792 return rc; 793 } 794 795 796 /* 797 ** Rerun the compilation of a statement after a schema change. 798 ** 799 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, 800 ** if the statement cannot be recompiled because another connection has 801 ** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error 802 ** occurs, return SQLITE_SCHEMA. 803 */ 804 int sqlite3Reprepare(Vdbe *p){ 805 int rc; 806 sqlite3_stmt *pNew; 807 const char *zSql; 808 sqlite3 *db; 809 u8 prepFlags; 810 811 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); 812 zSql = sqlite3_sql((sqlite3_stmt *)p); 813 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ 814 db = sqlite3VdbeDb(p); 815 assert( sqlite3_mutex_held(db->mutex) ); 816 prepFlags = sqlite3VdbePrepareFlags(p); 817 rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0); 818 if( rc ){ 819 if( rc==SQLITE_NOMEM ){ 820 sqlite3OomFault(db); 821 } 822 assert( pNew==0 ); 823 return rc; 824 }else{ 825 assert( pNew!=0 ); 826 } 827 sqlite3VdbeSwap((Vdbe*)pNew, p); 828 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); 829 sqlite3VdbeResetStepResult((Vdbe*)pNew); 830 sqlite3VdbeFinalize((Vdbe*)pNew); 831 return SQLITE_OK; 832 } 833 834 835 /* 836 ** Two versions of the official API. Legacy and new use. In the legacy 837 ** version, the original SQL text is not saved in the prepared statement 838 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by 839 ** sqlite3_step(). In the new version, the original SQL text is retained 840 ** and the statement is automatically recompiled if an schema change 841 ** occurs. 842 */ 843 int sqlite3_prepare( 844 sqlite3 *db, /* Database handle. */ 845 const char *zSql, /* UTF-8 encoded SQL statement. */ 846 int nBytes, /* Length of zSql in bytes. */ 847 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 848 const char **pzTail /* OUT: End of parsed string */ 849 ){ 850 int rc; 851 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); 852 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ 853 return rc; 854 } 855 int sqlite3_prepare_v2( 856 sqlite3 *db, /* Database handle. */ 857 const char *zSql, /* UTF-8 encoded SQL statement. */ 858 int nBytes, /* Length of zSql in bytes. */ 859 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 860 const char **pzTail /* OUT: End of parsed string */ 861 ){ 862 int rc; 863 /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works 864 ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags 865 ** parameter. 866 ** 867 ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */ 868 rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0, 869 ppStmt,pzTail); 870 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); 871 return rc; 872 } 873 int sqlite3_prepare_v3( 874 sqlite3 *db, /* Database handle. */ 875 const char *zSql, /* UTF-8 encoded SQL statement. */ 876 int nBytes, /* Length of zSql in bytes. */ 877 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 878 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 879 const char **pzTail /* OUT: End of parsed string */ 880 ){ 881 int rc; 882 /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from 883 ** sqlite3_prepare_v2() only in having the extra prepFlags parameter, 884 ** which is a bit array consisting of zero or more of the 885 ** SQLITE_PREPARE_* flags. 886 ** 887 ** Proof by comparison to the implementation of sqlite3_prepare_v2() 888 ** directly above. */ 889 rc = sqlite3LockAndPrepare(db,zSql,nBytes, 890 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), 891 0,ppStmt,pzTail); 892 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); 893 return rc; 894 } 895 896 897 #ifndef SQLITE_OMIT_UTF16 898 /* 899 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. 900 */ 901 static int sqlite3Prepare16( 902 sqlite3 *db, /* Database handle. */ 903 const void *zSql, /* UTF-16 encoded SQL statement. */ 904 int nBytes, /* Length of zSql in bytes. */ 905 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 906 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 907 const void **pzTail /* OUT: End of parsed string */ 908 ){ 909 /* This function currently works by first transforming the UTF-16 910 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The 911 ** tricky bit is figuring out the pointer to return in *pzTail. 912 */ 913 char *zSql8; 914 const char *zTail8 = 0; 915 int rc = SQLITE_OK; 916 917 #ifdef SQLITE_ENABLE_API_ARMOR 918 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; 919 #endif 920 *ppStmt = 0; 921 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ 922 return SQLITE_MISUSE_BKPT; 923 } 924 if( nBytes>=0 ){ 925 int sz; 926 const char *z = (const char*)zSql; 927 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){} 928 nBytes = sz; 929 } 930 sqlite3_mutex_enter(db->mutex); 931 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); 932 if( zSql8 ){ 933 rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8); 934 } 935 936 if( zTail8 && pzTail ){ 937 /* If sqlite3_prepare returns a tail pointer, we calculate the 938 ** equivalent pointer into the UTF-16 string by counting the unicode 939 ** characters between zSql8 and zTail8, and then returning a pointer 940 ** the same number of characters into the UTF-16 string. 941 */ 942 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); 943 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); 944 } 945 sqlite3DbFree(db, zSql8); 946 rc = sqlite3ApiExit(db, rc); 947 sqlite3_mutex_leave(db->mutex); 948 return rc; 949 } 950 951 /* 952 ** Two versions of the official API. Legacy and new use. In the legacy 953 ** version, the original SQL text is not saved in the prepared statement 954 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by 955 ** sqlite3_step(). In the new version, the original SQL text is retained 956 ** and the statement is automatically recompiled if an schema change 957 ** occurs. 958 */ 959 int sqlite3_prepare16( 960 sqlite3 *db, /* Database handle. */ 961 const void *zSql, /* UTF-16 encoded SQL statement. */ 962 int nBytes, /* Length of zSql in bytes. */ 963 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 964 const void **pzTail /* OUT: End of parsed string */ 965 ){ 966 int rc; 967 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); 968 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ 969 return rc; 970 } 971 int sqlite3_prepare16_v2( 972 sqlite3 *db, /* Database handle. */ 973 const void *zSql, /* UTF-16 encoded SQL statement. */ 974 int nBytes, /* Length of zSql in bytes. */ 975 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 976 const void **pzTail /* OUT: End of parsed string */ 977 ){ 978 int rc; 979 rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail); 980 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ 981 return rc; 982 } 983 int sqlite3_prepare16_v3( 984 sqlite3 *db, /* Database handle. */ 985 const void *zSql, /* UTF-16 encoded SQL statement. */ 986 int nBytes, /* Length of zSql in bytes. */ 987 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ 988 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 989 const void **pzTail /* OUT: End of parsed string */ 990 ){ 991 int rc; 992 rc = sqlite3Prepare16(db,zSql,nBytes, 993 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), 994 ppStmt,pzTail); 995 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ 996 return rc; 997 } 998 999 #endif /* SQLITE_OMIT_UTF16 */ 1000