kima2/src/core/database.cpp

62 lines
1.6 KiB
C++
Raw Normal View History

2018-07-06 13:30:23 +02:00
#include "database.h"
#include <stdexcept>
2018-07-10 14:12:37 +02:00
#include <iostream>
2018-07-06 13:30:23 +02:00
2018-07-10 14:12:37 +02:00
Database::Database(const std::string& dbname) : db_(nullptr)
2018-07-06 13:30:23 +02:00
{
2018-07-10 14:12:37 +02:00
const int errCode = sqlite3_open(dbname.c_str(), &db_);
2018-07-09 13:03:03 +02:00
if (errCode) {
2018-07-06 13:30:23 +02:00
throw std::runtime_error("Could not open database file.");
}
2018-07-10 14:12:37 +02:00
exec("PRAGMA foreign_key = 1");
2018-07-06 13:30:23 +02:00
}
2018-07-10 14:12:37 +02:00
Database::~Database() { sqlite3_close(db_); }
2018-07-06 13:30:23 +02:00
void Database::exec(const std::string& sql)
{
2018-07-10 14:12:37 +02:00
const int errCode = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, nullptr);
2018-07-09 13:03:03 +02:00
if (errCode) {
2018-07-06 13:30:23 +02:00
throw std::runtime_error("Error in SQL execution.");
}
2018-07-09 21:03:59 +02:00
}
2018-07-10 14:12:37 +02:00
void Database::init()
{
std::string sqlCreateSellers{
"CREATE TABLE IF NOT EXISTS sellers ("
"id TEXT PRIMARY KEY NOT NULL, "
"seller_no INTEGER, "
"first_name TEXT, "
"last_name TEXT, "
"offered_articles INTEGER, "
"UNIQUE (seller_no)"
");"
};
std::string sqlCreateArticles{
"CREATE TABLE IF NOT EXISTS articles ("
"id TEXT PRIMARY KEY NOT NULL, "
"seller_id TEXT NOT NULL, "
"source_no INTEGER NOT NULL, "
"article_no INTEGER NOT NULL, "
"description TEXT, "
"price INTEGER NOT NULL, "
"UNIQUE (source_no, article_no), "
"FOREIGN KEY (seller_id) REFERENCES sellers(id) ON DELETE CASCADE, "
"CHECK (article_no BETWEEN 0 AND 99999)"
");"
};
std::cout << sqlCreateArticles << "\n";
beginTransaction();
exec(sqlCreateSellers);
exec(sqlCreateArticles);
endTransaction();
}
2018-07-10 12:51:23 +02:00
void Database::beginTransaction() { exec("BEGIN TRANSACTION"); }
2018-07-09 21:03:59 +02:00
2018-07-10 12:51:23 +02:00
void Database::endTransaction() { exec("END TRANSACTION"); }