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