monotone

monotone Mtn Source Tree

Root/sqlite/main.c

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

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status