Botan 3.14.1
Crypto and TLS for C&
sqlite3.cpp
Go to the documentation of this file.
1/*
2* SQLite wrapper
3* (C) 2012 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/sqlite3.h>
9
10#include <botan/assert.h>
11#include <botan/mem_ops.h>
12#include <botan/internal/fmt.h>
13#include <botan/internal/int_utils.h>
14#include <sqlite3.h>
15
16namespace Botan {
17
18Sqlite3_Database::Sqlite3_Database(std::string_view db_filename, std::optional<int> sqlite_open_flags) {
19 // SQLITE_OPEN_FULLMUTEX ensures that the database object can be used
20 // concurrently from multiple threads.
21 const int open_flags =
22 sqlite_open_flags.value_or(SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX);
23 sqlite3* db = nullptr;
24 const int rc = ::sqlite3_open_v2(std::string(db_filename).c_str(), &db, open_flags, nullptr);
25
26 if(rc != 0) [[unlikely]] {
27 const std::string err_msg = (db != nullptr) ? ::sqlite3_errmsg(db) : "unknown error";
28 ::sqlite3_close_v2(db);
29 throw SQL_DB_Error("sqlite3_open failed - " + err_msg);
30 }
31
32 m_db = std::shared_ptr<sqlite3>(db, [](sqlite3* p) noexcept { ::sqlite3_close_v2(p); });
33}
34
36
37std::shared_ptr<SQL_Database::Statement> Sqlite3_Database::new_statement(std::string_view base_sql) const {
38 return std::make_shared<Sqlite3_Statement>(m_db, base_sql);
39}
40
41std::shared_ptr<SQL_Database::Statement> Sqlite3_Database::upsert(
42 std::string_view table, std::initializer_list<std::string_view> columns) const {
43 BOTAN_ARG_CHECK(columns.size() > 0, "upsert requires at least one column");
44
45 std::string sql = "INSERT OR REPLACE INTO ";
46 sql += table;
47 sql += " (";
48 bool first = true;
49 for(const auto& col : columns) {
50 if(!first) {
51 sql += ", ";
52 }
53 sql += col;
54 first = false;
55 }
56 sql += ") VALUES (";
57 for(size_t i = 1; i <= columns.size(); ++i) {
58 if(i > 1) {
59 sql += ", ";
60 }
61 sql += fmt("?{}", i);
62 }
63 sql += ')';
64
65 return new_statement(sql);
66}
67
68size_t Sqlite3_Database::row_count(std::string_view table_name) {
69 BOTAN_ARG_CHECK(is_valid_table_name(table_name), "Invalid table name");
70 const auto stmt = new_statement(fmt("select count(*) from {}", table_name));
71
72 if(stmt->step()) {
73 return stmt->get_size_t(0);
74 } else {
75 throw SQL_DB_Error(fmt("Querying size of table '{}' failed", table_name));
76 }
77}
78
80 BOTAN_ARG_CHECK(!schema.name().empty(), "create_table requires a table name");
81 BOTAN_ARG_CHECK(!schema.columns().empty(), "create_table requires at least one column");
82
83 std::string sql = "CREATE TABLE ";
84 if(schema.is_if_not_exists()) {
85 sql += "IF NOT EXISTS ";
86 }
87 sql += schema.name();
88 sql += " (";
89 bool first = true;
90 for(const auto& col : schema.columns()) {
91 if(!first) {
92 sql += ", ";
93 }
94 sql += col.name();
95 sql += ' ';
96 switch(col.type()) {
98 sql += "BLOB";
99 break;
101 sql += "TEXT";
102 break;
104 sql += "INTEGER";
105 break;
106 }
107 if(col.is_primary_key()) {
108 sql += " PRIMARY KEY";
109 }
110 if(col.is_unique()) {
111 sql += " UNIQUE";
112 }
113 if(col.is_not_null()) {
114 sql += " NOT NULL";
115 }
116 first = false;
117 }
118 sql += ')';
119
120 char* errmsg = nullptr;
121 const int rc = ::sqlite3_exec(m_db.get(), sql.c_str(), nullptr, nullptr, &errmsg);
122
123 if(rc != SQLITE_OK) {
124 const std::string err_msg = (errmsg != nullptr) ? errmsg : "unknown error";
125 ::sqlite3_free(errmsg);
126 throw SQL_DB_Error("sqlite3_exec for create_table failed - " + err_msg, rc);
127 }
128}
129
131 const auto result = ::sqlite3_changes64(m_db.get());
132 BOTAN_ASSERT_NOMSG(result >= 0);
133 return static_cast<size_t>(result);
134}
135
137 // sqlite3_db_mutex() returns the connection's mutex if the connection is in
138 // serialized mode, and nullptr otherwise. This reflects both the compile-time
139 // SQLITE_THREADSAFE setting and the per-connection SQLITE_OPEN_(FULL|NO)MUTEX
140 // open flags actually used.
141 //
142 // https://www.sqlite.org/c3ref/db_mutex.html
143 return ::sqlite3_db_mutex(m_db.get()) != nullptr;
144}
145
146Sqlite3_Database::Sqlite3_Statement::Sqlite3_Statement(std::shared_ptr<sqlite3> db, std::string_view base_sql) :
147 m_db(std::move(db)), m_stmt{} {
148 const int rc =
149 ::sqlite3_prepare_v2(m_db.get(), base_sql.data(), static_cast<int>(base_sql.size()), &m_stmt, nullptr);
150
151 if(rc != SQLITE_OK) {
152 throw SQL_DB_Error(fmt("sqlite3_prepare failed on '{}' with err {}", base_sql, rc), rc);
153 }
154}
155
156void Sqlite3_Database::Sqlite3_Statement::bind(int column, std::string_view val) {
157 if(val.data() == nullptr) {
158 bind_null(column);
159 return;
160 }
161 const int rc = ::sqlite3_bind_text64(m_stmt, column, val.data(), val.size(), SQLITE_TRANSIENT, SQLITE_UTF8);
162 if(rc != SQLITE_OK) {
163 throw SQL_DB_Error("sqlite3_bind_text failed", rc);
164 }
165}
166
167void Sqlite3_Database::Sqlite3_Statement::bind(int column, size_t val) {
168 const int rc = ::sqlite3_bind_int64(m_stmt, column, val);
169 if(rc != SQLITE_OK) {
170 throw SQL_DB_Error("sqlite3_bind_int failed", rc);
171 }
172}
173
174void Sqlite3_Database::Sqlite3_Statement::bind(int column, std::chrono::system_clock::time_point time) {
175 const uint64_t timeval = std::chrono::duration_cast<std::chrono::seconds>(time.time_since_epoch()).count();
176 bind(column, static_cast<size_t>(timeval));
177}
178
179void Sqlite3_Database::Sqlite3_Statement::bind(int column, const std::vector<uint8_t>& val) {
180 bind(column, val.data(), val.size());
181}
182
183void Sqlite3_Database::Sqlite3_Statement::bind(int column, const uint8_t* p, size_t len) {
184 if(p == nullptr) {
185 bind_null(column);
186 return;
187 }
188 const int rc = ::sqlite3_bind_blob64(m_stmt, column, p, len, SQLITE_TRANSIENT);
189 if(rc != SQLITE_OK) {
190 throw SQL_DB_Error("sqlite3_bind_blob failed", rc);
191 }
192}
193
194void Sqlite3_Database::Sqlite3_Statement::bind_null(int column) {
195 const int rc = ::sqlite3_bind_null(m_stmt, column);
196 if(rc != SQLITE_OK) {
197 throw SQL_DB_Error("sqlite3_bind_null failed", rc);
198 }
199}
200
201std::span<const uint8_t> Sqlite3_Database::Sqlite3_Statement::get_blob(int column) {
202 const auto column_type = ::sqlite3_column_type(m_stmt, column);
203 if(column_type == SQLITE_NULL) {
204 return {};
205 }
206
207 BOTAN_ASSERT(column_type == SQLITE_BLOB, "Return value is a blob");
208
209 const void* session_blob = ::sqlite3_column_blob(m_stmt, column);
210 const int session_blob_size = ::sqlite3_column_bytes(m_stmt, column);
211
212 BOTAN_ASSERT(session_blob_size >= 0, "Blob size is non-negative");
213
214 return {static_cast<const uint8_t*>(session_blob), static_cast<size_t>(session_blob_size)};
215}
216
217std::optional<std::string> Sqlite3_Database::Sqlite3_Statement::get_str(int column) {
218 const auto column_type = ::sqlite3_column_type(m_stmt, column);
219 if(column_type == SQLITE_NULL) {
220 return std::nullopt;
221 }
222
223 BOTAN_ASSERT(column_type == SQLITE_TEXT, "Return value is text");
224
225 const unsigned char* str = ::sqlite3_column_text(m_stmt, column);
226 const int len = ::sqlite3_column_bytes(m_stmt, column);
227 BOTAN_ASSERT(len >= 0, "Text length is non-negative");
228
229 return std::string(cast_uint8_ptr_to_char(str), static_cast<size_t>(len));
230}
231
232size_t Sqlite3_Database::Sqlite3_Statement::get_size_t(int column) {
233 BOTAN_ASSERT(::sqlite3_column_type(m_stmt, column) == SQLITE_INTEGER, "Return count is an integer");
234
235 return checked_cast_to<size_t>(::sqlite3_column_int64(m_stmt, column));
236}
237
239 size_t steps = 0;
240 while(step()) {
241 ++steps;
242 }
243
244 return steps;
245}
246
248 const int rc = ::sqlite3_step(m_stmt);
249 if(rc == SQLITE_ROW) {
250 return true;
251 }
252 if(rc == SQLITE_DONE) {
253 return false;
254 }
255 throw SQL_DB_Error(fmt("sqlite3_step failed - {}", ::sqlite3_errmsg(::sqlite3_db_handle(m_stmt))), rc);
256}
257
258Sqlite3_Database::Sqlite3_Statement::~Sqlite3_Statement() {
259 ::sqlite3_finalize(m_stmt);
260}
261
262} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:69
const std::string & name() const
Definition database.h:305
const std::vector< Column > & columns() const
Definition database.h:311
virtual bool is_valid_table_name(std::string_view table) const
Definition database.cpp:14
std::shared_ptr< Statement > upsert(std::string_view table, std::initializer_list< std::string_view > columns) const override
Definition sqlite3.cpp:41
~Sqlite3_Database() override
std::shared_ptr< Statement > new_statement(std::string_view sql) const override
Definition sqlite3.cpp:37
size_t rows_changed_by_last_statement() override
Definition sqlite3.cpp:130
bool is_threadsafe() const override
Definition sqlite3.cpp:136
BOTAN_FUTURE_EXPLICIT Sqlite3_Database(std::string_view file, std::optional< int > sqlite_open_flags=std::nullopt)
Definition sqlite3.cpp:18
size_t row_count(std::string_view table_name) override
Definition sqlite3.cpp:68
void create_table(const Table_Schema &schema) override
Definition sqlite3.cpp:79
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
constexpr RT checked_cast_to(AT i)
Definition int_utils.h:104
const char * cast_uint8_ptr_to_char(const uint8_t *b)
Definition mem_ops.h:323
Public Header.