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