3
// SQLite backend for PowerDNS
4
// Copyright (C) 2003, Michel Stol <michel@powerdns.com>
7
#include "pdns/utility.hh"
14
# define access _access
21
SSQLite3::SSQLite3( const std::string & database, bool creat )
23
// Open the database connection.
25
if ( access( database.c_str(), F_OK ) == -1 )
26
throw sPerrorException( "SQLite database does not exist yet" );
28
if ( sqlite3_open( database.c_str(), &m_pDB)!=SQLITE_OK )
29
throw sPerrorException( "Could not connect to the SQLite database '" + database + "'" );
31
sqlite3_busy_handler(m_pDB, busyHandler, 0);
38
for(int n = 0; n < 2 ; ++n) {
39
if((ret =sqlite3_close( m_pDB )) != SQLITE_OK) {
40
if(n || !m_pStmt || ret != SQLITE_BUSY) { // if we have SQLITE_BUSY, and a working m_Pstmt, try finalize
41
cerr<<"Unable to close down sqlite connection: "<<ret<<endl;
45
sqlite3_finalize(m_pStmt);
54
// Constructs a SSqlException object.
55
SSqlException SSQLite3::sPerrorException( const std::string & reason )
57
return SSqlException( reason );
62
int SSQLite3::doQuery( const std::string & query, result_t & result )
70
result.push_back( row );
77
int SSQLite3::doQuery( const std::string & query )
82
#if SQLITE_VERSION_NUMBER >= 3003009
83
if ( sqlite3_prepare_v2( m_pDB, query.c_str(), -1, &m_pStmt, &pTail ) != SQLITE_OK )
85
if ( sqlite3_prepare( m_pDB, query.c_str(), -1, &m_pStmt, &pTail ) != SQLITE_OK )
87
throw sPerrorException( string("Unable to compile SQLite statement : ")+ sqlite3_errmsg( m_pDB ) );
92
int SSQLite3::busyHandler(void*, int)
98
// Returns a row from the result set.
99
bool SSQLite3::getRow( row_t & row )
107
rc = sqlite3_step( m_pStmt );
109
if ( rc == SQLITE_ROW )
111
numCols = sqlite3_column_count( m_pStmt );
112
// Another row received, process it.
113
for ( int i = 0; i < numCols; i++ )
115
pData = (const char*) sqlite3_column_text( m_pStmt, i );
116
row.push_back( pData ? pData : "" ); // NULL value to "".
122
if ( rc == SQLITE_DONE )
124
// We're done, clean up.
125
sqlite3_finalize( m_pStmt );
130
if(rc == SQLITE_CANTOPEN) {
131
string error ="CANTOPEN error in sqlite3, often caused by unwritable sqlite3 db *directory*: "+string(sqlite3_errmsg(m_pDB));
132
sqlite3_finalize(m_pStmt);
134
throw sPerrorException(error);
137
// Something went wrong, complain.
138
throw sPerrorException( "Error while retrieving SQLite query results: "+string(sqlite3_errmsg(m_pDB) ));
140
// Prevent some compilers from complaining.
145
// Escape a SQL query.
146
std::string SSQLite3::escape( const std::string & name)
150
for( std::string::const_iterator i = name.begin(); i != name.end(); ++i )
152
if( *i == '\'' || *i == '\\' )