Skip to content
database.cc 2.74 KiB
Newer Older
Seblu's avatar
Seblu committed
#include "sls.hh"
#include "database.hh"
#include "error.hh"

// *****************************************************************************
// Public Method
// *****************************************************************************
Database::Database() : db_(0) {}

void Database::open(const string &path) {

  if (path.empty())
    throw Error(ERR_DB, "DB filename is empty");

  if (db_)
    throw Error(ERR_DB, "DB already open");

  // Try to open db
  if (sqlite3_open(path.c_str(), &db_)) {
    string msg = (string) "Can't open database: " + sqlite3_errmsg(db_);
    sqlite3_close(db_);
    db_ = 0;
    throw Error(ERR_DB, msg);
  }

  // load structs
  load_hosts_();
  load_groups_();
  load_users_();
  load_scripts_();
  load_aliases_();

}

void Database::close() {
  if (!db_)
    throw Error(ERR_DB, "DB not open");

  // save structs
  save_hosts_();
  save_groups_();
  save_users_();
  save_scripts_();
  save_aliases_();

  // close db
  sqlite3_close(db_);
  db_ = 0;
}

// *****************************************************************************
// Protected Method
// *****************************************************************************

void Database::exec(const string &sql) {
  if (sql.empty())
    throw Error(ERR_DB, "SQL command is empty");

  if (!db_)
    throw Error(ERR_DB, "DB is not open");

  char *ErrMsg = 0;

  if (sqlite3_exec(db_, sql.c_str(), 0, 0, &ErrMsg) != SQLITE_OK) {
    string msg = (string) "SQL error: %s\n" +  ErrMsg;
    sqlite3_free(ErrMsg);
    throw Error(ERR_DB, msg);
  }
}

void Database::load_hosts_() {
  // create host table if not exists
  exec("BEGIN TRANSACTION;");
  exec("CREATE TABLE IF NOT EXISTS 'host' ( 'login' TEXT, 'pass' TEXT, 'ipv4' TEXT, 'level' NUMERIC );");
  exec("COMMIT;");
}

void Database::load_groups_() {
  // create group table if not exists
  exec("BEGIN TRANSACTION;");
  exec("CREATE TABLE IF NOT EXISTS 'group' ( 'name' TEXT, 'hosts' TEXT );");
  exec("COMMIT;");
}

void Database::load_users_() {
  // create user table if not exists
  exec("BEGIN TRANSACTION;");
  exec("CREATE TABLE IF NOT EXISTS 'user' ('login' TEXT, 'pass' TEXT, 'level' NUMERIC, 'priv' NUMERIC );");
  exec("COMMIT;");
}

void Database::load_scripts_() {
  // create script table if not exists
  exec("BEGIN TRANSACTION;");
  exec("CREATE TABLE IF NOT EXISTS 'script' ( 'name' TEXT, 'path' TEXT, 'level' NUMERIC );");
  exec("COMMIT;");
}

void Database::load_aliases_() {
  // create alias table if not exists
  exec("BEGIN TRANSACTION;");
  exec("CREATE TABLE IF NOT EXISTS 'alias' ( 'name' TEXT, 'value' TEXT );");
  exec("COMMIT;");
}

void Database::save_hosts_() {

}

void Database::save_groups_() {

}

void Database::save_users_() {

}

void Database::save_scripts_() {

}

void Database::save_aliases_() {

}