000001  /*
000002  ** 2005 May 25
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains the implementation of the sqlite3_prepare()
000013  ** interface, and routines that contribute to loading the database schema
000014  ** from disk.
000015  */
000016  #include "sqliteInt.h"
000017  
000018  /*
000019  ** Fill the InitData structure with an error message that indicates
000020  ** that the database is corrupt.
000021  */
000022  static void corruptSchema(
000023    InitData *pData,     /* Initialization context */
000024    char **azObj,        /* Type and name of object being parsed */
000025    const char *zExtra   /* Error information */
000026  ){
000027    sqlite3 *db = pData->db;
000028    if( db->mallocFailed ){
000029      pData->rc = SQLITE_NOMEM_BKPT;
000030    }else if( pData->pzErrMsg[0]!=0 ){
000031      /* A error message has already been generated.  Do not overwrite it */
000032    }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
000033      static const char *azAlterType[] = {
000034         "rename",
000035         "drop column",
000036         "add column"
000037      };
000038      *pData->pzErrMsg = sqlite3MPrintf(db, 
000039          "error in %s %s after %s: %s", azObj[0], azObj[1], 
000040          azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1], 
000041          zExtra
000042      );
000043      pData->rc = SQLITE_ERROR;
000044    }else if( db->flags & SQLITE_WriteSchema ){
000045      pData->rc = SQLITE_CORRUPT_BKPT;
000046    }else{
000047      char *z;
000048      const char *zObj = azObj[1] ? azObj[1] : "?";
000049      z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
000050      if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
000051      *pData->pzErrMsg = z;
000052      pData->rc = SQLITE_CORRUPT_BKPT;
000053    }
000054  }
000055  
000056  /*
000057  ** Check to see if any sibling index (another index on the same table)
000058  ** of pIndex has the same root page number, and if it does, return true.
000059  ** This would indicate a corrupt schema.
000060  */
000061  int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
000062    Index *p;
000063    for(p=pIndex->pTable->pIndex; p; p=p->pNext){
000064      if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
000065    }
000066    return 0;
000067  }
000068  
000069  /* forward declaration */
000070  static int sqlite3Prepare(
000071    sqlite3 *db,              /* Database handle. */
000072    const char *zSql,         /* UTF-8 encoded SQL statement. */
000073    int nBytes,               /* Length of zSql in bytes. */
000074    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000075    Vdbe *pReprepare,         /* VM being reprepared */
000076    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000077    const char **pzTail       /* OUT: End of parsed string */
000078  );
000079  
000080  
000081  /*
000082  ** This is the callback routine for the code that initializes the
000083  ** database.  See sqlite3Init() below for additional information.
000084  ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
000085  **
000086  ** Each callback contains the following information:
000087  **
000088  **     argv[0] = type of object: "table", "index", "trigger", or "view".
000089  **     argv[1] = name of thing being created
000090  **     argv[2] = associated table if an index or trigger
000091  **     argv[3] = root page number for table or index. 0 for trigger or view.
000092  **     argv[4] = SQL text for the CREATE statement.
000093  **
000094  */
000095  int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
000096    InitData *pData = (InitData*)pInit;
000097    sqlite3 *db = pData->db;
000098    int iDb = pData->iDb;
000099  
000100    assert( argc==5 );
000101    UNUSED_PARAMETER2(NotUsed, argc);
000102    assert( sqlite3_mutex_held(db->mutex) );
000103    db->mDbFlags |= DBFLAG_EncodingFixed;
000104    if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
000105    pData->nInitRow++;
000106    if( db->mallocFailed ){
000107      corruptSchema(pData, argv, 0);
000108      return 1;
000109    }
000110  
000111    assert( iDb>=0 && iDb<db->nDb );
000112    if( argv[3]==0 ){
000113      corruptSchema(pData, argv, 0);
000114    }else if( argv[4]
000115           && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
000116           && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
000117      /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
000118      ** But because db->init.busy is set to 1, no VDBE code is generated
000119      ** or executed.  All the parser does is build the internal data
000120      ** structures that describe the table, index, or view.
000121      **
000122      ** No other valid SQL statement, other than the variable CREATE statements,
000123      ** can begin with the letters "C" and "R".  Thus, it is not possible run
000124      ** any other kind of statement while parsing the schema, even a corrupt
000125      ** schema.
000126      */
000127      int rc;
000128      u8 saved_iDb = db->init.iDb;
000129      sqlite3_stmt *pStmt;
000130      TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
000131  
000132      assert( db->init.busy );
000133      db->init.iDb = iDb;
000134      if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
000135       || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
000136      ){
000137        if( sqlite3Config.bExtraSchemaChecks ){
000138          corruptSchema(pData, argv, "invalid rootpage");
000139        }
000140      }
000141      db->init.orphanTrigger = 0;
000142      db->init.azInit = (const char**)argv;
000143      pStmt = 0;
000144      TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
000145      rc = db->errCode;
000146      assert( (rc&0xFF)==(rcp&0xFF) );
000147      db->init.iDb = saved_iDb;
000148      /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
000149      if( SQLITE_OK!=rc ){
000150        if( db->init.orphanTrigger ){
000151          assert( iDb==1 );
000152        }else{
000153          if( rc > pData->rc ) pData->rc = rc;
000154          if( rc==SQLITE_NOMEM ){
000155            sqlite3OomFault(db);
000156          }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
000157            corruptSchema(pData, argv, sqlite3_errmsg(db));
000158          }
000159        }
000160      }
000161      db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
000162      sqlite3_finalize(pStmt);
000163    }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
000164      corruptSchema(pData, argv, 0);
000165    }else{
000166      /* If the SQL column is blank it means this is an index that
000167      ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
000168      ** constraint for a CREATE TABLE.  The index should have already
000169      ** been created when we processed the CREATE TABLE.  All we have
000170      ** to do here is record the root page number for that index.
000171      */
000172      Index *pIndex;
000173      pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
000174      if( pIndex==0 ){
000175        corruptSchema(pData, argv, "orphan index");
000176      }else
000177      if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
000178       || pIndex->tnum<2
000179       || pIndex->tnum>pData->mxPage
000180       || sqlite3IndexHasDuplicateRootPage(pIndex)
000181      ){
000182        if( sqlite3Config.bExtraSchemaChecks ){
000183          corruptSchema(pData, argv, "invalid rootpage");
000184        }
000185      }
000186    }
000187    return 0;
000188  }
000189  
000190  /*
000191  ** Attempt to read the database schema and initialize internal
000192  ** data structures for a single database file.  The index of the
000193  ** database file is given by iDb.  iDb==0 is used for the main
000194  ** database.  iDb==1 should never be used.  iDb>=2 is used for
000195  ** auxiliary databases.  Return one of the SQLITE_ error codes to
000196  ** indicate success or failure.
000197  */
000198  int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
000199    int rc;
000200    int i;
000201  #ifndef SQLITE_OMIT_DEPRECATED
000202    int size;
000203  #endif
000204    Db *pDb;
000205    char const *azArg[6];
000206    int meta[5];
000207    InitData initData;
000208    const char *zSchemaTabName;
000209    int openedTransaction = 0;
000210    int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
000211  
000212    assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
000213    assert( iDb>=0 && iDb<db->nDb );
000214    assert( db->aDb[iDb].pSchema );
000215    assert( sqlite3_mutex_held(db->mutex) );
000216    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
000217  
000218    db->init.busy = 1;
000219  
000220    /* Construct the in-memory representation schema tables (sqlite_schema or
000221    ** sqlite_temp_schema) by invoking the parser directly.  The appropriate
000222    ** table name will be inserted automatically by the parser so we can just
000223    ** use the abbreviation "x" here.  The parser will also automatically tag
000224    ** the schema table as read-only. */
000225    azArg[0] = "table";
000226    azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
000227    azArg[2] = azArg[1];
000228    azArg[3] = "1";
000229    azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
000230                              "rootpage int,sql text)";
000231    azArg[5] = 0;
000232    initData.db = db;
000233    initData.iDb = iDb;
000234    initData.rc = SQLITE_OK;
000235    initData.pzErrMsg = pzErrMsg;
000236    initData.mInitFlags = mFlags;
000237    initData.nInitRow = 0;
000238    initData.mxPage = 0;
000239    sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
000240    db->mDbFlags &= mask;
000241    if( initData.rc ){
000242      rc = initData.rc;
000243      goto error_out;
000244    }
000245  
000246    /* Create a cursor to hold the database open
000247    */
000248    pDb = &db->aDb[iDb];
000249    if( pDb->pBt==0 ){
000250      assert( iDb==1 );
000251      DbSetProperty(db, 1, DB_SchemaLoaded);
000252      rc = SQLITE_OK;
000253      goto error_out;
000254    }
000255  
000256    /* If there is not already a read-only (or read-write) transaction opened
000257    ** on the b-tree database, open one now. If a transaction is opened, it 
000258    ** will be closed before this function returns.  */
000259    sqlite3BtreeEnter(pDb->pBt);
000260    if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
000261      rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
000262      if( rc!=SQLITE_OK ){
000263        sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
000264        goto initone_error_out;
000265      }
000266      openedTransaction = 1;
000267    }
000268  
000269    /* Get the database meta information.
000270    **
000271    ** Meta values are as follows:
000272    **    meta[0]   Schema cookie.  Changes with each schema change.
000273    **    meta[1]   File format of schema layer.
000274    **    meta[2]   Size of the page cache.
000275    **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
000276    **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
000277    **    meta[5]   User version
000278    **    meta[6]   Incremental vacuum mode
000279    **    meta[7]   unused
000280    **    meta[8]   unused
000281    **    meta[9]   unused
000282    **
000283    ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
000284    ** the possible values of meta[4].
000285    */
000286    for(i=0; i<ArraySize(meta); i++){
000287      sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
000288    }
000289    if( (db->flags & SQLITE_ResetDatabase)!=0 ){
000290      memset(meta, 0, sizeof(meta));
000291    }
000292    pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
000293  
000294    /* If opening a non-empty database, check the text encoding. For the
000295    ** main database, set sqlite3.enc to the encoding of the main database.
000296    ** For an attached db, it is an error if the encoding is not the same
000297    ** as sqlite3.enc.
000298    */
000299    if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
000300      if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
000301        u8 encoding;
000302  #ifndef SQLITE_OMIT_UTF16
000303        /* If opening the main database, set ENC(db). */
000304        encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
000305        if( encoding==0 ) encoding = SQLITE_UTF8;
000306  #else
000307        encoding = SQLITE_UTF8;
000308  #endif
000309        if( db->nVdbeActive>0 && encoding!=ENC(db)
000310         && (db->mDbFlags & DBFLAG_Vacuum)==0
000311        ){
000312          rc = SQLITE_LOCKED;
000313          goto initone_error_out;
000314        }else{
000315          sqlite3SetTextEncoding(db, encoding);
000316        }
000317      }else{
000318        /* If opening an attached database, the encoding much match ENC(db) */
000319        if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
000320          sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
000321              " text encoding as main database");
000322          rc = SQLITE_ERROR;
000323          goto initone_error_out;
000324        }
000325      }
000326    }
000327    pDb->pSchema->enc = ENC(db);
000328  
000329    if( pDb->pSchema->cache_size==0 ){
000330  #ifndef SQLITE_OMIT_DEPRECATED
000331      size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
000332      if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
000333      pDb->pSchema->cache_size = size;
000334  #else
000335      pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
000336  #endif
000337      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
000338    }
000339  
000340    /*
000341    ** file_format==1    Version 3.0.0.
000342    ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
000343    ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
000344    ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
000345    */
000346    pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
000347    if( pDb->pSchema->file_format==0 ){
000348      pDb->pSchema->file_format = 1;
000349    }
000350    if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
000351      sqlite3SetString(pzErrMsg, db, "unsupported file format");
000352      rc = SQLITE_ERROR;
000353      goto initone_error_out;
000354    }
000355  
000356    /* Ticket #2804:  When we open a database in the newer file format,
000357    ** clear the legacy_file_format pragma flag so that a VACUUM will
000358    ** not downgrade the database and thus invalidate any descending
000359    ** indices that the user might have created.
000360    */
000361    if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
000362      db->flags &= ~(u64)SQLITE_LegacyFileFmt;
000363    }
000364  
000365    /* Read the schema information out of the schema tables
000366    */
000367    assert( db->init.busy );
000368    initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
000369    {
000370      char *zSql;
000371      zSql = sqlite3MPrintf(db, 
000372          "SELECT*FROM\"%w\".%s ORDER BY rowid",
000373          db->aDb[iDb].zDbSName, zSchemaTabName);
000374  #ifndef SQLITE_OMIT_AUTHORIZATION
000375      {
000376        sqlite3_xauth xAuth;
000377        xAuth = db->xAuth;
000378        db->xAuth = 0;
000379  #endif
000380        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
000381  #ifndef SQLITE_OMIT_AUTHORIZATION
000382        db->xAuth = xAuth;
000383      }
000384  #endif
000385      if( rc==SQLITE_OK ) rc = initData.rc;
000386      sqlite3DbFree(db, zSql);
000387  #ifndef SQLITE_OMIT_ANALYZE
000388      if( rc==SQLITE_OK ){
000389        sqlite3AnalysisLoad(db, iDb);
000390      }
000391  #endif
000392    }
000393    assert( pDb == &(db->aDb[iDb]) );
000394    if( db->mallocFailed ){
000395      rc = SQLITE_NOMEM_BKPT;
000396      sqlite3ResetAllSchemasOfConnection(db);
000397      pDb = &db->aDb[iDb];
000398    }else
000399    if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
000400      /* Hack: If the SQLITE_NoSchemaError flag is set, then consider
000401      ** the schema loaded, even if errors (other than OOM) occurred. In
000402      ** this situation the current sqlite3_prepare() operation will fail,
000403      ** but the following one will attempt to compile the supplied statement
000404      ** against whatever subset of the schema was loaded before the error
000405      ** occurred.
000406      **
000407      ** The primary purpose of this is to allow access to the sqlite_schema
000408      ** table even when its contents have been corrupted.
000409      */
000410      DbSetProperty(db, iDb, DB_SchemaLoaded);
000411      rc = SQLITE_OK;
000412    }
000413  
000414    /* Jump here for an error that occurs after successfully allocating
000415    ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
000416    ** before that point, jump to error_out.
000417    */
000418  initone_error_out:
000419    if( openedTransaction ){
000420      sqlite3BtreeCommit(pDb->pBt);
000421    }
000422    sqlite3BtreeLeave(pDb->pBt);
000423  
000424  error_out:
000425    if( rc ){
000426      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
000427        sqlite3OomFault(db);
000428      }
000429      sqlite3ResetOneSchema(db, iDb);
000430    }
000431    db->init.busy = 0;
000432    return rc;
000433  }
000434  
000435  /*
000436  ** Initialize all database files - the main database file, the file
000437  ** used to store temporary tables, and any additional database files
000438  ** created using ATTACH statements.  Return a success code.  If an
000439  ** error occurs, write an error message into *pzErrMsg.
000440  **
000441  ** After a database is initialized, the DB_SchemaLoaded bit is set
000442  ** bit is set in the flags field of the Db structure. 
000443  */
000444  int sqlite3Init(sqlite3 *db, char **pzErrMsg){
000445    int i, rc;
000446    int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
000447    
000448    assert( sqlite3_mutex_held(db->mutex) );
000449    assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
000450    assert( db->init.busy==0 );
000451    ENC(db) = SCHEMA_ENC(db);
000452    assert( db->nDb>0 );
000453    /* Do the main schema first */
000454    if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
000455      rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
000456      if( rc ) return rc;
000457    }
000458    /* All other schemas after the main schema. The "temp" schema must be last */
000459    for(i=db->nDb-1; i>0; i--){
000460      assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
000461      if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
000462        rc = sqlite3InitOne(db, i, pzErrMsg, 0);
000463        if( rc ) return rc;
000464      }
000465    }
000466    if( commit_internal ){
000467      sqlite3CommitInternalChanges(db);
000468    }
000469    return SQLITE_OK;
000470  }
000471  
000472  /*
000473  ** This routine is a no-op if the database schema is already initialized.
000474  ** Otherwise, the schema is loaded. An error code is returned.
000475  */
000476  int sqlite3ReadSchema(Parse *pParse){
000477    int rc = SQLITE_OK;
000478    sqlite3 *db = pParse->db;
000479    assert( sqlite3_mutex_held(db->mutex) );
000480    if( !db->init.busy ){
000481      rc = sqlite3Init(db, &pParse->zErrMsg);
000482      if( rc!=SQLITE_OK ){
000483        pParse->rc = rc;
000484        pParse->nErr++;
000485      }else if( db->noSharedCache ){
000486        db->mDbFlags |= DBFLAG_SchemaKnownOk;
000487      }
000488    }
000489    return rc;
000490  }
000491  
000492  
000493  /*
000494  ** Check schema cookies in all databases.  If any cookie is out
000495  ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
000496  ** make no changes to pParse->rc.
000497  */
000498  static void schemaIsValid(Parse *pParse){
000499    sqlite3 *db = pParse->db;
000500    int iDb;
000501    int rc;
000502    int cookie;
000503  
000504    assert( pParse->checkSchema );
000505    assert( sqlite3_mutex_held(db->mutex) );
000506    for(iDb=0; iDb<db->nDb; iDb++){
000507      int openedTransaction = 0;         /* True if a transaction is opened */
000508      Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
000509      if( pBt==0 ) continue;
000510  
000511      /* If there is not already a read-only (or read-write) transaction opened
000512      ** on the b-tree database, open one now. If a transaction is opened, it 
000513      ** will be closed immediately after reading the meta-value. */
000514      if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
000515        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
000516        if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
000517          sqlite3OomFault(db);
000518          pParse->rc = SQLITE_NOMEM;
000519        }
000520        if( rc!=SQLITE_OK ) return;
000521        openedTransaction = 1;
000522      }
000523  
000524      /* Read the schema cookie from the database. If it does not match the 
000525      ** value stored as part of the in-memory schema representation,
000526      ** set Parse.rc to SQLITE_SCHEMA. */
000527      sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
000528      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
000529      if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
000530        if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
000531        sqlite3ResetOneSchema(db, iDb);
000532      }
000533  
000534      /* Close the transaction, if one was opened. */
000535      if( openedTransaction ){
000536        sqlite3BtreeCommit(pBt);
000537      }
000538    }
000539  }
000540  
000541  /*
000542  ** Convert a schema pointer into the iDb index that indicates
000543  ** which database file in db->aDb[] the schema refers to.
000544  **
000545  ** If the same database is attached more than once, the first
000546  ** attached database is returned.
000547  */
000548  int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
000549    int i = -32768;
000550  
000551    /* If pSchema is NULL, then return -32768. This happens when code in 
000552    ** expr.c is trying to resolve a reference to a transient table (i.e. one
000553    ** created by a sub-select). In this case the return value of this 
000554    ** function should never be used.
000555    **
000556    ** We return -32768 instead of the more usual -1 simply because using
000557    ** -32768 as the incorrect index into db->aDb[] is much 
000558    ** more likely to cause a segfault than -1 (of course there are assert()
000559    ** statements too, but it never hurts to play the odds) and
000560    ** -32768 will still fit into a 16-bit signed integer.
000561    */
000562    assert( sqlite3_mutex_held(db->mutex) );
000563    if( pSchema ){
000564      for(i=0; 1; i++){
000565        assert( i<db->nDb );
000566        if( db->aDb[i].pSchema==pSchema ){
000567          break;
000568        }
000569      }
000570      assert( i>=0 && i<db->nDb );
000571    }
000572    return i;
000573  }
000574  
000575  /*
000576  ** Free all memory allocations in the pParse object
000577  */
000578  void sqlite3ParseObjectReset(Parse *pParse){
000579    sqlite3 *db = pParse->db;
000580    assert( db!=0 );
000581    assert( db->pParse==pParse );
000582    assert( pParse->nested==0 );
000583  #ifndef SQLITE_OMIT_SHARED_CACHE
000584    if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
000585  #endif
000586    while( pParse->pCleanup ){
000587      ParseCleanup *pCleanup = pParse->pCleanup;
000588      pParse->pCleanup = pCleanup->pNext;
000589      pCleanup->xCleanup(db, pCleanup->pPtr);
000590      sqlite3DbNNFreeNN(db, pCleanup);
000591    }
000592    if( pParse->aLabel ) sqlite3DbNNFreeNN(db, pParse->aLabel);
000593    if( pParse->pConstExpr ){
000594      sqlite3ExprListDelete(db, pParse->pConstExpr);
000595    }
000596    assert( db->lookaside.bDisable >= pParse->disableLookaside );
000597    db->lookaside.bDisable -= pParse->disableLookaside;
000598    db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
000599    assert( pParse->db->pParse==pParse );
000600    db->pParse = pParse->pOuterParse;
000601  }
000602  
000603  /*
000604  ** Add a new cleanup operation to a Parser.  The cleanup should happen when
000605  ** the parser object is destroyed.  But, beware: the cleanup might happen
000606  ** immediately.
000607  **
000608  ** Use this mechanism for uncommon cleanups.  There is a higher setup
000609  ** cost for this mechanism (an extra malloc), so it should not be used
000610  ** for common cleanups that happen on most calls.  But for less
000611  ** common cleanups, we save a single NULL-pointer comparison in
000612  ** sqlite3ParseObjectReset(), which reduces the total CPU cycle count.
000613  **
000614  ** If a memory allocation error occurs, then the cleanup happens immediately.
000615  ** When either SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the
000616  ** pParse->earlyCleanup flag is set in that case.  Calling code show verify
000617  ** that test cases exist for which this happens, to guard against possible
000618  ** use-after-free errors following an OOM.  The preferred way to do this is
000619  ** to immediately follow the call to this routine with:
000620  **
000621  **       testcase( pParse->earlyCleanup );
000622  **
000623  ** This routine returns a copy of its pPtr input (the third parameter)
000624  ** except if an early cleanup occurs, in which case it returns NULL.  So
000625  ** another way to check for early cleanup is to check the return value.
000626  ** Or, stop using the pPtr parameter with this call and use only its
000627  ** return value thereafter.  Something like this:
000628  **
000629  **       pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
000630  */
000631  void *sqlite3ParserAddCleanup(
000632    Parse *pParse,                      /* Destroy when this Parser finishes */
000633    void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
000634    void *pPtr                          /* Pointer to object to be cleaned up */
000635  ){
000636    ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
000637    if( pCleanup ){
000638      pCleanup->pNext = pParse->pCleanup;
000639      pParse->pCleanup = pCleanup;
000640      pCleanup->pPtr = pPtr;
000641      pCleanup->xCleanup = xCleanup;
000642    }else{
000643      xCleanup(pParse->db, pPtr);
000644      pPtr = 0;
000645  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
000646      pParse->earlyCleanup = 1;
000647  #endif
000648    }
000649    return pPtr;
000650  }
000651  
000652  /*
000653  ** Turn bulk memory into a valid Parse object and link that Parse object
000654  ** into database connection db.
000655  **
000656  ** Call sqlite3ParseObjectReset() to undo this operation.
000657  **
000658  ** Caution:  Do not confuse this routine with sqlite3ParseObjectInit() which
000659  ** is generated by Lemon.
000660  */
000661  void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
000662    memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
000663    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
000664    assert( db->pParse!=pParse );
000665    pParse->pOuterParse = db->pParse;
000666    db->pParse = pParse;
000667    pParse->db = db;
000668    if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
000669  }
000670  
000671  /*
000672  ** Maximum number of times that we will try again to prepare a statement
000673  ** that returns SQLITE_ERROR_RETRY.
000674  */
000675  #ifndef SQLITE_MAX_PREPARE_RETRY
000676  # define SQLITE_MAX_PREPARE_RETRY 25
000677  #endif
000678  
000679  /*
000680  ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
000681  */
000682  static int sqlite3Prepare(
000683    sqlite3 *db,              /* Database handle. */
000684    const char *zSql,         /* UTF-8 encoded SQL statement. */
000685    int nBytes,               /* Length of zSql in bytes. */
000686    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000687    Vdbe *pReprepare,         /* VM being reprepared */
000688    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000689    const char **pzTail       /* OUT: End of parsed string */
000690  ){
000691    int rc = SQLITE_OK;       /* Result code */
000692    int i;                    /* Loop counter */
000693    Parse sParse;             /* Parsing context */
000694  
000695    /* sqlite3ParseObjectInit(&sParse, db); // inlined for performance */
000696    memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
000697    memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
000698    sParse.pOuterParse = db->pParse;
000699    db->pParse = &sParse;
000700    sParse.db = db;
000701    if( pReprepare ){
000702      sParse.pReprepare = pReprepare;
000703      sParse.explain = sqlite3_stmt_isexplain((sqlite3_stmt*)pReprepare);
000704    }else{
000705      assert( sParse.pReprepare==0 );
000706    }
000707    assert( ppStmt && *ppStmt==0 );
000708    if( db->mallocFailed ){
000709      sqlite3ErrorMsg(&sParse, "out of memory");
000710      db->errCode = rc = SQLITE_NOMEM;
000711      goto end_prepare;
000712    }
000713    assert( sqlite3_mutex_held(db->mutex) );
000714  
000715    /* For a long-term use prepared statement avoid the use of
000716    ** lookaside memory.
000717    */
000718    if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
000719      sParse.disableLookaside++;
000720      DisableLookaside;
000721    }
000722    sParse.prepFlags = prepFlags & 0xff;
000723  
000724    /* Check to verify that it is possible to get a read lock on all
000725    ** database schemas.  The inability to get a read lock indicates that
000726    ** some other database connection is holding a write-lock, which in
000727    ** turn means that the other connection has made uncommitted changes
000728    ** to the schema.
000729    **
000730    ** Were we to proceed and prepare the statement against the uncommitted
000731    ** schema changes and if those schema changes are subsequently rolled
000732    ** back and different changes are made in their place, then when this
000733    ** prepared statement goes to run the schema cookie would fail to detect
000734    ** the schema change.  Disaster would follow.
000735    **
000736    ** This thread is currently holding mutexes on all Btrees (because
000737    ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
000738    ** is not possible for another thread to start a new schema change
000739    ** while this routine is running.  Hence, we do not need to hold 
000740    ** locks on the schema, we just need to make sure nobody else is 
000741    ** holding them.
000742    **
000743    ** Note that setting READ_UNCOMMITTED overrides most lock detection,
000744    ** but it does *not* override schema lock detection, so this all still
000745    ** works even if READ_UNCOMMITTED is set.
000746    */
000747    if( !db->noSharedCache ){
000748      for(i=0; i<db->nDb; i++) {
000749        Btree *pBt = db->aDb[i].pBt;
000750        if( pBt ){
000751          assert( sqlite3BtreeHoldsMutex(pBt) );
000752          rc = sqlite3BtreeSchemaLocked(pBt);
000753          if( rc ){
000754            const char *zDb = db->aDb[i].zDbSName;
000755            sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
000756            testcase( db->flags & SQLITE_ReadUncommit );
000757            goto end_prepare;
000758          }
000759        }
000760      }
000761    }
000762  
000763  #ifndef SQLITE_OMIT_VIRTUALTABLE
000764    if( db->pDisconnect ) sqlite3VtabUnlockList(db);
000765  #endif
000766  
000767    if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
000768      char *zSqlCopy;
000769      int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
000770      testcase( nBytes==mxLen );
000771      testcase( nBytes==mxLen+1 );
000772      if( nBytes>mxLen ){
000773        sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
000774        rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
000775        goto end_prepare;
000776      }
000777      zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
000778      if( zSqlCopy ){
000779        sqlite3RunParser(&sParse, zSqlCopy);
000780        sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
000781        sqlite3DbFree(db, zSqlCopy);
000782      }else{
000783        sParse.zTail = &zSql[nBytes];
000784      }
000785    }else{
000786      sqlite3RunParser(&sParse, zSql);
000787    }
000788    assert( 0==sParse.nQueryLoop );
000789  
000790    if( pzTail ){
000791      *pzTail = sParse.zTail;
000792    }
000793  
000794    if( db->init.busy==0 ){
000795      sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
000796    }
000797    if( db->mallocFailed ){
000798      sParse.rc = SQLITE_NOMEM_BKPT;
000799      sParse.checkSchema = 0;
000800    }
000801    if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
000802      if( sParse.checkSchema && db->init.busy==0 ){
000803        schemaIsValid(&sParse);
000804      }
000805      if( sParse.pVdbe ){
000806        sqlite3VdbeFinalize(sParse.pVdbe);
000807      }
000808      assert( 0==(*ppStmt) );
000809      rc = sParse.rc;
000810      if( sParse.zErrMsg ){
000811        sqlite3ErrorWithMsg(db, rc, "%s", sParse.zErrMsg);
000812        sqlite3DbFree(db, sParse.zErrMsg);
000813      }else{
000814        sqlite3Error(db, rc);
000815      }
000816    }else{
000817      assert( sParse.zErrMsg==0 );
000818      *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
000819      rc = SQLITE_OK;
000820      sqlite3ErrorClear(db);
000821    }
000822  
000823  
000824    /* Delete any TriggerPrg structures allocated while parsing this statement. */
000825    while( sParse.pTriggerPrg ){
000826      TriggerPrg *pT = sParse.pTriggerPrg;
000827      sParse.pTriggerPrg = pT->pNext;
000828      sqlite3DbFree(db, pT);
000829    }
000830  
000831  end_prepare:
000832  
000833    sqlite3ParseObjectReset(&sParse);
000834    return rc;
000835  }
000836  static int sqlite3LockAndPrepare(
000837    sqlite3 *db,              /* Database handle. */
000838    const char *zSql,         /* UTF-8 encoded SQL statement. */
000839    int nBytes,               /* Length of zSql in bytes. */
000840    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000841    Vdbe *pOld,               /* VM being reprepared */
000842    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000843    const char **pzTail       /* OUT: End of parsed string */
000844  ){
000845    int rc;
000846    int cnt = 0;
000847  
000848  #ifdef SQLITE_ENABLE_API_ARMOR
000849    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
000850  #endif
000851    *ppStmt = 0;
000852    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
000853      return SQLITE_MISUSE_BKPT;
000854    }
000855    sqlite3_mutex_enter(db->mutex);
000856    sqlite3BtreeEnterAll(db);
000857    do{
000858      /* Make multiple attempts to compile the SQL, until it either succeeds
000859      ** or encounters a permanent error.  A schema problem after one schema
000860      ** reset is considered a permanent error. */
000861      rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
000862      assert( rc==SQLITE_OK || *ppStmt==0 );
000863      if( rc==SQLITE_OK || db->mallocFailed ) break;
000864    }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)
000865         || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
000866    sqlite3BtreeLeaveAll(db);
000867    rc = sqlite3ApiExit(db, rc);
000868    assert( (rc&db->errMask)==rc );
000869    db->busyHandler.nBusy = 0;
000870    sqlite3_mutex_leave(db->mutex);
000871    assert( rc==SQLITE_OK || (*ppStmt)==0 );
000872    return rc;
000873  }
000874  
000875  
000876  /*
000877  ** Rerun the compilation of a statement after a schema change.
000878  **
000879  ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
000880  ** if the statement cannot be recompiled because another connection has
000881  ** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
000882  ** occurs, return SQLITE_SCHEMA.
000883  */
000884  int sqlite3Reprepare(Vdbe *p){
000885    int rc;
000886    sqlite3_stmt *pNew;
000887    const char *zSql;
000888    sqlite3 *db;
000889    u8 prepFlags;
000890  
000891    assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
000892    zSql = sqlite3_sql((sqlite3_stmt *)p);
000893    assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
000894    db = sqlite3VdbeDb(p);
000895    assert( sqlite3_mutex_held(db->mutex) );
000896    prepFlags = sqlite3VdbePrepareFlags(p);
000897    rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
000898    if( rc ){
000899      if( rc==SQLITE_NOMEM ){
000900        sqlite3OomFault(db);
000901      }
000902      assert( pNew==0 );
000903      return rc;
000904    }else{
000905      assert( pNew!=0 );
000906    }
000907    sqlite3VdbeSwap((Vdbe*)pNew, p);
000908    sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
000909    sqlite3VdbeResetStepResult((Vdbe*)pNew);
000910    sqlite3VdbeFinalize((Vdbe*)pNew);
000911    return SQLITE_OK;
000912  }
000913  
000914  
000915  /*
000916  ** Two versions of the official API.  Legacy and new use.  In the legacy
000917  ** version, the original SQL text is not saved in the prepared statement
000918  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
000919  ** sqlite3_step().  In the new version, the original SQL text is retained
000920  ** and the statement is automatically recompiled if an schema change
000921  ** occurs.
000922  */
000923  int sqlite3_prepare(
000924    sqlite3 *db,              /* Database handle. */
000925    const char *zSql,         /* UTF-8 encoded SQL statement. */
000926    int nBytes,               /* Length of zSql in bytes. */
000927    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000928    const char **pzTail       /* OUT: End of parsed string */
000929  ){
000930    int rc;
000931    rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
000932    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
000933    return rc;
000934  }
000935  int sqlite3_prepare_v2(
000936    sqlite3 *db,              /* Database handle. */
000937    const char *zSql,         /* UTF-8 encoded SQL statement. */
000938    int nBytes,               /* Length of zSql in bytes. */
000939    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000940    const char **pzTail       /* OUT: End of parsed string */
000941  ){
000942    int rc;
000943    /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
000944    ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
000945    ** parameter.
000946    **
000947    ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
000948    rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
000949                               ppStmt,pzTail);
000950    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
000951    return rc;
000952  }
000953  int sqlite3_prepare_v3(
000954    sqlite3 *db,              /* Database handle. */
000955    const char *zSql,         /* UTF-8 encoded SQL statement. */
000956    int nBytes,               /* Length of zSql in bytes. */
000957    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
000958    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000959    const char **pzTail       /* OUT: End of parsed string */
000960  ){
000961    int rc;
000962    /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
000963    ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
000964    ** which is a bit array consisting of zero or more of the
000965    ** SQLITE_PREPARE_* flags.
000966    **
000967    ** Proof by comparison to the implementation of sqlite3_prepare_v2()
000968    ** directly above. */
000969    rc = sqlite3LockAndPrepare(db,zSql,nBytes,
000970                   SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
000971                   0,ppStmt,pzTail);
000972    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
000973    return rc;
000974  }
000975  
000976  
000977  #ifndef SQLITE_OMIT_UTF16
000978  /*
000979  ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
000980  */
000981  static int sqlite3Prepare16(
000982    sqlite3 *db,              /* Database handle. */ 
000983    const void *zSql,         /* UTF-16 encoded SQL statement. */
000984    int nBytes,               /* Length of zSql in bytes. */
000985    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000986    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000987    const void **pzTail       /* OUT: End of parsed string */
000988  ){
000989    /* This function currently works by first transforming the UTF-16
000990    ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
000991    ** tricky bit is figuring out the pointer to return in *pzTail.
000992    */
000993    char *zSql8;
000994    const char *zTail8 = 0;
000995    int rc = SQLITE_OK;
000996  
000997  #ifdef SQLITE_ENABLE_API_ARMOR
000998    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
000999  #endif
001000    *ppStmt = 0;
001001    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
001002      return SQLITE_MISUSE_BKPT;
001003    }
001004    if( nBytes>=0 ){
001005      int sz;
001006      const char *z = (const char*)zSql;
001007      for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
001008      nBytes = sz;
001009    }
001010    sqlite3_mutex_enter(db->mutex);
001011    zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
001012    if( zSql8 ){
001013      rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
001014    }
001015  
001016    if( zTail8 && pzTail ){
001017      /* If sqlite3_prepare returns a tail pointer, we calculate the
001018      ** equivalent pointer into the UTF-16 string by counting the unicode
001019      ** characters between zSql8 and zTail8, and then returning a pointer
001020      ** the same number of characters into the UTF-16 string.
001021      */
001022      int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
001023      *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
001024    }
001025    sqlite3DbFree(db, zSql8); 
001026    rc = sqlite3ApiExit(db, rc);
001027    sqlite3_mutex_leave(db->mutex);
001028    return rc;
001029  }
001030  
001031  /*
001032  ** Two versions of the official API.  Legacy and new use.  In the legacy
001033  ** version, the original SQL text is not saved in the prepared statement
001034  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
001035  ** sqlite3_step().  In the new version, the original SQL text is retained
001036  ** and the statement is automatically recompiled if an schema change
001037  ** occurs.
001038  */
001039  int sqlite3_prepare16(
001040    sqlite3 *db,              /* Database handle. */ 
001041    const void *zSql,         /* UTF-16 encoded SQL statement. */
001042    int nBytes,               /* Length of zSql in bytes. */
001043    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001044    const void **pzTail       /* OUT: End of parsed string */
001045  ){
001046    int rc;
001047    rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
001048    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001049    return rc;
001050  }
001051  int sqlite3_prepare16_v2(
001052    sqlite3 *db,              /* Database handle. */ 
001053    const void *zSql,         /* UTF-16 encoded SQL statement. */
001054    int nBytes,               /* Length of zSql in bytes. */
001055    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001056    const void **pzTail       /* OUT: End of parsed string */
001057  ){
001058    int rc;
001059    rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
001060    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001061    return rc;
001062  }
001063  int sqlite3_prepare16_v3(
001064    sqlite3 *db,              /* Database handle. */ 
001065    const void *zSql,         /* UTF-16 encoded SQL statement. */
001066    int nBytes,               /* Length of zSql in bytes. */
001067    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
001068    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001069    const void **pzTail       /* OUT: End of parsed string */
001070  ){
001071    int rc;
001072    rc = sqlite3Prepare16(db,zSql,nBytes,
001073           SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
001074           ppStmt,pzTail);
001075    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001076    return rc;
001077  }
001078  
001079  #endif /* SQLITE_OMIT_UTF16 */