SlHelpers
Loading...
Searching...
No Matches
SQLConn.h
1// SPDX-License-Identifier: GPL-2.0-only
2
3#pragma once
4
5#include <filesystem>
6#include <optional>
7#include <string>
8#include <variant>
9#include <vector>
10
11#include "../helpers/LastError.h"
12#include "SQLiteSmart.h"
13
14namespace SlSqlite {
15
19enum OpenFlags : unsigned {
20 CREATE = 1 << 0,
21 NO_FOREIGN_KEY = 1 << 1,
22 ERROR_ON_UNIQUE_CONSTRAINT = 1 << 2,
23 READ_ONLY = 1 << 3,
24};
25
29enum struct TransactionType {
30 DEFERRED,
31 IMMEDIATE,
32 EXCLUSIVE,
33};
34
35class Select;
36class SQLConn;
37
41class AutoTransaction {
42public:
43 AutoTransaction() = delete;
45 AutoTransaction(const SQLConn &conn,
46 TransactionType type = TransactionType::DEFERRED);
47 ~AutoTransaction() { end(); }
48
49 AutoTransaction(const AutoTransaction &) = delete;
50 AutoTransaction &operator=(const AutoTransaction &) = delete;
51
53 AutoTransaction(AutoTransaction &&other) noexcept : m_conn(other.m_conn) {
54 other.m_conn = nullptr;
55 }
56
57 AutoTransaction &operator=(AutoTransaction &&other) noexcept {
58 if (this != &other) {
59 end();
60 m_conn = other.m_conn;
61 other.m_conn = nullptr;
62 }
63
64 return *this;
65 }
66
68 void end();
69
71 bool operator!() const { return !m_conn; }
73 operator bool() const { return m_conn; }
74private:
75 const SQLConn *m_conn;
76};
77
81class SQLConn {
82 friend class Select;
83public:
84 virtual ~SQLConn() = default;
85
87 SQLConn(SQLConn &&) = default;
89 SQLConn &operator=(SQLConn &&) = default;
90
97 bool open(const std::filesystem::path &dbFile, unsigned int flags = 0)
98 {
99 return openDB(dbFile, flags) && createDB() && prepDB();
100 }
101
108 bool openDB(const std::filesystem::path &dbFile, unsigned int flags = 0) noexcept;
109
116 virtual bool createDB() { return true; }
117
124 virtual bool prepDB() { return true; }
125
131 bool exec(const std::string &sql) const noexcept { return exec(sql, "exec failed"); }
132
139 bool attach(const std::filesystem::path &dbFile,
140 std::string_view dbName) const noexcept;
141
147 bool begin(TransactionType type = TransactionType::DEFERRED) const noexcept;
148
153 bool end() const noexcept { return exec("END;", "db END failed"); }
154
160 AutoTransaction beginAuto(TransactionType type = TransactionType::DEFERRED) const noexcept {
161 return AutoTransaction(*this, type);
162 }
163
165 std::string lastError() const { return m_lastError.lastError(); }
167 int lastErrorCode() const { return m_lastError.get<0>(); }
169 int lastErrorCodeExt() const { return m_lastError.get<1>(); }
170
171protected:
172 SQLConn() : m_flags(0) {}
173
175 using BindVal = std::variant<std::monostate, int, unsigned, std::string, std::string_view>;
177 using Binding = std::vector<std::pair<std::string, BindVal>>;
179 using Column = std::variant<std::monostate, int, std::string>;
181 using Row = std::vector<Column>;
183 using SelectResult = std::vector<Row>;
184
186 enum TableFlags : unsigned {
187 TABLE_TEMPORARY = 1u << 0,
188 };
189
191 struct TableEntry {
193 std::string name;
195 std::vector<std::string> columns;
197 unsigned flags = 0u;
198 };
199
201 using Tables = std::vector<TableEntry>;
203 using Indices = std::vector<std::pair<std::string, std::string>>;
207 using Views = Indices;
209 using Statements = std::vector<std::pair<std::reference_wrapper<SQLStmtHolder>, std::string>>;
210
212 bool createTables(const Tables &tables) const noexcept;
214 bool createIndices(const Indices &indices) const noexcept;
216 bool createTriggers(const Triggers &triggers) const noexcept;
218 bool createViews(const Views &views) const noexcept;
219
221 bool prepareStatement(std::string_view sql, SQLStmtHolder &stmt) const noexcept;
223 bool prepareStatements(const Statements &stmts) const noexcept;
224
226 bool bind(const SQLStmtHolder &ins, const std::string &key,
227 const BindVal &val, bool transient = false) const noexcept;
229 bool bind(const SQLStmtHolder &ins, const Binding &binding,
230 bool transient = false) const noexcept;
232 bool step(const SQLStmtHolder &ins, uint64_t *affected = nullptr,
233 bool *uniqueError = nullptr) const noexcept;
235 bool insert(const SQLStmtHolder &ins, const Binding &binding = {},
236 uint64_t *affected = nullptr) const noexcept;
237
239 std::optional<SQLConn::SelectResult>
240 select(const SQLStmtHolder &sel, const Binding &binding) const noexcept;
241
243 static BindVal valueOrNull(bool cond, BindVal val) {
244 return cond ? std::move(val) : std::monostate();
245 }
246
249
251 LastError &setError(int ret, std::string_view error, bool errmsg = false) const;
252
254 SQLHolder sqlHolder;
256 unsigned int m_flags;
259private:
260 bool exec(const std::string &SQL, std::string_view errorMsg,
261 bool includeSQL = false) const noexcept;
262
263 static constexpr bool isUniqueConstraint(int sqlExtError) noexcept;
264 static int busyHandler(void *, int count);
265 void dumpBinding(const Binding &binding) const noexcept;
266};
267
268inline AutoTransaction::AutoTransaction(const SQLConn &conn, TransactionType type)
269 : m_conn(conn.begin(type) ? &conn : nullptr)
270{
271}
272
274{
275 if (m_conn) {
276 m_conn->end();
277 m_conn = nullptr;
278 }
279}
280
281}
Stores a string (usually an error string) to be retrieved later.
Definition LastError.h:87
Begin a transaction in the constructor and end in the destructor.
Definition SQLConn.h:41
void end()
End the transaction manually.
Definition SQLConn.h:273
AutoTransaction & operator=(AutoTransaction &&other) noexcept
Move assignment.
Definition SQLConn.h:57
bool operator!() const
Test whether AutoTransaction is valid.
Definition SQLConn.h:71
AutoTransaction(AutoTransaction &&other) noexcept
Move constructor.
Definition SQLConn.h:53
SQLite3 connection (the core class)
Definition SQLConn.h:81
bool prepareStatement(std::string_view sql, SQLStmtHolder &stmt) const noexcept
Prepate one sql string into stmt.
std::variant< std::monostate, int, unsigned, std::string, std::string_view > BindVal
Bind value (SQL's null, number, string)
Definition SQLConn.h:175
std::variant< std::monostate, int, std::string > Column
One column returned by SELECT.
Definition SQLConn.h:179
SQLHolder sqlHolder
The DB connection.
Definition SQLConn.h:254
virtual bool createDB()
Creates tables, views, triggers and such.
Definition SQLConn.h:116
bool insert(const SQLStmtHolder &ins, const Binding &binding={}, uint64_t *affected=nullptr) const noexcept
Bind, step, and reset the statement ins, using the passed binding.
LastError & setError(int ret, std::string_view error, bool errmsg=false) const
Set last error to ret and error.
bool step(const SQLStmtHolder &ins, uint64_t *affected=nullptr, bool *uniqueError=nullptr) const noexcept
Do one step of the statement ins.
bool createIndices(const Indices &indices) const noexcept
Create indices in the DB as specified in indices.
std::vector< Column > Row
One row returned by SELECT (ie. list of Columns)
Definition SQLConn.h:181
bool createTables(const Tables &tables) const noexcept
Create tables in the DB as specified in tables.
AutoTransaction beginAuto(TransactionType type=TransactionType::DEFERRED) const noexcept
Begin a transaction which is automatically ended when the returned object dies.
Definition SQLConn.h:160
bool attach(const std::filesystem::path &dbFile, std::string_view dbName) const noexcept
Attach another database using ATTACH.
int lastErrorCode() const
Return the last error number.
Definition SQLConn.h:167
SQLConn & operator=(SQLConn &&)=default
Move assignment.
SQLConn(SQLConn &&)=default
Move constructor.
unsigned int m_flags
OpenFlags.
Definition SQLConn.h:256
bool open(const std::filesystem::path &dbFile, unsigned int flags=0)
Open a database connection (openDB() + createDB() + prepDB())
Definition SQLConn.h:97
std::optional< SQLConn::SelectResult > select(const SQLStmtHolder &sel, const Binding &binding) const noexcept
Perform one SELECT (sel), using the passed binding.
int lastErrorCodeExt() const
Return the last extended error number.
Definition SQLConn.h:169
bool createViews(const Views &views) const noexcept
Create views in the DB as specified in views.
bool openDB(const std::filesystem::path &dbFile, unsigned int flags=0) noexcept
Just open a database file.
bool begin(TransactionType type=TransactionType::DEFERRED) const noexcept
Begin a transaction.
virtual bool prepDB()
Prepares statements.
Definition SQLConn.h:124
std::vector< Row > SelectResult
Complete SELECT result.
Definition SQLConn.h:183
std::vector< std::pair< std::string, std::string > > Indices
Indices to be created by createIndices()
Definition SQLConn.h:203
bool exec(const std::string &sql) const noexcept
Execute sql.
Definition SQLConn.h:131
SlHelpers::LastErrorStream< int, int > LastError
Store a string + 2 ints.
Definition SQLConn.h:248
bool bind(const SQLStmtHolder &ins, const std::string &key, const BindVal &val, bool transient=false) const noexcept
Bind one value val into key of the statement ins.
std::string lastError() const
Return the last error string if some.
Definition SQLConn.h:165
std::vector< TableEntry > Tables
Tables to be created by createTables()
Definition SQLConn.h:201
bool createTriggers(const Triggers &triggers) const noexcept
Create triggers in the DB as specified in triggers.
bool prepareStatements(const Statements &stmts) const noexcept
Prepate all statements as specified in stmts.
static BindVal valueOrNull(bool cond, BindVal val)
A helper to build a null BindVal if cond does not hold, val otherwise.
Definition SQLConn.h:243
Indices Triggers
Triggers to be created by createTriggers()
Definition SQLConn.h:205
Indices Views
Views to be created by createViews()
Definition SQLConn.h:207
TableFlags
Flags for TableEntry::flags.
Definition SQLConn.h:186
std::vector< std::pair< std::string, BindVal > > Binding
Bind name -> bind value.
Definition SQLConn.h:177
bool end() const noexcept
End a transaction.
Definition SQLConn.h:153
std::vector< std::pair< std::reference_wrapper< SQLStmtHolder >, std::string > > Statements
Statements to be prepared by prepareStatements()
Definition SQLConn.h:209
LastError m_lastError
The last error + error code + extended error code.
Definition SQLConn.h:258
A table to be created by createTables()
Definition SQLConn.h:191
unsigned flags
See TableFlags.
Definition SQLConn.h:197
std::string name
Name of the table.
Definition SQLConn.h:193
std::vector< std::string > columns
List of columns.
Definition SQLConn.h:195