/// <summary> /// Creates new instance of SQLiteVdbe class by compiling a statement /// </summary> /// <param name="query"></param> /// <returns>Vdbe</returns> public SQLiteVdbe(SQLiteDatabase db, String query) { vm = null; // prepare and compile Sqlite3.sqlite3_prepare_v2(db.Connection(), query, query.Length, ref vm, 0); }
/// <summary> /// Creates new instance of SQLiteVdbe class by compiling a statement /// </summary> /// <param name="query"></param> /// <returns>Vdbe</returns> public SQLiteVdbe(SQLiteDatabase db, String query) { vm = null; // prepare and compile #if NET_35 Sqlite3.PrepareV2NoTail #else Sqlite3.sqlite3_prepare_v2 #endif (db.Connection(), query, query.Length, ref vm, 0); }
public IDbStatement Prepare2(IDbHandle db, string query) { var dbHandle = (DbHandle) db; var stmt = new Sqlite3.Vdbe(); int r = Sqlite3.sqlite3_prepare_v2(dbHandle.InternalDbHandle, query, -1, ref stmt, 0); if (r != 0) { throw SQLiteException.New((Result) r, GetErrmsg(db)); } return new DbStatement(stmt); }
public static int sqlite3_prepare_v2( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; rc = sqlite3LockAndPrepare( db, zSql, nBytes, 1, null, ref ppStmt, ref pzTail ); Debug.Assert( rc == SQLITE_OK || ppStmt == null ); /* VERIFY: F13021 */ return rc; }
// private function for reading rows and creating table and columns private int ReadNextRow(Vdbe vm, DataTable table) { int columnCount = table.Columns.Count; if(columnCount == 0) { if((columnCount = ReadColumnNames(vm, table)) == 0) return Sqlite3.SQLITE_ERROR; } int resultType; if((resultType = Sqlite3.sqlite3_step(vm)) == Sqlite3.SQLITE_ROW) { object[] columnValues = new object[columnCount]; for(int i = 0; i < columnCount; i++) { int columnType = Sqlite3.sqlite3_column_type(vm, i); switch(columnType) { case Sqlite3.SQLITE_INTEGER: { table.Columns[i].DataType = typeof(Int64); columnValues[i] = Sqlite3.sqlite3_column_int(vm, i); break; } case Sqlite3.SQLITE_FLOAT: { table.Columns[i].DataType = typeof(Double); columnValues[i] = Sqlite3.sqlite3_column_double(vm, i); break; } case Sqlite3.SQLITE_TEXT: { table.Columns[i].DataType = typeof(String); columnValues[i] = Sqlite3.sqlite3_column_text(vm, i); break; } case Sqlite3.SQLITE_BLOB: { table.Columns[i].DataType = typeof(Byte[]); columnValues[i] = Sqlite3.sqlite3_column_blob(vm, i); break; } default: { table.Columns[i].DataType = null; columnValues[i] = ""; break; } } } table.Rows.Add(columnValues); } return resultType; }
// private function for creating Column Names // Return number of colums read private int ReadColumnNames(Vdbe vm, DataTable table) { String columnName = ""; int columnType = 0; // returns number of columns returned by statement int columnCount = Sqlite3.sqlite3_column_count(vm); object[] columnValues = new object[columnCount]; try { // reads columns one by one for(int i = 0; i < columnCount; i++) { columnName = Sqlite3.sqlite3_column_name(vm, i); columnType = Sqlite3.sqlite3_column_type(vm, i); switch(columnType) { case Sqlite3.SQLITE_INTEGER: { // adds new integer column to table table.Columns.Add(columnName, Type.GetType("System.Int64")); break; } case Sqlite3.SQLITE_FLOAT: { table.Columns.Add(columnName, Type.GetType("System.Double")); break; } case Sqlite3.SQLITE_TEXT: { table.Columns.Add(columnName, Type.GetType("System.String")); break; } case Sqlite3.SQLITE_BLOB: { table.Columns.Add(columnName, Type.GetType("System.byte[]")); break; } default: { table.Columns.Add(columnName, Type.GetType("System.String")); break; } } } } catch { return 0; } return table.Columns.Count; }
/* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the VACUUM command. ** ** Most of the code in this file may be omitted by defining the ** SQLITE_OMIT_VACUUM macro. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" /* ** Finalize a prepared statement. If there was an error, store the ** text of the error message in *pzErrMsg. Return the result code. */ static int vacuumFinalize(sqlite3 db, sqlite3_stmt pStmt, string pzErrMsg) { int rc; rc = sqlite3VdbeFinalize(ref pStmt); if (rc != 0) { sqlite3SetString(ref pzErrMsg, db, sqlite3_errmsg(db)); } return rc; }
private Sqlite3.Vdbe Prepare(String strStatement, Object[] values) { Sqlite3.Vdbe ppStmt=new Sqlite3.Vdbe(); Sqlite3.sqlite3_prepare_v2(m_db, strStatement, strStatement.Length, ref ppStmt, 0); checkError(); Bind(ppStmt, values); return ppStmt; }
public CSqliteResult(Sqlite3.Vdbe stmt, boolean bNoCopy) { m_bNoCopy = bNoCopy; m_st = stmt; }
public void close() { if (m_st != null) { Sqlite3.sqlite3_finalize(ref m_st); m_st = null; } }
/// <summary> /// Converts a USDX 1.01 or CMD 1.01 database to Vocaluxe format /// </summary> /// <param name="FilePath">Database file path</param> /// <returns>True if succeeded</returns> private static bool ConvertFrom101(string FilePath) { SQLiteConnection connection = new SQLiteConnection(); connection.ConnectionString = "Data Source=" + FilePath; SQLiteCommand command; SQLiteDataReader reader = null; try { connection.Open(); } catch (Exception) { return false; } command = new SQLiteCommand(connection); command.CommandText = "PRAGMA table_info(US_Scores);"; reader = command.ExecuteReader(); bool dateExists = false; //Check for column Date while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (reader.GetName(i) == "name") { if (reader.GetString(i) == "Date") dateExists = true; break; } } } reader.Close(); //This is a USDX 1.01 DB if (!dateExists) command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', '0', '0', '0', Difficulty from US_Scores"; else // This is a CMD 1.01 DB command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs"; command.ExecuteNonQuery(); // convert from CP1252 to UTF8 List<SData> scores = new List<SData>(); List<SData> songs = new List<SData>(); Sqlite3.sqlite3 OldDB; int res = Sqlite3.sqlite3_open(FilePath, out OldDB); if (res != Sqlite3.SQLITE_OK) { CLog.LogError("Error opening Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")"); } else { Sqlite3.Vdbe Stmt = new Sqlite3.Vdbe(); res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, Artist, Title FROM Songs", -1, ref Stmt, 0); if (res != Sqlite3.SQLITE_OK) { CLog.LogError("Error query Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")"); } else { //Sqlite3.sqlite3_step(Stmt); Encoding UTF8 = Encoding.UTF8; Encoding CP1252 = Encoding.GetEncoding(1252); while (Sqlite3.sqlite3_step(Stmt) == Sqlite3.SQLITE_ROW) { SData data = new SData(); data.id = Sqlite3.sqlite3_column_int(Stmt, 0); byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1); if (bytes != null) data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes)); else data.str1 = "Someone"; bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 2); if (bytes != null) data.str2 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes)); else data.str2 = "Someone"; songs.Add(data); } Sqlite3.sqlite3_finalize(Stmt); } Stmt = new Sqlite3.Vdbe(); if (!dateExists) res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName FROM Scores", -1, ref Stmt, 0); else res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName, Date FROM Scores", -1, ref Stmt, 0); if (res != Sqlite3.SQLITE_OK) { CLog.LogError("Error query Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")"); } else { //Sqlite3.sqlite3_step(Stmt); Encoding UTF8 = Encoding.UTF8; Encoding CP1252 = Encoding.GetEncoding(1252); while (Sqlite3.sqlite3_step(Stmt) == Sqlite3.SQLITE_ROW) { SData data = new SData(); data.id = Sqlite3.sqlite3_column_int(Stmt, 0); byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1); if (bytes != null) data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes)); else data.str1 = "Someone"; if (dateExists) data.ticks = UnixTimeToTicks(Sqlite3.sqlite3_column_int(Stmt, 2)); scores.Add(data); } Sqlite3.sqlite3_finalize(Stmt); } } Sqlite3.sqlite3_close(OldDB); SQLiteTransaction _Transaction = connection.BeginTransaction(); // update Title and Artist strings foreach (SData data in songs) { command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id"; command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = data.str2; command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = data.str1; command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id; command.ExecuteNonQuery(); } // update player names foreach (SData data in scores) { if (!dateExists) command.CommandText = "UPDATE Scores SET [PlayerName] = @player WHERE [id] = @id"; else { command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id"; command.Parameters.Add("@date", System.Data.DbType.Int64, 0).Value = data.ticks; } command.Parameters.Add("@player", System.Data.DbType.String, 0).Value = data.str1; command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id; command.ExecuteNonQuery(); } _Transaction.Commit(); //Delete old tables after conversion command.CommandText = "DROP TABLE US_Scores;"; command.ExecuteNonQuery(); command.CommandText = "DROP TABLE US_Songs;"; command.ExecuteNonQuery(); reader.Dispose(); command.Dispose(); connection.Close(); connection.Dispose(); return true; }
void executeUpdates() { for (int x = 0; x < ctrPaneles; x++) { if(!String.IsNullOrEmpty(updates[x])){ string select = "select votos from candidato where nombre='" + updates[x] + "';"; Sqlite3.Vdbe pstmt = new Sqlite3.Vdbe(); Sqlite3.sqlite3_prepare_v2(Program.db, select, select.Length, ref pstmt, 0); Sqlite3.sqlite3_step(pstmt); string des=Sqlite3.sqlite3_column_text(pstmt, 0); int voto = desencriptarint( SoapHexBinary.Parse(des).Value); voto++; string enc = new SoapHexBinary(encriptarint(voto)).ToString(); string update = "update candidato set votos='" + enc + "' where nombre='" + updates[x] + "';"; string error = ""; if (Sqlite3.sqlite3_exec(Program.db, update, null, null, ref error) != Sqlite3.SQLITE_OK) { MessageBox.Show(error); } Sqlite3.sqlite3_finalize(pstmt); } } }
/* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare16( sqlite3 db, /* Database handle. */ string zSql, /* UTF-15 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ bool saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { /* This function currently works by first transforming the UTF-16 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in pzTail. */ string zSql8; string zTail8 = ""; int rc = SQLITE_OK; assert( ppStmt ); *ppStmt = 0; if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } sqlite3_mutex_enter(db.mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 !=""){ rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, null, ref ppStmt, ref zTail8); } if( zTail8 !="" && pzTail !=""){ /* If sqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ Debugger.Break (); // TODO -- // int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); // pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); } sqlite3DbFree(db,ref zSql8); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; }
/* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ static int sqlite3Reprepare( Vdbe p ) { int rc; sqlite3_stmt pNew = new sqlite3_stmt(); string zSql; sqlite3 db; Debug.Assert( sqlite3_mutex_held( sqlite3VdbeDb( p ).mutex ) ); zSql = sqlite3_sql( (sqlite3_stmt)p ); Debug.Assert( zSql != null ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb( p ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); string dummy = ""; rc = sqlite3LockAndPrepare( db, zSql, -1, 0, p, ref pNew, ref dummy ); if ( rc != 0 ) { if ( rc == SQLITE_NOMEM ) { // db.mallocFailed = 1; } Debug.Assert( pNew == null ); return rc; } else { Debug.Assert( pNew != null ); } sqlite3VdbeSwap( (Vdbe)pNew, p ); sqlite3TransferBindings( pNew, (sqlite3_stmt)p ); sqlite3VdbeResetStepResult( (Vdbe)pNew ); sqlite3VdbeFinalize( (Vdbe)pNew ); return SQLITE_OK; }
/* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ static int sqlite3Prepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pReprepare, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { Parse pParse; /* Parsing context */ string zErrMsg = ""; /* Error message */ int rc = SQLITE_OK; /* Result code */ int i; /* Loop counter */ /* Allocate the parsing context */ pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); if ( pParse == null ) { rc = SQLITE_NOMEM; goto end_prepare; } pParse.pReprepare = pReprepare; pParse.sLastToken.z = ""; Debug.Assert( ppStmt == null );// assert( ppStmt && *ppStmt==0 ); //Debug.Assert( 0 == db.mallocFailed ); Debug.Assert( sqlite3_mutex_held( db.mutex ) ); /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that ** some other database connection is holding a write-lock, which in ** turn means that the other connection has made uncommitted changes ** to the schema. ** ** Were we to proceed and prepare the statement against the uncommitted ** schema changes and if those schema changes are subsequently rolled ** back and different changes are made in their place, then when this ** prepared statement goes to run the schema cookie would fail to detect ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is ** holding them. ** ** Note that setting READ_UNCOMMITTED overrides most lock detection, ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ for ( i = 0; i < db.nDb; i++ ) { Btree pBt = db.aDb[i].pBt; if ( pBt != null ) { Debug.Assert( sqlite3BtreeHoldsMutex( pBt ) ); rc = sqlite3BtreeSchemaLocked( pBt ); if ( rc != 0 ) { string zDb = db.aDb[i].zName; sqlite3Error( db, rc, "database schema is locked: %s", zDb ); testcase( db.flags & SQLITE_ReadUncommitted ); goto end_prepare; } } } sqlite3VtabUnlockList( db ); pParse.db = db; pParse.nQueryLoop = (double)1; if ( nBytes >= 0 && ( nBytes == 0 || zSql[nBytes - 1] != 0 ) ) { string zSqlCopy; int mxLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; testcase( nBytes == mxLen ); testcase( nBytes == mxLen + 1 ); if ( nBytes > mxLen ) { sqlite3Error( db, SQLITE_TOOBIG, "statement too long" ); rc = sqlite3ApiExit( db, SQLITE_TOOBIG ); goto end_prepare; } zSqlCopy = zSql.Substring( 0, nBytes );// sqlite3DbStrNDup(db, zSql, nBytes); if ( zSqlCopy != null ) { sqlite3RunParser( pParse, zSqlCopy, ref zErrMsg ); sqlite3DbFree( db, ref zSqlCopy ); //pParse->zTail = &zSql[pParse->zTail-zSqlCopy]; } else { //pParse->zTail = &zSql[nBytes]; } } else { sqlite3RunParser( pParse, zSql, ref zErrMsg ); } Debug.Assert( 1 == (int)pParse.nQueryLoop ); //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc == SQLITE_DONE ) pParse.rc = SQLITE_OK; if ( pParse.checkSchema != 0 ) { schemaIsValid( pParse ); } if ( pParse.rc == SQLITE_SCHEMA ) { sqlite3ResetInternalSchema( db, 0 ); } //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} //if (pzTail != null) { pzTail = pParse.zTail == null ? "" : pParse.zTail.ToString(); } rc = pParse.rc; #if !SQLITE_OMIT_EXPLAIN if ( rc == SQLITE_OK && pParse.pVdbe != null && pParse.explain != 0 ) { string[] azColName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; int iFirst, mx; if ( pParse.explain == 2 ) { sqlite3VdbeSetNumCols( pParse.pVdbe, 4 ); iFirst = 8; mx = 12; } else { sqlite3VdbeSetNumCols( pParse.pVdbe, 8 ); iFirst = 0; mx = 8; } for ( i = iFirst; i < mx; i++ ) { sqlite3VdbeSetColName( pParse.pVdbe, i - iFirst, COLNAME_NAME, azColName[i], SQLITE_STATIC ); } } #endif Debug.Assert( db.init.busy == 0 || saveSqlFlag == 0 ); if ( db.init.busy == 0 ) { Vdbe pVdbe = pParse.pVdbe; sqlite3VdbeSetSql( pVdbe, zSql, (int)( zSql.Length - ( pParse.zTail == null ? 0 : pParse.zTail.Length ) ), saveSqlFlag ); } if ( pParse.pVdbe != null && ( rc != SQLITE_OK /*|| db.mallocFailed != 0 */ ) ) { sqlite3VdbeFinalize( pParse.pVdbe ); Debug.Assert( ppStmt == null ); } else { ppStmt = pParse.pVdbe; } if ( zErrMsg != "" ) { sqlite3Error( db, rc, "%s", zErrMsg ); sqlite3DbFree( db, ref zErrMsg ); } else { sqlite3Error( db, rc, 0 ); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while ( pParse.pTriggerPrg != null ) { TriggerPrg pT = pParse.pTriggerPrg; pParse.pTriggerPrg = pT.pNext; sqlite3DbFree( db, ref pT ); } end_prepare: //sqlite3StackFree( db, pParse ); rc = sqlite3ApiExit( db, rc ); Debug.Assert( ( rc & db.errMask ) == rc ); return rc; }
static int sqlite3LockAndPrepare( sqlite3 db, /* Database handle. */ string zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ Vdbe pOld, /* VM being reprepared */ ref sqlite3_stmt ppStmt, /* OUT: A pointer to the prepared statement */ ref string pzTail /* OUT: End of parsed string */ ) { int rc; // assert( ppStmt!=0 ); ppStmt = null; if ( !sqlite3SafetyCheckOk( db ) ) { return SQLITE_MISUSE_BKPT(); } sqlite3_mutex_enter( db.mutex ); sqlite3BtreeEnterAll( db ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail ); if ( rc == SQLITE_SCHEMA ) { sqlite3_finalize( ppStmt ); rc = sqlite3Prepare( db, zSql, nBytes, saveSqlFlag, pOld, ref ppStmt, ref pzTail ); } sqlite3BtreeLeaveAll( db ); sqlite3_mutex_leave( db.mutex ); return rc; }