2008-10-09 17:29:32 UTC
previous
next
/* Echo Media Player
* Copyright (C) 2008 Shane O'Connell
*
* [ The original file includes a copyright header in this location describing
* the file as being released under the terms of the GNU General Public
* License. It has been removed in order to display the file as part of the
* archive. ]
*/
#ifndef SQL_H_
#define SQL_H_
#include <sqlite3.h>
#include <cassert>
#include <boost/noncopyable.hpp>
// TODO handle sqlite errors in these calls
class SQLstmt : boost::noncopyable
{
public:
SQLstmt() : stmt(0)
{}
~SQLstmt()
{
if (stmt)
sqlite3_finalize(stmt);
}
void bind(int index, const Glib::ustring& value)
{
assert(stmt);
int rc = sqlite3_bind_text(stmt, index, value.data(), -1, SQLITE_TRANSIENT);
assert(rc == SQLITE_OK);
}
void bind(int index, long long value)
{
assert(stmt);
int rc = sqlite3_bind_int64(stmt, index, value);
assert(rc == SQLITE_OK);
}
void bind(int index, int value)
{
assert(stmt);
int rc = sqlite3_bind_int(stmt, index, value);
assert(rc == SQLITE_OK);
}
bool step()
{
assert(stmt);
int rc = sqlite3_step(stmt);
assert(rc == SQLITE_DONE || rc == SQLITE_ROW);
return (rc == SQLITE_ROW);
}
long long get_column_int(int index) const
{
assert(stmt);
return sqlite3_column_int64(stmt, index);
}
const char* get_column_text(int index) const
{
assert(stmt);
return (const char*)sqlite3_column_text(stmt, index);
}
void reset()
{
assert(stmt);
int rc = sqlite3_reset(stmt);
assert(rc == SQLITE_OK);
}
private:
friend class SQL;
sqlite3_stmt* stmt;
};
class SQL : boost::noncopyable
{
public:
SQL() : db(0)
{}
~SQL()
{
if (db)
sqlite3_close(db);
}
void open(const std::string& path)
{
if (db)
sqlite3_close(db);
int rc = sqlite3_open(path.c_str(), &db);
assert(rc == SQLITE_OK);
}
void run(const Glib::ustring& sql)
{
sqlite3_stmt* stmt;
int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
assert(rc == SQLITE_OK);
rc = sqlite3_step(stmt);
assert(rc == SQLITE_DONE || rc == SQLITE_ROW);
rc = sqlite3_finalize(stmt);
assert(rc == SQLITE_OK);
}
void prepare(SQLstmt& stmt, const Glib::ustring& sql)
{
if (stmt.stmt)
sqlite3_finalize(stmt.stmt);
int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt.stmt, NULL);
assert(rc == SQLITE_OK);
}
long long last_rowid() const
{
return sqlite3_last_insert_rowid(db);
}
private:
sqlite3* db;
};
#endif /* SQL_H_ */