Skip to content

Commit

Permalink
[api] Added Sqlite.close()
Browse files Browse the repository at this point in the history
  • Loading branch information
pajama-coder committed Jul 14, 2024
1 parent 117d14f commit b44448a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/api/sqlite.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,13 @@ Database::Database(pjs::Str *filename, int flags) {
}

Database::~Database() {
sqlite3_close(m_db);
if (m_db) {
sqlite3_close_v2(m_db);
}
}

auto Database::sql(pjs::Str *sql) -> Statement* {
if (!m_db) throw std::runtime_error("Database is closed");
sqlite3_stmt *stmt = nullptr;
if (SQLITE_OK != sqlite3_prepare_v2(m_db, sql->c_str(), sql->size(), &stmt, nullptr)) {
throw_error(m_db);
Expand All @@ -143,6 +146,7 @@ auto Database::sql(pjs::Str *sql) -> Statement* {
}

auto Database::exec(pjs::Str *sql) -> pjs::Array* {
if (!m_db) throw std::runtime_error("Database is closed");
char *err = nullptr;
auto rows = pjs::Array::make();
sqlite3_exec(m_db, sql->c_str(), append_exec_row, rows, &err);
Expand All @@ -156,6 +160,13 @@ auto Database::exec(pjs::Str *sql) -> pjs::Array* {
return rows;
}

void Database::close() {
if (m_db) {
sqlite3_close_v2(m_db);
m_db = nullptr;
}
}

//
// Statement
//
Expand Down Expand Up @@ -282,6 +293,10 @@ template<> void ClassDef<Database>::init() {
ctx.error(err);
}
});

method("close", [](Context &ctx, Object *obj, Value &ret) {
static_cast<Database*>(obj)->close();
});
}

template<> void ClassDef<Statement>::init() {
Expand Down
1 change: 1 addition & 0 deletions src/api/sqlite.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class Database : public pjs::ObjectTemplate<Database> {
public:
auto sql(pjs::Str *sql) -> Statement*;
auto exec(pjs::Str *sql) -> pjs::Array*;
void close();

private:
Database(pjs::Str *filename, int flags = 0);
Expand Down

0 comments on commit b44448a

Please sign in to comment.