prepare.c

Go to the documentation of this file.
00001 /*
00002 ** 2005 May 25
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 ** This file contains the implementation of the sqlite3_prepare()
00013 ** interface, and routines that contribute to loading the database schema
00014 ** from disk.
00015 **
00016 ** $Id: prepare.c,v 1.98 2008/10/31 10:53:23 danielk1977 Exp $
00017 */
00018 #include "sqliteInt.h"
00019 #include <ctype.h>
00020 
00021 /*
00022 ** Fill the InitData structure with an error message that indicates
00023 ** that the database is corrupt.
00024 */
00025 static void corruptSchema(
00026   InitData *pData,     /* Initialization context */
00027   const char *zObj,    /* Object being parsed at the point of error */
00028   const char *zExtra   /* Error information */
00029 ){
00030   sqlite3 *db = pData->db;
00031   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
00032     if( zObj==0 ) zObj = "?";
00033     sqlite3SetString(pData->pzErrMsg, pData->db,
00034        "malformed database schema (%s)", zObj);
00035     if( zExtra && zExtra[0] ){
00036       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
00037                                   *pData->pzErrMsg, zExtra);
00038     }
00039   }
00040   pData->rc = SQLITE_CORRUPT;
00041 }
00042 
00043 /*
00044 ** This is the callback routine for the code that initializes the
00045 ** database.  See sqlite3Init() below for additional information.
00046 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
00047 **
00048 ** Each callback contains the following information:
00049 **
00050 **     argv[0] = name of thing being created
00051 **     argv[1] = root page number for table or index. 0 for trigger or view.
00052 **     argv[2] = SQL text for the CREATE statement.
00053 **
00054 */
00055 int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
00056   InitData *pData = (InitData*)pInit;
00057   sqlite3 *db = pData->db;
00058   int iDb = pData->iDb;
00059 
00060   assert( sqlite3_mutex_held(db->mutex) );
00061   DbClearProperty(db, iDb, DB_Empty);
00062   if( db->mallocFailed ){
00063     corruptSchema(pData, argv[0], 0);
00064     return SQLITE_NOMEM;
00065   }
00066 
00067   assert( argc==3 );
00068   assert( iDb>=0 && iDb<db->nDb );
00069   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
00070   if( argv[1]==0 ){
00071     corruptSchema(pData, argv[0], 0);
00072   }else if( argv[2] && argv[2][0] ){
00073     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
00074     ** But because db->init.busy is set to 1, no VDBE code is generated
00075     ** or executed.  All the parser does is build the internal data
00076     ** structures that describe the table, index, or view.
00077     */
00078     char *zErr;
00079     int rc;
00080     u8 lookasideEnabled;
00081     assert( db->init.busy );
00082     db->init.iDb = iDb;
00083     db->init.newTnum = atoi(argv[1]);
00084     lookasideEnabled = db->lookaside.bEnabled;
00085     db->lookaside.bEnabled = 0;
00086     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
00087     db->init.iDb = 0;
00088     db->lookaside.bEnabled = lookasideEnabled;
00089     assert( rc!=SQLITE_OK || zErr==0 );
00090     if( SQLITE_OK!=rc ){
00091       pData->rc = rc;
00092       if( rc==SQLITE_NOMEM ){
00093         db->mallocFailed = 1;
00094       }else if( rc!=SQLITE_INTERRUPT ){
00095         corruptSchema(pData, argv[0], zErr);
00096       }
00097       sqlite3DbFree(db, zErr);
00098     }
00099   }else if( argv[0]==0 ){
00100     corruptSchema(pData, 0, 0);
00101   }else{
00102     /* If the SQL column is blank it means this is an index that
00103     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
00104     ** constraint for a CREATE TABLE.  The index should have already
00105     ** been created when we processed the CREATE TABLE.  All we have
00106     ** to do here is record the root page number for that index.
00107     */
00108     Index *pIndex;
00109     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
00110     if( pIndex==0 || pIndex->tnum!=0 ){
00111       /* This can occur if there exists an index on a TEMP table which
00112       ** has the same name as another index on a permanent index.  Since
00113       ** the permanent table is hidden by the TEMP table, we can also
00114       ** safely ignore the index on the permanent table.
00115       */
00116       /* Do Nothing */;
00117     }else{
00118       pIndex->tnum = atoi(argv[1]);
00119     }
00120   }
00121   return 0;
00122 }
00123 
00124 /*
00125 ** Attempt to read the database schema and initialize internal
00126 ** data structures for a single database file.  The index of the
00127 ** database file is given by iDb.  iDb==0 is used for the main
00128 ** database.  iDb==1 should never be used.  iDb>=2 is used for
00129 ** auxiliary databases.  Return one of the SQLITE_ error codes to
00130 ** indicate success or failure.
00131 */
00132 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
00133   int rc;
00134   BtCursor *curMain;
00135   int size;
00136   Table *pTab;
00137   Db *pDb;
00138   char const *azArg[4];
00139   int meta[10];
00140   InitData initData;
00141   char const *zMasterSchema;
00142   char const *zMasterName = SCHEMA_TABLE(iDb);
00143 
00144   /*
00145   ** The master database table has a structure like this
00146   */
00147   static const char master_schema[] = 
00148      "CREATE TABLE sqlite_master(\n"
00149      "  type text,\n"
00150      "  name text,\n"
00151      "  tbl_name text,\n"
00152      "  rootpage integer,\n"
00153      "  sql text\n"
00154      ")"
00155   ;
00156 #ifndef SQLITE_OMIT_TEMPDB
00157   static const char temp_master_schema[] = 
00158      "CREATE TEMP TABLE sqlite_temp_master(\n"
00159      "  type text,\n"
00160      "  name text,\n"
00161      "  tbl_name text,\n"
00162      "  rootpage integer,\n"
00163      "  sql text\n"
00164      ")"
00165   ;
00166 #else
00167   #define temp_master_schema 0
00168 #endif
00169 
00170   assert( iDb>=0 && iDb<db->nDb );
00171   assert( db->aDb[iDb].pSchema );
00172   assert( sqlite3_mutex_held(db->mutex) );
00173   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
00174 
00175   /* zMasterSchema and zInitScript are set to point at the master schema
00176   ** and initialisation script appropriate for the database being
00177   ** initialised. zMasterName is the name of the master table.
00178   */
00179   if( !OMIT_TEMPDB && iDb==1 ){
00180     zMasterSchema = temp_master_schema;
00181   }else{
00182     zMasterSchema = master_schema;
00183   }
00184   zMasterName = SCHEMA_TABLE(iDb);
00185 
00186   /* Construct the schema tables.  */
00187   azArg[0] = zMasterName;
00188   azArg[1] = "1";
00189   azArg[2] = zMasterSchema;
00190   azArg[3] = 0;
00191   initData.db = db;
00192   initData.iDb = iDb;
00193   initData.rc = SQLITE_OK;
00194   initData.pzErrMsg = pzErrMsg;
00195   (void)sqlite3SafetyOff(db);
00196   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
00197   (void)sqlite3SafetyOn(db);
00198   if( initData.rc ){
00199     rc = initData.rc;
00200     goto error_out;
00201   }
00202   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
00203   if( pTab ){
00204     pTab->tabFlags |= TF_Readonly;
00205   }
00206 
00207   /* Create a cursor to hold the database open
00208   */
00209   pDb = &db->aDb[iDb];
00210   if( pDb->pBt==0 ){
00211     if( !OMIT_TEMPDB && iDb==1 ){
00212       DbSetProperty(db, 1, DB_SchemaLoaded);
00213     }
00214     return SQLITE_OK;
00215   }
00216   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
00217   if( !curMain ){
00218     rc = SQLITE_NOMEM;
00219     goto error_out;
00220   }
00221   sqlite3BtreeEnter(pDb->pBt);
00222   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
00223   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
00224     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
00225     goto initone_error_out;
00226   }
00227 
00228   /* Get the database meta information.
00229   **
00230   ** Meta values are as follows:
00231   **    meta[0]   Schema cookie.  Changes with each schema change.
00232   **    meta[1]   File format of schema layer.
00233   **    meta[2]   Size of the page cache.
00234   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
00235   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
00236   **    meta[5]   The user cookie. Used by the application.
00237   **    meta[6]   Incremental-vacuum flag.
00238   **    meta[7]
00239   **    meta[8]
00240   **    meta[9]
00241   **
00242   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
00243   ** the possible values of meta[4].
00244   */
00245   if( rc==SQLITE_OK ){
00246     int i;
00247     for(i=0; i<sizeof(meta)/sizeof(meta[0]); i++){
00248       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
00249       if( rc ){
00250         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
00251         goto initone_error_out;
00252       }
00253     }
00254   }else{
00255     memset(meta, 0, sizeof(meta));
00256   }
00257   pDb->pSchema->schema_cookie = meta[0];
00258 
00259   /* If opening a non-empty database, check the text encoding. For the
00260   ** main database, set sqlite3.enc to the encoding of the main database.
00261   ** For an attached db, it is an error if the encoding is not the same
00262   ** as sqlite3.enc.
00263   */
00264   if( meta[4] ){  /* text encoding */
00265     if( iDb==0 ){
00266       /* If opening the main database, set ENC(db). */
00267       ENC(db) = (u8)meta[4];
00268       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
00269     }else{
00270       /* If opening an attached database, the encoding much match ENC(db) */
00271       if( meta[4]!=ENC(db) ){
00272         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
00273             " text encoding as main database");
00274         rc = SQLITE_ERROR;
00275         goto initone_error_out;
00276       }
00277     }
00278   }else{
00279     DbSetProperty(db, iDb, DB_Empty);
00280   }
00281   pDb->pSchema->enc = ENC(db);
00282 
00283   if( pDb->pSchema->cache_size==0 ){
00284     size = meta[2];
00285     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
00286     if( size<0 ) size = -size;
00287     pDb->pSchema->cache_size = size;
00288     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
00289   }
00290 
00291   /*
00292   ** file_format==1    Version 3.0.0.
00293   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
00294   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
00295   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
00296   */
00297   pDb->pSchema->file_format = meta[1];
00298   if( pDb->pSchema->file_format==0 ){
00299     pDb->pSchema->file_format = 1;
00300   }
00301   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
00302     sqlite3SetString(pzErrMsg, db, "unsupported file format");
00303     rc = SQLITE_ERROR;
00304     goto initone_error_out;
00305   }
00306 
00307   /* Ticket #2804:  When we open a database in the newer file format,
00308   ** clear the legacy_file_format pragma flag so that a VACUUM will
00309   ** not downgrade the database and thus invalidate any descending
00310   ** indices that the user might have created.
00311   */
00312   if( iDb==0 && meta[1]>=4 ){
00313     db->flags &= ~SQLITE_LegacyFileFmt;
00314   }
00315 
00316   /* Read the schema information out of the schema tables
00317   */
00318   assert( db->init.busy );
00319   if( rc==SQLITE_EMPTY ){
00320     /* For an empty database, there is nothing to read */
00321     rc = SQLITE_OK;
00322   }else{
00323     char *zSql;
00324     zSql = sqlite3MPrintf(db, 
00325         "SELECT name, rootpage, sql FROM '%q'.%s",
00326         db->aDb[iDb].zName, zMasterName);
00327     (void)sqlite3SafetyOff(db);
00328 #ifndef SQLITE_OMIT_AUTHORIZATION
00329     {
00330       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
00331       xAuth = db->xAuth;
00332       db->xAuth = 0;
00333 #endif
00334       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
00335 #ifndef SQLITE_OMIT_AUTHORIZATION
00336       db->xAuth = xAuth;
00337     }
00338 #endif
00339     if( rc==SQLITE_OK ) rc = initData.rc;
00340     (void)sqlite3SafetyOn(db);
00341     sqlite3DbFree(db, zSql);
00342 #ifndef SQLITE_OMIT_ANALYZE
00343     if( rc==SQLITE_OK ){
00344       sqlite3AnalysisLoad(db, iDb);
00345     }
00346 #endif
00347   }
00348   if( db->mallocFailed ){
00349     rc = SQLITE_NOMEM;
00350     sqlite3ResetInternalSchema(db, 0);
00351   }
00352   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
00353     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
00354     ** the schema loaded, even if errors occured. In this situation the 
00355     ** current sqlite3_prepare() operation will fail, but the following one
00356     ** will attempt to compile the supplied statement against whatever subset
00357     ** of the schema was loaded before the error occured. The primary
00358     ** purpose of this is to allow access to the sqlite_master table
00359     ** even when its contents have been corrupted.
00360     */
00361     DbSetProperty(db, iDb, DB_SchemaLoaded);
00362     rc = SQLITE_OK;
00363   }
00364 
00365   /* Jump here for an error that occurs after successfully allocating
00366   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
00367   ** before that point, jump to error_out.
00368   */
00369 initone_error_out:
00370   sqlite3BtreeCloseCursor(curMain);
00371   sqlite3_free(curMain);
00372   sqlite3BtreeLeave(pDb->pBt);
00373 
00374 error_out:
00375   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
00376     db->mallocFailed = 1;
00377   }
00378   return rc;
00379 }
00380 
00381 /*
00382 ** Initialize all database files - the main database file, the file
00383 ** used to store temporary tables, and any additional database files
00384 ** created using ATTACH statements.  Return a success code.  If an
00385 ** error occurs, write an error message into *pzErrMsg.
00386 **
00387 ** After a database is initialized, the DB_SchemaLoaded bit is set
00388 ** bit is set in the flags field of the Db structure. If the database
00389 ** file was of zero-length, then the DB_Empty flag is also set.
00390 */
00391 int sqlite3Init(sqlite3 *db, char **pzErrMsg){
00392   int i, rc;
00393   int commit_internal = !(db->flags&SQLITE_InternChanges);
00394   
00395   assert( sqlite3_mutex_held(db->mutex) );
00396   if( db->init.busy ) return SQLITE_OK;
00397   rc = SQLITE_OK;
00398   db->init.busy = 1;
00399   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
00400     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
00401     rc = sqlite3InitOne(db, i, pzErrMsg);
00402     if( rc ){
00403       sqlite3ResetInternalSchema(db, i);
00404     }
00405   }
00406 
00407   /* Once all the other databases have been initialised, load the schema
00408   ** for the TEMP database. This is loaded last, as the TEMP database
00409   ** schema may contain references to objects in other databases.
00410   */
00411 #ifndef SQLITE_OMIT_TEMPDB
00412   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
00413     rc = sqlite3InitOne(db, 1, pzErrMsg);
00414     if( rc ){
00415       sqlite3ResetInternalSchema(db, 1);
00416     }
00417   }
00418 #endif
00419 
00420   db->init.busy = 0;
00421   if( rc==SQLITE_OK && commit_internal ){
00422     sqlite3CommitInternalChanges(db);
00423   }
00424 
00425   return rc; 
00426 }
00427 
00428 /*
00429 ** This routine is a no-op if the database schema is already initialised.
00430 ** Otherwise, the schema is loaded. An error code is returned.
00431 */
00432 int sqlite3ReadSchema(Parse *pParse){
00433   int rc = SQLITE_OK;
00434   sqlite3 *db = pParse->db;
00435   assert( sqlite3_mutex_held(db->mutex) );
00436   if( !db->init.busy ){
00437     rc = sqlite3Init(db, &pParse->zErrMsg);
00438   }
00439   if( rc!=SQLITE_OK ){
00440     pParse->rc = rc;
00441     pParse->nErr++;
00442   }
00443   return rc;
00444 }
00445 
00446 
00447 /*
00448 ** Check schema cookies in all databases.  If any cookie is out
00449 ** of date, return 0.  If all schema cookies are current, return 1.
00450 */
00451 static int schemaIsValid(sqlite3 *db){
00452   int iDb;
00453   int rc;
00454   BtCursor *curTemp;
00455   int cookie;
00456   int allOk = 1;
00457 
00458   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
00459   if( curTemp ){
00460     assert( sqlite3_mutex_held(db->mutex) );
00461     for(iDb=0; allOk && iDb<db->nDb; iDb++){
00462       Btree *pBt;
00463       pBt = db->aDb[iDb].pBt;
00464       if( pBt==0 ) continue;
00465       memset(curTemp, 0, sqlite3BtreeCursorSize());
00466       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
00467       if( rc==SQLITE_OK ){
00468         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
00469         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
00470           allOk = 0;
00471         }
00472         sqlite3BtreeCloseCursor(curTemp);
00473       }
00474       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
00475         db->mallocFailed = 1;
00476       }
00477     }
00478     sqlite3_free(curTemp);
00479   }else{
00480     allOk = 0;
00481     db->mallocFailed = 1;
00482   }
00483 
00484   return allOk;
00485 }
00486 
00487 /*
00488 ** Convert a schema pointer into the iDb index that indicates
00489 ** which database file in db->aDb[] the schema refers to.
00490 **
00491 ** If the same database is attached more than once, the first
00492 ** attached database is returned.
00493 */
00494 int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
00495   int i = -1000000;
00496 
00497   /* If pSchema is NULL, then return -1000000. This happens when code in 
00498   ** expr.c is trying to resolve a reference to a transient table (i.e. one
00499   ** created by a sub-select). In this case the return value of this 
00500   ** function should never be used.
00501   **
00502   ** We return -1000000 instead of the more usual -1 simply because using
00503   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
00504   ** more likely to cause a segfault than -1 (of course there are assert()
00505   ** statements too, but it never hurts to play the odds).
00506   */
00507   assert( sqlite3_mutex_held(db->mutex) );
00508   if( pSchema ){
00509     for(i=0; i<db->nDb; i++){
00510       if( db->aDb[i].pSchema==pSchema ){
00511         break;
00512       }
00513     }
00514     assert( i>=0 &&i>=0 &&  i<db->nDb );
00515   }
00516   return i;
00517 }
00518 
00519 /*
00520 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
00521 */
00522 static int sqlite3Prepare(
00523   sqlite3 *db,              /* Database handle. */
00524   const char *zSql,         /* UTF-8 encoded SQL statement. */
00525   int nBytes,               /* Length of zSql in bytes. */
00526   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
00527   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00528   const char **pzTail       /* OUT: End of parsed string */
00529 ){
00530   Parse sParse;
00531   char *zErrMsg = 0;
00532   int rc = SQLITE_OK;
00533   int i;
00534 
00535   assert( ppStmt );
00536   *ppStmt = 0;
00537   if( sqlite3SafetyOn(db) ){
00538     return SQLITE_MISUSE;
00539   }
00540   assert( !db->mallocFailed );
00541   assert( sqlite3_mutex_held(db->mutex) );
00542 
00543   /* If any attached database schemas are locked, do not proceed with
00544   ** compilation. Instead return SQLITE_LOCKED immediately.
00545   */
00546   for(i=0; i<db->nDb; i++) {
00547     Btree *pBt = db->aDb[i].pBt;
00548     if( pBt ){
00549       int rc;
00550       rc = sqlite3BtreeSchemaLocked(pBt);
00551       if( rc ){
00552         const char *zDb = db->aDb[i].zName;
00553         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
00554         (void)sqlite3SafetyOff(db);
00555         return sqlite3ApiExit(db, SQLITE_LOCKED);
00556       }
00557     }
00558   }
00559   
00560   memset(&sParse, 0, sizeof(sParse));
00561   sParse.db = db;
00562   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
00563     char *zSqlCopy;
00564     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
00565     if( nBytes>mxLen ){
00566       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
00567       (void)sqlite3SafetyOff(db);
00568       return sqlite3ApiExit(db, SQLITE_TOOBIG);
00569     }
00570     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
00571     if( zSqlCopy ){
00572       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
00573       sqlite3DbFree(db, zSqlCopy);
00574       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
00575     }else{
00576       sParse.zTail = &zSql[nBytes];
00577     }
00578   }else{
00579     sqlite3RunParser(&sParse, zSql, &zErrMsg);
00580   }
00581 
00582   if( db->mallocFailed ){
00583     sParse.rc = SQLITE_NOMEM;
00584   }
00585   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
00586   if( sParse.checkSchema && !schemaIsValid(db) ){
00587     sParse.rc = SQLITE_SCHEMA;
00588   }
00589   if( sParse.rc==SQLITE_SCHEMA ){
00590     sqlite3ResetInternalSchema(db, 0);
00591   }
00592   if( db->mallocFailed ){
00593     sParse.rc = SQLITE_NOMEM;
00594   }
00595   if( pzTail ){
00596     *pzTail = sParse.zTail;
00597   }
00598   rc = sParse.rc;
00599 
00600 #ifndef SQLITE_OMIT_EXPLAIN
00601   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
00602     if( sParse.explain==2 ){
00603       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
00604       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", SQLITE_STATIC);
00605       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", SQLITE_STATIC);
00606       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", SQLITE_STATIC);
00607     }else{
00608       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
00609       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", SQLITE_STATIC);
00610       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", SQLITE_STATIC);
00611       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", SQLITE_STATIC);
00612       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", SQLITE_STATIC);
00613       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", SQLITE_STATIC);
00614       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", SQLITE_STATIC);
00615       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", SQLITE_STATIC);
00616       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment", SQLITE_STATIC);
00617     }
00618   }
00619 #endif
00620 
00621   if( sqlite3SafetyOff(db) ){
00622     rc = SQLITE_MISUSE;
00623   }
00624 
00625   if( saveSqlFlag ){
00626     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
00627   }
00628   if( rc!=SQLITE_OK || db->mallocFailed ){
00629     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
00630     assert(!(*ppStmt));
00631   }else{
00632     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
00633   }
00634 
00635   if( zErrMsg ){
00636     sqlite3Error(db, rc, "%s", zErrMsg);
00637     sqlite3DbFree(db, zErrMsg);
00638   }else{
00639     sqlite3Error(db, rc, 0);
00640   }
00641 
00642   rc = sqlite3ApiExit(db, rc);
00643   assert( (rc&db->errMask)==rc );
00644   return rc;
00645 }
00646 static int sqlite3LockAndPrepare(
00647   sqlite3 *db,              /* Database handle. */
00648   const char *zSql,         /* UTF-8 encoded SQL statement. */
00649   int nBytes,               /* Length of zSql in bytes. */
00650   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
00651   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00652   const char **pzTail       /* OUT: End of parsed string */
00653 ){
00654   int rc;
00655   if( !sqlite3SafetyCheckOk(db) ){
00656     return SQLITE_MISUSE;
00657   }
00658   sqlite3_mutex_enter(db->mutex);
00659   sqlite3BtreeEnterAll(db);
00660   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
00661   sqlite3BtreeLeaveAll(db);
00662   sqlite3_mutex_leave(db->mutex);
00663   return rc;
00664 }
00665 
00666 /*
00667 ** Rerun the compilation of a statement after a schema change.
00668 ** Return true if the statement was recompiled successfully.
00669 ** Return false if there is an error of some kind.
00670 */
00671 int sqlite3Reprepare(Vdbe *p){
00672   int rc;
00673   sqlite3_stmt *pNew;
00674   const char *zSql;
00675   sqlite3 *db;
00676 
00677   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
00678   zSql = sqlite3_sql((sqlite3_stmt *)p);
00679   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
00680   db = sqlite3VdbeDb(p);
00681   assert( sqlite3_mutex_held(db->mutex) );
00682   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
00683   if( rc ){
00684     if( rc==SQLITE_NOMEM ){
00685       db->mallocFailed = 1;
00686     }
00687     assert( pNew==0 );
00688     return 0;
00689   }else{
00690     assert( pNew!=0 );
00691   }
00692   sqlite3VdbeSwap((Vdbe*)pNew, p);
00693   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
00694   sqlite3VdbeResetStepResult((Vdbe*)pNew);
00695   sqlite3VdbeFinalize((Vdbe*)pNew);
00696   return 1;
00697 }
00698 
00699 
00700 /*
00701 ** Two versions of the official API.  Legacy and new use.  In the legacy
00702 ** version, the original SQL text is not saved in the prepared statement
00703 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
00704 ** sqlite3_step().  In the new version, the original SQL text is retained
00705 ** and the statement is automatically recompiled if an schema change
00706 ** occurs.
00707 */
00708 int sqlite3_prepare(
00709   sqlite3 *db,              /* Database handle. */
00710   const char *zSql,         /* UTF-8 encoded SQL statement. */
00711   int nBytes,               /* Length of zSql in bytes. */
00712   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00713   const char **pzTail       /* OUT: End of parsed string */
00714 ){
00715   int rc;
00716   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
00717   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
00718   return rc;
00719 }
00720 int sqlite3_prepare_v2(
00721   sqlite3 *db,              /* Database handle. */
00722   const char *zSql,         /* UTF-8 encoded SQL statement. */
00723   int nBytes,               /* Length of zSql in bytes. */
00724   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00725   const char **pzTail       /* OUT: End of parsed string */
00726 ){
00727   int rc;
00728   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
00729   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
00730   return rc;
00731 }
00732 
00733 
00734 #ifndef SQLITE_OMIT_UTF16
00735 /*
00736 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
00737 */
00738 static int sqlite3Prepare16(
00739   sqlite3 *db,              /* Database handle. */ 
00740   const void *zSql,         /* UTF-8 encoded SQL statement. */
00741   int nBytes,               /* Length of zSql in bytes. */
00742   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
00743   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00744   const void **pzTail       /* OUT: End of parsed string */
00745 ){
00746   /* This function currently works by first transforming the UTF-16
00747   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
00748   ** tricky bit is figuring out the pointer to return in *pzTail.
00749   */
00750   char *zSql8;
00751   const char *zTail8 = 0;
00752   int rc = SQLITE_OK;
00753 
00754   if( !sqlite3SafetyCheckOk(db) ){
00755     return SQLITE_MISUSE;
00756   }
00757   sqlite3_mutex_enter(db->mutex);
00758   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
00759   if( zSql8 ){
00760     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
00761   }
00762 
00763   if( zTail8 && pzTail ){
00764     /* If sqlite3_prepare returns a tail pointer, we calculate the
00765     ** equivalent pointer into the UTF-16 string by counting the unicode
00766     ** characters between zSql8 and zTail8, and then returning a pointer
00767     ** the same number of characters into the UTF-16 string.
00768     */
00769     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
00770     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
00771   }
00772   sqlite3DbFree(db, zSql8); 
00773   rc = sqlite3ApiExit(db, rc);
00774   sqlite3_mutex_leave(db->mutex);
00775   return rc;
00776 }
00777 
00778 /*
00779 ** Two versions of the official API.  Legacy and new use.  In the legacy
00780 ** version, the original SQL text is not saved in the prepared statement
00781 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
00782 ** sqlite3_step().  In the new version, the original SQL text is retained
00783 ** and the statement is automatically recompiled if an schema change
00784 ** occurs.
00785 */
00786 int sqlite3_prepare16(
00787   sqlite3 *db,              /* Database handle. */ 
00788   const void *zSql,         /* UTF-8 encoded SQL statement. */
00789   int nBytes,               /* Length of zSql in bytes. */
00790   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00791   const void **pzTail       /* OUT: End of parsed string */
00792 ){
00793   int rc;
00794   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
00795   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
00796   return rc;
00797 }
00798 int sqlite3_prepare16_v2(
00799   sqlite3 *db,              /* Database handle. */ 
00800   const void *zSql,         /* UTF-8 encoded SQL statement. */
00801   int nBytes,               /* Length of zSql in bytes. */
00802   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
00803   const void **pzTail       /* OUT: End of parsed string */
00804 ){
00805   int rc;
00806   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
00807   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
00808   return rc;
00809 }
00810 
00811 #endif /* SQLITE_OMIT_UTF16 */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:55 2011 by Doxygen 1.6.1