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 ** Main file for the SQLite library. The routines in this file 13 ** implement the programmer interface to the library. Routines in 14 ** other files are for internal use by SQLite and should not be 15 ** accessed by users of the library. 16 ** 17 ** $Id: main.c,v 1.214 2004/06/10 10:50:22 danielk1977 Exp $ 18 */ 19 #include "sqliteInt.h" 20 #include "os.h" 21 #include <ctype.h> 22 23 /* 24 ** A pointer to this structure is used to communicate information 25 ** from sqlite3Init into the sqlite3InitCallback. 26 */ 27 typedef struct { 28 sqlite *db; /* The database being initialized */ 29 char **pzErrMsg; /* Error message stored here */ 30 } InitData; 31 32 /* 33 ** The following constant value is used by the SQLITE_BIGENDIAN and 34 ** SQLITE_LITTLEENDIAN macros. 35 */ 36 const int sqlite3one = 1; 37 38 /* 39 ** Fill the InitData structure with an error message that indicates 40 ** that the database is corrupt. 41 */ 42 static void corruptSchema(InitData *pData, const char *zExtra){ 43 sqlite3SetString(pData->pzErrMsg, "malformed database schema", 44 zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0); 45 } 46 47 /* 48 ** This is the callback routine for the code that initializes the 49 ** database. See sqlite3Init() below for additional information. 50 ** 51 ** Each callback contains the following information: 52 ** 53 ** argv[0] = "file-format" or "schema-cookie" or "table" or "index" 54 ** argv[1] = table or index name or meta statement type. 55 ** argv[2] = root page number for table or index. NULL for meta. 56 ** argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement. 57 ** argv[4] = "1" for temporary files, "0" for main database, "2" or more 58 ** for auxiliary database files. 59 ** 60 */ 61 static 62 int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){ 63 InitData *pData = (InitData*)pInit; 64 int nErr = 0; 65 66 assert( argc==5 ); 67 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ 68 if( argv[0]==0 ){ 69 corruptSchema(pData, 0); 70 return 1; 71 } 72 switch( argv[0][0] ){ 73 case 'v': 74 case 'i': 75 case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */ 76 sqlite *db = pData->db; 77 if( argv[2]==0 || argv[4]==0 ){ 78 corruptSchema(pData, 0); 79 return 1; 80 } 81 if( argv[3] && argv[3][0] ){ 82 /* Call the parser to process a CREATE TABLE, INDEX or VIEW. 83 ** But because db->init.busy is set to 1, no VDBE code is generated 84 ** or executed. All the parser does is build the internal data 85 ** structures that describe the table, index, or view. 86 */ 87 char *zErr; 88 assert( db->init.busy ); 89 db->init.iDb = atoi(argv[4]); 90 assert( db->init.iDb>=0 && db->init.iDb<db->nDb ); 91 db->init.newTnum = atoi(argv[2]); 92 if( sqlite3_exec(db, argv[3], 0, 0, &zErr) ){ 93 corruptSchema(pData, zErr); 94 sqlite3_free(zErr); 95 } 96 db->init.iDb = 0; 97 }else{ 98 /* If the SQL column is blank it means this is an index that 99 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE 100 ** constraint for a CREATE TABLE. The index should have already 101 ** been created when we processed the CREATE TABLE. All we have 102 ** to do here is record the root page number for that index. 103 */ 104 int iDb; 105 Index *pIndex; 106 107 iDb = atoi(argv[4]); 108 assert( iDb>=0 && iDb<db->nDb ); 109 pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zName); 110 if( pIndex==0 || pIndex->tnum!=0 ){ 111 /* This can occur if there exists an index on a TEMP table which 112 ** has the same name as another index on a permanent index. Since 113 ** the permanent table is hidden by the TEMP table, we can also 114 ** safely ignore the index on the permanent table. 115 */ 116 /* Do Nothing */; 117 }else{ 118 pIndex->tnum = atoi(argv[2]); 119 } 120 } 121 break; 122 } 123 default: { 124 /* This can not happen! */ 125 nErr = 1; 126 assert( nErr==0 ); 127 } 128 } 129 return nErr; 130 } 131 132 /* 133 ** Attempt to read the database schema and initialize internal 134 ** data structures for a single database file. The index of the 135 ** database file is given by iDb. iDb==0 is used for the main 136 ** database. iDb==1 should never be used. iDb>=2 is used for 137 ** auxiliary databases. Return one of the SQLITE_ error codes to 138 ** indicate success or failure. 139 */ 140 static int sqlite3InitOne(sqlite *db, int iDb, char **pzErrMsg){ 141 int rc; 142 BtCursor *curMain; 143 int size; 144 Table *pTab; 145 char *azArg[6]; 146 char zDbNum[30]; 147 int meta[10]; 148 InitData initData; 149 150 /* 151 ** The master database table has a structure like this 152 */ 153 static char master_schema[] = 154 "CREATE TABLE sqlite_master(\n" 155 " type text,\n" 156 " name text,\n" 157 " tbl_name text,\n" 158 " rootpage integer,\n" 159 " sql text\n" 160 ")" 161 ; 162 static char temp_master_schema[] = 163 "CREATE TEMP TABLE sqlite_temp_master(\n" 164 " type text,\n" 165 " name text,\n" 166 " tbl_name text,\n" 167 " rootpage integer,\n" 168 " sql text\n" 169 ")" 170 ; 171 172 /* The following SQL will read the schema from the master tables. 173 */ 174 static char init_script1[] = 175 "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master"; 176 static char init_script2[] = 177 "SELECT type, name, rootpage, sql, 0 FROM sqlite_master"; 178 179 assert( iDb>=0 && iDb!=1 && iDb<db->nDb ); 180 181 /* Construct the schema tables: sqlite_master and sqlite_temp_master 182 */ 183 sqlite3SafetyOff(db); 184 azArg[0] = "table"; 185 azArg[1] = MASTER_NAME; 186 azArg[2] = "1"; 187 azArg[3] = master_schema; 188 sprintf(zDbNum, "%d", iDb); 189 azArg[4] = zDbNum; 190 azArg[5] = 0; 191 initData.db = db; 192 initData.pzErrMsg = pzErrMsg; 193 sqlite3InitCallback(&initData, 5, azArg, 0); 194 pTab = sqlite3FindTable(db, MASTER_NAME, "main"); 195 if( pTab ){ 196 pTab->readOnly = 1; 197 } 198 if( iDb==0 ){ 199 azArg[1] = TEMP_MASTER_NAME; 200 azArg[3] = temp_master_schema; 201 azArg[4] = "1"; 202 sqlite3InitCallback(&initData, 5, azArg, 0); 203 pTab = sqlite3FindTable(db, TEMP_MASTER_NAME, "temp"); 204 if( pTab ){ 205 pTab->readOnly = 1; 206 } 207 } 208 sqlite3SafetyOn(db); 209 210 /* Create a cursor to hold the database open 211 */ 212 if( db->aDb[iDb].pBt==0 ) return SQLITE_OK; 213 rc = sqlite3BtreeCursor(db->aDb[iDb].pBt, MASTER_ROOT, 0, 0, 0, &curMain); 214 if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){ 215 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0); 216 return rc; 217 } 218 219 /* Get the database meta information. 220 ** 221 ** Meta values are as follows: 222 ** meta[0] Schema cookie. Changes with each schema change. 223 ** meta[1] File format of schema layer. 224 ** meta[2] Size of the page cache. 225 ** meta[3] Synchronous setting. 1:off, 2:normal, 3:full 226 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16 LE 3:UTF-16 BE 227 ** meta[5] Pragma temp_store value. See comments on BtreeFactory 228 ** meta[6] 229 ** meta[7] 230 ** meta[8] 231 ** meta[9] 232 ** 233 ** Note: The hash defined TEXT_Utf* symbols in sqliteInt.h correspond to 234 ** the possible values of meta[4]. 235 */ 236 if( rc==SQLITE_OK ){ 237 int i; 238 for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){ 239 rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, i+1, &meta[i]); 240 } 241 if( rc ){ 242 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0); 243 sqlite3BtreeCloseCursor(curMain); 244 return rc; 245 } 246 }else{ 247 memset(meta, 0, sizeof(meta)); 248 } 249 db->aDb[iDb].schema_cookie = meta[0]; 250 251 /* If opening a non-empty database, check the text encoding. For the 252 ** main database, set sqlite3.enc to the encoding of the main database. 253 ** For an attached db, it is an error if the encoding is not the same 254 ** as sqlite3.enc. 255 */ 256 if( meta[4] ){ /* text encoding */ 257 if( iDb==0 ){ 258 /* If opening the main database, set db->enc. */ 259 db->enc = (u8)meta[4]; 260 db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0); 261 }else{ 262 /* If opening an attached database, the encoding much match db->enc */ 263 if( meta[4]!=db->enc ){ 264 sqlite3BtreeCloseCursor(curMain); 265 sqlite3SetString(pzErrMsg, "attached databases must use the same" 266 " text encoding as main database", (char*)0); 267 return SQLITE_ERROR; 268 } 269 } 270 } 271 272 if( iDb==0 ){ 273 size = meta[2]; 274 if( size==0 ){ size = MAX_PAGES; } 275 db->cache_size = size; 276 db->safety_level = meta[3]; 277 if( meta[5]>0 && meta[5]<=2 && db->temp_store==0 ){ 278 db->temp_store = meta[5]; 279 } 280 if( db->safety_level==0 ) db->safety_level = 2; 281 282 /* FIX ME: Every struct Db will need a next_cookie */ 283 db->next_cookie = meta[0]; 284 db->file_format = meta[1]; 285 if( db->file_format==0 ){ 286 /* This happens if the database was initially empty */ 287 db->file_format = 1; 288 } 289 } 290 291 /* 292 ** file_format==1 Version 3.0.0. 293 */ 294 if( meta[1]>1 ){ 295 sqlite3BtreeCloseCursor(curMain); 296 sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0); 297 return SQLITE_ERROR; 298 } 299 300 sqlite3BtreeSetCacheSize(db->aDb[iDb].pBt, db->cache_size); 301 sqlite3BtreeSetSafetyLevel(db->aDb[iDb].pBt, meta[3]==0 ? 2 : meta[3]); 302 303 /* Read the schema information out of the schema tables 304 */ 305 assert( db->init.busy ); 306 if( rc==SQLITE_EMPTY ){ 307 /* For an empty database, there is nothing to read */ 308 rc = SQLITE_OK; 309 }else{ 310 sqlite3SafetyOff(db); 311 if( iDb==0 ){ 312 /* This SQL statement tries to read the temp.* schema from the 313 ** sqlite_temp_master table. It might return SQLITE_EMPTY. 314 */ 315 rc = sqlite3_exec(db, init_script1, sqlite3InitCallback, &initData, 0); 316 if( rc==SQLITE_OK || rc==SQLITE_EMPTY ){ 317 rc = sqlite3_exec(db, init_script2, sqlite3InitCallback, &initData, 0); 318 } 319 }else{ 320 char *zSql = 0; 321 sqlite3SetString(&zSql, 322 "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"", 323 db->aDb[iDb].zName, "\".sqlite_master", (char*)0); 324 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); 325 sqliteFree(zSql); 326 } 327 sqlite3SafetyOn(db); 328 sqlite3BtreeCloseCursor(curMain); 329 } 330 if( sqlite3_malloc_failed ){ 331 sqlite3SetString(pzErrMsg, "out of memory", (char*)0); 332 rc = SQLITE_NOMEM; 333 sqlite3ResetInternalSchema(db, 0); 334 } 335 if( rc==SQLITE_OK ){ 336 DbSetProperty(db, iDb, DB_SchemaLoaded); 337 if( iDb==0 ){ 338 DbSetProperty(db, 1, DB_SchemaLoaded); 339 } 340 }else{ 341 sqlite3ResetInternalSchema(db, iDb); 342 } 343 return rc; 344 } 345 346 /* 347 ** Initialize all database files - the main database file, the file 348 ** used to store temporary tables, and any additional database files 349 ** created using ATTACH statements. Return a success code. If an 350 ** error occurs, write an error message into *pzErrMsg. 351 ** 352 ** After the database is initialized, the SQLITE_Initialized 353 ** bit is set in the flags field of the sqlite structure. 354 */ 355 int sqlite3Init(sqlite *db, char **pzErrMsg){ 356 int i, rc; 357 358 if( db->init.busy ) return SQLITE_OK; 359 assert( (db->flags & SQLITE_Initialized)==0 ); 360 rc = SQLITE_OK; 361 db->init.busy = 1; 362 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 363 if( DbHasProperty(db, i, DB_SchemaLoaded) ) continue; 364 assert( i!=1 ); /* Should have been initialized together with 0 */ 365 rc = sqlite3InitOne(db, i, pzErrMsg); 366 if( rc ){ 367 sqlite3ResetInternalSchema(db, i); 368 } 369 } 370 db->init.busy = 0; 371 if( rc==SQLITE_OK ){ 372 db->flags |= SQLITE_Initialized; 373 sqlite3CommitInternalChanges(db); 374 } 375 376 if( rc!=SQLITE_OK ){ 377 db->flags &= ~SQLITE_Initialized; 378 } 379 return rc; 380 } 381 382 /* 383 ** This routine is a no-op if the database schema is already initialised. 384 ** Otherwise, the schema is loaded. An error code is returned. 385 */ 386 int sqlite3ReadSchema(sqlite *db, char **pzErrMsg){ 387 int rc = SQLITE_OK; 388 389 if( !db->init.busy ){ 390 if( (db->flags & SQLITE_Initialized)==0 ){ 391 rc = sqlite3Init(db, pzErrMsg); 392 } 393 } 394 assert( rc!=SQLITE_OK || (db->flags & SQLITE_Initialized)||db->init.busy ); 395 return rc; 396 } 397 398 /* 399 ** The version of the library 400 */ 401 const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $"; 402 const char sqlite3_version[] = SQLITE_VERSION; 403 404 /* 405 ** This is the default collating function named "BINARY" which is always 406 ** available. 407 */ 408 static int binaryCollatingFunc( 409 void *NotUsed, 410 int nKey1, const void *pKey1, 411 int nKey2, const void *pKey2 412 ){ 413 int rc, n; 414 n = nKey1<nKey2 ? nKey1 : nKey2; 415 rc = memcmp(pKey1, pKey2, n); 416 if( rc==0 ){ 417 rc = nKey1 - nKey2; 418 } 419 return rc; 420 } 421 422 /* 423 ** Another built-in collating sequence: NOCASE. At the moment there is 424 ** only a UTF-8 implementation. 425 */ 426 static int nocaseCollatingFunc( 427 void *NotUsed, 428 int nKey1, const void *pKey1, 429 int nKey2, const void *pKey2 430 ){ 431 int r = sqlite3StrNICmp( 432 (const char *)pKey1, (const char *)pKey2, (nKey1>nKey2)?nKey1:nKey2); 433 if( 0==r ){ 434 r = nKey1-nKey2; 435 } 436 return r; 437 } 438 439 /* 440 ** Return the ROWID of the most recent insert 441 */ 442 long long int sqlite3_last_insert_rowid(sqlite *db){ 443 return db->lastRowid; 444 } 445 446 /* 447 ** Return the number of changes in the most recent call to sqlite3_exec(). 448 */ 449 int sqlite3_changes(sqlite *db){ 450 return db->nChange; 451 } 452 453 /* 454 ** Return the number of changes produced by the last INSERT, UPDATE, or 455 ** DELETE statement to complete execution. The count does not include 456 ** changes due to SQL statements executed in trigger programs that were 457 ** triggered by that statement 458 */ 459 int sqlite3_last_statement_changes(sqlite *db){ 460 return db->lsChange; 461 } 462 463 /* 464 ** Close an existing SQLite database 465 */ 466 void sqlite3_close(sqlite *db){ 467 HashElem *i; 468 int j; 469 db->want_to_close = 1; 470 if( sqlite3SafetyCheck(db) || sqlite3SafetyOn(db) ){ 471 /* printf("DID NOT CLOSE\n"); fflush(stdout); */ 472 return; 473 } 474 db->magic = SQLITE_MAGIC_CLOSED; 475 for(j=0; j<db->nDb; j++){ 476 struct Db *pDb = &db->aDb[j]; 477 if( pDb->pBt ){ 478 sqlite3BtreeClose(pDb->pBt); 479 pDb->pBt = 0; 480 } 481 } 482 sqlite3ResetInternalSchema(db, 0); 483 assert( db->nDb<=2 ); 484 assert( db->aDb==db->aDbStatic ); 485 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ 486 FuncDef *pFunc, *pNext; 487 for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){ 488 pNext = pFunc->pNext; 489 sqliteFree(pFunc); 490 } 491 } 492 493 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ 494 CollSeq *pColl = (CollSeq *)sqliteHashData(i); 495 /* sqliteFree(pColl); */ 496 } 497 498 sqlite3HashClear(&db->aFunc); 499 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */ 500 sqliteFree(db); 501 } 502 503 /* 504 ** Rollback all database files. 505 */ 506 void sqlite3RollbackAll(sqlite *db){ 507 int i; 508 for(i=0; i<db->nDb; i++){ 509 if( db->aDb[i].pBt ){ 510 sqlite3BtreeRollback(db->aDb[i].pBt); 511 db->aDb[i].inTrans = 0; 512 } 513 } 514 sqlite3ResetInternalSchema(db, 0); 515 /* sqlite3RollbackInternalChanges(db); */ 516 } 517 518 /* 519 ** Return a static string that describes the kind of error specified in the 520 ** argument. 521 */ 522 const char *sqlite3ErrStr(int rc){ 523 const char *z; 524 switch( rc ){ 525 case SQLITE_OK: z = "not an error"; break; 526 case SQLITE_ERROR: z = "SQL logic error or missing database"; break; 527 case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break; 528 case SQLITE_PERM: z = "access permission denied"; break; 529 case SQLITE_ABORT: z = "callback requested query abort"; break; 530 case SQLITE_BUSY: z = "database is locked"; break; 531 case SQLITE_LOCKED: z = "database table is locked"; break; 532 case SQLITE_NOMEM: z = "out of memory"; break; 533 case SQLITE_READONLY: z = "attempt to write a readonly database"; break; 534 case SQLITE_INTERRUPT: z = "interrupted"; break; 535 case SQLITE_IOERR: z = "disk I/O error"; break; 536 case SQLITE_CORRUPT: z = "database disk image is malformed"; break; 537 case SQLITE_NOTFOUND: z = "table or record not found"; break; 538 case SQLITE_FULL: z = "database is full"; break; 539 case SQLITE_CANTOPEN: z = "unable to open database file"; break; 540 case SQLITE_PROTOCOL: z = "database locking protocol failure"; break; 541 case SQLITE_EMPTY: z = "table contains no data"; break; 542 case SQLITE_SCHEMA: z = "database schema has changed"; break; 543 case SQLITE_TOOBIG: z = "too much data for one table row"; break; 544 case SQLITE_CONSTRAINT: z = "constraint failed"; break; 545 case SQLITE_MISMATCH: z = "datatype mismatch"; break; 546 case SQLITE_MISUSE: z = "library routine called out of sequence";break; 547 case SQLITE_NOLFS: z = "kernel lacks large file support"; break; 548 case SQLITE_AUTH: z = "authorization denied"; break; 549 case SQLITE_FORMAT: z = "auxiliary database format error"; break; 550 case SQLITE_RANGE: z = "bind index out of range"; break; 551 case SQLITE_NOTADB: z = "file is encrypted or is not a database";break; 552 default: z = "unknown error"; break; 553 } 554 return z; 555 } 556 557 /* 558 ** This routine implements a busy callback that sleeps and tries 559 ** again until a timeout value is reached. The timeout value is 560 ** an integer number of milliseconds passed in as the first 561 ** argument. 562 */ 563 static int sqliteDefaultBusyCallback( 564 void *Timeout, /* Maximum amount of time to wait */ 565 const char *NotUsed, /* The name of the table that is busy */ 566 int count /* Number of times table has been busy */ 567 ){ 568 #if SQLITE_MIN_SLEEP_MS==1 569 static const char delays[] = 570 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 50, 100}; 571 static const short int totals[] = 572 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228, 287}; 573 # define NDELAY (sizeof(delays)/sizeof(delays[0])) 574 int timeout = (int)Timeout; 575 int delay, prior; 576 577 if( count <= NDELAY ){ 578 delay = delays[count-1]; 579 prior = totals[count-1]; 580 }else{ 581 delay = delays[NDELAY-1]; 582 prior = totals[NDELAY-1] + delay*(count-NDELAY-1); 583 } 584 if( prior + delay > timeout ){ 585 delay = timeout - prior; 586 if( delay<=0 ) return 0; 587 } 588 sqlite3OsSleep(delay); 589 return 1; 590 #else 591 int timeout = (int)Timeout; 592 if( (count+1)*1000 > timeout ){ 593 return 0; 594 } 595 sqlite3OsSleep(1000); 596 return 1; 597 #endif 598 } 599 600 /* 601 ** This routine sets the busy callback for an Sqlite database to the 602 ** given callback function with the given argument. 603 */ 604 void sqlite3_busy_handler( 605 sqlite *db, 606 int (*xBusy)(void*,const char*,int), 607 void *pArg 608 ){ 609 db->busyHandler.xFunc = xBusy; 610 db->busyHandler.pArg = pArg; 611 } 612 613 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 614 /* 615 ** This routine sets the progress callback for an Sqlite database to the 616 ** given callback function with the given argument. The progress callback will 617 ** be invoked every nOps opcodes. 618 */ 619 void sqlite3_progress_handler( 620 sqlite *db, 621 int nOps, 622 int (*xProgress)(void*), 623 void *pArg 624 ){ 625 if( nOps>0 ){ 626 db->xProgress = xProgress; 627 db->nProgressOps = nOps; 628 db->pProgressArg = pArg; 629 }else{ 630 db->xProgress = 0; 631 db->nProgressOps = 0; 632 db->pProgressArg = 0; 633 } 634 } 635 #endif 636 637 638 /* 639 ** This routine installs a default busy handler that waits for the 640 ** specified number of milliseconds before returning 0. 641 */ 642 void sqlite3_busy_timeout(sqlite *db, int ms){ 643 if( ms>0 ){ 644 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)ms); 645 }else{ 646 sqlite3_busy_handler(db, 0, 0); 647 } 648 } 649 650 /* 651 ** Cause any pending operation to stop at its earliest opportunity. 652 */ 653 void sqlite3_interrupt(sqlite *db){ 654 db->flags |= SQLITE_Interrupt; 655 } 656 657 /* 658 ** Windows systems should call this routine to free memory that 659 ** is returned in the in the errmsg parameter of sqlite3_open() when 660 ** SQLite is a DLL. For some reason, it does not work to call free() 661 ** directly. 662 ** 663 ** Note that we need to call free() not sqliteFree() here, since every 664 ** string that is exported from SQLite should have already passed through 665 ** sqlite3StrRealloc(). 666 */ 667 void sqlite3_free(char *p){ free(p); } 668 669 /* 670 ** Create new user functions. 671 */ 672 int sqlite3_create_function( 673 sqlite3 *db, 674 const char *zFunctionName, 675 int nArg, 676 int eTextRep, 677 int iCollateArg, 678 void *pUserData, 679 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), 680 void (*xStep)(sqlite3_context*,int,sqlite3_value **), 681 void (*xFinal)(sqlite3_context*) 682 ){ 683 FuncDef *p; 684 int nName; 685 686 if( (db==0 || zFunctionName==0 || sqlite3SafetyCheck(db)) || 687 (xFunc && (xFinal || xStep)) || 688 (!xFunc && (xFinal && !xStep)) || 689 (!xFunc && (!xFinal && xStep)) || 690 (nArg<-1 || nArg>127) || 691 (255<(nName = strlen(zFunctionName))) ){ 692 return SQLITE_ERROR; 693 } 694 695 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, eTextRep, 1); 696 if( p==0 ) return 1; 697 p->xFunc = xFunc; 698 p->xStep = xStep; 699 p->xFinalize = xFinal; 700 p->pUserData = pUserData; 701 return SQLITE_OK; 702 } 703 int sqlite3_create_function16( 704 sqlite3 *db, 705 const void *zFunctionName, 706 int nArg, 707 int eTextRep, 708 int iCollateArg, 709 void *pUserData, 710 void (*xFunc)(sqlite3_context*,int,sqlite3_value**), 711 void (*xStep)(sqlite3_context*,int,sqlite3_value**), 712 void (*xFinal)(sqlite3_context*) 713 ){ 714 int rc; 715 char *zFunctionName8; 716 zFunctionName8 = sqlite3utf16to8(zFunctionName, -1, SQLITE_BIGENDIAN); 717 if( !zFunctionName8 ){ 718 return SQLITE_NOMEM; 719 } 720 rc = sqlite3_create_function(db, zFunctionName8, nArg, eTextRep, 721 iCollateArg, pUserData, xFunc, xStep, xFinal); 722 sqliteFree(zFunctionName8); 723 return rc; 724 } 725 726 /* 727 ** Register a trace function. The pArg from the previously registered trace 728 ** is returned. 729 ** 730 ** A NULL trace function means that no tracing is executes. A non-NULL 731 ** trace is a pointer to a function that is invoked at the start of each 732 ** sqlite3_exec(). 733 */ 734 void *sqlite3_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){ 735 void *pOld = db->pTraceArg; 736 db->xTrace = xTrace; 737 db->pTraceArg = pArg; 738 return pOld; 739 } 740 741 /*** EXPERIMENTAL *** 742 ** 743 ** Register a function to be invoked when a transaction comments. 744 ** If either function returns non-zero, then the commit becomes a 745 ** rollback. 746 */ 747 void *sqlite3_commit_hook( 748 sqlite *db, /* Attach the hook to this database */ 749 int (*xCallback)(void*), /* Function to invoke on each commit */ 750 void *pArg /* Argument to the function */ 751 ){ 752 void *pOld = db->pCommitArg; 753 db->xCommitCallback = xCallback; 754 db->pCommitArg = pArg; 755 return pOld; 756 } 757 758 759 /* 760 ** This routine is called to create a connection to a database BTree 761 ** driver. If zFilename is the name of a file, then that file is 762 ** opened and used. If zFilename is the magic name ":memory:" then 763 ** the database is stored in memory (and is thus forgotten as soon as 764 ** the connection is closed.) If zFilename is NULL then the database 765 ** is for temporary use only and is deleted as soon as the connection 766 ** is closed. 767 ** 768 ** A temporary database can be either a disk file (that is automatically 769 ** deleted when the file is closed) or a set of red-black trees held in memory, 770 ** depending on the values of the TEMP_STORE compile-time macro and the 771 ** db->temp_store variable, according to the following chart: 772 ** 773 ** TEMP_STORE db->temp_store Location of temporary database 774 ** ---------- -------------- ------------------------------ 775 ** 0 any file 776 ** 1 1 file 777 ** 1 2 memory 778 ** 1 0 file 779 ** 2 1 file 780 ** 2 2 memory 781 ** 2 0 memory 782 ** 3 any memory 783 */ 784 int sqlite3BtreeFactory( 785 const sqlite *db, /* Main database when opening aux otherwise 0 */ 786 const char *zFilename, /* Name of the file containing the BTree database */ 787 int omitJournal, /* if TRUE then do not journal this file */ 788 int nCache, /* How many pages in the page cache */ 789 Btree **ppBtree /* Pointer to new Btree object written here */ 790 ){ 791 int btree_flags = 0; 792 793 assert( ppBtree != 0); 794 if( omitJournal ){ 795 btree_flags |= BTREE_OMIT_JOURNAL; 796 } 797 if( !zFilename ){ 798 btree_flags |= BTREE_MEMORY; 799 } 800 801 return sqlite3BtreeOpen(zFilename, ppBtree, nCache, btree_flags, 802 &db->busyHandler); 803 } 804 805 /* 806 ** Return UTF-8 encoded English language explanation of the most recent 807 ** error. 808 */ 809 const char *sqlite3_errmsg(sqlite3 *db){ 810 if( !db ){ 811 /* If db is NULL, then assume that a malloc() failed during an 812 ** sqlite3_open() call. 813 */ 814 return sqlite3ErrStr(SQLITE_NOMEM); 815 } 816 if( db->zErrMsg ){ 817 return db->zErrMsg; 818 } 819 return sqlite3ErrStr(db->errCode); 820 } 821 822 /* 823 ** Return UTF-16 encoded English language explanation of the most recent 824 ** error. 825 */ 826 const void *sqlite3_errmsg16(sqlite3 *db){ 827 if( !db ){ 828 /* If db is NULL, then assume that a malloc() failed during an 829 ** sqlite3_open() call. We have a static version of the string 830 ** "out of memory" encoded using UTF-16 just for this purpose. 831 ** 832 ** Because all the characters in the string are in the unicode 833 ** range 0x00-0xFF, if we pad the big-endian string with a 834 ** zero byte, we can obtain the little-endian string with 835 ** &big_endian[1]. 836 */ 837 static char outOfMemBe[] = { 838 0, 'o', 0, 'u', 0, 't', 0, ' ', 839 0, 'o', 0, 'f', 0, ' ', 840 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0 841 }; 842 static char *outOfMemLe = &outOfMemBe[1]; 843 844 if( SQLITE_BIGENDIAN ){ 845 return (void *)outOfMemBe; 846 }else{ 847 return (void *)outOfMemLe; 848 } 849 } 850 if( !db->zErrMsg16 ){ 851 char const *zErr8 = sqlite3_errmsg(db); 852 if( SQLITE_BIGENDIAN ){ 853 db->zErrMsg16 = sqlite3utf8to16be(zErr8, -1); 854 }else{ 855 db->zErrMsg16 = sqlite3utf8to16le(zErr8, -1); 856 } 857 } 858 return db->zErrMsg16; 859 } 860 861 int sqlite3_errcode(sqlite3 *db){ 862 return db->errCode; 863 } 864 865 /* 866 ** Check schema cookies in all databases except TEMP. If any cookie is out 867 ** of date, return 0. If all schema cookies are current, return 1. 868 */ 869 static int schemaIsValid(sqlite *db){ 870 int iDb; 871 int rc; 872 BtCursor *curTemp; 873 int cookie; 874 int allOk = 1; 875 876 for(iDb=0; allOk && iDb<db->nDb; iDb++){ 877 Btree *pBt; 878 if( iDb==1 ) continue; 879 pBt = db->aDb[iDb].pBt; 880 if( pBt==0 ) continue; 881 rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp); 882 if( rc==SQLITE_OK ){ 883 rc = sqlite3BtreeGetMeta(pBt, 1, &cookie); 884 if( rc==SQLITE_OK && cookie!=db->aDb[iDb].schema_cookie ){ 885 allOk = 0; 886 } 887 sqlite3BtreeCloseCursor(curTemp); 888 } 889 } 890 return allOk; 891 } 892 893 /* 894 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. 895 */ 896 int sqlite3_prepare( 897 sqlite3 *db, /* Database handle. */ 898 const char *zSql, /* UTF-8 encoded SQL statement. */ 899 int nBytes, /* Length of zSql in bytes. */ 900 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 901 const char** pzTail /* OUT: End of parsed string */ 902 ){ 903 Parse sParse; 904 char *zErrMsg = 0; 905 int rc = SQLITE_OK; 906 907 if( sqlite3SafetyOn(db) ){ 908 rc = SQLITE_MISUSE; 909 goto prepare_out; 910 } 911 912 if( db->pVdbe==0 ){ db->nChange = 0; } 913 memset(&sParse, 0, sizeof(sParse)); 914 sParse.db = db; 915 sqlite3RunParser(&sParse, zSql, &zErrMsg); 916 917 if( db->xTrace && !db->init.busy ){ 918 /* Trace only the statment that was compiled. 919 ** Make a copy of that part of the SQL string since zSQL is const 920 ** and we must pass a zero terminated string to the trace function 921 ** The copy is unnecessary if the tail pointer is pointing at the 922 ** beginnig or end of the SQL string. 923 */ 924 if( sParse.zTail && sParse.zTail!=zSql && *sParse.zTail ){ 925 char *tmpSql = sqliteStrNDup(zSql, sParse.zTail - zSql); 926 if( tmpSql ){ 927 db->xTrace(db->pTraceArg, tmpSql); 928 free(tmpSql); 929 }else{ 930 /* If a memory error occurred during the copy, 931 ** trace entire SQL string and fall through to the 932 ** sqlite3_malloc_failed test to report the error. 933 */ 934 db->xTrace(db->pTraceArg, zSql); 935 } 936 }else{ 937 db->xTrace(db->pTraceArg, zSql); 938 } 939 } 940 941 /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned 942 ** on in debugging mode. 943 */ 944 #ifdef SQLITE_DEBUG 945 if( (db->flags & SQLITE_SqlTrace)!=0 && sParse.zTail && sParse.zTail!=zSql ){ 946 sqlite3DebugPrintf("SQL-trace: %.*s\n", sParse.zTail - zSql, zSql); 947 } 948 #endif /* SQLITE_DEBUG */ 949 950 951 if( sqlite3_malloc_failed ){ 952 rc = SQLITE_NOMEM; 953 sqlite3RollbackAll(db); 954 sqlite3ResetInternalSchema(db, 0); 955 db->flags &= ~SQLITE_InTrans; 956 goto prepare_out; 957 } 958 if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK; 959 if( sParse.checkSchema && !schemaIsValid(db) ){ 960 sParse.rc = SQLITE_SCHEMA; 961 } 962 if( sParse.rc==SQLITE_SCHEMA ){ 963 sqlite3ResetInternalSchema(db, 0); 964 } 965 assert( ppStmt ); 966 *ppStmt = (sqlite3_stmt*)sParse.pVdbe; 967 if( pzTail ) *pzTail = sParse.zTail; 968 rc = sParse.rc; 969 970 if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ 971 sqlite3VdbeSetNumCols(sParse.pVdbe, 5); 972 sqlite3VdbeSetColName(sParse.pVdbe, 0, "addr", P3_STATIC); 973 sqlite3VdbeSetColName(sParse.pVdbe, 1, "opcode", P3_STATIC); 974 sqlite3VdbeSetColName(sParse.pVdbe, 2, "p1", P3_STATIC); 975 sqlite3VdbeSetColName(sParse.pVdbe, 3, "p2", P3_STATIC); 976 sqlite3VdbeSetColName(sParse.pVdbe, 4, "p3", P3_STATIC); 977 } 978 979 prepare_out: 980 if( sqlite3SafetyOff(db) ){ 981 rc = SQLITE_MISUSE; 982 } 983 if( zErrMsg ){ 984 sqlite3Error(db, rc, "%s", zErrMsg); 985 }else{ 986 sqlite3Error(db, rc, 0); 987 } 988 return rc; 989 } 990 991 /* 992 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. 993 */ 994 int sqlite3_prepare16( 995 sqlite3 *db, /* Database handle. */ 996 const void *zSql, /* UTF-8 encoded SQL statement. */ 997 int nBytes, /* Length of zSql in bytes. */ 998 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ 999 const void **pzTail /* OUT: End of parsed string */ 1000 ){ 1001 /* This function currently works by first transforming the UTF-16 1002 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The 1003 ** tricky bit is figuring out the pointer to return in *pzTail. 1004 */ 1005 char *zSql8 = 0; 1006 char const *zTail8 = 0; 1007 int rc; 1008 1009 zSql8 = sqlite3utf16to8(zSql, nBytes, SQLITE_BIGENDIAN); 1010 if( !zSql8 ){ 1011 sqlite3Error(db, SQLITE_NOMEM, 0); 1012 return SQLITE_NOMEM; 1013 } 1014 rc = sqlite3_prepare(db, zSql8, -1, ppStmt, &zTail8); 1015 1016 if( zTail8 && pzTail ){ 1017 /* If sqlite3_prepare returns a tail pointer, we calculate the 1018 ** equivalent pointer into the UTF-16 string by counting the unicode 1019 ** characters between zSql8 and zTail8, and then returning a pointer 1020 ** the same number of characters into the UTF-16 string. 1021 */ 1022 int chars_parsed = sqlite3utf8CharLen(zSql8, zTail8-zSql8); 1023 *pzTail = (u8 *)zSql + sqlite3utf16ByteLen(zSql, chars_parsed); 1024 } 1025 1026 return rc; 1027 } 1028 1029 /* 1030 ** This routine does the work of opening a database on behalf of 1031 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" 1032 ** is UTF-8 encoded. The fourth argument, "def_enc" is one of the TEXT_* 1033 ** macros from sqliteInt.h. If we end up creating a new database file 1034 ** (not opening an existing one), the text encoding of the database 1035 ** will be set to this value. 1036 */ 1037 static int openDatabase( 1038 const char *zFilename, /* Database filename UTF-8 encoded */ 1039 sqlite3 **ppDb /* OUT: Returned database handle */ 1040 ){ 1041 sqlite3 *db; 1042 int rc, i; 1043 char *zErrMsg = 0; 1044 1045 /* Allocate the sqlite data structure */ 1046 db = sqliteMalloc( sizeof(sqlite) ); 1047 if( db==0 ) goto opendb_out; 1048 db->priorNewRowid = 0; 1049 db->magic = SQLITE_MAGIC_BUSY; 1050 db->nDb = 2; 1051 db->aDb = db->aDbStatic; 1052 db->enc = TEXT_Utf8; 1053 db->autoCommit = 1; 1054 /* db->flags |= SQLITE_ShortColNames; */ 1055 sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0); 1056 sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0); 1057 for(i=0; i<db->nDb; i++){ 1058 sqlite3HashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0); 1059 sqlite3HashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0); 1060 sqlite3HashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0); 1061 sqlite3HashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1); 1062 } 1063 1064 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 1065 ** and UTF-16, so add a version for each to avoid any unnecessary 1066 ** conversions. The only error that can occur here is a malloc() failure. 1067 */ 1068 sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binaryCollatingFunc); 1069 sqlite3_create_collation(db, "BINARY", SQLITE_UTF16LE, 0,binaryCollatingFunc); 1070 sqlite3_create_collation(db, "BINARY", SQLITE_UTF16BE, 0,binaryCollatingFunc); 1071 db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0); 1072 if( !db->pDfltColl ){ 1073 rc = db->errCode; 1074 assert( rc!=SQLITE_OK ); 1075 db->magic = SQLITE_MAGIC_CLOSED; 1076 goto opendb_out; 1077 } 1078 1079 /* Also add a UTF-8 case-insensitive collation sequence. */ 1080 sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc); 1081 1082 /* Open the backend database driver */ 1083 if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){ 1084 db->temp_store = 2; 1085 db->nMaster = 0; /* Disable atomic multi-file commit for :memory: */ 1086 }else{ 1087 db->nMaster = -1; /* Size of master journal filename initially unknown */ 1088 } 1089 rc = sqlite3BtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt); 1090 if( rc!=SQLITE_OK ){ 1091 /* FIX ME: sqlite3BtreeFactory() should call sqlite3Error(). */ 1092 sqlite3Error(db, rc, 0); 1093 db->magic = SQLITE_MAGIC_CLOSED; 1094 goto opendb_out; 1095 } 1096 db->aDb[0].zName = "main"; 1097 db->aDb[1].zName = "temp"; 1098 1099 /* Register all built-in functions, but do not attempt to read the 1100 ** database schema yet. This is delayed until the first time the database 1101 ** is accessed. 1102 */ 1103 sqlite3RegisterBuiltinFunctions(db); 1104 if( rc==SQLITE_OK ){ 1105 db->magic = SQLITE_MAGIC_OPEN; 1106 }else{ 1107 sqlite3Error(db, rc, "%s", zErrMsg, 0); 1108 if( zErrMsg ) sqliteFree(zErrMsg); 1109 db->magic = SQLITE_MAGIC_CLOSED; 1110 } 1111 1112 opendb_out: 1113 *ppDb = db; 1114 return sqlite3_errcode(db); 1115 } 1116 1117 /* 1118 ** Open a new database handle. 1119 */ 1120 int sqlite3_open( 1121 const char *zFilename, 1122 sqlite3 **ppDb 1123 ){ 1124 return openDatabase(zFilename, ppDb); 1125 } 1126 1127 /* 1128 ** Open a new database handle. 1129 */ 1130 int sqlite3_open16( 1131 const void *zFilename, 1132 sqlite3 **ppDb 1133 ){ 1134 char *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ 1135 int rc; 1136 1137 assert( ppDb ); 1138 1139 zFilename8 = sqlite3utf16to8(zFilename, -1, SQLITE_BIGENDIAN); 1140 if( !zFilename8 ){ 1141 *ppDb = 0; 1142 return SQLITE_NOMEM; 1143 } 1144 rc = openDatabase(zFilename8, ppDb); 1145 if( rc==SQLITE_OK && *ppDb ){ 1146 sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0); 1147 } 1148 sqliteFree(zFilename8); 1149 1150 return rc; 1151 } 1152 1153 /* 1154 ** The following routine destroys a virtual machine that is created by 1155 ** the sqlite3_compile() routine. The integer returned is an SQLITE_ 1156 ** success/failure code that describes the result of executing the virtual 1157 ** machine. 1158 ** 1159 ** This routine sets the error code and string returned by 1160 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). 1161 */ 1162 int sqlite3_finalize(sqlite3_stmt *pStmt){ 1163 return sqlite3VdbeFinalize((Vdbe*)pStmt, 0); 1164 } 1165 1166 /* 1167 ** Terminate the current execution of an SQL statement and reset it 1168 ** back to its starting state so that it can be reused. A success code from 1169 ** the prior execution is returned. 1170 ** 1171 ** This routine sets the error code and string returned by 1172 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). 1173 */ 1174 int sqlite3_reset(sqlite3_stmt *pStmt){ 1175 int rc = sqlite3VdbeReset((Vdbe*)pStmt, 0); 1176 sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0); 1177 return rc; 1178 } 1179 1180 int sqlite3_create_collation( 1181 sqlite3* db, 1182 const char *zName, 1183 int enc, 1184 void* pCtx, 1185 int(*xCompare)(void*,int,const void*,int,const void*) 1186 ){ 1187 CollSeq *pColl; 1188 int rc = SQLITE_OK; 1189 if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16LE && enc!=SQLITE_UTF16BE ){ 1190 sqlite3Error(db, SQLITE_ERROR, 1191 "Param 3 to sqlite3_create_collation() must be one of " 1192 "SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE" 1193 ); 1194 return SQLITE_ERROR; 1195 } 1196 pColl = sqlite3FindCollSeq(db, (u8)enc, zName, strlen(zName), 1); 1197 if( 0==pColl ){ 1198 rc = SQLITE_NOMEM; 1199 }else{ 1200 pColl->xCmp = xCompare; 1201 pColl->pUser = pCtx; 1202 } 1203 sqlite3Error(db, rc, 0); 1204 return rc; 1205 } 1206 1207 int sqlite3_create_collation16( 1208 sqlite3* db, 1209 const char *zName, 1210 int enc, 1211 void* pCtx, 1212 int(*xCompare)(void*,int,const void*,int,const void*) 1213 ){ 1214 int rc; 1215 char *zName8 = sqlite3utf16to8(zName, -1, SQLITE_BIGENDIAN); 1216 rc = sqlite3_create_collation(db, zName8, enc, pCtx, xCompare); 1217 sqliteFree(zName8); 1218 return rc; 1219 } 1220 1221 int sqlite3_collation_needed( 1222 sqlite3 *db, 1223 void *pCollNeededArg, 1224 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) 1225 ){ 1226 db->xCollNeeded = xCollNeeded; 1227 db->xCollNeeded16 = 0; 1228 db->pCollNeededArg = pCollNeededArg; 1229 return SQLITE_OK; 1230 } 1231 int sqlite3_collation_needed16( 1232 sqlite3 *db, 1233 void *pCollNeededArg, 1234 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) 1235 ){ 1236 db->xCollNeeded = 0; 1237 db->xCollNeeded16 = xCollNeeded16; 1238 db->pCollNeededArg = pCollNeededArg; 1239 return SQLITE_OK; 1240 } 1241 1242