blob: d350e25be647c6771e49ae3751d3273b01b41b53 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
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**
drh92ed08a2002-07-30 18:43:40 +000017** $Id: main.c,v 1.93 2002/07/30 18:43:41 drh Exp $
drh75897232000-05-29 14:26:00 +000018*/
19#include "sqliteInt.h"
drh8cfbf082001-09-19 13:22:39 +000020#include "os.h"
drhce9079c2002-05-15 14:17:44 +000021#include <ctype.h>
drh75897232000-05-29 14:26:00 +000022
23/*
drhc2311722002-07-19 17:46:38 +000024** A pointer to this structure is used to communicate information
25** from sqliteInit into the sqliteInitCallback.
26*/
27typedef struct {
28 sqlite *db; /* The database being initialized */
29 char **pzErrMsg; /* Error message stored here */
30} InitData;
31
32
33/*
drh75897232000-05-29 14:26:00 +000034** This is the callback routine for the code that initializes the
drh382c0242001-10-06 16:33:02 +000035** database. See sqliteInit() below for additional information.
36**
37** Each callback contains the following information:
drh28037572000-08-02 13:47:41 +000038**
drh4a324312001-12-21 14:30:42 +000039** argv[0] = "file-format" or "schema-cookie" or "table" or "index"
drhe3c41372001-09-17 20:25:58 +000040** argv[1] = table or index name or meta statement type.
41** argv[2] = root page number for table or index. NULL for meta.
drhadbca9c2001-09-27 15:11:53 +000042** argv[3] = SQL create statement for the table or index
drhe0bc4042002-06-25 01:09:11 +000043** argv[4] = "1" for temporary files, "0" for main database
drhd78eeee2001-09-13 16:18:53 +000044**
drh75897232000-05-29 14:26:00 +000045*/
drhc2311722002-07-19 17:46:38 +000046static
47int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
48 InitData *pData = (InitData*)pInit;
drh75897232000-05-29 14:26:00 +000049 Parse sParse;
drhd78eeee2001-09-13 16:18:53 +000050 int nErr = 0;
drh75897232000-05-29 14:26:00 +000051
drh382c0242001-10-06 16:33:02 +000052 /* TODO: Do some validity checks on all fields. In particular,
53 ** make sure fields do not contain NULLs. Otherwise we might core
54 ** when attempting to initialize from a corrupt database file. */
drhe3c41372001-09-17 20:25:58 +000055
drhe0bc4042002-06-25 01:09:11 +000056 assert( argc==5 );
drhd78eeee2001-09-13 16:18:53 +000057 switch( argv[0][0] ){
drh17f71932002-02-21 12:01:27 +000058 case 'v':
drhd78eeee2001-09-13 16:18:53 +000059 case 'i':
drh17f71932002-02-21 12:01:27 +000060 case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
drhadbca9c2001-09-27 15:11:53 +000061 if( argv[3] && argv[3][0] ){
drh17f71932002-02-21 12:01:27 +000062 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
drh382c0242001-10-06 16:33:02 +000063 ** But because sParse.initFlag is set to 1, no VDBE code is generated
64 ** or executed. All the parser does is build the internal data
drh17f71932002-02-21 12:01:27 +000065 ** structures that describe the table, index, or view.
drh382c0242001-10-06 16:33:02 +000066 */
drhadbca9c2001-09-27 15:11:53 +000067 memset(&sParse, 0, sizeof(sParse));
drhc2311722002-07-19 17:46:38 +000068 sParse.db = pData->db;
drhadbca9c2001-09-27 15:11:53 +000069 sParse.initFlag = 1;
drhe0bc4042002-06-25 01:09:11 +000070 sParse.isTemp = argv[4][0] - '0';
drhadbca9c2001-09-27 15:11:53 +000071 sParse.newTnum = atoi(argv[2]);
drhc2311722002-07-19 17:46:38 +000072 sqliteRunParser(&sParse, argv[3], pData->pzErrMsg);
drhadbca9c2001-09-27 15:11:53 +000073 }else{
drh382c0242001-10-06 16:33:02 +000074 /* If the SQL column is blank it means this is an index that
75 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
drhaacc5432002-01-06 17:07:40 +000076 ** constraint for a CREATE TABLE. The index should have already
drh382c0242001-10-06 16:33:02 +000077 ** been created when we processed the CREATE TABLE. All we have
drhaacc5432002-01-06 17:07:40 +000078 ** to do here is record the root page number for that index.
drh382c0242001-10-06 16:33:02 +000079 */
drhc2311722002-07-19 17:46:38 +000080 Index *pIndex = sqliteFindIndex(pData->db, argv[1]);
drhadbca9c2001-09-27 15:11:53 +000081 if( pIndex==0 || pIndex->tnum!=0 ){
drhda9e0342002-01-10 14:31:48 +000082 /* This can occur if there exists an index on a TEMP table which
83 ** has the same name as another index on a permanent index. Since
84 ** the permanent table is hidden by the TEMP table, we can also
85 ** safely ignore the index on the permanent table.
86 */
87 /* Do Nothing */;
drhadbca9c2001-09-27 15:11:53 +000088 }else{
89 pIndex->tnum = atoi(argv[2]);
90 }
91 }
drhd78eeee2001-09-13 16:18:53 +000092 break;
93 }
94 default: {
95 /* This can not happen! */
96 nErr = 1;
97 assert( nErr==0 );
98 }
drh28037572000-08-02 13:47:41 +000099 }
drh75897232000-05-29 14:26:00 +0000100 return nErr;
101}
102
103/*
drh491791a2002-07-18 00:34:09 +0000104** This is a callback procedure used to reconstruct a table. The
105** name of the table to be reconstructed is passed in as argv[0].
106**
107** This routine is used to automatically upgrade a database from
108** format version 1 or 2 to version 3. The correct operation of
109** this routine relys on the fact that no indices are used when
110** copying a table out to a temporary file.
111*/
drhc2311722002-07-19 17:46:38 +0000112static
113int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
114 InitData *pData = (InitData*)pInit;
drh491791a2002-07-18 00:34:09 +0000115 int rc;
drh8e5ba842002-07-18 01:27:17 +0000116 Table *pTab;
117 Trigger *pTrig;
drh26b3e1b2002-07-19 18:52:40 +0000118 char *zErr = 0;
drh491791a2002-07-18 00:34:09 +0000119
drhc2311722002-07-19 17:46:38 +0000120 pTab = sqliteFindTable(pData->db, argv[0]);
drh8e5ba842002-07-18 01:27:17 +0000121 if( pTab ){
122 pTrig = pTab->pTrigger;
123 pTab->pTrigger = 0; /* Disable all triggers before rebuilding the table */
124 }
drhc2311722002-07-19 17:46:38 +0000125 rc = sqlite_exec_printf(pData->db,
drh491791a2002-07-18 00:34:09 +0000126 "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
127 "DELETE FROM '%q'; "
128 "INSERT INTO '%q' SELECT * FROM sqlite_x; "
129 "DROP TABLE sqlite_x;",
drhc2311722002-07-19 17:46:38 +0000130 0, 0, &zErr, argv[0], argv[0], argv[0]);
131 if( zErr ){
132 sqliteSetString(pData->pzErrMsg, zErr, 0);
133 sqlite_freemem(zErr);
134 }
drh8e5ba842002-07-18 01:27:17 +0000135 if( pTab ) pTab->pTrigger = pTrig; /* Re-enable triggers */
drh491791a2002-07-18 00:34:09 +0000136 return rc!=SQLITE_OK;
137}
138
139
140
141/*
drh58b95762000-06-02 01:17:37 +0000142** Attempt to read the database schema and initialize internal
143** data structures. Return one of the SQLITE_ error codes to
144** indicate success or failure.
drhbed86902000-06-02 13:27:59 +0000145**
146** After the database is initialized, the SQLITE_Initialized
147** bit is set in the flags field of the sqlite structure. An
148** attempt is made to initialize the database as soon as it
149** is opened. If that fails (perhaps because another process
150** has the sqlite_master table locked) than another attempt
151** is made the first time the database is accessed.
drh75897232000-05-29 14:26:00 +0000152*/
drhe0bc4042002-06-25 01:09:11 +0000153int sqliteInit(sqlite *db, char **pzErrMsg){
drh58b95762000-06-02 01:17:37 +0000154 int rc;
drhe0bc4042002-06-25 01:09:11 +0000155 BtCursor *curMain;
156 int size;
157 Table *pTab;
158 char *azArg[6];
159 int meta[SQLITE_N_BTREE_META];
160 Parse sParse;
drhc2311722002-07-19 17:46:38 +0000161 InitData initData;
drh58b95762000-06-02 01:17:37 +0000162
163 /*
164 ** The master database table has a structure like this
165 */
drh75897232000-05-29 14:26:00 +0000166 static char master_schema[] =
drhe0bc4042002-06-25 01:09:11 +0000167 "CREATE TABLE sqlite_master(\n"
168 " type text,\n"
169 " name text,\n"
170 " tbl_name text,\n"
171 " rootpage integer,\n"
172 " sql text\n"
173 ")"
174 ;
175 static char temp_master_schema[] =
176 "CREATE TEMP TABLE sqlite_temp_master(\n"
drh75897232000-05-29 14:26:00 +0000177 " type text,\n"
178 " name text,\n"
179 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +0000180 " rootpage integer,\n"
drh75897232000-05-29 14:26:00 +0000181 " sql text\n"
182 ")"
183 ;
184
drhe0bc4042002-06-25 01:09:11 +0000185 /* The following SQL will read the schema from the master tables.
186 ** The first version works with SQLite file formats 2 or greater.
187 ** The second version is for format 1 files.
drh75897232000-05-29 14:26:00 +0000188 **
drhe0bc4042002-06-25 01:09:11 +0000189 ** Beginning with file format 2, the rowid for new table entries
190 ** (including entries in sqlite_master) is an increasing integer.
191 ** So for file format 2 and later, we can play back sqlite_master
192 ** and all the CREATE statements will appear in the right order.
193 ** But with file format 1, table entries were random and so we
194 ** have to make sure the CREATE TABLEs occur before their corresponding
195 ** CREATE INDEXs. (We don't have to deal with CREATE VIEW or
196 ** CREATE TRIGGER in file format 1 because those constructs did
197 ** not exist then.)
drh75897232000-05-29 14:26:00 +0000198 */
drhe0bc4042002-06-25 01:09:11 +0000199 static char init_script[] =
200 "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
201 "UNION ALL "
202 "SELECT type, name, rootpage, sql, 0 FROM sqlite_master";
203 static char older_init_script[] =
204 "SELECT type, name, rootpage, sql, 1 FROM sqlite_temp_master "
205 "UNION ALL "
206 "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
207 "WHERE type='table' "
208 "UNION ALL "
209 "SELECT type, name, rootpage, sql, 0 FROM sqlite_master "
210 "WHERE type='index'";
drh17f71932002-02-21 12:01:27 +0000211
drh603240c2002-03-05 01:11:12 +0000212
drhe0bc4042002-06-25 01:09:11 +0000213 /* Construct the schema tables: sqlite_master and sqlite_temp_master
drh58b95762000-06-02 01:17:37 +0000214 */
drhe0bc4042002-06-25 01:09:11 +0000215 azArg[0] = "table";
216 azArg[1] = MASTER_NAME;
217 azArg[2] = "2";
218 azArg[3] = master_schema;
219 azArg[4] = "0";
220 azArg[5] = 0;
drhc2311722002-07-19 17:46:38 +0000221 initData.db = db;
222 initData.pzErrMsg = pzErrMsg;
223 sqliteInitCallback(&initData, 5, azArg, 0);
drhe0bc4042002-06-25 01:09:11 +0000224 pTab = sqliteFindTable(db, MASTER_NAME);
225 if( pTab ){
226 pTab->readOnly = 1;
drhd8bc7082000-06-07 23:51:50 +0000227 }
drhe0bc4042002-06-25 01:09:11 +0000228 azArg[1] = TEMP_MASTER_NAME;
229 azArg[3] = temp_master_schema;
230 azArg[4] = "1";
drhc2311722002-07-19 17:46:38 +0000231 sqliteInitCallback(&initData, 5, azArg, 0);
drhe0bc4042002-06-25 01:09:11 +0000232 pTab = sqliteFindTable(db, TEMP_MASTER_NAME);
233 if( pTab ){
234 pTab->readOnly = 1;
235 }
236
237 /* Create a cursor to hold the database open
238 */
239 if( db->pBe==0 ) return SQLITE_OK;
240 rc = sqliteBtreeCursor(db->pBe, 2, 0, &curMain);
drh92ed08a2002-07-30 18:43:40 +0000241 if( rc ){
242 sqliteResetInternalSchema(db);
243 return rc;
244 }
drhe0bc4042002-06-25 01:09:11 +0000245
246 /* Get the database meta information
247 */
248 rc = sqliteBtreeGetMeta(db->pBe, meta);
249 if( rc ){
drh92ed08a2002-07-30 18:43:40 +0000250 sqliteResetInternalSchema(db);
drhe0bc4042002-06-25 01:09:11 +0000251 sqliteBtreeCloseCursor(curMain);
252 return rc;
253 }
254 db->schema_cookie = meta[1];
255 db->next_cookie = db->schema_cookie;
256 db->file_format = meta[2];
257 size = meta[3];
258 if( size==0 ){ size = MAX_PAGES; }
259 db->cache_size = size;
260 sqliteBtreeSetCacheSize(db->pBe, size);
261
262 /*
263 ** file_format==1 Version 2.1.0.
264 ** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
drh491791a2002-07-18 00:34:09 +0000265 ** file_format==3 Version 2.6.0. Fix empty-string index bug.
266 ** file_format==4 Version 2.7.0. Add support for separate numeric and
drhe0bc4042002-06-25 01:09:11 +0000267 ** text datatypes.
268 */
269 if( db->file_format==0 ){
drh491791a2002-07-18 00:34:09 +0000270 /* This happens if the database was initially empty */
271 db->file_format = 3;
272 }else if( db->file_format>3 ){
drhe0bc4042002-06-25 01:09:11 +0000273 sqliteBtreeCloseCursor(curMain);
drhd78eeee2001-09-13 16:18:53 +0000274 sqliteSetString(pzErrMsg, "unsupported file format", 0);
drh8e5ba842002-07-18 01:27:17 +0000275 return SQLITE_ERROR;
drh28037572000-08-02 13:47:41 +0000276 }
drhaacc5432002-01-06 17:07:40 +0000277
drhe0bc4042002-06-25 01:09:11 +0000278 /* Read the schema information out of the schema tables
drhaacc5432002-01-06 17:07:40 +0000279 */
drhe0bc4042002-06-25 01:09:11 +0000280 memset(&sParse, 0, sizeof(sParse));
281 sParse.db = db;
282 sParse.pBe = db->pBe;
283 sParse.xCallback = sqliteInitCallback;
drhc2311722002-07-19 17:46:38 +0000284 sParse.pArg = (void*)&initData;
drhe0bc4042002-06-25 01:09:11 +0000285 sParse.initFlag = 1;
286 sqliteRunParser(&sParse,
287 db->file_format>=2 ? init_script : older_init_script,
288 pzErrMsg);
289 if( sqlite_malloc_failed ){
290 sqliteSetString(pzErrMsg, "out of memory", 0);
291 sParse.rc = SQLITE_NOMEM;
292 sqliteBtreeRollback(db->pBe);
293 sqliteResetInternalSchema(db);
294 }
295 if( sParse.rc==SQLITE_OK ){
drh58b95762000-06-02 01:17:37 +0000296 db->flags |= SQLITE_Initialized;
drh5e00f6c2001-09-13 13:46:56 +0000297 sqliteCommitInternalChanges(db);
drhe0bc4042002-06-25 01:09:11 +0000298 }else{
299 db->flags &= ~SQLITE_Initialized;
300 sqliteResetInternalSchema(db);
drh58b95762000-06-02 01:17:37 +0000301 }
drhe0bc4042002-06-25 01:09:11 +0000302 sqliteBtreeCloseCursor(curMain);
303 return sParse.rc;
drh58b95762000-06-02 01:17:37 +0000304}
305
306/*
drhb217a572000-08-22 13:40:18 +0000307** The version of the library
308*/
drh096c4972002-07-19 19:03:41 +0000309const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
drh3d0b5592000-08-22 13:40:51 +0000310const char sqlite_version[] = SQLITE_VERSION;
drhb217a572000-08-22 13:40:18 +0000311
312/*
drh297ecf12001-04-05 15:57:13 +0000313** Does the library expect data to be encoded as UTF-8 or iso8859? The
314** following global constant always lets us know.
315*/
316#ifdef SQLITE_UTF8
drhfbc3eab2001-04-06 16:13:42 +0000317const char sqlite_encoding[] = "UTF-8";
drh297ecf12001-04-05 15:57:13 +0000318#else
drhfbc3eab2001-04-06 16:13:42 +0000319const char sqlite_encoding[] = "iso8859";
drh297ecf12001-04-05 15:57:13 +0000320#endif
321
322/*
drh58b95762000-06-02 01:17:37 +0000323** Open a new SQLite database. Construct an "sqlite" structure to define
324** the state of this database and return a pointer to that structure.
325**
326** An attempt is made to initialize the in-memory data structures that
327** hold the database schema. But if this fails (because the schema file
328** is locked) then that step is deferred until the first call to
329** sqlite_exec().
330*/
331sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
332 sqlite *db;
333 int rc;
334
335 /* Allocate the sqlite data structure */
drh75897232000-05-29 14:26:00 +0000336 db = sqliteMalloc( sizeof(sqlite) );
337 if( pzErrMsg ) *pzErrMsg = 0;
drhdaffd0e2001-04-11 14:28:42 +0000338 if( db==0 ) goto no_mem_on_open;
drhbeae3192001-09-22 18:12:08 +0000339 sqliteHashInit(&db->tblHash, SQLITE_HASH_STRING, 0);
340 sqliteHashInit(&db->idxHash, SQLITE_HASH_STRING, 0);
danielk1977c3f9bad2002-05-15 08:30:12 +0000341 sqliteHashInit(&db->trigHash, SQLITE_HASH_STRING, 0);
drh0bce8352002-02-28 00:41:10 +0000342 sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
drh28f4b682002-06-09 10:14:18 +0000343 sqliteRegisterBuiltinFunctions(db);
drh1c928532002-01-31 15:54:21 +0000344 db->onError = OE_Default;
drh5cf8e8c2002-02-19 22:42:05 +0000345 db->priorNewRowid = 0;
drh247be432002-05-10 05:44:55 +0000346 db->magic = SQLITE_MAGIC_BUSY;
drh75897232000-05-29 14:26:00 +0000347
348 /* Open the backend database driver */
drha1b351a2001-09-14 16:42:12 +0000349 rc = sqliteBtreeOpen(zFilename, mode, MAX_PAGES, &db->pBe);
drh5e00f6c2001-09-13 13:46:56 +0000350 if( rc!=SQLITE_OK ){
351 switch( rc ){
352 default: {
drhaacc5432002-01-06 17:07:40 +0000353 sqliteSetString(pzErrMsg, "unable to open database: ", zFilename, 0);
drh5e00f6c2001-09-13 13:46:56 +0000354 }
355 }
drh75897232000-05-29 14:26:00 +0000356 sqliteFree(db);
drh5edc3122001-09-13 21:53:09 +0000357 sqliteStrRealloc(pzErrMsg);
drhbe0072d2001-09-13 14:46:09 +0000358 return 0;
drh75897232000-05-29 14:26:00 +0000359 }
360
drh58b95762000-06-02 01:17:37 +0000361 /* Attempt to read the schema */
362 rc = sqliteInit(db, pzErrMsg);
drhc67980b2002-06-14 20:54:14 +0000363 db->magic = SQLITE_MAGIC_OPEN;
drhdaffd0e2001-04-11 14:28:42 +0000364 if( sqlite_malloc_failed ){
drh6d4abfb2001-10-22 02:58:08 +0000365 sqlite_close(db);
drhdaffd0e2001-04-11 14:28:42 +0000366 goto no_mem_on_open;
367 }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
drh58b95762000-06-02 01:17:37 +0000368 sqlite_close(db);
drh5edc3122001-09-13 21:53:09 +0000369 sqliteStrRealloc(pzErrMsg);
drh58b95762000-06-02 01:17:37 +0000370 return 0;
drhaacc5432002-01-06 17:07:40 +0000371 }else if( pzErrMsg ){
drhdaffd0e2001-04-11 14:28:42 +0000372 sqliteFree(*pzErrMsg);
drhbed86902000-06-02 13:27:59 +0000373 *pzErrMsg = 0;
drh75897232000-05-29 14:26:00 +0000374 }
drh491791a2002-07-18 00:34:09 +0000375
376 /* If the database is in formats 1 or 2, then upgrade it to
377 ** version 3. This will reconstruct all indices. If the
378 ** upgrade fails for any reason (ex: out of disk space, database
379 ** is read only, interrupt receive, etc.) then refuse to open.
380 */
drh92ed08a2002-07-30 18:43:40 +0000381 if( rc==SQLITE_OK && db->file_format<3 ){
drhc2311722002-07-19 17:46:38 +0000382 char *zErr = 0;
383 InitData initData;
drh491791a2002-07-18 00:34:09 +0000384 int meta[SQLITE_N_BTREE_META];
385
drhc2311722002-07-19 17:46:38 +0000386 initData.db = db;
387 initData.pzErrMsg = &zErr;
drh491791a2002-07-18 00:34:09 +0000388 db->file_format = 3;
389 rc = sqlite_exec(db,
390 "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
391 upgrade_3_callback,
drhc2311722002-07-19 17:46:38 +0000392 &initData,
drh491791a2002-07-18 00:34:09 +0000393 &zErr);
394 if( rc==SQLITE_OK ){
395 sqliteBtreeGetMeta(db->pBe, meta);
396 meta[2] = 3;
397 sqliteBtreeUpdateMeta(db->pBe, meta);
398 sqlite_exec(db, "COMMIT", 0, 0, 0);
399 }
400 if( rc!=SQLITE_OK ){
401 sqliteSetString(pzErrMsg,
402 "unable to upgrade database to the version 2.6 format",
403 zErr ? ": " : 0, zErr, 0);
drhc2311722002-07-19 17:46:38 +0000404 sqlite_freemem(zErr);
drh491791a2002-07-18 00:34:09 +0000405 sqliteStrRealloc(pzErrMsg);
406 sqlite_close(db);
407 return 0;
408 }
drhc2311722002-07-19 17:46:38 +0000409 sqlite_freemem(zErr);
drh491791a2002-07-18 00:34:09 +0000410 }
411
412 /* Return a pointer to the newly opened database structure */
drh75897232000-05-29 14:26:00 +0000413 return db;
drhdaffd0e2001-04-11 14:28:42 +0000414
415no_mem_on_open:
416 sqliteSetString(pzErrMsg, "out of memory", 0);
417 sqliteStrRealloc(pzErrMsg);
418 return 0;
drh75897232000-05-29 14:26:00 +0000419}
420
421/*
drhaf9ff332002-01-16 21:00:27 +0000422** Return the ROWID of the most recent insert
423*/
424int sqlite_last_insert_rowid(sqlite *db){
425 return db->lastRowid;
426}
427
428/*
drhc8d30ac2002-04-12 10:08:59 +0000429** Return the number of changes in the most recent call to sqlite_exec().
430*/
431int sqlite_changes(sqlite *db){
432 return db->nChange;
433}
434
435/*
drh50e5dad2001-09-15 00:57:28 +0000436** Close an existing SQLite database
437*/
438void sqlite_close(sqlite *db){
drh8e0a2f92002-02-23 23:45:45 +0000439 HashElem *i;
drhc22bd472002-05-10 13:14:07 +0000440 if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){ return; }
drh247be432002-05-10 05:44:55 +0000441 db->magic = SQLITE_MAGIC_CLOSED;
drh50e5dad2001-09-15 00:57:28 +0000442 sqliteBtreeClose(db->pBe);
drhe0bc4042002-06-25 01:09:11 +0000443 sqliteResetInternalSchema(db);
drhf57b3392001-10-08 13:22:32 +0000444 if( db->pBeTemp ){
445 sqliteBtreeClose(db->pBeTemp);
446 }
drh0bce8352002-02-28 00:41:10 +0000447 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
448 FuncDef *pFunc, *pNext;
449 for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
drh8e0a2f92002-02-23 23:45:45 +0000450 pNext = pFunc->pNext;
451 sqliteFree(pFunc);
452 }
453 }
drh0bce8352002-02-28 00:41:10 +0000454 sqliteHashClear(&db->aFunc);
drh75897232000-05-29 14:26:00 +0000455 sqliteFree(db);
456}
457
458/*
459** Return TRUE if the given SQL string ends in a semicolon.
drhce9079c2002-05-15 14:17:44 +0000460**
461** Special handling is require for CREATE TRIGGER statements.
462** Whenever the CREATE TRIGGER keywords are seen, the statement
463** must end with ";END;".
drh75897232000-05-29 14:26:00 +0000464*/
465int sqlite_complete(const char *zSql){
drhce9079c2002-05-15 14:17:44 +0000466 int isComplete = 1;
467 int requireEnd = 0;
468 int seenText = 0;
danielk1977c3f9bad2002-05-15 08:30:12 +0000469 int seenCreate = 0;
drh8c82b352000-12-10 18:23:50 +0000470 while( *zSql ){
471 switch( *zSql ){
472 case ';': {
473 isComplete = 1;
drhce9079c2002-05-15 14:17:44 +0000474 seenText = 1;
475 seenCreate = 0;
drh75897232000-05-29 14:26:00 +0000476 break;
drh8c82b352000-12-10 18:23:50 +0000477 }
478 case ' ':
479 case '\t':
480 case '\n':
481 case '\f': {
drh75897232000-05-29 14:26:00 +0000482 break;
drh8c82b352000-12-10 18:23:50 +0000483 }
drh969fa7c2002-02-18 18:30:32 +0000484 case '[': {
485 isComplete = 0;
drhce9079c2002-05-15 14:17:44 +0000486 seenText = 1;
487 seenCreate = 0;
drh969fa7c2002-02-18 18:30:32 +0000488 zSql++;
489 while( *zSql && *zSql!=']' ){ zSql++; }
490 if( *zSql==0 ) return 0;
491 break;
492 }
drhce9079c2002-05-15 14:17:44 +0000493 case '"':
drh8c82b352000-12-10 18:23:50 +0000494 case '\'': {
drhce9079c2002-05-15 14:17:44 +0000495 int c = *zSql;
drh8c82b352000-12-10 18:23:50 +0000496 isComplete = 0;
drhce9079c2002-05-15 14:17:44 +0000497 seenText = 1;
498 seenCreate = 0;
drh8c82b352000-12-10 18:23:50 +0000499 zSql++;
drhce9079c2002-05-15 14:17:44 +0000500 while( *zSql && *zSql!=c ){ zSql++; }
drh8c82b352000-12-10 18:23:50 +0000501 if( *zSql==0 ) return 0;
502 break;
503 }
504 case '-': {
505 if( zSql[1]!='-' ){
506 isComplete = 0;
drhce9079c2002-05-15 14:17:44 +0000507 seenCreate = 0;
drh8c82b352000-12-10 18:23:50 +0000508 break;
509 }
510 while( *zSql && *zSql!='\n' ){ zSql++; }
drhce9079c2002-05-15 14:17:44 +0000511 if( *zSql==0 ) return seenText && isComplete && requireEnd==0;
512 break;
513 }
514 case 'c':
515 case 'C': {
516 seenText = 1;
517 if( !isComplete ) break;
518 isComplete = 0;
519 if( sqliteStrNICmp(zSql, "create", 6)!=0 ) break;
520 if( !isspace(zSql[6]) ) break;
521 zSql += 5;
522 seenCreate = 1;
523 while( isspace(zSql[1]) ) zSql++;
524 if( sqliteStrNICmp(&zSql[1],"trigger", 7)!=0 ) break;
525 zSql += 7;
526 requireEnd++;
527 break;
528 }
529 case 't':
530 case 'T': {
531 seenText = 1;
532 if( !seenCreate ) break;
533 seenCreate = 0;
534 isComplete = 0;
535 if( sqliteStrNICmp(zSql, "trigger", 7)!=0 ) break;
536 if( !isspace(zSql[7]) ) break;
537 zSql += 6;
538 requireEnd++;
539 break;
540 }
541 case 'e':
542 case 'E': {
543 seenCreate = 0;
544 seenText = 1;
545 if( !isComplete ) break;
546 isComplete = 0;
547 if( requireEnd==0 ) break;
548 if( sqliteStrNICmp(zSql, "end", 3)!=0 ) break;
549 zSql += 2;
550 while( isspace(zSql[1]) ) zSql++;
551 if( zSql[1]==';' ){
552 zSql++;
553 isComplete = 1;
554 requireEnd--;
555 }
drh8c82b352000-12-10 18:23:50 +0000556 break;
drh9adf9ac2002-05-15 11:44:13 +0000557 }
drh8c82b352000-12-10 18:23:50 +0000558 default: {
drhce9079c2002-05-15 14:17:44 +0000559 seenCreate = 0;
560 seenText = 1;
drh8c82b352000-12-10 18:23:50 +0000561 isComplete = 0;
562 break;
563 }
drh75897232000-05-29 14:26:00 +0000564 }
drh8c82b352000-12-10 18:23:50 +0000565 zSql++;
drh75897232000-05-29 14:26:00 +0000566 }
drhce9079c2002-05-15 14:17:44 +0000567 return seenText && isComplete && requireEnd==0;
drh75897232000-05-29 14:26:00 +0000568}
569
570/*
drhbed86902000-06-02 13:27:59 +0000571** 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.
drh75897232000-05-29 14:26:00 +0000579*/
580int sqlite_exec(
581 sqlite *db, /* The database on which the SQL executes */
drh9f71c2e2001-11-03 23:57:09 +0000582 const char *zSql, /* The SQL to be executed */
drh75897232000-05-29 14:26:00 +0000583 sqlite_callback xCallback, /* Invoke this callback routine */
584 void *pArg, /* First argument to xCallback() */
585 char **pzErrMsg /* Write error messages here */
586){
587 Parse sParse;
drh75897232000-05-29 14:26:00 +0000588
589 if( pzErrMsg ) *pzErrMsg = 0;
drhc22bd472002-05-10 13:14:07 +0000590 if( sqliteSafetyOn(db) ) goto exec_misuse;
drh70562cd2002-07-13 17:23:21 +0000591 if( (db->flags & SQLITE_InTrans)!=0 && db->pid!=sqliteOsProcessId() ){
592 goto exec_misuse;
593 }
drh58b95762000-06-02 01:17:37 +0000594 if( (db->flags & SQLITE_Initialized)==0 ){
595 int rc = sqliteInit(db, pzErrMsg);
drhdaffd0e2001-04-11 14:28:42 +0000596 if( rc!=SQLITE_OK ){
597 sqliteStrRealloc(pzErrMsg);
drh247be432002-05-10 05:44:55 +0000598 sqliteSafetyOff(db);
drhdaffd0e2001-04-11 14:28:42 +0000599 return rc;
600 }
drh58b95762000-06-02 01:17:37 +0000601 }
drh491791a2002-07-18 00:34:09 +0000602 if( db->file_format<3 ){
603 sqliteSafetyOff(db);
604 sqliteSetString(pzErrMsg, "obsolete database file format", 0);
605 return SQLITE_ERROR;
606 }
drhc8d30ac2002-04-12 10:08:59 +0000607 if( db->recursionDepth==0 ){ db->nChange = 0; }
608 db->recursionDepth++;
drh75897232000-05-29 14:26:00 +0000609 memset(&sParse, 0, sizeof(sParse));
610 sParse.db = db;
drh5e00f6c2001-09-13 13:46:56 +0000611 sParse.pBe = db->pBe;
drh75897232000-05-29 14:26:00 +0000612 sParse.xCallback = xCallback;
613 sParse.pArg = pArg;
drh4c504392000-10-16 22:06:40 +0000614 sqliteRunParser(&sParse, zSql, pzErrMsg);
drhdaffd0e2001-04-11 14:28:42 +0000615 if( sqlite_malloc_failed ){
616 sqliteSetString(pzErrMsg, "out of memory", 0);
617 sParse.rc = SQLITE_NOMEM;
drh6d4abfb2001-10-22 02:58:08 +0000618 sqliteBtreeRollback(db->pBe);
619 if( db->pBeTemp ) sqliteBtreeRollback(db->pBeTemp);
620 db->flags &= ~SQLITE_InTrans;
drhe0bc4042002-06-25 01:09:11 +0000621 sqliteResetInternalSchema(db);
drhdaffd0e2001-04-11 14:28:42 +0000622 }
623 sqliteStrRealloc(pzErrMsg);
drh50e5dad2001-09-15 00:57:28 +0000624 if( sParse.rc==SQLITE_SCHEMA ){
drhe0bc4042002-06-25 01:09:11 +0000625 sqliteResetInternalSchema(db);
drh50e5dad2001-09-15 00:57:28 +0000626 }
drhc8d30ac2002-04-12 10:08:59 +0000627 db->recursionDepth--;
drhc22bd472002-05-10 13:14:07 +0000628 if( sqliteSafetyOff(db) ) goto exec_misuse;
drh4c504392000-10-16 22:06:40 +0000629 return sParse.rc;
drhc22bd472002-05-10 13:14:07 +0000630
631exec_misuse:
632 if( pzErrMsg ){
633 *pzErrMsg = 0;
634 sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
635 sqliteStrRealloc(pzErrMsg);
636 }
637 return SQLITE_MISUSE;
drh75897232000-05-29 14:26:00 +0000638}
drh2dfbbca2000-07-28 14:32:48 +0000639
640/*
drhc22bd472002-05-10 13:14:07 +0000641** Return a static string that describes the kind of error specified in the
642** argument.
drh247be432002-05-10 05:44:55 +0000643*/
drhc22bd472002-05-10 13:14:07 +0000644const char *sqlite_error_string(int rc){
645 const char *z;
646 switch( rc ){
647 case SQLITE_OK: z = "not an error"; break;
648 case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
649 case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break;
650 case SQLITE_PERM: z = "access permission denied"; break;
651 case SQLITE_ABORT: z = "callback requested query abort"; break;
652 case SQLITE_BUSY: z = "database is locked"; break;
653 case SQLITE_LOCKED: z = "database table is locked"; break;
654 case SQLITE_NOMEM: z = "out of memory"; break;
655 case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
656 case SQLITE_INTERRUPT: z = "interrupted"; break;
657 case SQLITE_IOERR: z = "disk I/O error"; break;
658 case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
659 case SQLITE_NOTFOUND: z = "table or record not found"; break;
660 case SQLITE_FULL: z = "database is full"; break;
661 case SQLITE_CANTOPEN: z = "unable to open database file"; break;
662 case SQLITE_PROTOCOL: z = "database locking protocol failure"; break;
663 case SQLITE_EMPTY: z = "table contains no data"; break;
664 case SQLITE_SCHEMA: z = "database schema has changed"; break;
665 case SQLITE_TOOBIG: z = "too much data for one table row"; break;
666 case SQLITE_CONSTRAINT: z = "constraint failed"; break;
667 case SQLITE_MISMATCH: z = "datatype mismatch"; break;
668 case SQLITE_MISUSE: z = "library routine called out of sequence";break;
669 default: z = "unknown error"; break;
drh247be432002-05-10 05:44:55 +0000670 }
drhc22bd472002-05-10 13:14:07 +0000671 return z;
drh247be432002-05-10 05:44:55 +0000672}
673
674/*
drh2dfbbca2000-07-28 14:32:48 +0000675** This routine implements a busy callback that sleeps and tries
676** again until a timeout value is reached. The timeout value is
677** an integer number of milliseconds passed in as the first
678** argument.
679*/
drhdaffd0e2001-04-11 14:28:42 +0000680static int sqliteDefaultBusyCallback(
drh2dfbbca2000-07-28 14:32:48 +0000681 void *Timeout, /* Maximum amount of time to wait */
682 const char *NotUsed, /* The name of the table that is busy */
683 int count /* Number of times table has been busy */
684){
drh8cfbf082001-09-19 13:22:39 +0000685#if SQLITE_MIN_SLEEP_MS==1
686 int delay = 10;
drh2dfbbca2000-07-28 14:32:48 +0000687 int prior_delay = 0;
688 int timeout = (int)Timeout;
689 int i;
690
691 for(i=1; i<count; i++){
692 prior_delay += delay;
693 delay = delay*2;
drh8cfbf082001-09-19 13:22:39 +0000694 if( delay>=1000 ){
695 delay = 1000;
696 prior_delay += 1000*(count - i - 1);
drh2dfbbca2000-07-28 14:32:48 +0000697 break;
698 }
699 }
drh3109e022001-10-09 13:46:01 +0000700 if( prior_delay + delay > timeout ){
701 delay = timeout - prior_delay;
drh2dfbbca2000-07-28 14:32:48 +0000702 if( delay<=0 ) return 0;
703 }
drh8cfbf082001-09-19 13:22:39 +0000704 sqliteOsSleep(delay);
drh2dfbbca2000-07-28 14:32:48 +0000705 return 1;
706#else
707 int timeout = (int)Timeout;
708 if( (count+1)*1000 > timeout ){
709 return 0;
710 }
drh8cfbf082001-09-19 13:22:39 +0000711 sqliteOsSleep(1000);
drh2dfbbca2000-07-28 14:32:48 +0000712 return 1;
713#endif
714}
715
716/*
717** This routine sets the busy callback for an Sqlite database to the
718** given callback function with the given argument.
719*/
720void sqlite_busy_handler(
721 sqlite *db,
722 int (*xBusy)(void*,const char*,int),
723 void *pArg
724){
725 db->xBusyCallback = xBusy;
726 db->pBusyArg = pArg;
727}
728
729/*
730** This routine installs a default busy handler that waits for the
731** specified number of milliseconds before returning 0.
732*/
733void sqlite_busy_timeout(sqlite *db, int ms){
734 if( ms>0 ){
drhdaffd0e2001-04-11 14:28:42 +0000735 sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)ms);
drh2dfbbca2000-07-28 14:32:48 +0000736 }else{
737 sqlite_busy_handler(db, 0, 0);
738 }
739}
drh4c504392000-10-16 22:06:40 +0000740
741/*
742** Cause any pending operation to stop at its earliest opportunity.
743*/
744void sqlite_interrupt(sqlite *db){
745 db->flags |= SQLITE_Interrupt;
746}
drhfa86c412002-02-02 15:01:15 +0000747
748/*
749** Windows systems should call this routine to free memory that
750** is returned in the in the errmsg parameter of sqlite_open() when
751** SQLite is a DLL. For some reason, it does not work to call free()
752** directly.
753**
754** Note that we need to call free() not sqliteFree() here, since every
755** string that is exported from SQLite should have already passed through
756** sqliteStrRealloc().
757*/
758void sqlite_freemem(void *p){ free(p); }
759
760/*
761** Windows systems need functions to call to return the sqlite_version
762** and sqlite_encoding strings.
763*/
764const char *sqlite_libversion(void){ return sqlite_version; }
765const char *sqlite_libencoding(void){ return sqlite_encoding; }
drh8e0a2f92002-02-23 23:45:45 +0000766
767/*
768** Create new user-defined functions. The sqlite_create_function()
769** routine creates a regular function and sqlite_create_aggregate()
770** creates an aggregate function.
771**
772** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
773** disables the function. Calling sqlite_create_function() with the
774** same name and number of arguments as a prior call to
775** sqlite_create_aggregate() disables the prior call to
776** sqlite_create_aggregate(), and vice versa.
777**
778** If nArg is -1 it means that this function will accept any number
779** of arguments, including 0.
780*/
781int sqlite_create_function(
782 sqlite *db, /* Add the function to this database connection */
783 const char *zName, /* Name of the function to add */
784 int nArg, /* Number of arguments */
drh1350b032002-02-27 19:00:20 +0000785 void (*xFunc)(sqlite_func*,int,const char**), /* The implementation */
786 void *pUserData /* User data */
drh8e0a2f92002-02-23 23:45:45 +0000787){
drh0bce8352002-02-28 00:41:10 +0000788 FuncDef *p;
drhc22bd472002-05-10 13:14:07 +0000789 if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
drh0bce8352002-02-28 00:41:10 +0000790 p = sqliteFindFunction(db, zName, strlen(zName), nArg, 1);
drh4e0f9952002-02-27 01:53:13 +0000791 if( p==0 ) return 1;
drh8e0a2f92002-02-23 23:45:45 +0000792 p->xFunc = xFunc;
793 p->xStep = 0;
794 p->xFinalize = 0;
drh1350b032002-02-27 19:00:20 +0000795 p->pUserData = pUserData;
drh8e0a2f92002-02-23 23:45:45 +0000796 return 0;
797}
798int sqlite_create_aggregate(
799 sqlite *db, /* Add the function to this database connection */
800 const char *zName, /* Name of the function to add */
801 int nArg, /* Number of arguments */
drh1350b032002-02-27 19:00:20 +0000802 void (*xStep)(sqlite_func*,int,const char**), /* The step function */
803 void (*xFinalize)(sqlite_func*), /* The finalizer */
804 void *pUserData /* User data */
drh8e0a2f92002-02-23 23:45:45 +0000805){
drh0bce8352002-02-28 00:41:10 +0000806 FuncDef *p;
drhc22bd472002-05-10 13:14:07 +0000807 if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
drh0bce8352002-02-28 00:41:10 +0000808 p = sqliteFindFunction(db, zName, strlen(zName), nArg, 1);
drh4e0f9952002-02-27 01:53:13 +0000809 if( p==0 ) return 1;
drh8e0a2f92002-02-23 23:45:45 +0000810 p->xFunc = 0;
811 p->xStep = xStep;
812 p->xFinalize = xFinalize;
drh1350b032002-02-27 19:00:20 +0000813 p->pUserData = pUserData;
drh8e0a2f92002-02-23 23:45:45 +0000814 return 0;
815}
drhc9b84a12002-06-20 11:36:48 +0000816
817/*
drh411995d2002-06-25 19:31:18 +0000818** Change the datatype for all functions with a given name. See the
819** header comment for the prototype of this function in sqlite.h for
820** additional information.
drhc9b84a12002-06-20 11:36:48 +0000821*/
822int sqlite_function_type(sqlite *db, const char *zName, int dataType){
823 FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
824 while( p ){
825 p->dataType = dataType;
826 p = p->pNext;
827 }
drhf46f9052002-06-22 02:33:38 +0000828 return SQLITE_OK;
drhc9b84a12002-06-20 11:36:48 +0000829}
drh411995d2002-06-25 19:31:18 +0000830
831/*
832** Attempt to open the file named in the argument as the auxiliary database
833** file. The auxiliary database file is used to store TEMP tables. But
834** by using this API, it is possible to trick SQLite into opening two
835** separate databases and acting on them as if they were one.
836**
837** This routine closes the existing auxiliary database file, which will
838** cause any previously created TEMP tables to be created.
839**
840** The zName parameter can be a NULL pointer or an empty string to cause
841** a temporary file to be opened and automatically deleted when closed.
842*/
843int sqlite_open_aux_file(sqlite *db, const char *zName, char **pzErrMsg){
844 int rc;
845 if( zName && zName[0]==0 ) zName = 0;
846 if( sqliteSafetyOn(db) ) goto openaux_misuse;
847 sqliteResetInternalSchema(db);
848 if( db->pBeTemp!=0 ){
849 sqliteBtreeClose(db->pBeTemp);
850 }
851 rc = sqliteBtreeOpen(zName, 0, MAX_PAGES, &db->pBeTemp);
852 if( rc ){
853 if( zName==0 ) zName = "a temporary file";
854 sqliteSetString(pzErrMsg, "unable to open ", zName,
855 ": ", sqlite_error_string(rc), 0);
856 sqliteStrRealloc(pzErrMsg);
857 sqliteSafetyOff(db);
858 return rc;
859 }
860 rc = sqliteInit(db, pzErrMsg);
861 if( sqliteSafetyOff(db) ) goto openaux_misuse;
862 sqliteStrRealloc(pzErrMsg);
863 return rc;
864
865openaux_misuse:
866 sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), 0);
867 sqliteStrRealloc(pzErrMsg);
868 return SQLITE_MISUSE;
869}