You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1139 lines
36 KiB

  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$
  18. */
  19. #include "sqliteInt.h"
  20. #include "os.h"
  21. #include <ctype.h>
  22. /*
  23. ** A pointer to this structure is used to communicate information
  24. ** from sqliteInit into the sqliteInitCallback.
  25. */
  26. typedef struct {
  27. sqlite *db; /* The database being initialized */
  28. char **pzErrMsg; /* Error message stored here */
  29. } InitData;
  30. /*
  31. ** Fill the InitData structure with an error message that indicates
  32. ** that the database is corrupt.
  33. */
  34. static void corruptSchema(InitData *pData, const char *zExtra){
  35. sqliteSetString(pData->pzErrMsg, "malformed database schema",
  36. zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
  37. }
  38. /*
  39. ** This is the callback routine for the code that initializes the
  40. ** database. See sqliteInit() below for additional information.
  41. **
  42. ** Each callback contains the following information:
  43. **
  44. ** argv[0] = "file-format" or "schema-cookie" or "table" or "index"
  45. ** argv[1] = table or index name or meta statement type.
  46. ** argv[2] = root page number for table or index. NULL for meta.
  47. ** argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
  48. ** argv[4] = "1" for temporary files, "0" for main database, "2" or more
  49. ** for auxiliary database files.
  50. **
  51. */
  52. static
  53. int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
  54. InitData *pData = (InitData*)pInit;
  55. int nErr = 0;
  56. assert( argc==5 );
  57. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  58. if( argv[0]==0 ){
  59. corruptSchema(pData, 0);
  60. return 1;
  61. }
  62. switch( argv[0][0] ){
  63. case 'v':
  64. case 'i':
  65. case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
  66. sqlite *db = pData->db;
  67. if( argv[2]==0 || argv[4]==0 ){
  68. corruptSchema(pData, 0);
  69. return 1;
  70. }
  71. if( argv[3] && argv[3][0] ){
  72. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  73. ** But because db->init.busy is set to 1, no VDBE code is generated
  74. ** or executed. All the parser does is build the internal data
  75. ** structures that describe the table, index, or view.
  76. */
  77. char *zErr;
  78. assert( db->init.busy );
  79. db->init.iDb = atoi(argv[4]);
  80. assert( db->init.iDb>=0 && db->init.iDb<db->nDb );
  81. db->init.newTnum = atoi(argv[2]);
  82. if( sqlite_exec(db, argv[3], 0, 0, &zErr) ){
  83. corruptSchema(pData, zErr);
  84. sqlite_freemem(zErr);
  85. }
  86. db->init.iDb = 0;
  87. }else{
  88. /* If the SQL column is blank it means this is an index that
  89. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  90. ** constraint for a CREATE TABLE. The index should have already
  91. ** been created when we processed the CREATE TABLE. All we have
  92. ** to do here is record the root page number for that index.
  93. */
  94. int iDb;
  95. Index *pIndex;
  96. iDb = atoi(argv[4]);
  97. assert( iDb>=0 && iDb<db->nDb );
  98. pIndex = sqliteFindIndex(db, argv[1], db->aDb[iDb].zName);
  99. if( pIndex==0 || pIndex->tnum!=0 ){
  100. /* This can occur if there exists an index on a TEMP table which
  101. ** has the same name as another index on a permanent index. Since
  102. ** the permanent table is hidden by the TEMP table, we can also
  103. ** safely ignore the index on the permanent table.
  104. */
  105. /* Do Nothing */;
  106. }else{
  107. pIndex->tnum = atoi(argv[2]);
  108. }
  109. }
  110. break;
  111. }
  112. default: {
  113. /* This can not happen! */
  114. nErr = 1;
  115. assert( nErr==0 );
  116. }
  117. }
  118. return nErr;
  119. }
  120. /*
  121. ** This is a callback procedure used to reconstruct a table. The
  122. ** name of the table to be reconstructed is passed in as argv[0].
  123. **
  124. ** This routine is used to automatically upgrade a database from
  125. ** format version 1 or 2 to version 3. The correct operation of
  126. ** this routine relys on the fact that no indices are used when
  127. ** copying a table out to a temporary file.
  128. **
  129. ** The change from version 2 to version 3 occurred between SQLite
  130. ** version 2.5.6 and 2.6.0 on 2002-July-18.
  131. */
  132. static
  133. int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
  134. InitData *pData = (InitData*)pInit;
  135. int rc;
  136. Table *pTab;
  137. Trigger *pTrig;
  138. char *zErr = 0;
  139. pTab = sqliteFindTable(pData->db, argv[0], 0);
  140. assert( pTab!=0 );
  141. assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
  142. if( pTab ){
  143. pTrig = pTab->pTrigger;
  144. pTab->pTrigger = 0; /* Disable all triggers before rebuilding the table */
  145. }
  146. rc = sqlite_exec_printf(pData->db,
  147. "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
  148. "DELETE FROM '%q'; "
  149. "INSERT INTO '%q' SELECT * FROM sqlite_x; "
  150. "DROP TABLE sqlite_x;",
  151. 0, 0, &zErr, argv[0], argv[0], argv[0]);
  152. if( zErr ){
  153. if( *pData->pzErrMsg ) sqlite_freemem(*pData->pzErrMsg);
  154. *pData->pzErrMsg = zErr;
  155. }
  156. /* If an error occurred in the SQL above, then the transaction will
  157. ** rollback which will delete the internal symbol tables. This will
  158. ** cause the structure that pTab points to be deleted. In case that
  159. ** happened, we need to refetch pTab.
  160. */
  161. pTab = sqliteFindTable(pData->db, argv[0], 0);
  162. if( pTab ){
  163. assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
  164. pTab->pTrigger = pTrig; /* Re-enable triggers */
  165. }
  166. return rc!=SQLITE_OK;
  167. }
  168. /*
  169. ** Attempt to read the database schema and initialize internal
  170. ** data structures for a single database file. The index of the
  171. ** database file is given by iDb. iDb==0 is used for the main
  172. ** database. iDb==1 should never be used. iDb>=2 is used for
  173. ** auxiliary databases. Return one of the SQLITE_ error codes to
  174. ** indicate success or failure.
  175. */
  176. static int sqliteInitOne(sqlite *db, int iDb, char **pzErrMsg){
  177. int rc;
  178. BtCursor *curMain;
  179. int size;
  180. Table *pTab;
  181. char *azArg[6];
  182. char zDbNum[30];
  183. int meta[SQLITE_N_BTREE_META];
  184. InitData initData;
  185. /*
  186. ** The master database table has a structure like this
  187. */
  188. static char master_schema[] =
  189. "CREATE TABLE sqlite_master(\n"
  190. " type text,\n"
  191. " name text,\n"
  192. " tbl_name text,\n"
  193. " rootpage integer,\n"
  194. " sql text\n"
  195. ")"
  196. ;
  197. static char temp_master_schema[] =
  198. "CREATE TEMP TABLE sqlite_temp_master(\n"
  199. " type text,\n"
  200. " name text,\n"
  201. " tbl_name text,\n"
  202. " rootpage integer,\n"
  203. " sql text\n"
  204. ")"
  205. ;
  206. /* The following SQL will read the schema from the master tables.
  207. ** The first version works with SQLite file formats 2 or greater.
  208. ** The second version is for format 1 files.
  209. **
  210. ** Beginning with file format 2, the rowid for new table entries
  211. ** (including entries in sqlite_master) is an increasing integer.
  212. ** So for file format 2 and later, we can play back sqlite_master
  213. ** and all the CREATE statements will appear in the right order.
  214. ** But with file format 1, table entries were random and so we
  215. ** have to make sure the CREATE TABLEs occur before their corresponding
  216. ** CREATE INDEXs. (We don't have to deal with CREATE VIEW or
  217. ** CREATE TRIGGER in file format 1 because those constructs did
  218. ** not exist then.)
  219. */
  220. static char init_script[] =
  221. "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
  222. "UNION ALL "
  223. "SELECT type, name, rootpage, sql, 0 FROM sqlite_master";
  224. static char older_init_script[] =
  225. "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
  226. "UNION ALL "
  227. "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
  228. "WHERE type='table' "
  229. "UNION ALL "
  230. "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
  231. "WHERE type='index'";
  232. assert( iDb>=0 && iDb!=1 && iDb<db->nDb );
  233. /* Construct the schema tables: sqlite_master and sqlite_temp_master
  234. */
  235. sqliteSafetyOff(db);
  236. azArg[0] = "table";
  237. azArg[1] = MASTER_NAME;
  238. azArg[2] = "2";
  239. azArg[3] = master_schema;
  240. sprintf(zDbNum, "%d", iDb);
  241. azArg[4] = zDbNum;
  242. azArg[5] = 0;
  243. initData.db = db;
  244. initData.pzErrMsg = pzErrMsg;
  245. sqliteInitCallback(&initData, 5, azArg, 0);
  246. pTab = sqliteFindTable(db, MASTER_NAME, "main");
  247. if( pTab ){
  248. pTab->readOnly = 1;
  249. }
  250. if( iDb==0 ){
  251. azArg[1] = TEMP_MASTER_NAME;
  252. azArg[3] = temp_master_schema;
  253. azArg[4] = "1";
  254. sqliteInitCallback(&initData, 5, azArg, 0);
  255. pTab = sqliteFindTable(db, TEMP_MASTER_NAME, "temp");
  256. if( pTab ){
  257. pTab->readOnly = 1;
  258. }
  259. }
  260. sqliteSafetyOn(db);
  261. /* Create a cursor to hold the database open
  262. */
  263. if( db->aDb[iDb].pBt==0 ) return SQLITE_OK;
  264. rc = sqliteBtreeCursor(db->aDb[iDb].pBt, 2, 0, &curMain);
  265. if( rc ){
  266. sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
  267. return rc;
  268. }
  269. /* Get the database meta information
  270. */
  271. rc = sqliteBtreeGetMeta(db->aDb[iDb].pBt, meta);
  272. if( rc ){
  273. sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
  274. sqliteBtreeCloseCursor(curMain);
  275. return rc;
  276. }
  277. db->aDb[iDb].schema_cookie = meta[1];
  278. if( iDb==0 ){
  279. db->next_cookie = meta[1];
  280. db->file_format = meta[2];
  281. size = meta[3];
  282. if( size==0 ){ size = MAX_PAGES; }
  283. db->cache_size = size;
  284. db->safety_level = meta[4];
  285. if( meta[6]>0 && meta[6]<=2 && db->temp_store==0 ){
  286. db->temp_store = meta[6];
  287. }
  288. if( db->safety_level==0 ) db->safety_level = 2;
  289. /*
  290. ** file_format==1 Version 2.1.0.
  291. ** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
  292. ** file_format==3 Version 2.6.0. Fix empty-string index bug.
  293. ** file_format==4 Version 2.7.0. Add support for separate numeric and
  294. ** text datatypes.
  295. */
  296. if( db->file_format==0 ){
  297. /* This happens if the database was initially empty */
  298. db->file_format = 4;
  299. }else if( db->file_format>4 ){
  300. sqliteBtreeCloseCursor(curMain);
  301. sqliteSetString(pzErrMsg, "unsupported file format", (char*)0);
  302. return SQLITE_ERROR;
  303. }
  304. }else if( db->file_format!=meta[2] || db->file_format<4 ){
  305. assert( db->file_format>=4 );
  306. if( meta[2]==0 ){
  307. sqliteSetString(pzErrMsg, "cannot attach empty database: ",
  308. db->aDb[iDb].zName, (char*)0);
  309. }else{
  310. sqliteSetString(pzErrMsg, "incompatible file format in auxiliary "
  311. "database: ", db->aDb[iDb].zName, (char*)0);
  312. }
  313. sqliteBtreeClose(db->aDb[iDb].pBt);
  314. db->aDb[iDb].pBt = 0;
  315. return SQLITE_FORMAT;
  316. }
  317. sqliteBtreeSetCacheSize(db->aDb[iDb].pBt, db->cache_size);
  318. sqliteBtreeSetSafetyLevel(db->aDb[iDb].pBt, meta[4]==0 ? 2 : meta[4]);
  319. /* Read the schema information out of the schema tables
  320. */
  321. assert( db->init.busy );
  322. sqliteSafetyOff(db);
  323. if( iDb==0 ){
  324. rc = sqlite_exec(db,
  325. db->file_format>=2 ? init_script : older_init_script,
  326. sqliteInitCallback, &initData, 0);
  327. }else{
  328. char *zSql = 0;
  329. sqliteSetString(&zSql,
  330. "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
  331. db->aDb[iDb].zName, "\".sqlite_master", (char*)0);
  332. rc = sqlite_exec(db, zSql, sqliteInitCallback, &initData, 0);
  333. sqliteFree(zSql);
  334. }
  335. sqliteSafetyOn(db);
  336. sqliteBtreeCloseCursor(curMain);
  337. if( sqlite_malloc_failed ){
  338. sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  339. rc = SQLITE_NOMEM;
  340. sqliteResetInternalSchema(db, 0);
  341. }
  342. if( rc==SQLITE_OK ){
  343. DbSetProperty(db, iDb, DB_SchemaLoaded);
  344. if( iDb==0 ){
  345. DbSetProperty(db, 1, DB_SchemaLoaded);
  346. }
  347. }else{
  348. sqliteResetInternalSchema(db, iDb);
  349. }
  350. return rc;
  351. }
  352. /*
  353. ** Initialize all database files - the main database file, the file
  354. ** used to store temporary tables, and any additional database files
  355. ** created using ATTACH statements. Return a success code. If an
  356. ** error occurs, write an error message into *pzErrMsg.
  357. **
  358. ** After the database is initialized, the SQLITE_Initialized
  359. ** bit is set in the flags field of the sqlite structure. An
  360. ** attempt is made to initialize the database as soon as it
  361. ** is opened. If that fails (perhaps because another process
  362. ** has the sqlite_master table locked) than another attempt
  363. ** is made the first time the database is accessed.
  364. */
  365. int sqliteInit(sqlite *db, char **pzErrMsg){
  366. int i, rc;
  367. if( db->init.busy ) return SQLITE_OK;
  368. assert( (db->flags & SQLITE_Initialized)==0 );
  369. rc = SQLITE_OK;
  370. db->init.busy = 1;
  371. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  372. if( DbHasProperty(db, i, DB_SchemaLoaded) ) continue;
  373. assert( i!=1 ); /* Should have been initialized together with 0 */
  374. rc = sqliteInitOne(db, i, pzErrMsg);
  375. if( rc ){
  376. sqliteResetInternalSchema(db, i);
  377. }
  378. }
  379. db->init.busy = 0;
  380. if( rc==SQLITE_OK ){
  381. db->flags |= SQLITE_Initialized;
  382. sqliteCommitInternalChanges(db);
  383. }
  384. /* If the database is in formats 1 or 2, then upgrade it to
  385. ** version 3. This will reconstruct all indices. If the
  386. ** upgrade fails for any reason (ex: out of disk space, database
  387. ** is read only, interrupt received, etc.) then fail the init.
  388. */
  389. if( rc==SQLITE_OK && db->file_format<3 ){
  390. char *zErr = 0;
  391. InitData initData;
  392. int meta[SQLITE_N_BTREE_META];
  393. db->magic = SQLITE_MAGIC_OPEN;
  394. initData.db = db;
  395. initData.pzErrMsg = &zErr;
  396. db->file_format = 3;
  397. rc = sqlite_exec(db,
  398. "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
  399. upgrade_3_callback,
  400. &initData,
  401. &zErr);
  402. if( rc==SQLITE_OK ){
  403. sqliteBtreeGetMeta(db->aDb[0].pBt, meta);
  404. meta[2] = 4;
  405. sqliteBtreeUpdateMeta(db->aDb[0].pBt, meta);
  406. sqlite_exec(db, "COMMIT", 0, 0, 0);
  407. }
  408. if( rc!=SQLITE_OK ){
  409. sqliteSetString(pzErrMsg,
  410. "unable to upgrade database to the version 2.6 format",
  411. zErr ? ": " : 0, zErr, (char*)0);
  412. }
  413. sqlite_freemem(zErr);
  414. }
  415. if( rc!=SQLITE_OK ){
  416. db->flags &= ~SQLITE_Initialized;
  417. }
  418. return rc;
  419. }
  420. /*
  421. ** The version of the library
  422. */
  423. const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
  424. const char sqlite_version[] = SQLITE_VERSION;
  425. /*
  426. ** Does the library expect data to be encoded as UTF-8 or iso8859? The
  427. ** following global constant always lets us know.
  428. */
  429. #ifdef SQLITE_UTF8
  430. const char sqlite_encoding[] = "UTF-8";
  431. #else
  432. const char sqlite_encoding[] = "iso8859";
  433. #endif
  434. /*
  435. ** Open a new SQLite database. Construct an "sqlite" structure to define
  436. ** the state of this database and return a pointer to that structure.
  437. **
  438. ** An attempt is made to initialize the in-memory data structures that
  439. ** hold the database schema. But if this fails (because the schema file
  440. ** is locked) then that step is deferred until the first call to
  441. ** sqlite_exec().
  442. */
  443. sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
  444. sqlite *db;
  445. int rc, i;
  446. /* Allocate the sqlite data structure */
  447. db = sqliteMalloc( sizeof(sqlite) );
  448. if( pzErrMsg ) *pzErrMsg = 0;
  449. if( db==0 ) goto no_mem_on_open;
  450. db->onError = OE_Default;
  451. db->priorNewRowid = 0;
  452. db->magic = SQLITE_MAGIC_BUSY;
  453. db->nDb = 2;
  454. db->aDb = db->aDbStatic;
  455. /* db->flags |= SQLITE_ShortColNames; */
  456. sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
  457. for(i=0; i<db->nDb; i++){
  458. sqliteHashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
  459. sqliteHashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
  460. sqliteHashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
  461. sqliteHashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
  462. }
  463. /* Open the backend database driver */
  464. if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
  465. db->temp_store = 2;
  466. }
  467. rc = sqliteBtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
  468. if( rc!=SQLITE_OK ){
  469. switch( rc ){
  470. default: {
  471. sqliteSetString(pzErrMsg, "unable to open database: ",
  472. zFilename, (char*)0);
  473. }
  474. }
  475. sqliteFree(db);
  476. sqliteStrRealloc(pzErrMsg);
  477. return 0;
  478. }
  479. db->aDb[0].zName = "main";
  480. db->aDb[1].zName = "temp";
  481. /* Attempt to read the schema */
  482. sqliteRegisterBuiltinFunctions(db);
  483. rc = sqliteInit(db, pzErrMsg);
  484. db->magic = SQLITE_MAGIC_OPEN;
  485. if( sqlite_malloc_failed ){
  486. sqlite_close(db);
  487. goto no_mem_on_open;
  488. }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  489. sqlite_close(db);
  490. sqliteStrRealloc(pzErrMsg);
  491. return 0;
  492. }else if( pzErrMsg ){
  493. sqliteFree(*pzErrMsg);
  494. *pzErrMsg = 0;
  495. }
  496. /* Return a pointer to the newly opened database structure */
  497. return db;
  498. no_mem_on_open:
  499. sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  500. sqliteStrRealloc(pzErrMsg);
  501. return 0;
  502. }
  503. /*
  504. ** Return the ROWID of the most recent insert
  505. */
  506. int sqlite_last_insert_rowid(sqlite *db){
  507. return db->lastRowid;
  508. }
  509. /*
  510. ** Return the number of changes in the most recent call to sqlite_exec().
  511. */
  512. int sqlite_changes(sqlite *db){
  513. return db->nChange;
  514. }
  515. /*
  516. ** Return the number of changes produced by the last INSERT, UPDATE, or
  517. ** DELETE statement to complete execution. The count does not include
  518. ** changes due to SQL statements executed in trigger programs that were
  519. ** triggered by that statement
  520. */
  521. int sqlite_last_statement_changes(sqlite *db){
  522. return db->lsChange;
  523. }
  524. /*
  525. ** Close an existing SQLite database
  526. */
  527. void sqlite_close(sqlite *db){
  528. HashElem *i;
  529. int j;
  530. db->want_to_close = 1;
  531. if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
  532. /* printf("DID NOT CLOSE\n"); fflush(stdout); */
  533. return;
  534. }
  535. db->magic = SQLITE_MAGIC_CLOSED;
  536. for(j=0; j<db->nDb; j++){
  537. struct Db *pDb = &db->aDb[j];
  538. if( pDb->pBt ){
  539. sqliteBtreeClose(pDb->pBt);
  540. pDb->pBt = 0;
  541. }
  542. }
  543. sqliteResetInternalSchema(db, 0);
  544. assert( db->nDb<=2 );
  545. assert( db->aDb==db->aDbStatic );
  546. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  547. FuncDef *pFunc, *pNext;
  548. for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
  549. pNext = pFunc->pNext;
  550. sqliteFree(pFunc);
  551. }
  552. }
  553. sqliteHashClear(&db->aFunc);
  554. sqliteFree(db);
  555. }
  556. /*
  557. ** Rollback all database files.
  558. */
  559. void sqliteRollbackAll(sqlite *db){
  560. int i;
  561. for(i=0; i<db->nDb; i++){
  562. if( db->aDb[i].pBt ){
  563. sqliteBtreeRollback(db->aDb[i].pBt);
  564. db->aDb[i].inTrans = 0;
  565. }
  566. }
  567. sqliteResetInternalSchema(db, 0);
  568. /* sqliteRollbackInternalChanges(db); */
  569. }
  570. /*
  571. ** Execute SQL code. Return one of the SQLITE_ success/failure
  572. ** codes. Also write an error message into memory obtained from
  573. ** malloc() and make *pzErrMsg point to that message.
  574. **
  575. ** If the SQL is a query, then for each row in the query result
  576. ** the xCallback() function is called. pArg becomes the first
  577. ** argument to xCallback(). If xCallback=NULL then no callback
  578. ** is invoked, even for queries.
  579. */
  580. int sqlite_exec(
  581. sqlite *db, /* The database on which the SQL executes */
  582. const char *zSql, /* The SQL to be executed */
  583. sqlite_callback xCallback, /* Invoke this callback routine */
  584. void *pArg, /* First argument to xCallback() */
  585. char **pzErrMsg /* Write error messages here */
  586. ){
  587. int rc = SQLITE_OK;
  588. const char *zLeftover;
  589. sqlite_vm *pVm;
  590. int nRetry = 0;
  591. int nChange = 0;
  592. int nCallback;
  593. if( zSql==0 ) return SQLITE_OK;
  594. while( rc==SQLITE_OK && zSql[0] ){
  595. pVm = 0;
  596. rc = sqlite_compile(db, zSql, &zLeftover, &pVm, pzErrMsg);
  597. if( rc!=SQLITE_OK ){
  598. assert( pVm==0 || sqlite_malloc_failed );
  599. return rc;
  600. }
  601. if( pVm==0 ){
  602. /* This happens if the zSql input contained only whitespace */
  603. break;
  604. }
  605. db->nChange += nChange;
  606. nCallback = 0;
  607. while(1){
  608. int nArg;
  609. char **azArg, **azCol;
  610. rc = sqlite_step(pVm, &nArg, (const char***)&azArg,(const char***)&azCol);
  611. if( rc==SQLITE_ROW ){
  612. if( xCallback!=0 && xCallback(pArg, nArg, azArg, azCol) ){
  613. sqlite_finalize(pVm, 0);
  614. return SQLITE_ABORT;
  615. }
  616. nCallback++;
  617. }else{
  618. if( rc==SQLITE_DONE && nCallback==0
  619. && (db->flags & SQLITE_NullCallback)!=0 && xCallback!=0 ){
  620. xCallback(pArg, nArg, azArg, azCol);
  621. }
  622. rc = sqlite_finalize(pVm, pzErrMsg);
  623. if( rc==SQLITE_SCHEMA && nRetry<2 ){
  624. nRetry++;
  625. rc = SQLITE_OK;
  626. break;
  627. }
  628. if( db->pVdbe==0 ){
  629. nChange = db->nChange;
  630. }
  631. nRetry = 0;
  632. zSql = zLeftover;
  633. while( isspace(zSql[0]) ) zSql++;
  634. break;
  635. }
  636. }
  637. }
  638. return rc;
  639. }
  640. /*
  641. ** Compile a single statement of SQL into a virtual machine. Return one
  642. ** of the SQLITE_ success/failure codes. Also write an error message into
  643. ** memory obtained from malloc() and make *pzErrMsg point to that message.
  644. */
  645. int sqlite_compile(
  646. sqlite *db, /* The database on which the SQL executes */
  647. const char *zSql, /* The SQL to be executed */
  648. const char **pzTail, /* OUT: Next statement after the first */
  649. sqlite_vm **ppVm, /* OUT: The virtual machine */
  650. char **pzErrMsg /* OUT: Write error messages here */
  651. ){
  652. Parse sParse;
  653. if( pzErrMsg ) *pzErrMsg = 0;
  654. if( sqliteSafetyOn(db) ) goto exec_misuse;
  655. if( !db->init.busy ){
  656. if( (db->flags & SQLITE_Initialized)==0 ){
  657. int rc, cnt = 1;
  658. while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
  659. && db->xBusyCallback
  660. && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
  661. if( rc!=SQLITE_OK ){
  662. sqliteStrRealloc(pzErrMsg);
  663. sqliteSafetyOff(db);
  664. return rc;
  665. }
  666. if( pzErrMsg ){
  667. sqliteFree(*pzErrMsg);
  668. *pzErrMsg = 0;
  669. }
  670. }
  671. if( db->file_format<3 ){
  672. sqliteSafetyOff(db);
  673. sqliteSetString(pzErrMsg, "obsolete database file format", (char*)0);
  674. return SQLITE_ERROR;
  675. }
  676. }
  677. assert( (db->flags & SQLITE_Initialized)!=0 || db->init.busy );
  678. if( db->pVdbe==0 ){ db->nChange = 0; }
  679. memset(&sParse, 0, sizeof(sParse));
  680. sParse.db = db;
  681. sqliteRunParser(&sParse, zSql, pzErrMsg);
  682. if( db->xTrace && !db->init.busy ){
  683. /* Trace only the statment that was compiled.
  684. ** Make a copy of that part of the SQL string since zSQL is const
  685. ** and we must pass a zero terminated string to the trace function
  686. ** The copy is unnecessary if the tail pointer is pointing at the
  687. ** beginnig or end of the SQL string.
  688. */
  689. if( sParse.zTail && sParse.zTail!=zSql && *sParse.zTail ){
  690. char *tmpSql = sqliteStrNDup(zSql, sParse.zTail - zSql);
  691. if( tmpSql ){
  692. db->xTrace(db->pTraceArg, tmpSql);
  693. free(tmpSql);
  694. }else{
  695. /* If a memory error occurred during the copy,
  696. ** trace entire SQL string and fall through to the
  697. ** sqlite_malloc_failed test to report the error.
  698. */
  699. db->xTrace(db->pTraceArg, zSql);
  700. }
  701. }else{
  702. db->xTrace(db->pTraceArg, zSql);
  703. }
  704. }
  705. if( sqlite_malloc_failed ){
  706. sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  707. sParse.rc = SQLITE_NOMEM;
  708. sqliteRollbackAll(db);
  709. sqliteResetInternalSchema(db, 0);
  710. db->flags &= ~SQLITE_InTrans;
  711. }
  712. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  713. if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
  714. sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), (char*)0);
  715. }
  716. sqliteStrRealloc(pzErrMsg);
  717. if( sParse.rc==SQLITE_SCHEMA ){
  718. sqliteResetInternalSchema(db, 0);
  719. }
  720. assert( ppVm );
  721. *ppVm = (sqlite_vm*)sParse.pVdbe;
  722. if( pzTail ) *pzTail = sParse.zTail;
  723. if( sqliteSafetyOff(db) ) goto exec_misuse;
  724. return sParse.rc;
  725. exec_misuse:
  726. if( pzErrMsg ){
  727. *pzErrMsg = 0;
  728. sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
  729. sqliteStrRealloc(pzErrMsg);
  730. }
  731. return SQLITE_MISUSE;
  732. }
  733. /*
  734. ** The following routine destroys a virtual machine that is created by
  735. ** the sqlite_compile() routine.
  736. **
  737. ** The integer returned is an SQLITE_ success/failure code that describes
  738. ** the result of executing the virtual machine. An error message is
  739. ** written into memory obtained from malloc and *pzErrMsg is made to
  740. ** point to that error if pzErrMsg is not NULL. The calling routine
  741. ** should use sqlite_freemem() to delete the message when it has finished
  742. ** with it.
  743. */
  744. int sqlite_finalize(
  745. sqlite_vm *pVm, /* The virtual machine to be destroyed */
  746. char **pzErrMsg /* OUT: Write error messages here */
  747. ){
  748. int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
  749. sqliteStrRealloc(pzErrMsg);
  750. return rc;
  751. }
  752. /*
  753. ** Terminate the current execution of a virtual machine then
  754. ** reset the virtual machine back to its starting state so that it
  755. ** can be reused. Any error message resulting from the prior execution
  756. ** is written into *pzErrMsg. A success code from the prior execution
  757. ** is returned.
  758. */
  759. int sqlite_reset(
  760. sqlite_vm *pVm, /* The virtual machine to be destroyed */
  761. char **pzErrMsg /* OUT: Write error messages here */
  762. ){
  763. int rc = sqliteVdbeReset((Vdbe*)pVm, pzErrMsg);
  764. sqliteVdbeMakeReady((Vdbe*)pVm, -1, 0);
  765. sqliteStrRealloc(pzErrMsg);
  766. return rc;
  767. }
  768. /*
  769. ** Return a static string that describes the kind of error specified in the
  770. ** argument.
  771. */
  772. const char *sqlite_error_string(int rc){
  773. const char *z;
  774. switch( rc ){
  775. case SQLITE_OK: z = "not an error"; break;
  776. case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
  777. case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break;
  778. case SQLITE_PERM: z = "access permission denied"; break;
  779. case SQLITE_ABORT: z = "callback requested query abort"; break;
  780. case SQLITE_BUSY: z = "database is locked"; break;
  781. case SQLITE_LOCKED: z = "database table is locked"; break;
  782. case SQLITE_NOMEM: z = "out of memory"; break;
  783. case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
  784. case SQLITE_INTERRUPT: z = "interrupted"; break;
  785. case SQLITE_IOERR: z = "disk I/O error"; break;
  786. case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
  787. case SQLITE_NOTFOUND: z = "table or record not found"; break;
  788. case SQLITE_FULL: z = "database is full"; break;
  789. case SQLITE_CANTOPEN: z = "unable to open database file"; break;
  790. case SQLITE_PROTOCOL: z = "database locking protocol failure"; break;
  791. case SQLITE_EMPTY: z = "table contains no data"; break;
  792. case SQLITE_SCHEMA: z = "database schema has changed"; break;
  793. case SQLITE_TOOBIG: z = "too much data for one table row"; break;
  794. case SQLITE_CONSTRAINT: z = "constraint failed"; break;
  795. case SQLITE_MISMATCH: z = "datatype mismatch"; break;
  796. case SQLITE_MISUSE: z = "library routine called out of sequence";break;
  797. case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
  798. case SQLITE_AUTH: z = "authorization denied"; break;
  799. case SQLITE_FORMAT: z = "auxiliary database format error"; break;
  800. case SQLITE_RANGE: z = "bind index out of range"; break;
  801. case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
  802. default: z = "unknown error"; break;
  803. }
  804. return z;
  805. }
  806. /*
  807. ** This routine implements a busy callback that sleeps and tries
  808. ** again until a timeout value is reached. The timeout value is
  809. ** an integer number of milliseconds passed in as the first
  810. ** argument.
  811. */
  812. static int sqliteDefaultBusyCallback(
  813. void *Timeout, /* Maximum amount of time to wait */
  814. const char *NotUsed, /* The name of the table that is busy */
  815. int count /* Number of times table has been busy */
  816. ){
  817. #if SQLITE_MIN_SLEEP_MS==1
  818. static const char delays[] =
  819. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 50, 100};
  820. static const short int totals[] =
  821. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228, 287};
  822. # define NDELAY (sizeof(delays)/sizeof(delays[0]))
  823. int timeout = (int)(long)Timeout;
  824. int delay, prior;
  825. if( count <= NDELAY ){
  826. delay = delays[count-1];
  827. prior = totals[count-1];
  828. }else{
  829. delay = delays[NDELAY-1];
  830. prior = totals[NDELAY-1] + delay*(count-NDELAY-1);
  831. }
  832. if( prior + delay > timeout ){
  833. delay = timeout - prior;
  834. if( delay<=0 ) return 0;
  835. }
  836. sqliteOsSleep(delay);
  837. return 1;
  838. #else
  839. int timeout = (int)(long)Timeout;
  840. if( (count+1)*1000 > timeout ){
  841. return 0;
  842. }
  843. sqliteOsSleep(1000);
  844. return 1;
  845. #endif
  846. }
  847. /*
  848. ** This routine sets the busy callback for an Sqlite database to the
  849. ** given callback function with the given argument.
  850. */
  851. void sqlite_busy_handler(
  852. sqlite *db,
  853. int (*xBusy)(void*,const char*,int),
  854. void *pArg
  855. ){
  856. db->xBusyCallback = xBusy;
  857. db->pBusyArg = pArg;
  858. }
  859. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  860. /*
  861. ** This routine sets the progress callback for an Sqlite database to the
  862. ** given callback function with the given argument. The progress callback will
  863. ** be invoked every nOps opcodes.
  864. */
  865. void sqlite_progress_handler(
  866. sqlite *db,
  867. int nOps,
  868. int (*xProgress)(void*),
  869. void *pArg
  870. ){
  871. if( nOps>0 ){
  872. db->xProgress = xProgress;
  873. db->nProgressOps = nOps;
  874. db->pProgressArg = pArg;
  875. }else{
  876. db->xProgress = 0;
  877. db->nProgressOps = 0;
  878. db->pProgressArg = 0;
  879. }
  880. }
  881. #endif
  882. /*
  883. ** This routine installs a default busy handler that waits for the
  884. ** specified number of milliseconds before returning 0.
  885. */
  886. void sqlite_busy_timeout(sqlite *db, int ms){
  887. if( ms>0 ){
  888. sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)(long)ms);
  889. }else{
  890. sqlite_busy_handler(db, 0, 0);
  891. }
  892. }
  893. /*
  894. ** Cause any pending operation to stop at its earliest opportunity.
  895. */
  896. void sqlite_interrupt(sqlite *db){
  897. db->flags |= SQLITE_Interrupt;
  898. }
  899. /*
  900. ** Windows systems should call this routine to free memory that
  901. ** is returned in the in the errmsg parameter of sqlite_open() when
  902. ** SQLite is a DLL. For some reason, it does not work to call free()
  903. ** directly.
  904. **
  905. ** Note that we need to call free() not sqliteFree() here, since every
  906. ** string that is exported from SQLite should have already passed through
  907. ** sqliteStrRealloc().
  908. */
  909. void sqlite_freemem(void *p){ free(p); }
  910. /*
  911. ** Windows systems need functions to call to return the sqlite_version
  912. ** and sqlite_encoding strings since they are unable to access constants
  913. ** within DLLs.
  914. */
  915. const char *sqlite_libversion(void){ return sqlite_version; }
  916. const char *sqlite_libencoding(void){ return sqlite_encoding; }
  917. /*
  918. ** Create new user-defined functions. The sqlite_create_function()
  919. ** routine creates a regular function and sqlite_create_aggregate()
  920. ** creates an aggregate function.
  921. **
  922. ** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
  923. ** disables the function. Calling sqlite_create_function() with the
  924. ** same name and number of arguments as a prior call to
  925. ** sqlite_create_aggregate() disables the prior call to
  926. ** sqlite_create_aggregate(), and vice versa.
  927. **
  928. ** If nArg is -1 it means that this function will accept any number
  929. ** of arguments, including 0. The maximum allowed value of nArg is 127.
  930. */
  931. int sqlite_create_function(
  932. sqlite *db, /* Add the function to this database connection */
  933. const char *zName, /* Name of the function to add */
  934. int nArg, /* Number of arguments */
  935. void (*xFunc)(sqlite_func*,int,const char**), /* The implementation */
  936. void *pUserData /* User data */
  937. ){
  938. FuncDef *p;
  939. int nName;
  940. if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
  941. if( nArg<-1 || nArg>127 ) return 1;
  942. nName = strlen(zName);
  943. if( nName>255 ) return 1;
  944. p = sqliteFindFunction(db, zName, nName, nArg, 1);
  945. if( p==0 ) return 1;
  946. p->xFunc = xFunc;
  947. p->xStep = 0;
  948. p->xFinalize = 0;
  949. p->pUserData = pUserData;
  950. return 0;
  951. }
  952. int sqlite_create_aggregate(
  953. sqlite *db, /* Add the function to this database connection */
  954. const char *zName, /* Name of the function to add */
  955. int nArg, /* Number of arguments */
  956. void (*xStep)(sqlite_func*,int,const char**), /* The step function */
  957. void (*xFinalize)(sqlite_func*), /* The finalizer */
  958. void *pUserData /* User data */
  959. ){
  960. FuncDef *p;
  961. int nName;
  962. if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
  963. if( nArg<-1 || nArg>127 ) return 1;
  964. nName = strlen(zName);
  965. if( nName>255 ) return 1;
  966. p = sqliteFindFunction(db, zName, nName, nArg, 1);
  967. if( p==0 ) return 1;
  968. p->xFunc = 0;
  969. p->xStep = xStep;
  970. p->xFinalize = xFinalize;
  971. p->pUserData = pUserData;
  972. return 0;
  973. }
  974. /*
  975. ** Change the datatype for all functions with a given name. See the
  976. ** header comment for the prototype of this function in sqlite.h for
  977. ** additional information.
  978. */
  979. int sqlite_function_type(sqlite *db, const char *zName, int dataType){
  980. FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
  981. while( p ){
  982. p->dataType = dataType;
  983. p = p->pNext;
  984. }
  985. return SQLITE_OK;
  986. }
  987. /*
  988. ** Register a trace function. The pArg from the previously registered trace
  989. ** is returned.
  990. **
  991. ** A NULL trace function means that no tracing is executes. A non-NULL
  992. ** trace is a pointer to a function that is invoked at the start of each
  993. ** sqlite_exec().
  994. */
  995. void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
  996. void *pOld = db->pTraceArg;
  997. db->xTrace = xTrace;
  998. db->pTraceArg = pArg;
  999. return pOld;
  1000. }
  1001. /*** EXPERIMENTAL ***
  1002. **
  1003. ** Register a function to be invoked when a transaction comments.
  1004. ** If either function returns non-zero, then the commit becomes a
  1005. ** rollback.
  1006. */
  1007. void *sqlite_commit_hook(
  1008. sqlite *db, /* Attach the hook to this database */
  1009. int (*xCallback)(void*), /* Function to invoke on each commit */
  1010. void *pArg /* Argument to the function */
  1011. ){
  1012. void *pOld = db->pCommitArg;
  1013. db->xCommitCallback = xCallback;
  1014. db->pCommitArg = pArg;
  1015. return pOld;
  1016. }
  1017. /*
  1018. ** This routine is called to create a connection to a database BTree
  1019. ** driver. If zFilename is the name of a file, then that file is
  1020. ** opened and used. If zFilename is the magic name ":memory:" then
  1021. ** the database is stored in memory (and is thus forgotten as soon as
  1022. ** the connection is closed.) If zFilename is NULL then the database
  1023. ** is for temporary use only and is deleted as soon as the connection
  1024. ** is closed.
  1025. **
  1026. ** A temporary database can be either a disk file (that is automatically
  1027. ** deleted when the file is closed) or a set of red-black trees held in memory,
  1028. ** depending on the values of the TEMP_STORE compile-time macro and the
  1029. ** db->temp_store variable, according to the following chart:
  1030. **
  1031. ** TEMP_STORE db->temp_store Location of temporary database
  1032. ** ---------- -------------- ------------------------------
  1033. ** 0 any file
  1034. ** 1 1 file
  1035. ** 1 2 memory
  1036. ** 1 0 file
  1037. ** 2 1 file
  1038. ** 2 2 memory
  1039. ** 2 0 memory
  1040. ** 3 any memory
  1041. */
  1042. int sqliteBtreeFactory(
  1043. const sqlite *db, /* Main database when opening aux otherwise 0 */
  1044. const char *zFilename, /* Name of the file containing the BTree database */
  1045. int omitJournal, /* if TRUE then do not journal this file */
  1046. int nCache, /* How many pages in the page cache */
  1047. Btree **ppBtree){ /* Pointer to new Btree object written here */
  1048. assert( ppBtree != 0);
  1049. #ifndef SQLITE_OMIT_INMEMORYDB
  1050. if( zFilename==0 ){
  1051. if (TEMP_STORE == 0) {
  1052. /* Always use file based temporary DB */
  1053. return sqliteBtreeOpen(0, omitJournal, nCache, ppBtree);
  1054. } else if (TEMP_STORE == 1 || TEMP_STORE == 2) {
  1055. /* Switch depending on compile-time and/or runtime settings. */
  1056. int location = db->temp_store==0 ? TEMP_STORE : db->temp_store;
  1057. if (location == 1) {
  1058. return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
  1059. } else {
  1060. return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  1061. }
  1062. } else {
  1063. /* Always use in-core DB */
  1064. return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  1065. }
  1066. }else if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
  1067. return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  1068. }else
  1069. #endif
  1070. {
  1071. return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
  1072. }
  1073. }