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