Back to index

php5  5.3.10
main.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** Main file for the SQLite library.  The routines in this file
00013 ** implement the programmer interface to the library.  Routines in
00014 ** other files are for internal use by SQLite and should not be
00015 ** accessed by users of the library.
00016 **
00017 ** $Id: main.c 195361 2005-09-07 15:11:33Z iliaa $
00018 */
00019 #include "sqliteInt.h"
00020 #include "os.h"
00021 #include <ctype.h>
00022 
00023 /*
00024 ** A pointer to this structure is used to communicate information
00025 ** from sqliteInit into the sqliteInitCallback.
00026 */
00027 typedef struct {
00028   sqlite *db;         /* The database being initialized */
00029   char **pzErrMsg;    /* Error message stored here */
00030 } InitData;
00031 
00032 /*
00033 ** Fill the InitData structure with an error message that indicates
00034 ** that the database is corrupt.
00035 */
00036 static void corruptSchema(InitData *pData, const char *zExtra){
00037   sqliteSetString(pData->pzErrMsg, "malformed database schema",
00038      zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
00039 }
00040 
00041 /*
00042 ** This is the callback routine for the code that initializes the
00043 ** database.  See sqliteInit() below for additional information.
00044 **
00045 ** Each callback contains the following information:
00046 **
00047 **     argv[0] = "file-format" or "schema-cookie" or "table" or "index"
00048 **     argv[1] = table or index name or meta statement type.
00049 **     argv[2] = root page number for table or index.  NULL for meta.
00050 **     argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
00051 **     argv[4] = "1" for temporary files, "0" for main database, "2" or more
00052 **               for auxiliary database files.
00053 **
00054 */
00055 static
00056 int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
00057   InitData *pData = (InitData*)pInit;
00058   int nErr = 0;
00059 
00060   assert( argc==5 );
00061   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
00062   if( argv[0]==0 ){
00063     corruptSchema(pData, 0);
00064     return 1;
00065   }
00066   switch( argv[0][0] ){
00067     case 'v':
00068     case 'i':
00069     case 't': {  /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
00070       sqlite *db = pData->db;
00071       if( argv[2]==0 || argv[4]==0 ){
00072         corruptSchema(pData, 0);
00073         return 1;
00074       }
00075       if( argv[3] && argv[3][0] ){
00076         /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
00077         ** But because db->init.busy is set to 1, no VDBE code is generated
00078         ** or executed.  All the parser does is build the internal data
00079         ** structures that describe the table, index, or view.
00080         */
00081         char *zErr;
00082         assert( db->init.busy );
00083         db->init.iDb = atoi(argv[4]);
00084         assert( db->init.iDb>=0 && db->init.iDb<db->nDb );
00085         db->init.newTnum = atoi(argv[2]);
00086         if( sqlite_exec(db, argv[3], 0, 0, &zErr) ){
00087           corruptSchema(pData, zErr);
00088           sqlite_freemem(zErr);
00089         }
00090         db->init.iDb = 0;
00091       }else{
00092         /* If the SQL column is blank it means this is an index that
00093         ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
00094         ** constraint for a CREATE TABLE.  The index should have already
00095         ** been created when we processed the CREATE TABLE.  All we have
00096         ** to do here is record the root page number for that index.
00097         */
00098         int iDb;
00099         Index *pIndex;
00100 
00101         iDb = atoi(argv[4]);
00102         assert( iDb>=0 && iDb<db->nDb );
00103         pIndex = sqliteFindIndex(db, argv[1], db->aDb[iDb].zName);
00104         if( pIndex==0 || pIndex->tnum!=0 ){
00105           /* This can occur if there exists an index on a TEMP table which
00106           ** has the same name as another index on a permanent index.  Since
00107           ** the permanent table is hidden by the TEMP table, we can also
00108           ** safely ignore the index on the permanent table.
00109           */
00110           /* Do Nothing */;
00111         }else{
00112           pIndex->tnum = atoi(argv[2]);
00113         }
00114       }
00115       break;
00116     }
00117     default: {
00118       /* This can not happen! */
00119       nErr = 1;
00120       assert( nErr==0 );
00121     }
00122   }
00123   return nErr;
00124 }
00125 
00126 /*
00127 ** This is a callback procedure used to reconstruct a table.  The
00128 ** name of the table to be reconstructed is passed in as argv[0].
00129 **
00130 ** This routine is used to automatically upgrade a database from
00131 ** format version 1 or 2 to version 3.  The correct operation of
00132 ** this routine relys on the fact that no indices are used when
00133 ** copying a table out to a temporary file.
00134 **
00135 ** The change from version 2 to version 3 occurred between SQLite
00136 ** version 2.5.6 and 2.6.0 on 2002-July-18.  
00137 */
00138 static
00139 int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
00140   InitData *pData = (InitData*)pInit;
00141   int rc;
00142   Table *pTab;
00143   Trigger *pTrig;
00144   char *zErr = 0;
00145 
00146   pTab = sqliteFindTable(pData->db, argv[0], 0);
00147   assert( pTab!=0 );
00148   assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
00149   if( pTab ){
00150     pTrig = pTab->pTrigger;
00151     pTab->pTrigger = 0;  /* Disable all triggers before rebuilding the table */
00152   }
00153   rc = sqlite_exec_printf(pData->db,
00154     "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
00155     "DELETE FROM '%q'; "
00156     "INSERT INTO '%q' SELECT * FROM sqlite_x; "
00157     "DROP TABLE sqlite_x;",
00158     0, 0, &zErr, argv[0], argv[0], argv[0]);
00159   if( zErr ){
00160     if( *pData->pzErrMsg ) sqlite_freemem(*pData->pzErrMsg);
00161     *pData->pzErrMsg = zErr;
00162   }
00163 
00164   /* If an error occurred in the SQL above, then the transaction will
00165   ** rollback which will delete the internal symbol tables.  This will
00166   ** cause the structure that pTab points to be deleted.  In case that
00167   ** happened, we need to refetch pTab.
00168   */
00169   pTab = sqliteFindTable(pData->db, argv[0], 0);
00170   if( pTab ){
00171     assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
00172     pTab->pTrigger = pTrig;  /* Re-enable triggers */
00173   }
00174   return rc!=SQLITE_OK;
00175 }
00176 
00177 
00178 
00179 /*
00180 ** Attempt to read the database schema and initialize internal
00181 ** data structures for a single database file.  The index of the
00182 ** database file is given by iDb.  iDb==0 is used for the main
00183 ** database.  iDb==1 should never be used.  iDb>=2 is used for
00184 ** auxiliary databases.  Return one of the SQLITE_ error codes to
00185 ** indicate success or failure.
00186 */
00187 static int sqliteInitOne(sqlite *db, int iDb, char **pzErrMsg){
00188   int rc;
00189   BtCursor *curMain;
00190   int size;
00191   Table *pTab;
00192   char const *azArg[6];
00193   char zDbNum[30];
00194   int meta[SQLITE_N_BTREE_META];
00195   InitData initData;
00196   char const *zMasterSchema;
00197   char const *zMasterName;
00198   char *zSql = 0;
00199 
00200   /*
00201   ** The master database table has a structure like this
00202   */
00203   static char master_schema[] = 
00204      "CREATE TABLE sqlite_master(\n"
00205      "  type text,\n"
00206      "  name text,\n"
00207      "  tbl_name text,\n"
00208      "  rootpage integer,\n"
00209      "  sql text\n"
00210      ")"
00211   ;
00212   static char temp_master_schema[] = 
00213      "CREATE TEMP TABLE sqlite_temp_master(\n"
00214      "  type text,\n"
00215      "  name text,\n"
00216      "  tbl_name text,\n"
00217      "  rootpage integer,\n"
00218      "  sql text\n"
00219      ")"
00220   ;
00221 
00222   assert( iDb>=0 && iDb<db->nDb );
00223 
00224   /* zMasterSchema and zInitScript are set to point at the master schema
00225   ** and initialisation script appropriate for the database being
00226   ** initialised. zMasterName is the name of the master table.
00227   */
00228   if( iDb==1 ){
00229     zMasterSchema = temp_master_schema;
00230     zMasterName = TEMP_MASTER_NAME;
00231   }else{
00232     zMasterSchema = master_schema;
00233     zMasterName = MASTER_NAME;
00234   }
00235 
00236   /* Construct the schema table.
00237   */
00238   sqliteSafetyOff(db);
00239   azArg[0] = "table";
00240   azArg[1] = zMasterName;
00241   azArg[2] = "2";
00242   azArg[3] = zMasterSchema;
00243   sprintf(zDbNum, "%d", iDb);
00244   azArg[4] = zDbNum;
00245   azArg[5] = 0;
00246   initData.db = db;
00247   initData.pzErrMsg = pzErrMsg;
00248   sqliteInitCallback(&initData, 5, (char **)azArg, 0);
00249   pTab = sqliteFindTable(db, zMasterName, db->aDb[iDb].zName);
00250   if( pTab ){
00251     pTab->readOnly = 1;
00252   }else{
00253     return SQLITE_NOMEM;
00254   }
00255   sqliteSafetyOn(db);
00256 
00257   /* Create a cursor to hold the database open
00258   */
00259   if( db->aDb[iDb].pBt==0 ) return SQLITE_OK;
00260   rc = sqliteBtreeCursor(db->aDb[iDb].pBt, 2, 0, &curMain);
00261   if( rc ){
00262     sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
00263     return rc;
00264   }
00265 
00266   /* Get the database meta information
00267   */
00268   rc = sqliteBtreeGetMeta(db->aDb[iDb].pBt, meta);
00269   if( rc ){
00270     sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
00271     sqliteBtreeCloseCursor(curMain);
00272     return rc;
00273   }
00274   db->aDb[iDb].schema_cookie = meta[1];
00275   if( iDb==0 ){
00276     db->next_cookie = meta[1];
00277     db->file_format = meta[2];
00278     size = meta[3];
00279     if( size==0 ){ size = MAX_PAGES; }
00280     db->cache_size = size;
00281     db->safety_level = meta[4];
00282     if( meta[6]>0 && meta[6]<=2 && db->temp_store==0 ){
00283       db->temp_store = meta[6];
00284     }
00285     if( db->safety_level==0 ) db->safety_level = 2;
00286 
00287     /*
00288     **  file_format==1    Version 2.1.0.
00289     **  file_format==2    Version 2.2.0. Add support for INTEGER PRIMARY KEY.
00290     **  file_format==3    Version 2.6.0. Fix empty-string index bug.
00291     **  file_format==4    Version 2.7.0. Add support for separate numeric and
00292     **                    text datatypes.
00293     */
00294     if( db->file_format==0 ){
00295       /* This happens if the database was initially empty */
00296       db->file_format = 4;
00297     }else if( db->file_format>4 ){
00298       sqliteBtreeCloseCursor(curMain);
00299       sqliteSetString(pzErrMsg, "unsupported file format", (char*)0);
00300       return SQLITE_ERROR;
00301     }
00302   }else if( iDb!=1 && (db->file_format!=meta[2] || db->file_format<4) ){
00303     assert( db->file_format>=4 );
00304     if( meta[2]==0 ){
00305       sqliteSetString(pzErrMsg, "cannot attach empty database: ",
00306          db->aDb[iDb].zName, (char*)0);
00307     }else{
00308       sqliteSetString(pzErrMsg, "incompatible file format in auxiliary "
00309          "database: ", db->aDb[iDb].zName, (char*)0);
00310     }
00311     sqliteBtreeClose(db->aDb[iDb].pBt);
00312     db->aDb[iDb].pBt = 0;
00313     return SQLITE_FORMAT;
00314   }
00315   sqliteBtreeSetCacheSize(db->aDb[iDb].pBt, db->cache_size);
00316   sqliteBtreeSetSafetyLevel(db->aDb[iDb].pBt, meta[4]==0 ? 2 : meta[4]);
00317 
00318   /* Read the schema information out of the schema tables
00319   */
00320   assert( db->init.busy );
00321   sqliteSafetyOff(db);
00322 
00323   /* The following SQL will read the schema from the master tables.
00324   ** The first version works with SQLite file formats 2 or greater.
00325   ** The second version is for format 1 files.
00326   **
00327   ** Beginning with file format 2, the rowid for new table entries
00328   ** (including entries in sqlite_master) is an increasing integer.
00329   ** So for file format 2 and later, we can play back sqlite_master
00330   ** and all the CREATE statements will appear in the right order.
00331   ** But with file format 1, table entries were random and so we
00332   ** have to make sure the CREATE TABLEs occur before their corresponding
00333   ** CREATE INDEXs.  (We don't have to deal with CREATE VIEW or
00334   ** CREATE TRIGGER in file format 1 because those constructs did
00335   ** not exist then.) 
00336   */
00337   if( db->file_format>=2 ){
00338     sqliteSetString(&zSql, 
00339         "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
00340        db->aDb[iDb].zName, "\".", zMasterName, (char*)0);
00341   }else{
00342     sqliteSetString(&zSql, 
00343         "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
00344        db->aDb[iDb].zName, "\".", zMasterName, 
00345        " WHERE type IN ('table', 'index')"
00346        " ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END", (char*)0);
00347   }
00348   rc = sqlite_exec(db, zSql, sqliteInitCallback, &initData, 0);
00349 
00350   sqliteFree(zSql);
00351   sqliteSafetyOn(db);
00352   sqliteBtreeCloseCursor(curMain);
00353   if( sqlite_malloc_failed ){
00354     sqliteSetString(pzErrMsg, "out of memory", (char*)0);
00355     rc = SQLITE_NOMEM;
00356     sqliteResetInternalSchema(db, 0);
00357   }
00358   if( rc==SQLITE_OK ){
00359     DbSetProperty(db, iDb, DB_SchemaLoaded);
00360   }else{
00361     sqliteResetInternalSchema(db, iDb);
00362   }
00363   return rc;
00364 }
00365 
00366 /*
00367 ** Initialize all database files - the main database file, the file
00368 ** used to store temporary tables, and any additional database files
00369 ** created using ATTACH statements.  Return a success code.  If an
00370 ** error occurs, write an error message into *pzErrMsg.
00371 **
00372 ** After the database is initialized, the SQLITE_Initialized
00373 ** bit is set in the flags field of the sqlite structure.  An
00374 ** attempt is made to initialize the database as soon as it
00375 ** is opened.  If that fails (perhaps because another process
00376 ** has the sqlite_master table locked) than another attempt
00377 ** is made the first time the database is accessed.
00378 */
00379 int sqliteInit(sqlite *db, char **pzErrMsg){
00380   int i, rc;
00381   
00382   if( db->init.busy ) return SQLITE_OK;
00383   assert( (db->flags & SQLITE_Initialized)==0 );
00384   rc = SQLITE_OK;
00385   db->init.busy = 1;
00386   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
00387     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
00388     rc = sqliteInitOne(db, i, pzErrMsg);
00389     if( rc ){
00390       sqliteResetInternalSchema(db, i);
00391     }
00392   }
00393 
00394   /* Once all the other databases have been initialised, load the schema
00395   ** for the TEMP database. This is loaded last, as the TEMP database
00396   ** schema may contain references to objects in other databases.
00397   */
00398   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
00399     rc = sqliteInitOne(db, 1, pzErrMsg);
00400     if( rc ){
00401       sqliteResetInternalSchema(db, 1);
00402     }
00403   }
00404 
00405   db->init.busy = 0;
00406   if( rc==SQLITE_OK ){
00407     db->flags |= SQLITE_Initialized;
00408     sqliteCommitInternalChanges(db);
00409   }
00410 
00411   /* If the database is in formats 1 or 2, then upgrade it to
00412   ** version 3.  This will reconstruct all indices.  If the
00413   ** upgrade fails for any reason (ex: out of disk space, database
00414   ** is read only, interrupt received, etc.) then fail the init.
00415   */
00416   if( rc==SQLITE_OK && db->file_format<3 ){
00417     char *zErr = 0;
00418     InitData initData;
00419     int meta[SQLITE_N_BTREE_META];
00420 
00421     db->magic = SQLITE_MAGIC_OPEN;
00422     initData.db = db;
00423     initData.pzErrMsg = &zErr;
00424     db->file_format = 3;
00425     rc = sqlite_exec(db,
00426       "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
00427       upgrade_3_callback,
00428       &initData,
00429       &zErr);
00430     if( rc==SQLITE_OK ){
00431       sqliteBtreeGetMeta(db->aDb[0].pBt, meta);
00432       meta[2] = 4;
00433       sqliteBtreeUpdateMeta(db->aDb[0].pBt, meta);
00434       sqlite_exec(db, "COMMIT", 0, 0, 0);
00435     }
00436     if( rc!=SQLITE_OK ){
00437       sqliteSetString(pzErrMsg, 
00438         "unable to upgrade database to the version 2.6 format",
00439         zErr ? ": " : 0, zErr, (char*)0);
00440     }
00441     sqlite_freemem(zErr);
00442   }
00443 
00444   if( rc!=SQLITE_OK ){
00445     db->flags &= ~SQLITE_Initialized;
00446   }
00447   return rc;
00448 }
00449 
00450 /*
00451 ** The version of the library
00452 */
00453 const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
00454 const char sqlite_version[] = SQLITE_VERSION;
00455 
00456 /*
00457 ** Does the library expect data to be encoded as UTF-8 or iso8859?  The
00458 ** following global constant always lets us know.
00459 */
00460 #ifdef SQLITE_UTF8
00461 const char sqlite_encoding[] = "UTF-8";
00462 #else
00463 const char sqlite_encoding[] = "iso8859";
00464 #endif
00465 
00466 /*
00467 ** Open a new SQLite database.  Construct an "sqlite" structure to define
00468 ** the state of this database and return a pointer to that structure.
00469 **
00470 ** An attempt is made to initialize the in-memory data structures that
00471 ** hold the database schema.  But if this fails (because the schema file
00472 ** is locked) then that step is deferred until the first call to
00473 ** sqlite_exec().
00474 */
00475 sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
00476   sqlite *db;
00477   int rc, i;
00478 
00479   /* Allocate the sqlite data structure */
00480   db = sqliteMalloc( sizeof(sqlite) );
00481   if( pzErrMsg ) *pzErrMsg = 0;
00482   if( db==0 ) goto no_mem_on_open;
00483   db->onError = OE_Default;
00484   db->priorNewRowid = 0;
00485   db->magic = SQLITE_MAGIC_BUSY;
00486   db->nDb = 2;
00487   db->aDb = db->aDbStatic;
00488   /* db->flags |= SQLITE_ShortColNames; */
00489   sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
00490   for(i=0; i<db->nDb; i++){
00491     sqliteHashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
00492     sqliteHashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
00493     sqliteHashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
00494     sqliteHashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
00495   }
00496   
00497   /* Open the backend database driver */
00498   if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
00499     db->temp_store = 2;
00500   }
00501   rc = sqliteBtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
00502   if( rc!=SQLITE_OK ){
00503     switch( rc ){
00504       default: {
00505         sqliteSetString(pzErrMsg, "unable to open database: ",
00506            zFilename, (char*)0);
00507       }
00508     }
00509     sqliteFree(db);
00510     sqliteStrRealloc(pzErrMsg);
00511     return 0;
00512   }
00513   db->aDb[0].zName = "main";
00514   db->aDb[1].zName = "temp";
00515 
00516   /* Attempt to read the schema */
00517   sqliteRegisterBuiltinFunctions(db);
00518   rc = sqliteInit(db, pzErrMsg);
00519   db->magic = SQLITE_MAGIC_OPEN;
00520   if( sqlite_malloc_failed ){
00521     sqlite_close(db);
00522     goto no_mem_on_open;
00523   }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
00524     sqlite_close(db);
00525     sqliteStrRealloc(pzErrMsg);
00526     return 0;
00527   }else if( pzErrMsg ){
00528     sqliteFree(*pzErrMsg);
00529     *pzErrMsg = 0;
00530   }
00531 
00532   /* Return a pointer to the newly opened database structure */
00533   return db;
00534 
00535 no_mem_on_open:
00536   sqliteSetString(pzErrMsg, "out of memory", (char*)0);
00537   sqliteStrRealloc(pzErrMsg);
00538   return 0;
00539 }
00540 
00541 /*
00542 ** Return the ROWID of the most recent insert
00543 */
00544 int sqlite_last_insert_rowid(sqlite *db){
00545   return db->lastRowid;
00546 }
00547 
00548 /*
00549 ** Return the number of changes in the most recent call to sqlite_exec().
00550 */
00551 int sqlite_changes(sqlite *db){
00552   return db->nChange;
00553 }
00554 
00555 /*
00556 ** Return the number of changes produced by the last INSERT, UPDATE, or
00557 ** DELETE statement to complete execution. The count does not include
00558 ** changes due to SQL statements executed in trigger programs that were
00559 ** triggered by that statement
00560 */
00561 int sqlite_last_statement_changes(sqlite *db){
00562   return db->lsChange;
00563 }
00564 
00565 /*
00566 ** Close an existing SQLite database
00567 */
00568 void sqlite_close(sqlite *db){
00569   HashElem *i;
00570   int j;
00571   db->want_to_close = 1;
00572   if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
00573     /* printf("DID NOT CLOSE\n"); fflush(stdout); */
00574     return;
00575   }
00576   db->magic = SQLITE_MAGIC_CLOSED;
00577   for(j=0; j<db->nDb; j++){
00578     struct Db *pDb = &db->aDb[j];
00579     if( pDb->pBt ){
00580       sqliteBtreeClose(pDb->pBt);
00581       pDb->pBt = 0;
00582     }
00583   }
00584   sqliteResetInternalSchema(db, 0);
00585   assert( db->nDb<=2 );
00586   assert( db->aDb==db->aDbStatic );
00587   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
00588     FuncDef *pFunc, *pNext;
00589     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
00590       pNext = pFunc->pNext;
00591       sqliteFree(pFunc);
00592     }
00593   }
00594   sqliteHashClear(&db->aFunc);
00595   sqliteFree(db);
00596 }
00597 
00598 /*
00599 ** Rollback all database files.
00600 */
00601 void sqliteRollbackAll(sqlite *db){
00602   int i;
00603   for(i=0; i<db->nDb; i++){
00604     if( db->aDb[i].pBt ){
00605       sqliteBtreeRollback(db->aDb[i].pBt);
00606       db->aDb[i].inTrans = 0;
00607     }
00608   }
00609   sqliteResetInternalSchema(db, 0);
00610   /* sqliteRollbackInternalChanges(db); */
00611 }
00612 
00613 /*
00614 ** Execute SQL code.  Return one of the SQLITE_ success/failure
00615 ** codes.  Also write an error message into memory obtained from
00616 ** malloc() and make *pzErrMsg point to that message.
00617 **
00618 ** If the SQL is a query, then for each row in the query result
00619 ** the xCallback() function is called.  pArg becomes the first
00620 ** argument to xCallback().  If xCallback=NULL then no callback
00621 ** is invoked, even for queries.
00622 */
00623 int sqlite_exec(
00624   sqlite *db,                 /* The database on which the SQL executes */
00625   const char *zSql,           /* The SQL to be executed */
00626   sqlite_callback xCallback,  /* Invoke this callback routine */
00627   void *pArg,                 /* First argument to xCallback() */
00628   char **pzErrMsg             /* Write error messages here */
00629 ){
00630   int rc = SQLITE_OK;
00631   const char *zLeftover;
00632   sqlite_vm *pVm;
00633   int nRetry = 0;
00634   int nChange = 0;
00635   int nCallback;
00636 
00637   if( zSql==0 ) return SQLITE_OK;
00638   while( rc==SQLITE_OK && zSql[0] ){
00639     pVm = 0;
00640     rc = sqlite_compile(db, zSql, &zLeftover, &pVm, pzErrMsg);
00641     if( rc!=SQLITE_OK ){
00642       assert( pVm==0 || sqlite_malloc_failed );
00643       return rc;
00644     }
00645     if( pVm==0 ){
00646       /* This happens if the zSql input contained only whitespace */
00647       break;
00648     }
00649     db->nChange += nChange;
00650     nCallback = 0;
00651     while(1){
00652       int nArg;
00653       char **azArg, **azCol;
00654       rc = sqlite_step(pVm, &nArg, (const char***)&azArg,(const char***)&azCol);
00655       if( rc==SQLITE_ROW ){
00656         if( xCallback!=0 && xCallback(pArg, nArg, azArg, azCol) ){
00657           sqlite_finalize(pVm, 0);
00658           return SQLITE_ABORT;
00659         }
00660         nCallback++;
00661       }else{
00662         if( rc==SQLITE_DONE && nCallback==0
00663           && (db->flags & SQLITE_NullCallback)!=0 && xCallback!=0 ){
00664           xCallback(pArg, nArg, azArg, azCol);
00665         }
00666         rc = sqlite_finalize(pVm, pzErrMsg);
00667         if( rc==SQLITE_SCHEMA && nRetry<2 ){
00668           nRetry++;
00669           rc = SQLITE_OK;
00670           break;
00671         }
00672         if( db->pVdbe==0 ){
00673           nChange = db->nChange;
00674         }
00675         nRetry = 0;
00676         zSql = zLeftover;
00677         while( isspace(zSql[0]) ) zSql++;
00678         break;
00679       }
00680     }
00681   }
00682   return rc;
00683 }
00684 
00685 
00686 /*
00687 ** Compile a single statement of SQL into a virtual machine.  Return one
00688 ** of the SQLITE_ success/failure codes.  Also write an error message into
00689 ** memory obtained from malloc() and make *pzErrMsg point to that message.
00690 */
00691 int sqlite_compile(
00692   sqlite *db,                 /* The database on which the SQL executes */
00693   const char *zSql,           /* The SQL to be executed */
00694   const char **pzTail,        /* OUT: Next statement after the first */
00695   sqlite_vm **ppVm,           /* OUT: The virtual machine */
00696   char **pzErrMsg             /* OUT: Write error messages here */
00697 ){
00698   Parse sParse;
00699 
00700   if( pzErrMsg ) *pzErrMsg = 0;
00701   if( sqliteSafetyOn(db) ) goto exec_misuse;
00702   if( !db->init.busy ){
00703     if( (db->flags & SQLITE_Initialized)==0 ){
00704       int rc, cnt = 1;
00705       while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
00706          && db->xBusyCallback
00707          && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
00708       if( rc!=SQLITE_OK ){
00709         sqliteStrRealloc(pzErrMsg);
00710         sqliteSafetyOff(db);
00711         return rc;
00712       }
00713       if( pzErrMsg ){
00714         sqliteFree(*pzErrMsg);
00715         *pzErrMsg = 0;
00716       }
00717     }
00718     if( db->file_format<3 ){
00719       sqliteSafetyOff(db);
00720       sqliteSetString(pzErrMsg, "obsolete database file format", (char*)0);
00721       return SQLITE_ERROR;
00722     }
00723   }
00724   assert( (db->flags & SQLITE_Initialized)!=0 || db->init.busy );
00725   if( db->pVdbe==0 ){ db->nChange = 0; }
00726   memset(&sParse, 0, sizeof(sParse));
00727   sParse.db = db;
00728   sqliteRunParser(&sParse, zSql, pzErrMsg);
00729   if( db->xTrace && !db->init.busy ){
00730     /* Trace only the statment that was compiled.
00731     ** Make a copy of that part of the SQL string since zSQL is const
00732     ** and we must pass a zero terminated string to the trace function
00733     ** The copy is unnecessary if the tail pointer is pointing at the
00734     ** beginnig or end of the SQL string.
00735     */
00736     if( sParse.zTail && sParse.zTail!=zSql && *sParse.zTail ){
00737       char *tmpSql = sqliteStrNDup(zSql, sParse.zTail - zSql);
00738       if( tmpSql ){
00739         db->xTrace(db->pTraceArg, tmpSql);
00740         free(tmpSql);
00741       }else{
00742         /* If a memory error occurred during the copy,
00743         ** trace entire SQL string and fall through to the
00744         ** sqlite_malloc_failed test to report the error.
00745         */
00746         db->xTrace(db->pTraceArg, zSql); 
00747       }
00748     }else{
00749       db->xTrace(db->pTraceArg, zSql); 
00750     }
00751   }
00752   if( sqlite_malloc_failed ){
00753     sqliteSetString(pzErrMsg, "out of memory", (char*)0);
00754     sParse.rc = SQLITE_NOMEM;
00755     sqliteRollbackAll(db);
00756     sqliteResetInternalSchema(db, 0);
00757     db->flags &= ~SQLITE_InTrans;
00758   }
00759   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
00760   if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
00761     sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), (char*)0);
00762   }
00763   sqliteStrRealloc(pzErrMsg);
00764   if( sParse.rc==SQLITE_SCHEMA ){
00765     sqliteResetInternalSchema(db, 0);
00766   }
00767   assert( ppVm );
00768   *ppVm = (sqlite_vm*)sParse.pVdbe;
00769   if( pzTail ) *pzTail = sParse.zTail;
00770   if( sqliteSafetyOff(db) ) goto exec_misuse;
00771   return sParse.rc;
00772 
00773 exec_misuse:
00774   if( pzErrMsg ){
00775     *pzErrMsg = 0;
00776     sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
00777     sqliteStrRealloc(pzErrMsg);
00778   }
00779   return SQLITE_MISUSE;
00780 }
00781 
00782 
00783 /*
00784 ** The following routine destroys a virtual machine that is created by
00785 ** the sqlite_compile() routine.
00786 **
00787 ** The integer returned is an SQLITE_ success/failure code that describes
00788 ** the result of executing the virtual machine.  An error message is
00789 ** written into memory obtained from malloc and *pzErrMsg is made to
00790 ** point to that error if pzErrMsg is not NULL.  The calling routine
00791 ** should use sqlite_freemem() to delete the message when it has finished
00792 ** with it.
00793 */
00794 int sqlite_finalize(
00795   sqlite_vm *pVm,            /* The virtual machine to be destroyed */
00796   char **pzErrMsg            /* OUT: Write error messages here */
00797 ){
00798   int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
00799   sqliteStrRealloc(pzErrMsg);
00800   return rc;
00801 }
00802 
00803 /*
00804 ** Terminate the current execution of a virtual machine then
00805 ** reset the virtual machine back to its starting state so that it
00806 ** can be reused.  Any error message resulting from the prior execution
00807 ** is written into *pzErrMsg.  A success code from the prior execution
00808 ** is returned.
00809 */
00810 int sqlite_reset(
00811   sqlite_vm *pVm,            /* The virtual machine to be destroyed */
00812   char **pzErrMsg            /* OUT: Write error messages here */
00813 ){
00814   int rc = sqliteVdbeReset((Vdbe*)pVm, pzErrMsg);
00815   sqliteVdbeMakeReady((Vdbe*)pVm, -1, 0);
00816   sqliteStrRealloc(pzErrMsg);
00817   return rc;
00818 }
00819 
00820 /*
00821 ** Return a static string that describes the kind of error specified in the
00822 ** argument.
00823 */
00824 const char *sqlite_error_string(int rc){
00825   const char *z;
00826   switch( rc ){
00827     case SQLITE_OK:         z = "not an error";                          break;
00828     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
00829     case SQLITE_INTERNAL:   z = "internal SQLite implementation flaw";   break;
00830     case SQLITE_PERM:       z = "access permission denied";              break;
00831     case SQLITE_ABORT:      z = "callback requested query abort";        break;
00832     case SQLITE_BUSY:       z = "database is locked";                    break;
00833     case SQLITE_LOCKED:     z = "database table is locked";              break;
00834     case SQLITE_NOMEM:      z = "out of memory";                         break;
00835     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
00836     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
00837     case SQLITE_IOERR:      z = "disk I/O error";                        break;
00838     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
00839     case SQLITE_NOTFOUND:   z = "table or record not found";             break;
00840     case SQLITE_FULL:       z = "database is full";                      break;
00841     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
00842     case SQLITE_PROTOCOL:   z = "database locking protocol failure";     break;
00843     case SQLITE_EMPTY:      z = "table contains no data";                break;
00844     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
00845     case SQLITE_TOOBIG:     z = "too much data for one table row";       break;
00846     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
00847     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
00848     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
00849     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
00850     case SQLITE_AUTH:       z = "authorization denied";                  break;
00851     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
00852     case SQLITE_RANGE:      z = "bind index out of range";               break;
00853     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
00854     default:                z = "unknown error";                         break;
00855   }
00856   return z;
00857 }
00858 
00859 /*
00860 ** This routine implements a busy callback that sleeps and tries
00861 ** again until a timeout value is reached.  The timeout value is
00862 ** an integer number of milliseconds passed in as the first
00863 ** argument.
00864 */
00865 static int sqliteDefaultBusyCallback(
00866  void *Timeout,           /* Maximum amount of time to wait */
00867  const char *NotUsed,     /* The name of the table that is busy */
00868  int count                /* Number of times table has been busy */
00869 ){
00870 #if SQLITE_MIN_SLEEP_MS==1
00871   static const char delays[] =
00872      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50,  50, 100};
00873   static const short int totals[] =
00874      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228, 287};
00875 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
00876   int timeout = (int)(long)Timeout;
00877   int delay, prior;
00878 
00879   if( count <= NDELAY ){
00880     delay = delays[count-1];
00881     prior = totals[count-1];
00882   }else{
00883     delay = delays[NDELAY-1];
00884     prior = totals[NDELAY-1] + delay*(count-NDELAY-1);
00885   }
00886   if( prior + delay > timeout ){
00887     delay = timeout - prior;
00888     if( delay<=0 ) return 0;
00889   }
00890   sqliteOsSleep(delay);
00891   return 1;
00892 #else
00893   int timeout = (int)(long)Timeout;
00894   if( (count+1)*1000 > timeout ){
00895     return 0;
00896   }
00897   sqliteOsSleep(1000);
00898   return 1;
00899 #endif
00900 }
00901 
00902 /*
00903 ** This routine sets the busy callback for an Sqlite database to the
00904 ** given callback function with the given argument.
00905 */
00906 void sqlite_busy_handler(
00907   sqlite *db,
00908   int (*xBusy)(void*,const char*,int),
00909   void *pArg
00910 ){
00911   db->xBusyCallback = xBusy;
00912   db->pBusyArg = pArg;
00913 }
00914 
00915 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
00916 /*
00917 ** This routine sets the progress callback for an Sqlite database to the
00918 ** given callback function with the given argument. The progress callback will
00919 ** be invoked every nOps opcodes.
00920 */
00921 void sqlite_progress_handler(
00922   sqlite *db, 
00923   int nOps,
00924   int (*xProgress)(void*), 
00925   void *pArg
00926 ){
00927   if( nOps>0 ){
00928     db->xProgress = xProgress;
00929     db->nProgressOps = nOps;
00930     db->pProgressArg = pArg;
00931   }else{
00932     db->xProgress = 0;
00933     db->nProgressOps = 0;
00934     db->pProgressArg = 0;
00935   }
00936 }
00937 #endif
00938 
00939 
00940 /*
00941 ** This routine installs a default busy handler that waits for the
00942 ** specified number of milliseconds before returning 0.
00943 */
00944 void sqlite_busy_timeout(sqlite *db, int ms){
00945   if( ms>0 ){
00946     sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)(long)ms);
00947   }else{
00948     sqlite_busy_handler(db, 0, 0);
00949   }
00950 }
00951 
00952 /*
00953 ** Cause any pending operation to stop at its earliest opportunity.
00954 */
00955 void sqlite_interrupt(sqlite *db){
00956   db->flags |= SQLITE_Interrupt;
00957 }
00958 
00959 /*
00960 ** Windows systems should call this routine to free memory that
00961 ** is returned in the in the errmsg parameter of sqlite_open() when
00962 ** SQLite is a DLL.  For some reason, it does not work to call free()
00963 ** directly.
00964 **
00965 ** Note that we need to call free() not sqliteFree() here, since every
00966 ** string that is exported from SQLite should have already passed through
00967 ** sqliteStrRealloc().
00968 */
00969 void sqlite_freemem(void *p){ free(p); }
00970 
00971 /*
00972 ** Windows systems need functions to call to return the sqlite_version
00973 ** and sqlite_encoding strings since they are unable to access constants
00974 ** within DLLs.
00975 */
00976 const char *sqlite_libversion(void){ return sqlite_version; }
00977 const char *sqlite_libencoding(void){ return sqlite_encoding; }
00978 
00979 /*
00980 ** Create new user-defined functions.  The sqlite_create_function()
00981 ** routine creates a regular function and sqlite_create_aggregate()
00982 ** creates an aggregate function.
00983 **
00984 ** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
00985 ** disables the function.  Calling sqlite_create_function() with the
00986 ** same name and number of arguments as a prior call to
00987 ** sqlite_create_aggregate() disables the prior call to
00988 ** sqlite_create_aggregate(), and vice versa.
00989 **
00990 ** If nArg is -1 it means that this function will accept any number
00991 ** of arguments, including 0.  The maximum allowed value of nArg is 127.
00992 */
00993 int sqlite_create_function(
00994   sqlite *db,          /* Add the function to this database connection */
00995   const char *zName,   /* Name of the function to add */
00996   int nArg,            /* Number of arguments */
00997   void (*xFunc)(sqlite_func*,int,const char**),  /* The implementation */
00998   void *pUserData      /* User data */
00999 ){
01000   FuncDef *p;
01001   int nName;
01002   if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
01003   if( nArg<-1 || nArg>127 ) return 1;
01004   nName = strlen(zName);
01005   if( nName>255 ) return 1;
01006   p = sqliteFindFunction(db, zName, nName, nArg, 1);
01007   if( p==0 ) return 1;
01008   p->xFunc = xFunc;
01009   p->xStep = 0;
01010   p->xFinalize = 0;
01011   p->pUserData = pUserData;
01012   return 0;
01013 }
01014 int sqlite_create_aggregate(
01015   sqlite *db,          /* Add the function to this database connection */
01016   const char *zName,   /* Name of the function to add */
01017   int nArg,            /* Number of arguments */
01018   void (*xStep)(sqlite_func*,int,const char**), /* The step function */
01019   void (*xFinalize)(sqlite_func*),              /* The finalizer */
01020   void *pUserData      /* User data */
01021 ){
01022   FuncDef *p;
01023   int nName;
01024   if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
01025   if( nArg<-1 || nArg>127 ) return 1;
01026   nName = strlen(zName);
01027   if( nName>255 ) return 1;
01028   p = sqliteFindFunction(db, zName, nName, nArg, 1);
01029   if( p==0 ) return 1;
01030   p->xFunc = 0;
01031   p->xStep = xStep;
01032   p->xFinalize = xFinalize;
01033   p->pUserData = pUserData;
01034   return 0;
01035 }
01036 
01037 /*
01038 ** Change the datatype for all functions with a given name.  See the
01039 ** header comment for the prototype of this function in sqlite.h for
01040 ** additional information.
01041 */
01042 int sqlite_function_type(sqlite *db, const char *zName, int dataType){
01043   FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
01044   while( p ){
01045     p->dataType = dataType; 
01046     p = p->pNext;
01047   }
01048   return SQLITE_OK;
01049 }
01050 
01051 /*
01052 ** Register a trace function.  The pArg from the previously registered trace
01053 ** is returned.  
01054 **
01055 ** A NULL trace function means that no tracing is executes.  A non-NULL
01056 ** trace is a pointer to a function that is invoked at the start of each
01057 ** sqlite_exec().
01058 */
01059 void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
01060   void *pOld = db->pTraceArg;
01061   db->xTrace = xTrace;
01062   db->pTraceArg = pArg;
01063   return pOld;
01064 }
01065 
01066 /*** EXPERIMENTAL ***
01067 **
01068 ** Register a function to be invoked when a transaction comments.
01069 ** If either function returns non-zero, then the commit becomes a
01070 ** rollback.
01071 */
01072 void *sqlite_commit_hook(
01073   sqlite *db,               /* Attach the hook to this database */
01074   int (*xCallback)(void*),  /* Function to invoke on each commit */
01075   void *pArg                /* Argument to the function */
01076 ){
01077   void *pOld = db->pCommitArg;
01078   db->xCommitCallback = xCallback;
01079   db->pCommitArg = pArg;
01080   return pOld;
01081 }
01082 
01083 
01084 /*
01085 ** This routine is called to create a connection to a database BTree
01086 ** driver.  If zFilename is the name of a file, then that file is
01087 ** opened and used.  If zFilename is the magic name ":memory:" then
01088 ** the database is stored in memory (and is thus forgotten as soon as
01089 ** the connection is closed.)  If zFilename is NULL then the database
01090 ** is for temporary use only and is deleted as soon as the connection
01091 ** is closed.
01092 **
01093 ** A temporary database can be either a disk file (that is automatically
01094 ** deleted when the file is closed) or a set of red-black trees held in memory,
01095 ** depending on the values of the TEMP_STORE compile-time macro and the
01096 ** db->temp_store variable, according to the following chart:
01097 **
01098 **       TEMP_STORE     db->temp_store     Location of temporary database
01099 **       ----------     --------------     ------------------------------
01100 **           0               any             file
01101 **           1                1              file
01102 **           1                2              memory
01103 **           1                0              file
01104 **           2                1              file
01105 **           2                2              memory
01106 **           2                0              memory
01107 **           3               any             memory
01108 */
01109 int sqliteBtreeFactory(
01110   const sqlite *db,      /* Main database when opening aux otherwise 0 */
01111   const char *zFilename,    /* Name of the file containing the BTree database */
01112   int omitJournal,          /* if TRUE then do not journal this file */
01113   int nCache,               /* How many pages in the page cache */
01114   Btree **ppBtree){         /* Pointer to new Btree object written here */
01115 
01116   assert( ppBtree != 0);
01117 
01118 #ifndef SQLITE_OMIT_INMEMORYDB
01119   if( zFilename==0 ){
01120     if (TEMP_STORE == 0) {
01121       /* Always use file based temporary DB */
01122       return sqliteBtreeOpen(0, omitJournal, nCache, ppBtree);
01123     } else if (TEMP_STORE == 1 || TEMP_STORE == 2) {
01124       /* Switch depending on compile-time and/or runtime settings. */
01125       int location = db->temp_store==0 ? TEMP_STORE : db->temp_store;
01126 
01127       if (location == 1) {
01128         return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
01129       } else {
01130         return sqliteRbtreeOpen(0, 0, 0, ppBtree);
01131       }
01132     } else {
01133       /* Always use in-core DB */
01134       return sqliteRbtreeOpen(0, 0, 0, ppBtree);
01135     }
01136   }else if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
01137     return sqliteRbtreeOpen(0, 0, 0, ppBtree);
01138   }else
01139 #endif
01140   {
01141     return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
01142   }
01143 }