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