StormByte-Database 3.0.0
C++26 database module of the StormByte suite
Loading...
Searching...
No Matches
database.hxx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This file is part of StormByte-Database.
5 *
6 * StormByte-Database original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte-Database source in this
20 * repository. They do not cover other StormByte modules or any third-party
21 * material shipped with this repository (including everything under
22 * thirdparty/, and in particular the bundled StormByte-Logger tree and
23 * the PostgreSQL, MariaDB and SQLite trees), which remain under their own
24 * licenses.
25 *
26 * Neither license grants any patent rights. Any patent licenses required
27 * to use this software or third-party components must be obtained separately
28 * from the patent holders.
29 *
30 * StormByte-Database is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU Lesser General Public License for more details.
34 *
35 * You should have received a copy of the GNU Lesser General Public License
36 * version 3 along with StormByte-Database. If not, see
37 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
38 *
39 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
40 */
41
42#pragma once
43
49#include <StormByte/logger/log.hxx>
50#include <StormByte/safe/pointers.hxx>
51#include <StormByte/size.hxx>
52
53#include <string_view>
54
59namespace StormByte {
64 namespace Database {
74 private:
79 class OperationMutex;
80
81 protected:
87 public:
92 explicit OperationGuard(const Database& database) noexcept;
93
98 OperationGuard(const OperationGuard& other) = delete;
99
103 ~OperationGuard() noexcept;
104
105 private:
106 const Database& m_database;
107 };
108
109 public:
114 Database(const StormByte::Safe::Shared<Logger::Log>& logger);
115
119 Database(const Database &) = delete;
120
124 Database(Database &&other) noexcept;
125
129 Database &operator=(const Database &) = delete;
130
134 Database &operator=(Database &&other) noexcept;
135
139 virtual ~Database() noexcept;
140
145 StormByte::Safe::Shared<class Telemetry> Telemetry() const noexcept;
146
151 bool Connect() noexcept;
152
157 void Disconnect() noexcept;
158
163 bool IsConnected() const noexcept {
164 OperationGuard lock{*this};
165 return m_connected;
166 }
167
173 OperationGuard lock{*this};
174 m_ssl_mode = mode;
175 }
176
182 OperationGuard lock{*this};
183 return m_ssl_mode;
184 }
185
193 template <typename... Args>
194 ExpectedRows ExecuteSTMT(std::string_view name, Args &&...args) {
196 OperationGuard lock{*this};
197 PreparedSTMT *statement = FindPreparedSTMT(name);
198 if (!statement)
200 ExpectedRows result = statement->Execute(std::forward<Args>(args)...);
201 telemetry.Complete(result.has_value(), result ? static_cast<std::uint64_t>(result->Count()) : std::uint64_t{0});
202 return result;
203 }
204
210 virtual ExpectedRows Query(std::string_view query) = 0;
211
217 virtual bool SilentQuery(std::string_view query) noexcept = 0;
218
225
230
235
236 protected:
237 friend class Transaction;
240
246
251 void RecordBackendEvent(BackendEvent event) noexcept {
252 m_telemetry->RecordEvent(event);
253 }
254
263
266
268
272 void ClearPreparedSTMTs() noexcept;
273
279
283 virtual void DoPreConnect() noexcept {}
284
289 virtual bool DoConnect() noexcept = 0;
290
294 virtual void DoPostConnect() noexcept {}
295
299 virtual void DoPreDisconnect() noexcept {}
300
304 virtual void DoDisconnect() noexcept = 0;
305
309 virtual void DoPostDisconnect() noexcept {}
310
312
319 virtual StormByte::Safe::Unique<PreparedSTMT> CreatePreparedSTMT(std::string_view name, std::string_view query) noexcept = 0;
320
326 void PrepareSTMT(std::string_view name, std::string_view query) noexcept;
327
333 void DoPrepareSTMT(std::string_view name, std::string_view query) noexcept;
334
339 virtual void DoBeginTransaction(IsolationLevel level) = 0;
340
346 virtual bool DoSilentQuery(std::string_view query) noexcept = 0;
347
348 private:
349 friend class Transaction;
350
354 void LockOperation() const noexcept;
355
359 void UnlockOperation() const noexcept;
360
365 struct PreparedStatements;
366
367 StormByte::Safe::Unique<PreparedStatements> m_prepared_stmts;
368
374 PreparedSTMT *FindPreparedSTMT(std::string_view name);
375 };
376 }
377}
378
RAII ownership of the connection operation gate.
Definition database.hxx:86
OperationGuard(const Database &database) noexcept
Acquire the connection operation gate.
OperationGuard(const OperationGuard &other)=delete
Copying a lock guard is disabled.
~OperationGuard() noexcept
Release the connection operation gate.
void SslMode(StormByte::Database::SslMode mode) noexcept
TLS policy for the next Connect().
Definition database.hxx:172
virtual void DoPostConnect() noexcept
Post-connect hook.
Definition database.hxx:294
Expected< Transaction, TransactionError > BeginTransaction(IsolationLevel level=IsolationLevel::Default)
Begin a transaction.
virtual void DoPreConnect() noexcept
Pre-connect hook.
Definition database.hxx:283
virtual void DoPreDisconnect() noexcept
Pre-disconnect hook.
Definition database.hxx:299
StormByte::Safe::Shared< OperationMutex > m_operation_mutex
Base-heap owner of the private reentrant operation gate.
Definition database.hxx:238
void ClearPreparedSTMTs() noexcept
Destroy all registered statements inside the Database module.
StormByte::Safe::Shared< class Telemetry > Telemetry() const noexcept
Obtain the cumulative connection telemetry handle.
virtual void DoBeginTransaction(IsolationLevel level)=0
Backend BEGIN with isolation.
StormByte::Database::Telemetry::OperationScope TrackOperation(Operation operation) const noexcept
Start timing a Database operation without invoking user callbacks.
Definition database.hxx:260
Database(const StormByte::Safe::Shared< Logger::Log > &logger)
Construct with an optional logger.
void DoPrepareSTMT(std::string_view name, std::string_view query) noexcept
Same as PrepareSTMT; kept for hook symmetry.
void RecordBackendEvent(BackendEvent event) noexcept
Record a categorized event reported by the active backend.
Definition database.hxx:251
virtual void DoDisconnect() noexcept=0
Backend disconnect.
friend class Transaction
Definition database.hxx:237
void Disconnect() noexcept
Disconnect.
virtual ExpectedRows Query(std::string_view query)=0
Execute a query that returns rows.
StormByte::Safe::Shared< class Telemetry > m_telemetry
Shared cumulative counters for this connection.
Definition database.hxx:239
virtual bool SilentQuery(std::string_view query) noexcept=0
Execute a query that does not return rows.
void Telemetry(StormByte::Safe::Shared< class Telemetry > telemetry) noexcept
Replace the telemetry implementation, normally in a concrete backend constructor.
void PrepareSTMT(std::string_view name, std::string_view query) noexcept
Register a prepared statement under name.
void CommitTransaction()
Commit the current transaction.
void RollbackTransaction()
Roll back the current transaction.
ExpectedRows ExecuteSTMT(std::string_view name, Args &&...args)
Execute a prepared statement by name.
Definition database.hxx:194
virtual void DoPostDisconnect() noexcept
Post-disconnect hook.
Definition database.hxx:309
StormByte::Safe::Shared< Logger::Log > m_logger
Shared logger, safe across the DLL boundary.
Definition database.hxx:267
virtual bool DoSilentQuery(std::string_view query) noexcept=0
Backend silent query.
StormByte::Database::SslMode m_ssl_mode
TLS policy for network backends.
Definition database.hxx:265
bool m_connected
Connection state.
Definition database.hxx:264
virtual StormByte::Safe::Unique< PreparedSTMT > CreatePreparedSTMT(std::string_view name, std::string_view query) noexcept=0
Create a backend prepared statement.
bool Connect() noexcept
Connect.
bool IsConnected() const noexcept
Whether the connection is open.
Definition database.hxx:163
virtual bool DoConnect() noexcept=0
Backend connect.
StormByte::Database::SslMode SslMode() const noexcept
Current TLS policy.
Definition database.hxx:181
Abstract prepared statement.
Definition prepared_stmt.hxx:69
ExpectedRows Execute(Args &&...args)
Bind arguments and execute.
Definition prepared_stmt.hxx:121
Records one operation and its elapsed time on destruction.
Definition telemetry.hxx:136
Prepared statement name is not registered.
Definition exception.hxx:414
STORMBYTE_DECLARE_MAYBE_SAFE(StormByte::Logger::Exception)
Database module of the StormByte suite.
BackendEvent
Shared error and warning categories for backend-specific telemetry.
Definition telemetry.hxx:88
SslMode
TLS policy for MariaDB / PostgreSQL.
Definition typedefs.hxx:87
Expected< Rows, QueryException > ExpectedRows
Query result: Rows or QueryException.
Definition typedefs.hxx:81
Operation
Database operation categories measured by telemetry.
Definition telemetry.hxx:71
@ PreparedStatement
Prepared-statement execution attempts.
Definition telemetry.hxx:77
IsolationLevel
Isolation for BeginTransaction().
Definition typedefs.hxx:98
@ Default
Backend default.
Definition typedefs.hxx:99
Root namespace of the StormByte C++ suite.
std::conditional_t< Type::Reference< T >, std::expected< std::reference_wrapper< std::remove_reference_t< T > >, Safe::Shared< E > >, std::expected< T, Safe::Shared< E > > > Expected
auto Unexpected(Safe::Shared< E > error)
STL namespace.
#define STORMBYTE_DATABASE_PUBLIC
Definition visibility.h:54