Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031 #include "cmtkSQLite.h"
00032
00033 #include <System/cmtkConsole.h>
00034
00035 #include <stdlib.h>
00036
00037 cmtk::SQLite::SQLite
00038 ( const std::string& dbPath, const bool readOnly )
00039 : m_Good( false ),
00040 m_DebugMode( false )
00041 {
00042 if ( readOnly )
00043 {
00044 this->m_Good = (sqlite3_open_v2( dbPath.c_str(), &this->m_DB, SQLITE_OPEN_READONLY, NULL ) == SQLITE_OK);
00045 }
00046 else
00047 {
00048 this->m_Good = (sqlite3_open_v2( dbPath.c_str(), &this->m_DB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL ) == SQLITE_OK);
00049 }
00050 }
00051
00052 cmtk::SQLite::~SQLite()
00053 {
00054 if ( this->m_Good )
00055 sqlite3_close( this->m_DB );
00056 }
00057
00058 void
00059 cmtk::SQLite::Exec( const std::string& sql )
00060 {
00061 if ( ! this->Good() )
00062 throw Self::Exception( "Attempting operation on invalid SQLite database object" );
00063
00064 if ( this->m_DebugMode )
00065 {
00066 StdErr << sql << "\n";
00067 }
00068
00069 char* err = NULL;
00070 if ( sqlite3_exec( this->m_DB, sql.c_str(), NULL, NULL, &err ) != SQLITE_OK )
00071 {
00072 StdErr << "Exec " << sql << "\nSQL error: " << err << "\n";
00073 sqlite3_free( err );
00074 }
00075 }
00076
00078 extern "C"
00079 int
00080 cmtkSQLiteQueryCallback( void* pTable, int ncols, char** rowdata, char** )
00081 {
00082 cmtk::SQLite::TableType* table = static_cast<cmtk::SQLite::TableType*>( pTable );
00083
00084 std::vector< std::string > tableRow( ncols );
00085 for ( int col = 0; col < ncols; ++col )
00086 {
00087 if ( rowdata[col] )
00088 tableRow[col] = std::string( rowdata[col] );
00089 else
00090 tableRow[col] = std::string( "NULL" );
00091 }
00092 table->push_back( tableRow );
00093
00094 return 0;
00095 }
00096
00097 void
00098 cmtk::SQLite::Query( const std::string& sql, cmtk::SQLite::TableType& table ) const
00099 {
00100 if ( ! this->Good() )
00101 throw Self::Exception( "Attempting operation on invalid SQLite database object" );
00102
00103 if ( this->m_DebugMode )
00104 {
00105 StdErr << sql << "\n";
00106 }
00107
00108 table.resize( 0 );
00109
00110 char* err = NULL;
00111 if ( sqlite3_exec( this->m_DB, sql.c_str(), cmtkSQLiteQueryCallback, &table, &err ) != SQLITE_OK )
00112 {
00113 StdErr << "Query " << sql << "\nSQL error: " << err << "\n";
00114 sqlite3_free( err );
00115 }
00116 }
00117
00118 bool
00119 cmtk::SQLite::TableExists( const std::string& tableName ) const
00120 {
00121 Self::TableType table;
00122 this->Query( "SELECT name FROM SQLite_Master WHERE name='"+tableName+"'", table );
00123
00124 return table.size() && table[0].size() && (table[0][0] == tableName);
00125 }