-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.cpp
More file actions
84 lines (72 loc) · 2.53 KB
/
Database.cpp
File metadata and controls
84 lines (72 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "Constraint.hpp"
#include "fmt/format.h"
#include "Database.hpp"
#include "CommonTypes.hpp"
#include "Table.hpp"
#include <memory>
auto Database::addTable(TablePtr table) -> void {
auto table_name = table->getName();
std::transform(table_name.begin(), table_name.end(), table_name.begin(), ::tolower);
if (tableExists(table_name)) {
throw std::runtime_error(
fmt::format("table already exists: {}", table->getName())
);
}
tables_[table_name] = std::move(table);
}
auto Database::dropTable(const std::string& name) -> bool {
auto table_name = name;
std::transform(table_name.begin(), table_name.end(), table_name.begin(), ::tolower);
if (!tableExists(table_name)) {
return false;
}
tables_.erase(table_name);
return true;
}
auto Database::getTable(const std::string& name) const -> TablePtr {
auto table_name = name;
std::transform(table_name.begin(), table_name.end(), table_name.begin(), ::tolower);
auto it = tables_.find(table_name);
if (it != tables_.end()) return it->second;
return nullptr;
}
auto Database::tableExists(const std::string& name) const -> bool {
auto table_name = name;
std::transform(table_name.begin(), table_name.end(), table_name.begin(), ::tolower);
return tables_.find(table_name) != tables_.end();
}
auto Database::getName() const -> const std::string& {
return name_;
}
auto Database::setName(std::string new_name) -> void {
if (new_name.empty()) {
throw std::runtime_error("database name cannot be empty");
}
name_ = std::move(new_name);
}
auto Database::getTableNames() const -> std::vector<std::string> {
auto names = std::vector<std::string>();
names.reserve(tables_.size());
for (const auto& [name, _] : tables_) {
names.push_back(name);
}
return names;
}
auto Database::validateRow(const std::string& table_name, const Row& row) -> bool {
auto table = getTable(table_name);
if (!table) return false;
if (!table->validateRow(row)) return false; // not sure if this is neccessary but lets leave it like that for now.
// check db-level constraints
for (const auto& constraint : table->getConstraints()) {
if (constraint->getType() == ConstraintType::FOREIGN_KEY) {
auto fk = std::dynamic_pointer_cast<ForeignKeyConstraint>(constraint);
if (fk && !fk->validate(row, *table, *this)) {
return false;
}
}
}
return true;
}
auto Database::clear() -> void {
tables_.clear();
}