-
Notifications
You must be signed in to change notification settings - Fork 0
/
scientistrepository.cpp
93 lines (64 loc) · 2.7 KB
/
scientistrepository.cpp
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
85
86
87
88
89
90
91
92
93
#include "scientistrepository.h"
#include <stdexcept>
#include <string>
#include <iostream>
ScientistRepository::ScientistRepository() {
createConnection();
}
ScientistRepository::~ScientistRepository() {
}
void ScientistRepository::add(Scientist scientist) {
QSqlQuery query(db);
QString gender;
query.prepare("INSERT INTO Scientists (Name, DateOfBirth, DateOfDeath, Gender) VALUES (:name,:dob,:dod,:gender)");
query.bindValue(":name", QString::fromStdString(scientist.getName()));
query.bindValue(":dob", QString::fromStdString(scientist.getDateOfBirth()));
query.bindValue(":dod", QString::fromStdString(scientist.getDateOfDeath()));
query.bindValue(":gender", QString::number(scientist.getGender()));
query.exec();
}
void ScientistRepository::remove(std::string id) {
QSqlQuery query(db);
query.prepare("DELETE FROM Scientists WHERE id = :id");
query.bindValue(":id", std::atoi(id.c_str()));
query.exec();
query.prepare("DELETE FROM ScientistComputerConnections WHERE s_ID = :id");
query.bindValue(":id", std::atoi(id.c_str()));
query.exec();
}
std::list<Scientist> ScientistRepository::list() {
return list("","");
}
std::list<Scientist> ScientistRepository::list(std::string col, std::string mod) {
std::list<Scientist> scientistList = std::list<Scientist>();
QSqlQuery query(db);
std::string orderBy = "";
if(!col.empty()){
mod = mod.empty() ? "ASC" : (mod.find("desc") != std::string::npos ? "DESC" : "ASC");
orderBy = "order by " + col + " " + mod;
}
query.exec("SELECT * FROM Scientists " + QString::fromStdString(orderBy));
populateScientistList(scientistList, query);
return scientistList;
}
std::list<Scientist> ScientistRepository::search(std::string searchTerm) {
// Naive search implementation, finds a substring in the name field
std::list<Scientist> scientistList = std::list<Scientist>();
QSqlQuery query(db);
std::string q = "SELECT * FROM Scientists WHERE Name LIKE '%"+searchTerm+"%'";
query.exec(QString::fromStdString(q));
populateScientistList(scientistList, query);
return scientistList;
}
void ScientistRepository::populateScientistList(std::list<Scientist> &scientistList, QSqlQuery query){
while(query.next()){
Scientist s = Scientist();
s.setId(query.value("ID").toInt());
s.setName(query.value("Name").toString().toStdString());
s.setDateOfBirth(query.value("DateOfBirth").toString().toStdString());
s.setDateOfDeath(query.value("DateOfDeath").toString().toStdString());
s.setGender(query.value("Gender").toInt());
s.setBlob( query.value("Pic"));
scientistList.push_back(s);
}
}