Lightweight 0.20260921.0
Loading...
Searching...
No Matches
Core.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5// See SqlOdbcPrelude.hpp's header comment for why this replaces a direct <Windows.h> include.
6#include "../Api.hpp"
7#include "../SqlOdbcPrelude.hpp"
8#include "../SqlServerType.hpp"
9
10#include <concepts>
11#include <cstddef>
12#include <cstdint>
13#include <functional>
14#include <memory>
15#include <optional>
16
17#include <sql.h>
18#include <sqlext.h>
19#include <sqltypes.h>
20
21namespace Lightweight
22{
23
24/// @defgroup DataTypes Data Types
25///
26/// @brief Special purpose data types for SQL data binding.
27
28/// Callback interface for SqlDataBinder to allow post-processing of output columns.
29///
30/// This is needed because the SQLBindCol() function does not allow to specify a callback function to be called
31/// after the data has been fetched from the database. This is needed to trim strings to the correct size, for
32/// example.
33class LIGHTWEIGHT_API SqlDataBinderCallback
34{
35 public:
36 /// Default constructor.
38 /// Default move constructor.
40 /// Default copy constructor.
42 /// Default move assignment operator.
44 /// Default copy assignment operator.
46
47 virtual ~SqlDataBinderCallback() = default;
48
49 /// Plans a callback to be called after the statement has been executed.
50 ///
51 /// @see SqlDataBinder::PostExecute()
52 virtual void PlanPostExecuteCallback(std::function<void()>&&) = 0;
53
54 /// Plans a callback to be called after a column has been processed.
55 ///
56 /// @see SqlDataBinder::PostProcessOutputColumn()
57 virtual void PlanPostProcessOutputColumn(std::function<void()>&&) = 0;
58
59 /// Provides a pointer to a single indicator for a single input parameter.
60 ///
61 /// @note The caller is responsible for filling the indicator with the length of the data or
62 /// SQL_NULL_DATA.
63 /// @note The indicator must remain valid until the statement is executed.
64 ///
65 /// @return A pointer to the indicator.
66 virtual SQLLEN* ProvideInputIndicator() = 0;
67
68 /// Provides a pointer to a contiguous array of indicators for a batch of input parameters.
69 ///
70 /// @note The caller is responsible for filling the indicators with the lengths of the data or
71 /// SQL_NULL_DATA.
72 /// @note The indicators must remain valid until the statement is executed.
73 ///
74 /// @param rowCount The number of rows in the batch.
75 /// @return A pointer to the first element of the indicator array.
76 virtual SQLLEN* ProvideInputIndicators(size_t rowCount) = 0;
77
78 /// Provides a pointer to a contiguous, suitably aligned temporary byte buffer that remains valid
79 /// until the statement is executed.
80 ///
81 /// This is used by batch input parameter binders that need scratch storage whose lifetime must
82 /// outlive the bind call but not the execution — for example a row-strided NULL/length indicator
83 /// array used by native row-wise array binding of @c std::optional columns.
84 ///
85 /// @note The buffer contents are unspecified; the caller is responsible for initializing it.
86 /// @note The returned storage is aligned to at least @c alignof(std::max_align_t).
87 /// @note Row-wise callers request @c ~rowStride*rowCount bytes to hold only @c rowCount @c SQLLEN
88 /// indicators. This over-allocation is intrinsic to ODBC row-wise binding, which strides the
89 /// @c StrLen_or_IndPtr array by @c SQL_ATTR_PARAM_BIND_TYPE (the row stride) — there is no separate
90 /// indicator stride — so a tightly packed indicator array would require descriptor-level binding.
91 ///
92 /// @param byteCount The number of bytes to provide.
93 /// @return A pointer to the first byte of the buffer.
94 virtual std::byte* ProvideBatchStagingBuffer(std::size_t byteCount) = 0;
95
96 /// @return The server type of the database.
97 [[nodiscard]] virtual SqlServerType ServerType() const noexcept = 0;
98
99 /// @return The driver name of the database.
100 [[nodiscard]] virtual std::string const& DriverName() const noexcept = 0;
101};
102
103template <typename>
104struct SqlDataBinder;
105
106// Default traits for output string parameters
107// This needs to be implemented for each string type that should be used as output parameter via
108// SqlDataBinder<>. An std::string specialization is provided below. Feel free to add more specializations for
109// other string types, such as CString, etc.
110template <typename>
111struct SqlBasicStringOperations;
112
113// -----------------------------------------------------------------------------------------------
114
115namespace detail
116{
117
118 /// @brief Satisfied when @p T is the same type as at least one of @p Us.
119 ///
120 /// Mirrors @c Lightweight::detail::OneOf, but lives in the DataBinder layer so the low-level binder
121 /// headers can use it without reaching up to the higher-level Utils.hpp.
122 template <typename T, typename... Us>
123 concept IsAnyOf = (std::same_as<T, Us> || ...);
124
125 /// @brief Byte offset of the contained value within a @c std::optional<T>.
126 ///
127 /// Used by the row-wise batch binders to address the inner value of each row's optional in place. The
128 /// offset is 0 on all known standard libraries, but is computed rather than assumed so the address
129 /// arithmetic does not bake in that assumption. It is derived from the integer addresses of a probe
130 /// optional and its contained value (rather than @c byte* subtraction) to keep the computation defined.
131 ///
132 /// @tparam T The contained value type.
133 /// @return The offset, in bytes, of the contained value within the optional.
134 template <typename T>
135 [[nodiscard]] inline std::size_t OptionalValueOffset() noexcept
136 {
137 std::optional<T> const probe { T {} };
138 return static_cast<std::size_t>(reinterpret_cast<std::uintptr_t>(std::addressof(*probe))
139 - reinterpret_cast<std::uintptr_t>(std::addressof(probe)));
140 }
141
142 // clang-format off
143template <typename T>
144concept HasGetStringAndGetLength = requires(T const& t) {
145 { t.GetLength() } -> std::same_as<int>;
146 { t.GetString() } -> std::same_as<char const*>;
147};
148
149template <typename T>
150concept HasGetStringAndLength = requires(T const& t)
151{
152 { t.Length() } -> std::same_as<int>;
153 { t.GetString() } -> std::same_as<char const*>;
154};
155 // clang-format on
156
157 template <typename>
158 struct SqlViewHelper;
159
160 template <typename T>
161 concept HasSqlViewHelper = requires(T const& t) {
162 { SqlViewHelper<T>::View(t) } -> std::convertible_to<std::string_view>;
163 };
164
165 template <typename CharT>
166 struct SqlViewHelper<std::basic_string<CharT>>
167 {
168 static LIGHTWEIGHT_FORCE_INLINE std::basic_string_view<CharT> View(std::basic_string<CharT> const& str) noexcept
169 {
170 return { str.data(), str.size() };
171 }
172 };
173
174 template <detail::HasGetStringAndGetLength CStringLike>
175 struct SqlViewHelper<CStringLike>
176 {
177 static LIGHTWEIGHT_FORCE_INLINE std::string_view View(CStringLike const& str) noexcept
178 {
179 return { str.GetString(), static_cast<size_t>(str.GetLength()) };
180 }
181 };
182
183 template <detail::HasGetStringAndLength StringLike>
184 struct SqlViewHelper<StringLike>
185 {
186 static LIGHTWEIGHT_FORCE_INLINE std::string_view View(StringLike const& str) noexcept
187 {
188 return { str.GetString(), static_cast<size_t>(str.Length()) };
189 }
190 };
191
192} // namespace detail
193
194// -----------------------------------------------------------------------------------------------
195
196template <typename T>
197concept SqlInputParameterBinder = requires(SQLHSTMT hStmt, SQLUSMALLINT column, T const& value, SqlDataBinderCallback& cb) {
198 { SqlDataBinder<T>::InputParameter(hStmt, column, value, cb) } -> std::same_as<SQLRETURN>;
199};
200
201template <typename T>
202concept SqlOutputColumnBinder =
203 requires(SQLHSTMT hStmt, SQLUSMALLINT column, T* result, SQLLEN* indicator, SqlDataBinderCallback& cb) {
204 { SqlDataBinder<T>::OutputColumn(hStmt, column, result, indicator, cb) } -> std::same_as<SQLRETURN>;
205 };
206
207template <typename T>
208concept SqlInputParameterBatchBinder =
209 requires(SQLHSTMT hStmt, SQLUSMALLINT column, std::ranges::range_value_t<T>* result, SqlDataBinderCallback& cb) {
210 {
211 SqlDataBinder<std::ranges::range_value_t<T>>::InputParameter(
212 hStmt, column, std::declval<std::ranges::range_value_t<T>>(), cb)
213 } -> std::same_as<SQLRETURN>;
214 };
215
216/// @brief Opt-in trait marking a value type as bindable in a native ODBC row-wise parameter array.
217///
218/// A type qualifies when it is fixed-width, stored inline, bound via a plain @c SQLBindParameter with
219/// no per-call heap conversion, and identically across all supported backends — so its address can be
220/// handed to ODBC and strided by @c SQL_ATTR_PARAM_BIND_TYPE. The primary template is @c false; each
221/// eligible binder header specializes it to @c true (primitives, date/time/datetime, numeric).
222///
223/// @note @c SqlGuid is intentionally NOT marked: on SQLite it is bound via a per-value text conversion,
224/// which cannot be expressed as a zero-copy row-wise array — GUID columns use the soft batch path.
225template <typename T>
226inline constexpr bool SqlIsNativeRowBindableValue = false;
227
228/// @brief Opt-in trait marking a value type as an @c SqlNumeric specialization.
229///
230/// Numeric values are row-wise bindable, but @c std::optional<SqlNumeric> is not (the contained value
231/// is not bound at a uniform offset/representation across backends), so the optional batch path
232/// excludes them via this trait.
233template <typename T>
234inline constexpr bool SqlIsNumericValue = false;
235
236/// @brief Whether @p T is a @c std::optional specialization.
237///
238/// Defined locally rather than reusing @c Lightweight::IsSpecializationOf (Utils.hpp) or the DataMapper
239/// @c IsStdOptional (Field.hpp): this low-level binder header is deliberately kept free of dependencies on
240/// those higher-level headers, so it carries its own minimal optional traits.
241template <typename T>
242inline constexpr bool SqlIsStdOptional = false;
243
244template <typename T>
245inline constexpr bool SqlIsStdOptional<std::optional<T>> = true;
246
247template <typename T>
248concept SqlGetColumnNativeType =
249 requires(SQLHSTMT hStmt, SQLUSMALLINT column, T* result, SQLLEN* indicator, SqlDataBinderCallback const& cb) {
250 { SqlDataBinder<T>::GetColumn(hStmt, column, result, indicator, cb) } -> std::same_as<SQLRETURN>;
251 };
252
253template <typename T>
254concept SqlDataBinderSupportsInspect = requires(T const& value) {
255 { SqlDataBinder<std::remove_cvref_t<T>>::Inspect(value) } -> std::convertible_to<std::string>;
256};
257
258// clang-format off
259template <typename StringType, typename CharType>
260concept SqlBasicStringBinderConcept = requires(StringType* str) {
261 { SqlBasicStringOperations<StringType>::Data(str) } -> std::same_as<CharType*>;
262 { SqlBasicStringOperations<StringType>::Size(str) } -> std::same_as<SQLULEN>;
263 { SqlBasicStringOperations<StringType>::Reserve(str, size_t {}) } -> std::same_as<void>;
264 { SqlBasicStringOperations<StringType>::Resize(str, SQLLEN {}) } -> std::same_as<void>;
265 { SqlBasicStringOperations<StringType>::Clear(str) } -> std::same_as<void>;
266};
267// clang-format on
268
269} // namespace Lightweight
virtual void PlanPostExecuteCallback(std::function< void()> &&)=0
virtual SQLLEN * ProvideInputIndicator()=0
SqlDataBinderCallback(SqlDataBinderCallback &&)=default
Default move constructor.
virtual SqlServerType ServerType() const noexcept=0
virtual void PlanPostProcessOutputColumn(std::function< void()> &&)=0
SqlDataBinderCallback & operator=(SqlDataBinderCallback const &)=default
Default copy assignment operator.
SqlDataBinderCallback & operator=(SqlDataBinderCallback &&)=default
Default move assignment operator.
SqlDataBinderCallback()=default
Default constructor.
virtual SQLLEN * ProvideInputIndicators(size_t rowCount)=0
SqlDataBinderCallback(SqlDataBinderCallback const &)=default
Default copy constructor.
virtual std::byte * ProvideBatchStagingBuffer(std::size_t byteCount)=0