Skip to content

Commit bdfcb45

Browse files
empty value safety, non-throwing .at() for database rows and fields
1 parent 119a689 commit bdfcb45

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

include/ssod/database.h

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,39 @@ namespace db {
3333
/**
3434
* @brief Definition of a row in a result set
3535
*/
36-
using row = std::map<std::string, std::string>;
36+
struct row {
37+
std::map<std::string, std::string> fields;
38+
39+
[[nodiscard]] inline const std::string at(const std::string& index) const {
40+
try {
41+
return fields.at(index);
42+
}
43+
catch (const std::exception&) {
44+
return "";
45+
}
46+
}
47+
48+
inline void emplace(const std::string& k, const std::string& v) {
49+
fields.emplace(k, v);
50+
}
51+
52+
[[nodiscard]] inline auto begin() const {
53+
return fields.begin();
54+
}
55+
56+
[[nodiscard]] inline auto end() const {
57+
return fields.end();
58+
}
59+
60+
[[nodiscard]] inline bool empty() const {
61+
return fields.empty();
62+
}
63+
64+
[[nodiscard]] inline size_t size() const {
65+
return fields.size();
66+
}
67+
68+
};
3769

3870
/**
3971
* @brief Definition of a result set. Supports iteration and accessing its
@@ -68,8 +100,13 @@ namespace db {
68100
* @param index row to rerieve
69101
* @return row
70102
*/
71-
[[nodiscard]] inline const row& at(size_t index) const {
72-
return rows.at(index);
103+
[[nodiscard]] inline const row at(size_t index) const {
104+
try {
105+
return rows.at(index);
106+
}
107+
catch (const std::exception&) {
108+
return {};
109+
}
73110
}
74111

75112
/**

src/database.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ namespace db {
551551
while (s_field_count < mysql_num_fields(a_res)) {
552552
std::string a = (fields[s_field_count].name ? fields[s_field_count].name : "");
553553
std::string b = is_null[s_field_count] ? "" : std::string(string_buffers[s_field_count], lengths[s_field_count]);
554-
thisrow[a] = b;
554+
thisrow.emplace(a, b);
555555
s_field_count++;
556556
}
557557
if (!thisrow.empty()) {

0 commit comments

Comments
 (0)