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;
000637    if( sqlite3FaultSim(300) ){
000638      pCleanup = 0;
000639      sqlite3OomFault(pParse->db);
000640    }else{
000641      pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
000642    }
000643    if( pCleanup ){
000644      pCleanup->pNext = pParse->pCleanup;
000645      pParse->pCleanup = pCleanup;
000646      pCleanup->pPtr = pPtr;
000647      pCleanup->xCleanup = xCleanup;
000648    }else{
000649      xCleanup(pParse->db, pPtr);
000650      pPtr = 0;
000651  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
000652      pParse->earlyCleanup = 1;
000653  #endif
000654    }
000655    return pPtr;
000656  }
000657  
000658  /*
000659  ** Turn bulk memory into a valid Parse object and link that Parse object
000660  ** into database connection db.
000661  **
000662  ** Call sqlite3ParseObjectReset() to undo this operation.
000663  **
000664  ** Caution:  Do not confuse this routine with sqlite3ParseObjectInit() which
000665  ** is generated by Lemon.
000666  */
000667  void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
000668    memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
000669    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
000670    assert( db->pParse!=pParse );
000671    pParse->pOuterParse = db->pParse;
000672    db->pParse = pParse;
000673    pParse->db = db;
000674    if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
000675  }
000676  
000677  /*
000678  ** Maximum number of times that we will try again to prepare a statement
000679  ** that returns SQLITE_ERROR_RETRY.
000680  */
000681  #ifndef SQLITE_MAX_PREPARE_RETRY
000682  # define SQLITE_MAX_PREPARE_RETRY 25
000683  #endif
000684  
000685  /*
000686  ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
000687  */
000688  static int sqlite3Prepare(
000689    sqlite3 *db,              /* Database handle. */
000690    const char *zSql,         /* UTF-8 encoded SQL statement. */
000691    int nBytes,               /* Length of zSql in bytes. */
000692    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000693    Vdbe *pReprepare,         /* VM being reprepared */
000694    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000695    const char **pzTail       /* OUT: End of parsed string */
000696  ){
000697    int rc = SQLITE_OK;       /* Result code */
000698    int i;                    /* Loop counter */
000699    Parse sParse;             /* Parsing context */
000700  
000701    /* sqlite3ParseObjectInit(&sParse, db); // inlined for performance */
000702    memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
000703    memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
000704    sParse.pOuterParse = db->pParse;
000705    db->pParse = &sParse;
000706    sParse.db = db;
000707    if( pReprepare ){
000708      sParse.pReprepare = pReprepare;
000709      sParse.explain = sqlite3_stmt_isexplain((sqlite3_stmt*)pReprepare);
000710    }else{
000711      assert( sParse.pReprepare==0 );
000712    }
000713    assert( ppStmt && *ppStmt==0 );
000714    if( db->mallocFailed ){
000715      sqlite3ErrorMsg(&sParse, "out of memory");
000716      db->errCode = rc = SQLITE_NOMEM;
000717      goto end_prepare;
000718    }
000719    assert( sqlite3_mutex_held(db->mutex) );
000720  
000721    /* For a long-term use prepared statement avoid the use of
000722    ** lookaside memory.
000723    */
000724    if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
000725      sParse.disableLookaside++;
000726      DisableLookaside;
000727    }
000728    sParse.prepFlags = prepFlags & 0xff;
000729  
000730    /* Check to verify that it is possible to get a read lock on all
000731    ** database schemas.  The inability to get a read lock indicates that
000732    ** some other database connection is holding a write-lock, which in
000733    ** turn means that the other connection has made uncommitted changes
000734    ** to the schema.
000735    **
000736    ** Were we to proceed and prepare the statement against the uncommitted
000737    ** schema changes and if those schema changes are subsequently rolled
000738    ** back and different changes are made in their place, then when this
000739    ** prepared statement goes to run the schema cookie would fail to detect
000740    ** the schema change.  Disaster would follow.
000741    **
000742    ** This thread is currently holding mutexes on all Btrees (because
000743    ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
000744    ** is not possible for another thread to start a new schema change
000745    ** while this routine is running.  Hence, we do not need to hold 
000746    ** locks on the schema, we just need to make sure nobody else is 
000747    ** holding them.
000748    **
000749    ** Note that setting READ_UNCOMMITTED overrides most lock detection,
000750    ** but it does *not* override schema lock detection, so this all still
000751    ** works even if READ_UNCOMMITTED is set.
000752    */
000753    if( !db->noSharedCache ){
000754      for(i=0; i<db->nDb; i++) {
000755        Btree *pBt = db->aDb[i].pBt;
000756        if( pBt ){
000757          assert( sqlite3BtreeHoldsMutex(pBt) );
000758          rc = sqlite3BtreeSchemaLocked(pBt);
000759          if( rc ){
000760            const char *zDb = db->aDb[i].zDbSName;
000761            sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
000762            testcase( db->flags & SQLITE_ReadUncommit );
000763            goto end_prepare;
000764          }
000765        }
000766      }
000767    }
000768  
000769  #ifndef SQLITE_OMIT_VIRTUALTABLE
000770    if( db->pDisconnect ) sqlite3VtabUnlockList(db);
000771  #endif
000772  
000773    if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
000774      char *zSqlCopy;
000775      int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
000776      testcase( nBytes==mxLen );
000777      testcase( nBytes==mxLen+1 );
000778      if( nBytes>mxLen ){
000779        sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
000780        rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
000781        goto end_prepare;
000782      }
000783      zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
000784      if( zSqlCopy ){
000785        sqlite3RunParser(&sParse, zSqlCopy);
000786        sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
000787        sqlite3DbFree(db, zSqlCopy);
000788      }else{
000789        sParse.zTail = &zSql[nBytes];
000790      }
000791    }else{
000792      sqlite3RunParser(&sParse, zSql);
000793    }
000794    assert( 0==sParse.nQueryLoop );
000795  
000796    if( pzTail ){
000797      *pzTail = sParse.zTail;
000798    }
000799  
000800    if( db->init.busy==0 ){
000801      sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
000802    }
000803    if( db->mallocFailed ){
000804      sParse.rc = SQLITE_NOMEM_BKPT;
000805      sParse.checkSchema = 0;
000806    }
000807    if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
000808      if( sParse.checkSchema && db->init.busy==0 ){
000809        schemaIsValid(&sParse);
000810      }
000811      if( sParse.pVdbe ){
000812        sqlite3VdbeFinalize(sParse.pVdbe);
000813      }
000814      assert( 0==(*ppStmt) );
000815      rc = sParse.rc;
000816      if( sParse.zErrMsg ){
000817        sqlite3ErrorWithMsg(db, rc, "%s", sParse.zErrMsg);
000818        sqlite3DbFree(db, sParse.zErrMsg);
000819      }else{
000820        sqlite3Error(db, rc);
000821      }
000822    }else{
000823      assert( sParse.zErrMsg==0 );
000824      *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
000825      rc = SQLITE_OK;
000826      sqlite3ErrorClear(db);
000827    }
000828  
000829  
000830    /* Delete any TriggerPrg structures allocated while parsing this statement. */
000831    while( sParse.pTriggerPrg ){
000832      TriggerPrg *pT = sParse.pTriggerPrg;
000833      sParse.pTriggerPrg = pT->pNext;
000834      sqlite3DbFree(db, pT);
000835    }
000836  
000837  end_prepare:
000838  
000839    sqlite3ParseObjectReset(&sParse);
000840    return rc;
000841  }
000842  static int sqlite3LockAndPrepare(
000843    sqlite3 *db,              /* Database handle. */
000844    const char *zSql,         /* UTF-8 encoded SQL statement. */
000845    int nBytes,               /* Length of zSql in bytes. */
000846    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000847    Vdbe *pOld,               /* VM being reprepared */
000848    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000849    const char **pzTail       /* OUT: End of parsed string */
000850  ){
000851    int rc;
000852    int cnt = 0;
000853  
000854  #ifdef SQLITE_ENABLE_API_ARMOR
000855    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
000856  #endif
000857    *ppStmt = 0;
000858    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
000859      return SQLITE_MISUSE_BKPT;
000860    }
000861    sqlite3_mutex_enter(db->mutex);
000862    sqlite3BtreeEnterAll(db);
000863    do{
000864      /* Make multiple attempts to compile the SQL, until it either succeeds
000865      ** or encounters a permanent error.  A schema problem after one schema
000866      ** reset is considered a permanent error. */
000867      rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
000868      assert( rc==SQLITE_OK || *ppStmt==0 );
000869      if( rc==SQLITE_OK || db->mallocFailed ) break;
000870    }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)
000871         || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
000872    sqlite3BtreeLeaveAll(db);
000873    rc = sqlite3ApiExit(db, rc);
000874    assert( (rc&db->errMask)==rc );
000875    db->busyHandler.nBusy = 0;
000876    sqlite3_mutex_leave(db->mutex);
000877    assert( rc==SQLITE_OK || (*ppStmt)==0 );
000878    return rc;
000879  }
000880  
000881  
000882  /*
000883  ** Rerun the compilation of a statement after a schema change.
000884  **
000885  ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
000886  ** if the statement cannot be recompiled because another connection has
000887  ** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
000888  ** occurs, return SQLITE_SCHEMA.
000889  */
000890  int sqlite3Reprepare(Vdbe *p){
000891    int rc;
000892    sqlite3_stmt *pNew;
000893    const char *zSql;
000894    sqlite3 *db;
000895    u8 prepFlags;
000896  
000897    assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
000898    zSql = sqlite3_sql((sqlite3_stmt *)p);
000899    assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
000900    db = sqlite3VdbeDb(p);
000901    assert( sqlite3_mutex_held(db->mutex) );
000902    prepFlags = sqlite3VdbePrepareFlags(p);
000903    rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
000904    if( rc ){
000905      if( rc==SQLITE_NOMEM ){
000906        sqlite3OomFault(db);
000907      }
000908      assert( pNew==0 );
000909      return rc;
000910    }else{
000911      assert( pNew!=0 );
000912    }
000913    sqlite3VdbeSwap((Vdbe*)pNew, p);
000914    sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
000915    sqlite3VdbeResetStepResult((Vdbe*)pNew);
000916    sqlite3VdbeFinalize((Vdbe*)pNew);
000917    return SQLITE_OK;
000918  }
000919  
000920  
000921  /*
000922  ** Two versions of the official API.  Legacy and new use.  In the legacy
000923  ** version, the original SQL text is not saved in the prepared statement
000924  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
000925  ** sqlite3_step().  In the new version, the original SQL text is retained
000926  ** and the statement is automatically recompiled if an schema change
000927  ** occurs.
000928  */
000929  int sqlite3_prepare(
000930    sqlite3 *db,              /* Database handle. */
000931    const char *zSql,         /* UTF-8 encoded SQL statement. */
000932    int nBytes,               /* Length of zSql in bytes. */
000933    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000934    const char **pzTail       /* OUT: End of parsed string */
000935  ){
000936    int rc;
000937    rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
000938    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
000939    return rc;
000940  }
000941  int sqlite3_prepare_v2(
000942    sqlite3 *db,              /* Database handle. */
000943    const char *zSql,         /* UTF-8 encoded SQL statement. */
000944    int nBytes,               /* Length of zSql in bytes. */
000945    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000946    const char **pzTail       /* OUT: End of parsed string */
000947  ){
000948    int rc;
000949    /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
000950    ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
000951    ** parameter.
000952    **
000953    ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
000954    rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
000955                               ppStmt,pzTail);
000956    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
000957    return rc;
000958  }
000959  int sqlite3_prepare_v3(
000960    sqlite3 *db,              /* Database handle. */
000961    const char *zSql,         /* UTF-8 encoded SQL statement. */
000962    int nBytes,               /* Length of zSql in bytes. */
000963    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
000964    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000965    const char **pzTail       /* OUT: End of parsed string */
000966  ){
000967    int rc;
000968    /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
000969    ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
000970    ** which is a bit array consisting of zero or more of the
000971    ** SQLITE_PREPARE_* flags.
000972    **
000973    ** Proof by comparison to the implementation of sqlite3_prepare_v2()
000974    ** directly above. */
000975    rc = sqlite3LockAndPrepare(db,zSql,nBytes,
000976                   SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
000977                   0,ppStmt,pzTail);
000978    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
000979    return rc;
000980  }
000981  
000982  
000983  #ifndef SQLITE_OMIT_UTF16
000984  /*
000985  ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
000986  */
000987  static int sqlite3Prepare16(
000988    sqlite3 *db,              /* Database handle. */ 
000989    const void *zSql,         /* UTF-16 encoded SQL statement. */
000990    int nBytes,               /* Length of zSql in bytes. */
000991    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
000992    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
000993    const void **pzTail       /* OUT: End of parsed string */
000994  ){
000995    /* This function currently works by first transforming the UTF-16
000996    ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
000997    ** tricky bit is figuring out the pointer to return in *pzTail.
000998    */
000999    char *zSql8;
001000    const char *zTail8 = 0;
001001    int rc = SQLITE_OK;
001002  
001003  #ifdef SQLITE_ENABLE_API_ARMOR
001004    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
001005  #endif
001006    *ppStmt = 0;
001007    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
001008      return SQLITE_MISUSE_BKPT;
001009    }
001010    if( nBytes>=0 ){
001011      int sz;
001012      const char *z = (const char*)zSql;
001013      for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
001014      nBytes = sz;
001015    }
001016    sqlite3_mutex_enter(db->mutex);
001017    zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
001018    if( zSql8 ){
001019      rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
001020    }
001021  
001022    if( zTail8 && pzTail ){
001023      /* If sqlite3_prepare returns a tail pointer, we calculate the
001024      ** equivalent pointer into the UTF-16 string by counting the unicode
001025      ** characters between zSql8 and zTail8, and then returning a pointer
001026      ** the same number of characters into the UTF-16 string.
001027      */
001028      int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
001029      *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
001030    }
001031    sqlite3DbFree(db, zSql8); 
001032    rc = sqlite3ApiExit(db, rc);
001033    sqlite3_mutex_leave(db->mutex);
001034    return rc;
001035  }
001036  
001037  /*
001038  ** Two versions of the official API.  Legacy and new use.  In the legacy
001039  ** version, the original SQL text is not saved in the prepared statement
001040  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
001041  ** sqlite3_step().  In the new version, the original SQL text is retained
001042  ** and the statement is automatically recompiled if an schema change
001043  ** occurs.
001044  */
001045  int sqlite3_prepare16(
001046    sqlite3 *db,              /* Database handle. */ 
001047    const void *zSql,         /* UTF-16 encoded SQL statement. */
001048    int nBytes,               /* Length of zSql in bytes. */
001049    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001050    const void **pzTail       /* OUT: End of parsed string */
001051  ){
001052    int rc;
001053    rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
001054    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001055    return rc;
001056  }
001057  int sqlite3_prepare16_v2(
001058    sqlite3 *db,              /* Database handle. */ 
001059    const void *zSql,         /* UTF-16 encoded SQL statement. */
001060    int nBytes,               /* Length of zSql in bytes. */
001061    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001062    const void **pzTail       /* OUT: End of parsed string */
001063  ){
001064    int rc;
001065    rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
001066    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001067    return rc;
001068  }
001069  int sqlite3_prepare16_v3(
001070    sqlite3 *db,              /* Database handle. */ 
001071    const void *zSql,         /* UTF-16 encoded SQL statement. */
001072    int nBytes,               /* Length of zSql in bytes. */
001073    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
001074    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
001075    const void **pzTail       /* OUT: End of parsed string */
001076  ){
001077    int rc;
001078    rc = sqlite3Prepare16(db,zSql,nBytes,
001079           SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
001080           ppStmt,pzTail);
001081    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
001082    return rc;
001083  }
001084  
001085  #endif /* SQLITE_OMIT_UTF16 */