Lightweight 0.20261105.1
Loading...
Searching...
No Matches
Diagnostics.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// <sql.h> below needs a few symbols resolved first — see SqlOdbcPrelude.hpp's header comment.
6#include "../../Api.hpp"
7#include "../../SqlBindingTypes.hpp"
8#include "../../SqlError.hpp"
9#include "Handles.hpp"
10#include "SqlOdbcPrelude.hpp"
11
12#include <optional>
13#include <source_location>
14
15#include <sql.h>
16#include <sqlext.h>
17
18namespace Lightweight::Driver::Odbc
19{
20
21/// @brief Converts an ODBC return code to the driver-neutral @ref SqlResult.
22///
23/// Free: the two are bit-identical, which @c Handles.hpp asserts.
24///
25/// @param rc The ODBC return code.
26/// @return The same code as a @ref SqlResult.
27[[nodiscard]] constexpr SqlResult ToResult(SQLRETURN rc) noexcept
28{
29 return static_cast<SqlResult>(rc);
30}
31
32/// @brief Supplies diagnostics for an ODBC handle.
33///
34/// Exists so error paths can be driven from a unit test without a database. Production code never
35/// installs one: with no source configured, @ref Diagnose reads diagnostics from the driver as
36/// usual. A test installs a source that returns a scripted @ref SqlErrorInfo, which makes the
37/// classification and propagation logic reachable without provoking a real driver failure.
38///
39/// @see SetDiagnosticSource
41{
42 public:
43 SqlDiagnosticSource() = default;
45 SqlDiagnosticSource& operator=(SqlDiagnosticSource const&) = delete;
47 SqlDiagnosticSource& operator=(SqlDiagnosticSource&&) = delete;
48 virtual ~SqlDiagnosticSource() = default;
49
50 /// @brief Returns the diagnostics for the given handle.
51 ///
52 /// @param handleType One of @c SQL_HANDLE_ENV, @c SQL_HANDLE_DBC or @c SQL_HANDLE_STMT.
53 /// @param handle The handle the diagnostics are requested for. A fake may ignore it.
54 /// @return The diagnostics to report for @p handle.
55 [[nodiscard]] virtual SqlErrorInfo Diagnose(SQLSMALLINT handleType, SQLHANDLE handle) = 0;
56};
57
58/// @brief Overrides the source of ODBC diagnostics process-wide.
59///
60/// Intended for tests. Ownership is not transferred and remains with the caller, which must keep
61/// @p source alive until it is cleared. Pass @c nullptr to restore the real ODBC reader.
62///
63/// This mirrors how @c SqlLogger::SetLogger installs a logger, and costs nothing on the success
64/// path: the override is consulted only once a call has already failed and diagnostics are being
65/// retrieved.
66///
67/// @param source The source to install, or @c nullptr to restore the default.
68LIGHTWEIGHT_API void SetDiagnosticSource(SqlDiagnosticSource* source);
69
70/// @brief Returns the currently installed diagnostic source, or @c nullptr if none is installed.
71[[nodiscard]] LIGHTWEIGHT_API SqlDiagnosticSource* GetDiagnosticSource() noexcept;
72
73/// @brief Reads the first diagnostic record of a statement handle.
74///
75/// Consults the installed @ref SqlDiagnosticSource, if any, instead of the driver. Never throws on
76/// encoding errors: those degrade to a best-effort lossy conversion.
77///
78/// @param stmt The statement whose diagnostics are read.
79/// @return The diagnostics; value-initialized fields when the driver has none to report.
80[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo Diagnose(Statement const& stmt);
81
82/// @brief Reads the first diagnostic record of a statement handle that is not a warning.
83///
84/// ODBC orders the records of a block fetch by row, so a warning of an earlier row (01S07, 01004) comes
85/// before the error of a later one. Consults the installed @ref SqlDiagnosticSource, if any, instead of
86/// the driver.
87///
88/// @param stmt The statement whose diagnostics are read.
89/// @return The first record whose SQLSTATE class is not 01; record 1 when every record is a warning.
90[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo DiagnoseFirstError(Statement const& stmt);
91
92/// @brief Reads the first diagnostic record of a connection.
93///
94/// Reads the connection handle; reads the environment handle instead when the connection handle is
95/// null and the environment handle is not (a failed @c SQLAllocHandle for the connection reports on
96/// the environment). Consults the installed @ref SqlDiagnosticSource, if any, instead of the driver.
97///
98/// @param connection The connection whose diagnostics are read.
99/// @return The diagnostics; value-initialized fields when the driver has none to report.
100[[nodiscard]] LIGHTWEIGHT_API SqlErrorInfo Diagnose(Connection const& connection);
101
102// The error-handling policy RequireSuccess applies is driver-neutral; it lives in Driver/Concept.hpp.
103// (Inside this namespace, `Driver` names the ODBC driver struct, hence the full qualification.)
104using ::Lightweight::Driver::ClassifyResult;
105
106/// @brief Reports the diagnostics of @p stmt to the installed logger when @p result is a failure.
107///
108/// @param stmt The statement @p result came from.
109/// @param result The return code to check.
110/// @param location Where the check originated; reported to the logger.
111LIGHTWEIGHT_API void LogIfFailed(Statement const& stmt, SqlResult result, std::source_location location);
112
113/// @brief Substitutes a scripted failure for an ODBC call that actually succeeded.
114///
115/// Exists so error-recovery paths can be driven from a test. Some failures cannot be provoked
116/// through a real driver at all: a backup worker's transient-error retry arm needs a class-08 or
117/// HYT00 SQLSTATE, but every fault reachable from a test file (unreachable driver, unwritable path,
118/// dropped table) surfaces as HY000, which the retry policy classifies as non-transient. Without a
119/// seam those arms are unreachable rather than merely untested.
120///
121/// Production code never installs one: with no source configured, @c RequireSuccess consults
122/// nothing and returns on success exactly as before. This mirrors @c SqlDiagnosticSource and
123/// @c SqlLogger::SetLogger, injection mechanisms the project already uses.
124///
125/// @see SetFaultSource
127{
128 public:
129 SqlFaultSource() = default;
130 SqlFaultSource(SqlFaultSource const&) = delete;
131 SqlFaultSource& operator=(SqlFaultSource const&) = delete;
132 SqlFaultSource(SqlFaultSource&&) = delete;
133 SqlFaultSource& operator=(SqlFaultSource&&) = delete;
134 virtual ~SqlFaultSource() = default;
135
136 /// @brief Decides whether the next statement-handle check should fail.
137 ///
138 /// Called by @c RequireSuccess for a call that the driver reported as successful. Returning
139 /// an engaged optional makes @c RequireSuccess throw @c SqlException carrying that
140 /// diagnostic, as though the driver had failed.
141 ///
142 /// @note Never called for a null statement handle. @c RequireSuccess also guards
143 /// @c SQLAllocHandle during statement construction, where failing would leave a
144 /// half-constructed @c SqlStatement whose destructor cannot release the handle; it
145 /// therefore skips injection entirely while @p hStmt is still @c SQL_NULL_HSTMT. A fake
146 /// may narrow further via @p sourceLocation — the function name of a real execution is
147 /// @c ExecuteDirect / @c Execute / @c Prepare — but does not have to in order to be safe.
148 ///
149 /// @param hStmt The statement handle being checked, never @c SQL_NULL_HSTMT. A fake may ignore it.
150 /// @param sourceLocation Where in the library the check is happening.
151 /// @return The error to inject, or @c std::nullopt to let the successful call through.
152 [[nodiscard]] virtual std::optional<SqlErrorInfo> NextFailure(SQLHSTMT hStmt,
153 std::source_location const& sourceLocation) = 0;
154
155 /// @brief Decides whether the next connection-handle check should fail.
156 ///
157 /// The connection-side counterpart of @ref NextFailure, consulted by
158 /// @c detail::CheckOdbcConnectionCall for a call that the driver reported as successful on a
159 /// @c SQLHDBC rather than a @c SQLHSTMT (e.g. a pre-connect attribute set). Returning an engaged
160 /// optional makes the caller treat the call as failed, exactly as an injected @ref NextFailure
161 /// does for a statement check.
162 ///
163 /// Defaults to never injecting, so a fake that predates connection-handle support and overrides
164 /// only @ref NextFailure keeps compiling and behaving exactly as before.
165 ///
166 /// @note Never called for a null connection handle, for the same reason @ref NextFailure is never
167 /// called for a null statement handle: a fault injected while a @c SqlConnection is still
168 /// being constructed or is in the middle of tearing down its handle could leave the handle
169 /// leaked or double-released.
170 ///
171 /// @param hDbc The connection handle being checked, never @c SQL_NULL_HDBC. A fake may ignore it.
172 /// @param sourceLocation Where in the library the check is happening.
173 /// @return The error to inject, or @c std::nullopt to let the successful call through.
174 [[nodiscard]] virtual std::optional<SqlErrorInfo> NextConnectionFailure(
175 [[maybe_unused]] SQLHDBC hDbc, [[maybe_unused]] std::source_location const& sourceLocation)
176 {
177 return std::nullopt;
178 }
179};
180
181/// @brief Installs a fault source process-wide.
182///
183/// Intended for tests. Ownership is not transferred and remains with the caller, which must keep
184/// @p source alive until it is cleared. Pass @c nullptr to disable fault injection.
185///
186/// @param source The source to install, or @c nullptr to disable.
187LIGHTWEIGHT_API void SetFaultSource(SqlFaultSource* source) noexcept;
188
189/// @brief Returns the currently installed fault source, or @c nullptr if none is installed.
190[[nodiscard]] LIGHTWEIGHT_API SqlFaultSource* GetFaultSource() noexcept;
191
192/// @brief Throws unless the given return code indicates success.
193///
194/// Retrieves the diagnostics for @p stmt and applies @ref ClassifyResult to decide how the
195/// failure surfaces: @c std::invalid_argument for a soft failure the caller is expected to recover
196/// from, @c SqlException otherwise.
197///
198/// @param stmt The statement @p result came from.
199/// @param result The return code to check.
200/// @param location Where the check originated; reported in the exception message. Defaults to
201/// the caller's location.
202LIGHTWEIGHT_API void RequireSuccess(Statement const& stmt,
203 SqlResult result,
204 std::source_location location = std::source_location::current());
205
206namespace detail
207{
208 /// @brief Verdict of a non-throwing checked ODBC call: the driver-neutral
209 /// @ref Lightweight::Driver::CallOutcome, whose injected error comes from a @ref SqlFaultSource.
210 ///
211 /// @see CheckOdbcCall, CheckOdbcConnectionCall
212 using OdbcCallOutcome = ::Lightweight::Driver::CallOutcome;
213
214 /// @brief Non-throwing checked-call helper for inline `SQL_SUCCEEDED` recovery checks against a
215 /// statement handle.
216 ///
217 /// Some recovery arms cannot go through @ref RequireSuccess because they must not throw: the
218 /// caller recovers by branching (e.g. declining to retry, or declining to pool a handle), and
219 /// that recovery is the whole point of being able to drive the call to its failure branch from a
220 /// test. This helper gives such a call site the same fault-injection seam @ref RequireSuccess
221 /// already offers, without the throw: the returned outcome carries the @c SQL_SUCCEEDED verdict
222 /// for @p result, unless an installed @ref SqlFaultSource overrides a real success into an
223 /// injected failure via @ref SqlFaultSource::NextFailure — in which case it also carries that
224 /// injected diagnostic, since the handle has none to offer.
225 ///
226 /// Mirrors @ref RequireSuccess's safety property: never consults the fault source while @p hStmt
227 /// is @c SQL_NULL_HSTMT, so a call made before a statement handle is fully valid cannot be
228 /// disturbed by injection.
229 ///
230 /// @param result The ODBC return code to check.
231 /// @param hStmt The statement handle @p result came from.
232 /// @param sourceLocation Where the check originated; forwarded to the fault source. Defaults to
233 /// the caller's location.
234 /// @return The verdict for @p result, plus the injected diagnostic when one was injected.
235 [[nodiscard]] LIGHTWEIGHT_API OdbcCallOutcome
236 CheckOdbcCall(SQLRETURN result, SQLHSTMT hStmt, std::source_location sourceLocation = std::source_location::current());
237
238 /// @brief Non-throwing checked-call helper for inline `SQL_SUCCEEDED` recovery checks against a
239 /// connection handle.
240 ///
241 /// The connection-handle counterpart of @ref CheckOdbcCall(SQLRETURN, SQLHSTMT,
242 /// std::source_location): same contract, keyed on a @c SQLHDBC via
243 /// @ref SqlFaultSource::NextConnectionFailure instead of @ref SqlFaultSource::NextFailure. Never
244 /// consults the fault source while @p hDbc is @c SQL_NULL_HDBC, for the same reason the
245 /// statement-handle overload skips a null @c SQLHSTMT.
246 ///
247 /// @param result The ODBC return code to check.
248 /// @param hDbc The connection handle @p result came from.
249 /// @param sourceLocation Where the check originated; forwarded to the fault source. Defaults to
250 /// the caller's location.
251 /// @return The verdict for @p result, plus the injected diagnostic when one was injected.
252 [[nodiscard]] LIGHTWEIGHT_API OdbcCallOutcome CheckOdbcConnectionCall(
253 SQLRETURN result, SQLHDBC hDbc, std::source_location sourceLocation = std::source_location::current());
254} // namespace detail
255
256} // namespace Lightweight::Driver::Odbc
Supplies diagnostics for an ODBC handle.
virtual SqlErrorInfo Diagnose(SQLSMALLINT handleType, SQLHANDLE handle)=0
Returns the diagnostics for the given handle.
Substitutes a scripted failure for an ODBC call that actually succeeded.
virtual std::optional< SqlErrorInfo > NextFailure(SQLHSTMT hStmt, std::source_location const &sourceLocation)=0
Decides whether the next statement-handle check should fail.
virtual std::optional< SqlErrorInfo > NextConnectionFailure(SQLHDBC hDbc, std::source_location const &sourceLocation)
Decides whether the next connection-handle check should fail.
Verdict of a non-throwing checked driver call, carrying the diagnostic that justifies a failure verdi...
Definition Concept.hpp:76
The ODBC driver's connection handle struct.
Definition Handles.hpp:53
The ODBC driver: names its handle structs and its driver id.
Definition Handles.hpp:66
The ODBC driver's statement handle struct.
Definition Handles.hpp:43
Represents a SQL error as reported by the database driver.
Definition SqlError.hpp:29