7#include "DataBinder/Core.hpp"
8#include "DataBinder/SqlDate.hpp"
9#include "DataBinder/SqlDateTime.hpp"
10#include "DataBinder/SqlDynamicNumeric.hpp"
11#include "DataBinder/SqlFixedString.hpp"
12#include "DataBinder/SqlGuid.hpp"
13#include "DataBinder/SqlNumeric.hpp"
14#include "DataBinder/StringInterface.hpp"
15#include "DataBinder/UnicodeConverter.hpp"
16#include "DataMapper/Record.hpp"
18#include "Driver/DriverSet.hpp"
19#if defined(LIGHTWEIGHT_DRIVER_ODBC)
20 #include "Driver/Odbc/Diagnostics.hpp"
21 #include "Driver/Odbc/RowArrayCursor.hpp"
22 #include "Driver/Odbc/SqlOdbcPrelude.hpp"
24#include "SqlConnection.hpp"
25#include "SqlPreparedStatementCache.hpp"
26#include "SqlQuery.hpp"
27#include "SqlQueryFormatter.hpp"
28#include "SqlServerType.hpp"
29#include "SqlStatistics.hpp"
30#include "TracyProfiler.hpp"
33#include <reflection-cpp/reflection.hpp>
49#include <source_location>
61#if defined(LIGHTWEIGHT_DRIVER_ODBC)
66template <
typename QueryObject>
68 { queryObject.ToSql() } -> std::convertible_to<std::string>;
76template <
typename QueryObject>
78 { queryObject.ProjectedFieldNames() } -> std::convertible_to<std::span<std::string const>>;
79 { queryObject.ProjectionHasWildcard() } -> std::convertible_to<bool>;
83class SqlVariantRowCursor;
84#if defined(LIGHTWEIGHT_DRIVER_ODBC)
122 [[nodiscard]] LIGHTWEIGHT_API
bool IsAlive() const noexcept;
125 [[nodiscard]] LIGHTWEIGHT_API
bool IsPrepared() const noexcept;
141 std::string_view
const& tableAlias)
const;
144 [[nodiscard]] Driver::StatementHandle
const& DriverHandle() const noexcept;
155 template <typename F>
156 decltype(auto) VisitDriver(std::string_view operation, F&& f);
164 template <typename F>
165 decltype(auto) VisitDriver(std::string_view operation, F&& f) const;
168 [[nodiscard]] SqlDriverId DriverId() const noexcept;
174 LIGHTWEIGHT_API
void Prepare(std::string_view query) &;
189 [[nodiscard]] std::
string const& PreparedQuery() const noexcept;
226 LIGHTWEIGHT_API
void SetQueryTimeout(std::chrono::seconds timeout);
235 [[nodiscard]] LIGHTWEIGHT_API std::chrono::seconds QueryTimeout() const;
262 void BindInputParameter(std::int16_t columnIndex, Arg const& arg);
270 void BindInputParameter(std::int16_t columnIndex, Arg const& arg, ColumnName&& columnNameHint);
274 void BindInputParameter(std::int16_t columnIndex, Arg const&& arg) = delete;
278 void BindInputParameter(std::int16_t columnIndex, Arg const&& arg, ColumnName&& columnNameHint) = delete;
311 [[nodiscard]]
SqlResultCursor ExecuteBatchNative(FirstColumnBatch const& firstColumnBatch,
312 MoreColumnBatches const&... moreColumnBatches);
327 [[nodiscard]]
SqlResultCursor ExecuteBatchSoft(FirstColumnBatch const& firstColumnBatch,
328 MoreColumnBatches const&... moreColumnBatches);
341 MoreColumnBatches const&... moreColumnBatches);
343#if defined(LIGHTWEIGHT_DRIVER_ODBC)
380 std::size_t rowCount,
381 std::span<Driver::Odbc::RowStatus> paramStatus,
415 template <std::ranges::contiguous_range Rows,
typename... ColumnAccessors>
416 requires(
sizeof...(ColumnAccessors) >= 1
417 && (std::invocable<ColumnAccessors
const&, std::ranges::range_value_t<Rows>
const&> && ...))
422 ExecuteDirect(std::string_view
const& query, std::source_location location = std::source_location::current());
426 std::source_location location = std::source_location::current());
428#if defined(LIGHTWEIGHT_DRIVER_ODBC)
445 template <
typename Callable>
446 requires std::invocable<Callable, SqlMigrationQueryBuilder&>
447 void MigrateDirect(Callable
const& callable, std::source_location location = std::source_location::current());
454 template <
typename T>
455 requires(!std::same_as<T, SqlVariant>)
456 [[nodiscard]] std::optional<T> ExecuteDirectScalar(std::string_view
const& query,
457 std::source_location location = std::source_location::current());
463 template <
typename T>
464 requires(std::same_as<T, SqlVariant>)
465 [[nodiscard]] T ExecuteDirectScalar(std::string_view
const& query,
466 std::source_location location = std::source_location::current());
473 template <
typename T>
474 requires(!std::same_as<T, SqlVariant>)
475 [[nodiscard]] std::optional<T> ExecuteDirectScalar(
SqlQueryObject auto const& query,
476 std::source_location location = std::source_location::current());
482 template <
typename T>
483 requires(std::same_as<T, SqlVariant>)
484 [[nodiscard]] T ExecuteDirectScalar(
SqlQueryObject auto const& query,
485 std::source_location location = std::source_location::current());
488 [[nodiscard]] LIGHTWEIGHT_API
size_t LastInsertId(std::string_view tableName);
505#if defined(LIGHTWEIGHT_DRIVER_ODBC)
508 friend class SqlVariantRowIterator;
509 template <
typename T>
514 [[nodiscard]] LIGHTWEIGHT_API
size_t NumRowsAffected()
const;
517 [[nodiscard]] LIGHTWEIGHT_API
size_t NumColumnsAffected()
const;
518 [[nodiscard]] LIGHTWEIGHT_API
bool FetchRow();
519 [[nodiscard]] LIGHTWEIGHT_API std::expected<bool, SqlErrorInfo> TryFetchRow(
520 std::source_location location = std::source_location::current()) noexcept;
521 void CloseCursor() noexcept;
530 void BindOutputColumns(Args*... args);
536 template <typename... Records>
537 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
538 void BindOutputColumnsToRecord(Records*... records);
545 void BindOutputColumn(SqlColumnIndex columnIndex, T* arg);
553 [[nodiscard]]
bool GetColumn(SqlColumnIndex column, T* result) const;
561 [[nodiscard]] T GetColumn(SqlColumnIndex column) const;
565 template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
566 [[nodiscard]]
SqlResultCursor ExecuteBatchNativeRowWise(Rows const& rows, ColumnAccessors const&... accessors);
570 template <std::ranges::contiguous_range Rows, typename... ColumnAccessors>
571 [[nodiscard]]
SqlResultCursor ExecuteBatchSoftRowMajor(Rows const& rows, ColumnAccessors const&... accessors);
597 template <typename Record, typename... ColumnAccessors>
598 void FetchAllRowWise(std::vector<Record>& out, std::
size_t arrayDepth, ColumnAccessors const&... accessors);
603 template <typename ValueType>
604 [[nodiscard]] SqlIndicator* BindRowWiseOutputColumn(SqlColumnIndex column,
606 std::
size_t rowStride,
613 template <typename Value>
614 void BindRowWiseValue(SqlColumnIndex column,
void* base0, SqlIndicator* indicators);
621 template <typename ValueType>
622 static
void FinalizeRowWiseOutputColumn(
void* base0,
623 std::
size_t rowStride,
624 std::
size_t rowCount,
625 SqlIndicator const* indicators,
626 SqlColumnIndex column,
627 bool booleanTrueMayBeMinusOne);
636 static
void CheckRowWiseBool(
bool* value, SqlColumnIndex column,
bool booleanTrueMayBeMinusOne);
639 [[nodiscard]] std::optional<T> GetNullableColumn(SqlColumnIndex column) const;
642 [[nodiscard]] T GetColumnOr(SqlColumnIndex column, T&& defaultValue) const;
656 [[nodiscard]] LIGHTWEIGHT_API SqlColumnIndex ResolveColumnName(std::string_view name) const;
659 [[nodiscard]] LIGHTWEIGHT_API std::
string DescribeProjectedFieldNames() const;
664 LIGHTWEIGHT_API
void RequireSuccess(SqlResult result,
665 std::source_location sourceLocation = std::source_location::current()) const;
666 LIGHTWEIGHT_API
void PlanPostExecuteCallback(std::function<
void()>&& cb) override;
667 LIGHTWEIGHT_API
void KeepInputParameterAlive(SqlColumnIndex column, std::shared_ptr<
void const> buffer) override;
668 LIGHTWEIGHT_API
void PlanPostProcessOutputColumn(std::function<
void()>&& cb) override;
670 [[nodiscard]] LIGHTWEIGHT_API std::
size_t MinimumOutputColumnSize(SqlColumnIndex column,
671 SqlOutputColumnLength length) override;
675 LIGHTWEIGHT_API
void BeginOutputColumnBinding(SqlColumnIndex column) noexcept;
681 void BindOutputColumnNow(SqlColumnIndex column, T* arg);
683 using NullResetFunction =
void (*)(
void* target) noexcept;
690 LIGHTWEIGHT_API
void PlanNullReset(SqlColumnIndex column,
691 SqlIndicator const* indicator,
693 NullResetFunction reset);
695 LIGHTWEIGHT_API
void ResetOutputColumnCallbacks() noexcept;
697 LIGHTWEIGHT_API
void DropOutputColumnCallbacks(SqlColumnIndex column) noexcept;
701 LIGHTWEIGHT_API
void DropOutputColumnBindings() noexcept;
704 LIGHTWEIGHT_API
void NoteOutputColumnBoundDirectly() noexcept;
705 [[nodiscard]] LIGHTWEIGHT_API SqlServerType ServerType() const noexcept override;
706 [[nodiscard]] LIGHTWEIGHT_API std::
string const& DriverName() const noexcept override;
707 [[nodiscard]] LIGHTWEIGHT_API detail::NarrowTextBinding NarrowTextBindingMode() const noexcept override;
709 [[nodiscard]] LIGHTWEIGHT_API
bool ConvertsNarrowIntegerCTypes() const noexcept override;
711 [[nodiscard]] LIGHTWEIGHT_API
SqlOutputColumnStaging* ProvideOutputColumnStaging(SqlColumnIndex column) override;
713 [[nodiscard]] LIGHTWEIGHT_API
bool BooleanTrueMayBeMinusOne() const noexcept override;
714 LIGHTWEIGHT_API
void ProcessPostExecuteCallbacks();
716 LIGHTWEIGHT_API SqlIndicator* ProvideInputIndicator() override;
717 LIGHTWEIGHT_API SqlIndicator* ProvideInputIndicators(
size_t rowCount) override;
718 LIGHTWEIGHT_API std::
byte* ProvideBatchStagingBuffer(std::
size_t byteCount) override;
723 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::int16_t> DescribeInputParameterType(
724 SqlColumnIndex column) noexcept override;
726 [[nodiscard]] LIGHTWEIGHT_API std::optional<std::int16_t> DescribeResultColumnType(
727 SqlColumnIndex column) const noexcept override;
731 LIGHTWEIGHT_API
void ReportInputParameterError(
SqlErrorInfo const& error) noexcept override;
732 LIGHTWEIGHT_API
void ClearBatchIndicators();
737 LIGHTWEIGHT_API std::
byte* ProvideRowWiseFetchIndicators(std::
size_t byteCount);
739 LIGHTWEIGHT_API
void ReleaseRowWiseFetchIndicators() noexcept;
742 LIGHTWEIGHT_API
void DropInputParameterKeepAlives() noexcept;
744 enum class ParameterSlotReuse : std::uint8_t
764 template <
typename DriverStatement,
typename T>
765 SqlResult BindParameterValue(DriverStatement& stmt, SqlColumnIndex column, T
const& value, ParameterSlotReuse reuse)
767 m_parameterBeingBound = column;
768 m_slotReuseBeingBound = reuse;
769 m_parameterTookSlots =
false;
771 auto const endBind = detail::Finally([
this] { m_parameterBeingBound = 0; });
772 auto const result = Driver::BindInputParameter(stmt, column, value, *
this);
773 if (m_parameterTookSlots && reuse == ParameterSlotReuse::NextBinding && Succeeded(result))
774 AdoptParameterSlots();
778 LIGHTWEIGHT_API
void AdoptParameterSlots() noexcept;
781 LIGHTWEIGHT_API
void DropRoundBindings();
782#if defined(LIGHTWEIGHT_DRIVER_ODBC)
788 LIGHTWEIGHT_API
void StartRawBatchRound(std::span<SqlRawColumn const> columns);
794 LIGHTWEIGHT_API
void BindRawBatchColumns(std::span<SqlRawColumn const> columns,
795 std::size_t rowCount,
796 std::source_location sourceLocation);
801 LIGHTWEIGHT_API
void ResetParameterArrayBinding() noexcept;
804 LIGHTWEIGHT_API
void RequireExecuteSucceededOrNoData(
805 SqlResult result, std::source_location sourceLocation = std::source_location::current()) const;
808 LIGHTWEIGHT_API
void RequireSuccessfulBatchExecute(
810 std::
size_t processedCount,
811 std::
size_t expectedCount,
812 std::source_location sourceLocation = std::source_location::current()) const;
829 [[nodiscard]] LIGHTWEIGHT_API
bool RetryStalePreparedStatement(SqlResult result);
831 LIGHTWEIGHT_API
void RequireIndicators();
832 LIGHTWEIGHT_API SqlIndicator* GetIndicatorForColumn(SqlColumnIndex column) noexcept;
841 [[nodiscard]] std::
size_t EffectivePrefetchDepth() const noexcept;
843 void ArmPrefetchOnFirstFetch() noexcept;
845 [[nodiscard]] std::expected<
void, SqlErrorInfo> IssueDeferredBinds(std::source_location location) noexcept;
847 [[nodiscard]] std::expected<
void, SqlErrorInfo> RunPreFetchSteps(std::source_location location) noexcept;
849 [[nodiscard]] std::expected<
void, SqlErrorInfo> RunPostProcessCallbacks(std::source_location location) noexcept;
852 [[nodiscard]] std::expected<
bool, SqlErrorInfo> FetchRowPrefetched() noexcept;
854 [[nodiscard]] LIGHTWEIGHT_API
bool IsPrefetchActive() const noexcept;
855#if defined(LIGHTWEIGHT_DRIVER_ODBC)
857 [[nodiscard]] LIGHTWEIGHT_API RowArrayCursor
const& PrefetchCursorRef() const noexcept;
860 [[nodiscard]] LIGHTWEIGHT_API std::size_t PrefetchRowInBlock() const noexcept;
863 [[nodiscard]] LIGHTWEIGHT_API
bool ShouldRecordPrefetchBinding() const noexcept;
865 LIGHTWEIGHT_API
void ResetPrefetchBindings() noexcept;
868 LIGHTWEIGHT_API
void MarkPrefetchBindingUnsupported() noexcept;
872 LIGHTWEIGHT_API
void KeepVariantReadsPerRow() noexcept;
877 enum class PrefetchTarget : std::uint8_t
887 template <
typename T>
888 [[nodiscard]]
static constexpr PrefetchTarget PrefetchTargetOf() noexcept;
899 LIGHTWEIGHT_API
void RecordPrefetchColumn(SqlColumnIndex column,
900 PrefetchTarget target,
901 std::function<
void()> scatter,
902 std::function<
void()> deferredBind);
908 LIGHTWEIGHT_API
void RecordPrefetchColumnTarget(SqlColumnIndex column, PrefetchTarget target);
910 LIGHTWEIGHT_API
void ResetPrefetchState() noexcept;
911#if defined(LIGHTWEIGHT_DRIVER_ODBC)
913 [[nodiscard]] LIGHTWEIGHT_API SqlVariant MakePrefetchVariantCell(RowArrayCursor
const& cursor,
915 SqlColumnIndex column)
const;
917 template <
typename T>
918 [[nodiscard]] T ConvertCell(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
const;
924 [[nodiscard]] LIGHTWEIGHT_API SqlDataBinder<SqlDynamicNumeric>::DeclaredDigits DeclaredDynamicNumericDigits(
925 SqlColumnIndex column)
const;
927#if defined(LIGHTWEIGHT_DRIVER_ODBC)
931 LIGHTWEIGHT_API
void RequirePrefetchColumnInRange(RowArrayCursor
const& cursor, SqlColumnIndex column)
const;
935 template <SqlOutputColumnBinder T>
936 void RecordPrefetchOutputColumn(SqlColumnIndex column, T* arg);
943 template <SqlQueryObject QueryObject>
944 void AdoptProjectedFieldNames(QueryObject
const& queryObject);
949 [[nodiscard]] SqlPreparedStatementCache* UsablePreparedStatementCache() const noexcept;
960 [[nodiscard]]
bool AcquirePreparedHandle(SqlPreparedStatementCache& cache, std::string_view query);
969 void PrepareOnHandle(std::
string queryText);
975 [[nodiscard]] SqlResult ExecDirectOnHandle(std::string_view query);
980 void RegisterHandleTextEntry();
984 LIGHTWEIGHT_API
void RequireCurrentSession();
988 void RequireLiveHandle() const;
991 [[nodiscard]]
bool HasLiveHandle() const noexcept;
995 void ReleaseHandle() noexcept;
999 LIGHTWEIGHT_API
void ForgetHandleOfEndedSession() noexcept;
1008 [[nodiscard]] std::vector<std::int16_t> DescribeInputParameterTypes() noexcept;
1012 bool ReleasePreparedHandle() noexcept;
1016 bool ReleasePreparedHandle(SqlPreparedStatementCache& cache) noexcept;
1020 void ReleasePreparedHandleForDirectExecution();
1023 void EnsureStatementHandle();
1026 void ApplyQueryTimeoutToNewHandle();
1030 [[nodiscard]] SqlResult AllocateHandle() noexcept;
1034 std::unique_ptr<Data,
void (*)(Data*)> m_data;
1035 SqlConnection* m_connection {};
1036 Driver::StatementHandle m_handle {};
1037 uint64_t m_sessionId {};
1038 std::string m_preparedQuery;
1039 std::optional<std::int16_t> m_numColumns;
1042 std::vector<std::string> m_projectedFieldNames;
1043 bool m_projectionHasWildcard =
false;
1045 SqlColumnIndex m_parameterBeingBound = 0;
1047 ParameterSlotReuse m_slotReuseBeingBound = ParameterSlotReuse::NextBinding;
1049 bool m_parameterTookSlots =
false;
1052 std::uint64_t m_executeAttempts = 0;
1055 bool m_parameterRoundBound =
false;
1056 std::int16_t m_expectedParameterCount {};
1061 std::int16_t m_preparedParameterCount {};
1062 bool m_reusedPreparedQuery {
false };
1064 SqlPreparedStatementCaching::Enabled
1070 return m_preparedStatementCaching;
1077 friend class SqlVariantRowIterator;
1086 SqlResultCursor() =
delete;
1087 SqlResultCursor(SqlResultCursor
const&) =
delete;
1088 SqlResultCursor& operator=(SqlResultCursor
const&) =
delete;
1092 m_stmt { other.m_stmt }
1094 other.m_stmt =
nullptr;
1102 m_stmt = other.m_stmt;
1103 other.m_stmt =
nullptr;
1112 m_stmt->CloseCursor();
1121 return m_stmt->NumRowsAffected();
1128 return m_stmt->NumColumnsAffected();
1134 return m_stmt->NarrowTextBindingMode();
1141 [[nodiscard]] LIGHTWEIGHT_API std::expected<SqlResultColumnType, SqlErrorInfo>
ColumnSqlType(
1142 SqlColumnIndex column)
const;
1147 m_stmt->ConsumePendingResults(location);
1156 m_stmt->BindOutputColumns(args...);
1160 template <SqlOutputColumnBinder T>
1163 m_stmt->BindOutputColumn(columnIndex, arg);
1175 return m_stmt->FetchRow();
1179 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::expected<bool, SqlErrorInfo>
TryFetchRow(
1180 std::source_location location = std::source_location::current()) noexcept
1182 return m_stmt->TryFetchRow(location);
1186 template <
typename... Records>
1187 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
1190 m_stmt->BindOutputColumnsToRecord(records...);
1199 template <
typename Record,
typename... ColumnAccessors>
1201 std::size_t arrayDepth,
1202 ColumnAccessors
const&... accessors)
1204 m_stmt->FetchAllRowWise(out, arrayDepth, accessors...);
1214 template <SqlGetColumnNativeType T>
1215 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE
bool GetColumn(SqlColumnIndex column, T* result)
const
1217 return m_stmt->GetColumn<T>(column, result);
1227 template <SqlGetColumnNativeType T>
1228 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE T
GetColumn(SqlColumnIndex column)
const
1230 return m_stmt->GetColumn<T>(column);
1236 template <SqlGetColumnNativeType T>
1237 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::optional<T>
GetNullableColumn(SqlColumnIndex column)
const
1239 return m_stmt->GetNullableColumn<T>(column);
1245 template <SqlGetColumnNativeType T>
1246 [[nodiscard]] T
GetColumnOr(SqlColumnIndex column, T&& defaultValue)
const
1248 return m_stmt->GetColumnOr(column, std::forward<T>(defaultValue));
1264 template <SqlGetColumnNativeType T>
1265 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE T
GetColumn(std::string_view name)
const
1267 return m_stmt->GetColumn<T>(m_stmt->ResolveColumnName(name));
1278 template <SqlGetColumnNativeType T>
1279 [[nodiscard]] LIGHTWEIGHT_FORCE_INLINE std::optional<T>
GetNullableColumn(std::string_view name)
const
1281 return m_stmt->GetNullableColumn<T>(m_stmt->ResolveColumnName(name));
1293 template <SqlGetColumnNativeType T>
1294 [[nodiscard]] T
GetColumnOr(std::string_view name, T&& defaultValue)
const
1296 return m_stmt->GetColumnOr(m_stmt->ResolveColumnName(name), std::forward<T>(defaultValue));
1303struct [[nodiscard]] SqlSentinelIterator
1307class [[nodiscard]] SqlVariantRowIterator
1310 explicit SqlVariantRowIterator(SqlSentinelIterator )
noexcept:
1316 explicit SqlVariantRowIterator(SqlResultCursor& cursor):
1317 _numResultColumns { static_cast<SqlColumnIndex>(cursor.NumColumnsAffected()) },
1320 _row.reserve(_numResultColumns);
1321 cursor.m_stmt->KeepVariantReadsPerRow();
1325 SqlVariantRow& operator*() noexcept
1330 SqlVariantRow
const& operator*() const noexcept
1336 SqlVariantRowIterator& operator++()
1338 _end = !_cursor->FetchRow();
1342 for (
auto const i: std::views::iota(SqlColumnIndex(1), SqlColumnIndex(_numResultColumns + 1)))
1343 _row.emplace_back(_cursor->GetColumn<SqlVariant>(i));
1348 bool operator!=(SqlSentinelIterator )
const noexcept
1353 bool operator!=(SqlVariantRowIterator
const& )
const noexcept
1360 SqlColumnIndex _numResultColumns = 0;
1361 SqlResultCursor* _cursor;
1365class [[nodiscard]] SqlVariantRowCursor
1368 explicit SqlVariantRowCursor(SqlResultCursor&& cursor):
1369 _resultCursor { std::move(cursor) }
1374 SqlVariantRowIterator begin()
1376 return SqlVariantRowIterator { _resultCursor };
1379 static SqlSentinelIterator end() noexcept
1381 return SqlSentinelIterator {};
1385 SqlResultCursor _resultCursor;
1422template <
typename T>
1434 _connection { &conn }
1443 _connection { &conn },
1444 _queryCustomizer { std::move(queryCustomizer) }
1451 using difference_type = bool;
1452 using value_type = T;
1454 iterator& operator++()
1458 _is_end = !_cursor->FetchRow();
1466 LIGHTWEIGHT_FORCE_INLINE value_type operator*()
1468 auto res = detail::MakeUninitialized<T>();
1474 SqlColumnIndex columnIndex = 0;
1476 if constexpr (RecordColumnMember<FieldType>)
1479 if constexpr (FieldWithStorage<FieldType>)
1480 value = _cursor->GetColumn<
typename FieldType::ValueType>(columnIndex);
1482 value = _cursor->GetColumn<FieldType>(columnIndex);
1489 LIGHTWEIGHT_FORCE_INLINE
constexpr bool operator!=(iterator
const& other)
const noexcept
1491 return _is_end != other._is_end;
1494 constexpr iterator(std::default_sentinel_t )
noexcept:
1496 _cursor { std::nullopt }
1500 explicit iterator(SqlConnection& conn):
1501 _stmt { std::make_unique<SqlStatement>(conn) },
1502 _cursor { std::nullopt }
1506 LIGHTWEIGHT_FORCE_INLINE SqlStatement& Statement() noexcept
1511 void SetCursor(SqlResultCursor cursor)
noexcept
1513 _cursor.emplace(std::move(cursor));
1517 bool _is_end =
false;
1518 std::unique_ptr<SqlStatement> _stmt;
1519 std::optional<SqlResultCursor> _cursor;
1525 auto it = iterator { *_connection };
1526 auto& stmt = it.Statement();
1527 stmt.Prepare(it.Statement().Query(RecordTableName<T>).Select().template Fields<T>().Build(_queryCustomizer).All());
1528 it.SetCursor(stmt.Execute());
1534 if constexpr (ColumnsArePrefetchConvertible())
1535 RecordColumnPrefetchTargets(stmt);
1537 stmt.MarkPrefetchBindingUnsupported();
1545 return iterator { std::default_sentinel };
1550 static constexpr bool ColumnsArePrefetchConvertible() noexcept;
1555 static
void RecordColumnPrefetchTargets(
SqlStatement& stmt);
1565 return m_connection && m_connection->
IsAlive() && !m_handle.IsEmpty();
1570 return !m_preparedQuery.empty();
1575 return *m_connection;
1580 return *m_connection;
1592template <
typename F>
1595 return Driver::VisitRequired(m_handle, operation, std::forward<F>(f));
1602template <
typename F>
1605 return Driver::VisitRequired(m_handle, operation, std::forward<F>(f));
1610 return m_handle.DriverId();
1613#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1614inline LIGHTWEIGHT_FORCE_INLINE Driver::Odbc::NativeStatementHandle Driver::Odbc::NativeHandle(
1618 return Visit(stmt.DriverHandle(), [](
auto const& held) -> NativeStatementHandle {
1619 if constexpr (std::same_as<std::remove_cvref_t<decltype(held)>, Statement>)
1622 return NativeStatementHandle {};
1627template <SqlQueryObject QueryObject>
1628inline void SqlStatement::AdoptProjectedFieldNames(QueryObject
const& queryObject)
1630 if constexpr (SqlNamedProjectionQueryObject<QueryObject>)
1632 auto const names = queryObject.ProjectedFieldNames();
1633 m_projectedFieldNames.assign(names.begin(), names.end());
1634 m_projectionHasWildcard = queryObject.ProjectionHasWildcard();
1640 m_projectedFieldNames.clear();
1641 m_projectionHasWildcard =
false;
1645inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::Prepare(
SqlQueryObject auto const& queryObject) &
1647 Prepare(queryObject.ToSql());
1649 AdoptProjectedFieldNames(queryObject);
1654 auto preparedStatement = std::move(*this).
Prepare(queryObject.ToSql());
1655 preparedStatement.AdoptProjectedFieldNames(queryObject);
1656 return preparedStatement;
1659inline LIGHTWEIGHT_FORCE_INLINE std::string
const& SqlStatement::PreparedQuery() const noexcept
1661 return m_preparedQuery;
1666inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::BindOutputColumns(Args*... args)
1668#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1669 if (ShouldRecordPrefetchBinding())
1674 ResetPrefetchBindings();
1675 SqlColumnIndex i = 0;
1676 ((++i, RecordPrefetchOutputColumn<Args>(i, args)), ...);
1683 RequireCurrentSession();
1684 RequireIndicators();
1685 NoteOutputColumnBoundDirectly();
1687 SqlColumnIndex i = 0;
1688 ((++i, BindOutputColumnNow<Args>(i, args)), ...);
1697 template <
typename T>
1698 concept ResetsBoundValueOnNull = std::is_trivially_copyable_v<T> && std::is_default_constructible_v<T>
1699 && std::is_assignable_v<T&, T> && !SqlIsStdOptional<T> && !IsSqlFixedString<T>;
1706 template <
typename T>
1707 [[nodiscard]]
constexpr auto& BoundNullResetTarget(T& value)
noexcept
1709 if constexpr (
requires {
requires std::is_lvalue_reference_v<
decltype(value.MutableValue())>; })
1710 return BoundNullResetTarget(value.MutableValue());
1721template <SqlOutputColumnBinder T>
1722inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::BindOutputColumnNow(SqlColumnIndex column, T* arg)
1724 BeginOutputColumnBinding(column);
1725 auto*
const indicator = GetIndicatorForColumn(column);
1727 Driver::Visit(m_handle, [&](
auto& stmt) {
return Driver::BindOutputColumn(stmt, column, arg, indicator, *
this); });
1730 if (!Succeeded(result))
1731 DropOutputColumnCallbacks(column);
1732 RequireSuccess(result);
1737 auto& target = detail::BoundNullResetTarget(*arg);
1738 using Target = std::remove_cvref_t<
decltype(target)>;
1739 if constexpr (detail::ResetsBoundValueOnNull<Target>)
1740 PlanNullReset(column, indicator, std::addressof(target), [](
void* value)
noexcept {
1741 *
static_cast<Target*
>(value) = Target {};
1745template <
typename... Records>
1746 requires(((std::is_class_v<Records> && std::is_aggregate_v<Records>) && ...))
1747void SqlStatement::BindOutputColumnsToRecord(Records*... records)
1749#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1750 if (ShouldRecordPrefetchBinding())
1752 ResetPrefetchBindings();
1753 SqlColumnIndex i = 0;
1755 [
this, &i]<
size_t I,
typename FieldType>(FieldType& value) {
1760 this->RecordPrefetchOutputColumn<FieldType>(i, &value);
1770 RequireCurrentSession();
1771 RequireIndicators();
1772 NoteOutputColumnBoundDirectly();
1774 SqlColumnIndex i = 0;
1776 [
this, &i]<
size_t I,
typename FieldType>(FieldType& value) {
1778 if constexpr (RecordColumnMember<FieldType>)
1781 this->BindOutputColumnNow<FieldType>(i, &value);
1788template <SqlOutputColumnBinder T>
1789inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::BindOutputColumn(SqlColumnIndex columnIndex, T* arg)
1793#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1794 if (ShouldRecordPrefetchBinding())
1796 RecordPrefetchOutputColumn<T>(columnIndex, arg);
1801 RequireIndicators();
1802 NoteOutputColumnBoundDirectly();
1804 BindOutputColumnNow<T>(columnIndex, arg);
1808template <SqlInputParameterBinder Arg>
1809inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::BindInputParameter(std::int16_t columnIndex, Arg
const& arg)
1811 RequireCurrentSession();
1812 if (m_parameterRoundBound)
1813 DropRoundBindings();
1815 m_expectedParameterCount = (std::numeric_limits<
decltype(m_expectedParameterCount)>::max)();
1816 Driver::Visit(m_handle, [&](
auto& stmt) {
1818 BindParameterValue(stmt,
static_cast<SqlColumnIndex
>(columnIndex), arg, ParameterSlotReuse::NextBinding));
1823template <SqlInputParameterBinder Arg,
typename ColumnName>
1824inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::BindInputParameter(std::int16_t columnIndex,
1826 ColumnName&& columnNameHint)
1828 SqlLogger::GetLogger().OnBindInputParameter(std::forward<ColumnName>(columnNameHint), arg);
1829 BindInputParameter(columnIndex, arg);
1839 ZoneScopedN(
"SqlStatement::Execute");
1840 ZoneTextObject(m_preparedQuery);
1841 RequireCurrentSession();
1842 SqlLogger::GetLogger().OnExecute(m_preparedQuery);
1844 if (!(m_expectedParameterCount == (std::numeric_limits<
decltype(m_expectedParameterCount)>::max)()
1845 &&
sizeof...(args) == 0)
1846 && !(m_expectedParameterCount ==
sizeof...(args)))
1847 throw std::invalid_argument {
"Invalid argument count" };
1851 if constexpr (
sizeof...(Args) > 0)
1852 m_parameterRoundBound =
true;
1855 Driver::Visit(m_handle, [&]([[maybe_unused]]
auto& stmt) {
1856 SqlColumnIndex i = 0;
1858 SqlLogger::GetLogger().OnBindInputParameter({}, args),
1859 RequireSuccess(BindParameterValue(stmt, i, args, ParameterSlotReuse::InPlace))),
1864 ++m_executeAttempts;
1865 auto result = Driver::Execute(m_handle);
1868 if (RetryStalePreparedStatement(result))
1869 result = Driver::Execute(m_handle);
1871 if (result != SqlResult::NoData && result != SqlResult::Success && result != SqlResult::SuccessWithInfo)
1872 throw SqlException(LastError(), std::source_location::current());
1874 ProcessPostExecuteCallbacks();
1884#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1886template <
typename T>
1887concept SqlNativeContiguousValueConcept =
1888 ( std::same_as<T, bool>
1889 || std::same_as<T, char>
1890 || std::same_as<T, unsigned char>
1891 || std::same_as<T, std::int16_t>
1892 || std::same_as<T, std::uint16_t>
1893 || std::same_as<T, std::int32_t>
1894 || std::same_as<T, std::uint32_t>
1895 || std::same_as<T, std::int64_t>
1896 || std::same_as<T, std::uint64_t>
1897 || std::same_as<T, float>
1898 || std::same_as<T, double>
1899 || std::same_as<T, SqlDate>
1900 || std::same_as<T, SqlDateTime>
1901 || std::same_as<T, SqlFixedString<T::Capacity, typename T::value_type, T::PostRetrieveOperation>>)
1903 { SqlDataBinder<T>::BatchInputParameter(stmt, column, values, rowCount, cb) } -> std::same_as<SqlResult>;
1906template <
typename FirstColumnBatch,
typename... MoreColumnBatches>
1907concept SqlNativeBatchable =
1908 std::ranges::contiguous_range<FirstColumnBatch>
1909 && (std::ranges::contiguous_range<MoreColumnBatches> && ...)
1910 && SqlNativeContiguousValueConcept<std::ranges::range_value_t<FirstColumnBatch>>
1911 && (SqlNativeContiguousValueConcept<std::ranges::range_value_t<MoreColumnBatches>> && ...);
1917template <
typename FirstColumnBatch,
typename... MoreColumnBatches>
1918concept SqlNativeBatchable =
false;
1924template <
typename V>
1930template <
typename V>
1936template <
typename V>
1949template <
typename V>
1958template <
typename V>
1959constexpr bool SqlColumnMayStage() noexcept
1961 if constexpr (SqlIsStdOptional<V>)
1962 return SqlColumnMayStage<typename V::value_type>();
1964 return requires { &SqlDataBinder<V>::OutputColumnInPlace; };
1973#if defined(LIGHTWEIGHT_DRIVER_ODBC)
1974template <
typename V>
1976 Driver::Odbc::Statement& stmt, SqlColumnIndex column, V
const* elem0, std::size_t n, SqlDataBinderCallback& cb) {
1977 { SqlDataBinder<V>::BatchRowWiseInputParameter(stmt, column, elem0, n, n, cb) } -> std::same_as<SqlResult>;
1981template <
typename V>
1987 template <
typename V>
1988 struct IsNarrowFixedStringColumn: std::false_type
1992 template <std::
size_t N, SqlFixedStringMode Mode>
1993 struct IsNarrowFixedStringColumn<SqlFixedString<N, char, Mode>>: std::true_type
1997 template <std::
size_t N, SqlFixedStringMode Mode>
1998 struct IsNarrowFixedStringColumn<std::optional<SqlFixedString<N, char, Mode>>>: std::true_type
2010 template <std::ranges::range Values,
typename Project>
2011 void RequireWritableYears(Values
const& values, Project
const& project)
2014 std::remove_cvref_t<std::invoke_result_t<Project const&, std::ranges::range_reference_t<Values const>>>;
2015 if constexpr (SqlBinderChecksYear<Value>)
2016 for (
auto const& element: values)
2017 if (auto const year = SqlDataBinder<Value>::UnwritableYear(std::invoke(project, element)))
2018 throw SqlException(UnwritableYearError(*year));
2024template <
typename V>
2025constexpr bool SqlIsNarrowFixedStringColumn = detail::IsNarrowFixedStringColumn<V>::value;
2027#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2028template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::contiguous_range... MoreColumnBatches>
2030 MoreColumnBatches
const&... moreColumnBatches)
2032 static_assert(SqlNativeBatchable<FirstColumnBatch, MoreColumnBatches...>,
2033 "Must be a supported native contiguous element type.");
2035 ZoneScopedN(
"SqlStatement::ExecuteBatchNative");
2036 ZoneTextObject(m_preparedQuery);
2037 RequireCurrentSession();
2039 if (m_expectedParameterCount != 1 +
sizeof...(moreColumnBatches))
2040 throw std::invalid_argument {
"Invalid number of columns" };
2042 auto const rowCount = std::ranges::size(firstColumnBatch);
2043 ZoneValue(rowCount);
2044 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2045 throw std::invalid_argument {
"Uneven number of rows" };
2046 m_parameterRoundBound =
true;
2048 size_t rowStart = 0;
2053 auto const restoreParameterBinding = detail::Finally([
this] {
2054 ResetParameterArrayBinding();
2055 ClearBatchIndicators();
2056 DropInputParameterKeepAlives();
2059 auto const location = std::source_location::current();
2061 Driver::Odbc::SetColumnWiseParameterArray(
2062 stmt, rowCount, &rowStart, [&](SqlResult result) { RequireSuccess(result, location); });
2064 ClearBatchIndicators();
2068 SqlDataBinder<std::remove_cvref_t<
decltype(*std::ranges::data(firstColumnBatch))>>::BatchInputParameter(
2069 stmt, 1, std::ranges::data(firstColumnBatch), rowCount, *
this));
2070 SqlColumnIndex column = 1;
2072 SqlDataBinder<std::remove_cvref_t<
decltype(*std::ranges::data(moreColumnBatches))>>::BatchInputParameter(
2073 stmt, ++column, std::ranges::data(moreColumnBatches), rowCount, *
this)),
2076 SqlLogger::GetLogger().OnExecuteNativeBatch(m_preparedQuery);
2079 ++m_executeAttempts;
2080 RequireSuccess(Driver::Execute(m_handle));
2082 ProcessPostExecuteCallbacks();
2089SqlResultCursor SqlStatement::ExecuteBatchNative(FirstColumnBatch
const& firstColumnBatch,
2090 MoreColumnBatches
const&... moreColumnBatches)
2092 ZoneScopedN(
"SqlStatement::ExecuteBatchNative");
2093 ZoneTextObject(m_preparedQuery);
2094 RequireCurrentSession();
2096 if (m_expectedParameterCount != 1 +
sizeof...(moreColumnBatches))
2097 throw std::invalid_argument {
"Invalid number of columns" };
2099 auto const rowCount = std::ranges::size(firstColumnBatch);
2100 ZoneValue(rowCount);
2101 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2102 throw std::invalid_argument {
"Uneven number of rows" };
2103 m_parameterRoundBound =
true;
2105 auto const restoreParameterBinding = detail::Finally([
this] {
2106 ResetParameterArrayBinding();
2107 ClearBatchIndicators();
2108 DropInputParameterKeepAlives();
2110 throw SqlException(Driver::NotSupportedByDriver(m_handle.DriverId(),
"ExecuteBatchNative"));
2115template <SqlInputParameterBatchBinder FirstColumnBatch, std::ranges::range... MoreColumnBatches>
2116inline LIGHTWEIGHT_FORCE_INLINE
SqlResultCursor SqlStatement::ExecuteBatch(FirstColumnBatch
const& firstColumnBatch,
2117 MoreColumnBatches
const&... moreColumnBatches)
2123 if constexpr (SqlNativeBatchable<FirstColumnBatch, MoreColumnBatches...>)
2125 if (Driver::SupportsParameterArrays(m_handle.DriverId()))
2126 return ExecuteBatchNative(firstColumnBatch, moreColumnBatches...);
2128 return ExecuteBatchSoft(firstColumnBatch, moreColumnBatches...);
2133 MoreColumnBatches
const&... moreColumnBatches)
2135 ZoneScopedN(
"SqlStatement::ExecuteBatchSoft");
2136 ZoneTextObject(m_preparedQuery);
2137 RequireCurrentSession();
2139 if (m_expectedParameterCount != 1 +
sizeof...(moreColumnBatches))
2140 throw std::invalid_argument {
"Invalid number of columns" };
2142 auto const rowCount = std::ranges::size(firstColumnBatch);
2143 ZoneValue(rowCount);
2144 if (!((std::size(moreColumnBatches) == rowCount) && ...))
2145 throw std::invalid_argument {
"Uneven number of rows" };
2146 m_parameterRoundBound =
true;
2149 detail::RequireWritableYears(firstColumnBatch, std::identity {});
2150 (detail::RequireWritableYears(moreColumnBatches, std::identity {}), ...);
2152 for (
auto const rowIndex: std::views::iota(
size_t { 0 }, rowCount))
2156 Driver::Visit(m_handle, [&](auto& stmt) {
2157 SqlColumnIndex column = 0;
2158 ((++column, RequireSuccess(BindParameterValue(stmt, column, columnsInRow, ParameterSlotReuse::InPlace))),
2163 ++m_executeAttempts;
2164 RequireSuccess(Driver::Execute(m_handle));
2166 ProcessPostExecuteCallbacks();
2169 std::ref(*std::ranges::next(std::ranges::begin(firstColumnBatch),
static_cast<std::ptrdiff_t
>(rowIndex))),
2171 *std::ranges::next(std::ranges::begin(moreColumnBatches),
static_cast<std::ptrdiff_t
>(rowIndex)))...));
2176template <std::ranges::contiguous_range Rows,
typename... ColumnAccessors>
2177 requires(
sizeof...(ColumnAccessors) >= 1
2178 && (std::invocable<ColumnAccessors
const&, std::ranges::range_value_t<Rows>
const&> && ...))
2179SqlResultCursor SqlStatement::ExecuteBatch(Rows
const& rows, ColumnAccessors
const&... accessors)
2181 ZoneScopedN(
"SqlStatement::ExecuteBatch(row-major)");
2182 ZoneTextObject(m_preparedQuery);
2183 RequireCurrentSession();
2185 using RowElem = std::ranges::range_value_t<Rows>;
2187 auto const rowCount = std::ranges::size(rows);
2191 if (m_expectedParameterCount !=
static_cast<std::int16_t
>(
sizeof...(accessors)))
2192 throw std::invalid_argument {
"Invalid number of columns" };
2198 constexpr bool allColumnsRowBindable =
2200 constexpr bool allAccessorsReturnReference =
2201 (std::is_reference_v<std::invoke_result_t<ColumnAccessors const&, RowElem const&>> && ...);
2202 constexpr bool anyStridedIndicatorColumn =
2204 constexpr bool indicatorAlignmentSatisfied = (
sizeof(RowElem) %
alignof(SqlIndicator)) == 0;
2205 constexpr bool anyNarrowFixedStringColumn =
2206 (SqlIsNarrowFixedStringColumn<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, RowElem const&>>>
2209 if constexpr (allColumnsRowBindable && allAccessorsReturnReference
2210 && (!anyStridedIndicatorColumn || indicatorAlignmentSatisfied))
2212 auto const* rowData = std::ranges::data(rows);
2216 auto const accessorStrideMatchesRow = [&](
auto const& accessor)
noexcept ->
bool {
2217 auto const* first =
reinterpret_cast<std::byte const*
>(std::addressof(accessor(rowData[0])));
2218 auto const* second =
reinterpret_cast<std::byte const*
>(std::addressof(accessor(rowData[1])));
2219 return static_cast<std::size_t
>(second - first) ==
sizeof(RowElem);
2221 bool const rowStrideOk = rowCount < 2 || (accessorStrideMatchesRow(accessors) && ...);
2225 bool const narrowColumnsBindInPlace =
2226 !anyNarrowFixedStringColumn || NarrowTextBindingMode() != detail::NarrowTextBinding::WideFromProcessCodePage;
2229 constexpr bool anyColumnMayStage =
2230 (SqlColumnMayStage<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, RowElem const&>>>() || ...);
2231 bool const bindsInPlace = !anyColumnMayStage || detail::ConvertsNarrowIntegerCTypes(m_connection->ServerType());
2233 if (m_connection->SupportsNativeRowBatch() && rowStrideOk && narrowColumnsBindInPlace && bindsInPlace)
2234 return ExecuteBatchNativeRowWise(rows, accessors...);
2237 return ExecuteBatchSoftRowMajor(rows, accessors...);
2240#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2241template <std::ranges::contiguous_range Rows,
typename... ColumnAccessors>
2242SqlResultCursor SqlStatement::ExecuteBatchNativeRowWise(Rows
const& rows, ColumnAccessors
const&... accessors)
2244 ZoneScopedN(
"SqlStatement::ExecuteBatchNativeRowWise");
2245 ZoneTextObject(m_preparedQuery);
2246 m_parameterRoundBound =
true;
2248 using RowElem = std::ranges::range_value_t<Rows>;
2249 auto const rowCount = std::ranges::size(rows);
2250 ZoneValue(rowCount);
2251 auto const* rowData = std::ranges::data(rows);
2261 auto const restoreParameterBinding = detail::Finally([
this] {
2262 ResetParameterArrayBinding();
2263 ClearBatchIndicators();
2264 DropInputParameterKeepAlives();
2268 auto const location = std::source_location::current();
2269 Driver::VisitRequired(m_handle,
"row-wise native batch", [&](Driver::Odbc::Statement& stmt) {
2270 Driver::Odbc::SetRowWiseParameterArray(
2271 stmt, rowCount,
sizeof(RowElem), &processedCount, [&](SqlResult result) { RequireSuccess(result, location); });
2275 Driver::VisitRequired(m_handle,
"row-wise native batch", [&](Driver::Odbc::Statement& stmt) {
2276 SqlColumnIndex column = 0;
2277 auto const bindColumn = [&](
auto const& accessor) {
2279 using ValueType = std::remove_cvref_t<
decltype(accessor(rowData[0]))>;
2283 detail::RequireWritableYears(std::span { rowData, rowCount }, accessor);
2284 if constexpr (SqlHasRowWiseBatchBinder<ValueType>)
2285 RequireSuccess(SqlDataBinder<ValueType>::BatchRowWiseInputParameter(
2286 stmt, column, std::addressof(accessor(rowData[0])),
sizeof(RowElem), rowCount, *
this));
2288 RequireSuccess(BindParameterValue(stmt, column, accessor(rowData[0]), ParameterSlotReuse::InPlace));
2290 (bindColumn(accessors), ...);
2293 SqlLogger::GetLogger().OnExecuteNativeBatch(m_preparedQuery);
2297 ++m_executeAttempts;
2298 auto const executeResult = Driver::Execute(m_handle);
2299 RequireSuccessfulBatchExecute(executeResult, processedCount, rowCount);
2300 ProcessPostExecuteCallbacks();
2302 return SqlResultCursor { *
this };
2305template <std::ranges::contiguous_range Rows,
typename... ColumnAccessors>
2306SqlResultCursor SqlStatement::ExecuteBatchNativeRowWise(Rows
const& rows, ColumnAccessors
const&... accessors)
2310 return ExecuteBatchSoftRowMajor(rows, accessors...);
2314template <std::ranges::contiguous_range Rows,
typename... ColumnAccessors>
2315SqlResultCursor SqlStatement::ExecuteBatchSoftRowMajor(Rows
const& rows, ColumnAccessors
const&... accessors)
2317 ZoneScopedN(
"SqlStatement::ExecuteBatchSoftRowMajor");
2318 ZoneTextObject(m_preparedQuery);
2319 m_parameterRoundBound =
true;
2321 auto const* rowData = std::ranges::data(rows);
2322 auto const rowCount = std::ranges::size(rows);
2323 ZoneValue(rowCount);
2326 (detail::RequireWritableYears(std::span { rowData, rowCount }, accessors), ...);
2331 auto const bindAndExecuteRow = [
this](
auto const&... values) {
2332 Driver::Visit(m_handle, [&](
auto& stmt) {
2333 SqlColumnIndex column = 0;
2334 ((++column,
RequireSuccess(BindParameterValue(stmt, column, values, ParameterSlotReuse::InPlace))), ...);
2336 SqlLogger::GetLogger().OnExecute(m_preparedQuery);
2339 ++m_executeAttempts;
2340 RequireExecuteSucceededOrNoData(Driver::Execute(m_handle));
2342 ProcessPostExecuteCallbacks();
2344 for (
auto const rowIndex: std::views::iota(std::size_t { 0 }, rowCount))
2345 bindAndExecuteRow(accessors(rowData[rowIndex])...);
2347 return SqlResultCursor { *
this };
2350#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2351template <
typename Value>
2352void SqlStatement::BindRowWiseValue(SqlColumnIndex column,
void* base0, SqlIndicator* indicators)
2354 if constexpr (IsSqlFixedString<Value>)
2361 Driver::VisitRequired(m_handle,
"block fetch", [&](Driver::Odbc::Statement& stmt) {
2364 SqlBasicStringOperations<Value>::Data(
static_cast<Value*
>(base0)),
2365 static_cast<SqlIndicator
>(Value::Capacity) + 1,
2369 else if constexpr (std::same_as<Value, bool>)
2373 BeginOutputColumnBinding(column);
2374 Driver::VisitRequired(m_handle,
"block fetch", [&](Driver::Odbc::Statement& stmt) {
2375 RequireSuccess(SqlDataBinder<bool>::OutputBitColumnInPlace(stmt, column,
static_cast<bool*
>(base0), indicators));
2378 else if constexpr (SqlColumnMayStage<Value>())
2383 BeginOutputColumnBinding(column);
2384 Driver::VisitRequired(m_handle,
"block fetch", [&](Driver::Odbc::Statement& stmt) {
2385 RequireSuccess(SqlDataBinder<Value>::OutputColumnInPlace(stmt, column,
static_cast<Value*
>(base0), indicators));
2392 BeginOutputColumnBinding(column);
2393 Driver::Visit(m_handle, [&](
auto& stmt) {
2394 RequireSuccess(Driver::BindOutputColumn(stmt, column,
static_cast<Value*
>(base0), indicators, *
this));
2399template <
typename ValueType>
2400SqlIndicator* SqlStatement::BindRowWiseOutputColumn(SqlColumnIndex column,
2402 std::size_t rowStride,
2409 auto*
const indicatorBytes = ProvideRowWiseFetchIndicators(((depth - 1) * rowStride) +
sizeof(SqlIndicator));
2410 auto*
const indicators =
reinterpret_cast<SqlIndicator*
>(indicatorBytes);
2412 if constexpr (SqlIsStdOptional<ValueType>)
2414 using Inner = ValueType::value_type;
2415 auto*
const optBytes =
static_cast<std::byte*
>(base0);
2418 for (
auto const i: std::views::iota(std::size_t { 0 }, depth))
2419 reinterpret_cast<ValueType*>(optBytes + (i * rowStride))->emplace();
2422 auto*
const contained0 =
reinterpret_cast<Inner*
>(optBytes + detail::OptionalValueOffset<Inner>());
2423 BindRowWiseValue<Inner>(column, contained0, indicators);
2427 BindRowWiseValue<ValueType>(column, base0, indicators);
2432template <
typename ValueType>
2433void SqlStatement::FinalizeRowWiseOutputColumn(
void* base0,
2434 std::size_t rowStride,
2435 std::size_t rowCount,
2436 SqlIndicator
const* indicators,
2437 SqlColumnIndex column,
2438 bool booleanTrueMayBeMinusOne)
2440 auto const indicatorAt = [&](std::size_t i)
noexcept {
2441 return *
reinterpret_cast<SqlIndicator const*
>(
reinterpret_cast<std::byte const*
>(indicators) + (i * rowStride));
2444 if constexpr (SqlIsStdOptional<ValueType>)
2446 using Inner = ValueType::value_type;
2447 auto*
const optBytes =
static_cast<std::byte*
>(base0);
2448 for (
auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2450 auto*
const optional =
reinterpret_cast<ValueType*
>(optBytes + (i * rowStride));
2451 if (indicatorAt(i) == SqlNullData)
2453 else if constexpr (IsSqlFixedString<Inner>)
2459 if (optional->has_value())
2460 SqlBasicStringOperations<Inner>::PostProcessOutputColumn(std::addressof(**optional), indicatorAt(i));
2462 else if constexpr (std::same_as<Inner, bool>)
2464 if (optional->has_value())
2465 CheckRowWiseBool(std::addressof(**optional), column, booleanTrueMayBeMinusOne);
2470 else if constexpr (std::same_as<ValueType, bool>)
2472 auto*
const base =
static_cast<std::byte*
>(base0);
2473 for (
auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2474 if (indicatorAt(i) != SqlNullData)
2475 CheckRowWiseBool(reinterpret_cast<bool*>(base + (i * rowStride)), column, booleanTrueMayBeMinusOne);
2477 else if constexpr (IsSqlFixedString<ValueType>)
2479 auto*
const base =
static_cast<std::byte*
>(base0);
2480 for (
auto const i: std::views::iota(std::size_t { 0 }, rowCount))
2481 SqlBasicStringOperations<ValueType>::PostProcessOutputColumn(
2482 reinterpret_cast<ValueType*>(base + (i * rowStride)), indicatorAt(i));
2489inline void SqlStatement::CheckRowWiseBool(
bool* value, SqlColumnIndex column,
bool booleanTrueMayBeMinusOne)
2491 auto written =
static_cast<unsigned char>(0);
2492 std::memcpy(&written, value, 1);
2495 auto const minusOne = written == std::numeric_limits<unsigned char>::max() && booleanTrueMayBeMinusOne;
2496 auto const valid =
static_cast<unsigned char>(minusOne ? 1 : 0);
2497 std::memcpy(value, &valid, 1);
2499 detail::ThrowNumericValueOutOfRange(column,
static_cast<unsigned>(written), 0U, 1U);
2502template <
typename Record,
typename... ColumnAccessors>
2503void SqlStatement::FetchAllRowWise(std::vector<Record>& out,
2504 [[maybe_unused]] std::size_t arrayDepth,
2505 ColumnAccessors
const&... accessors)
2507 ZoneScopedN(
"SqlStatement::FetchAllRowWise");
2508 ZoneTextObject(m_preparedQuery);
2509 RequireCurrentSession();
2511 static_assert(
sizeof...(ColumnAccessors) >= 1,
"FetchAllRowWise requires at least one column accessor");
2516 constexpr bool anyColumnMayStage =
2517 (SqlColumnMayStage<std::remove_cvref_t<std::invoke_result_t<ColumnAccessors const&, Record&>>>() || ...);
2518 auto const readsPerRow = !m_connection->SupportsNativeRowArrayFetch()
2519 || (anyColumnMayStage && !detail::ConvertsNarrowIntegerCTypes(m_connection->ServerType()));
2524 auto& record = detail::EmplaceBackUninitialized(out);
2527 SqlColumnIndex column = 0;
2528 ((++column, (void) GetColumn(column, std::addressof(accessors(record)))), ...);
2539#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2540 constexpr std::size_t columnCount =
sizeof...(ColumnAccessors);
2547 auto const perRow =
sizeof(Record) * (1 + columnCount);
2548 auto const budgetDepth = RowArrayCursor::MemoryBudgetBytes / std::max<std::size_t>(perRow, 1);
2549 auto const minDepth = std::min(RowArrayCursor::MinArrayDepth, arrayDepth);
2550 arrayDepth = std::clamp(budgetDepth, minDepth, arrayDepth);
2553 std::vector<Driver::Odbc::RowStatus> rowStatus(arrayDepth);
2554 Driver::Odbc::ProcessedCount rowsFetched = 0;
2559 auto const restoreFetchState = detail::Finally([
this] {
2560 Driver::VisitIfSupported(m_handle, [](Driver::Odbc::Statement& stmt) {
2561 (void) Driver::Odbc::UnbindColumns(stmt);
2562 Driver::Odbc::ResetRowArrayAttributes(stmt);
2564 DropOutputColumnBindings();
2565 ReleaseRowWiseFetchIndicators();
2568 auto const location = std::source_location::current();
2569 Driver::VisitRequired(m_handle,
"block fetch", [&](Driver::Odbc::Statement& stmt) {
2570 Driver::Odbc::SetRowArray(stmt,
sizeof(Record), arrayDepth, rowStatus.data(), &rowsFetched, [&](SqlResult result) {
2571 RequireSuccess(result, location);
2575 auto const booleanTrueMayBeMinusOne = BooleanTrueMayBeMinusOne();
2578 std::size_t
const base = out.size();
2579 detail::ResizeUninitialized(out, base + arrayDepth);
2583 Record*
const row0 = out.data() + base;
2587 ReleaseRowWiseFetchIndicators();
2588 std::array<SqlIndicator*, columnCount> indicators {};
2589 SqlColumnIndex column = 0;
2590 std::size_t bindIndex = 0;
2591 ((indicators[bindIndex++] = BindRowWiseOutputColumn<std::remove_cvref_t<
decltype(accessors(*row0))>>(
2592 ++column, std::addressof(accessors(*row0)),
sizeof(Record), arrayDepth)),
2596 auto const fetchResult = Driver::VisitRequired(
2597 m_handle,
"block fetch", [](Driver::Odbc::Statement& stmt) {
return Driver::Odbc::FetchNextBlock(stmt); });
2598 if (fetchResult == SqlResult::NoData)
2600 detail::ResizeUninitialized(out, base);
2605 if (!Succeeded(fetchResult))
2608 auto const fetched =
static_cast<std::size_t
>(rowsFetched);
2612 if (fetchResult == SqlResult::SuccessWithInfo
2613 && std::ranges::contains(rowStatus | std::views::take(fetched), Driver::Odbc::RowStatusError))
2614 Driver::VisitRequired(m_handle,
"block fetch", [](Driver::Odbc::Statement
const& stmt) {
2615 throw SqlException(Driver::Odbc::DiagnoseFirstError(stmt));
2617 SqlLogger::GetLogger().OnFetchRow();
2618 LIGHTWEIGHT_STATS_ROWS(fetched,
true);
2620 SqlColumnIndex finalizeColumn = 0;
2622 FinalizeRowWiseOutputColumn<std::remove_cvref_t<
decltype(accessors(*row0))>>(std::addressof(accessors(*row0)),
2625 indicators[finalizeColumn - 1],
2627 booleanTrueMayBeMinusOne)),
2630 detail::ResizeUninitialized(out, base + fetched);
2631 if (fetched < arrayDepth)
2636 detail::ResizeUninitialized(out, base);
2641 SqlLogger::GetLogger().OnFetchEnd();
2645 throw std::logic_error(
"SqlStatement: no driver of this build fetches blocks of rows");
2649template <SqlGetColumnNativeType T>
2650inline bool SqlStatement::GetColumn(SqlColumnIndex column, T* result)
const
2652#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2653 if (IsPrefetchActive())
2655 auto const& cursor = PrefetchCursorRef();
2656 auto const row = PrefetchRowInBlock();
2657 RequirePrefetchColumnInRange(cursor, column);
2658 if (cursor.IsCellNull(row, column))
2662 if constexpr (std::default_initializable<T>)
2666 *result = ConvertCell<T>(cursor, row, column);
2670 SqlIndicator indicator {};
2672 Driver::Visit(m_handle, [&](
auto const& held) {
2674 RequireSuccess(Driver::ReadColumn(stmt, column, result, &indicator, *
this));
2676 if (indicator != SqlNullData)
2681 if constexpr (std::default_initializable<T>)
2689 template <
typename T>
2690 concept SqlNullableType = (std::same_as<T, SqlVariant> || IsSpecializationOf<std::optional, T>);
2693 template <
typename T>
2694 struct IsSqlFixedStringSpec: std::false_type
2697 template <std::
size_t N,
typename Char, SqlFixedStringMode Mode>
2698 struct IsSqlFixedStringSpec<SqlFixedString<N, Char, Mode>>: std::true_type
2701 template <
typename T>
2702 concept SqlFixedStringCell = IsSqlFixedStringSpec<std::remove_cvref_t<T>>::value;
2705 template <
typename T>
2706 concept PlainStringCell =
2707 std::same_as<T, std::string> || std::same_as<T, std::u8string> || std::same_as<T, std::u16string>
2708 || std::same_as<T, std::u32string> || std::same_as<T, std::wstring>;
2711 template <
typename T>
2712 struct IsSqlNumericSpec: std::false_type
2715 template <std::
size_t Precision, std::
size_t Scale>
2716 struct IsSqlNumericSpec<SqlNumeric<Precision, Scale>>: std::true_type
2719 template <
typename T>
2720 concept SqlNumericCell = IsSqlNumericSpec<std::remove_cvref_t<T>>::value;
2723 [[nodiscard]]
inline std::u8string_view AsU8View(std::string
const& utf8)
noexcept
2725 return std::u8string_view {
reinterpret_cast<char8_t const*
>(utf8.data()), utf8.size() };
2737 template <SqlFixedStringMode Mode>
2738 inline void TrimFixedStringBytes(std::string& bytes)
noexcept
2740 auto const isTrailingTrimmable = [](
char c)
noexcept {
2743 if constexpr (Mode == SqlFixedStringMode::FIXED_SIZE_RIGHT_TRIMMED)
2744 return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r' || c ==
'\v' || c ==
'\f';
2748 while (!bytes.empty() && isTrailingTrimmable(bytes.back()))
2758 template <
typename Char>
2759 [[nodiscard]]
inline std::basic_string<Char> DecodeUtf8To(std::string
const& utf8)
2761 if constexpr (std::same_as<Char, char>)
2763 else if constexpr (std::same_as<Char, char8_t>)
2764 return std::u8string { AsU8View(utf8) };
2765 else if constexpr (std::same_as<Char, char16_t>)
2766 return ToUtf16(AsU8View(utf8));
2767 else if constexpr (std::same_as<Char, char32_t>)
2768 return ToUtf32<std::u32string>(AsU8View(utf8));
2776 template <
typename T>
2777 concept StringLikeCell = PlainStringCell<T> || SqlStringInterface<T>;
2783 template <
typename T>
2784 concept PrefetchConvertibleScalar =
2785 std::same_as<T, SqlVariant> || std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlGuid>
2786 || std::same_as<T, SqlDateTime::native_type> || std::same_as<T, SqlDynamicNumeric> || StringLikeCell<T>
2787 || std::is_floating_point_v<T> || (std::is_integral_v<T> && !std::same_as<T, char>) || std::is_enum_v<T>;
2789 template <
typename T>
2790 struct PrefetchConvertibleOptional: std::false_type
2793 template <
typename U>
2794 struct PrefetchConvertibleOptional<std::optional<U>>: std::bool_constant<PrefetchConvertibleScalar<U>>
2799 template <
typename T>
2800 concept PrefetchConvertible = PrefetchConvertibleScalar<T> || PrefetchConvertibleOptional<T>::value;
2802#if defined(LIGHTWEIGHT_DRIVER_ODBC)
2804 [[nodiscard]]
constexpr std::string_view BoundTypeName(RowArrayCursor::BoundType boundType)
noexcept
2806 constexpr auto Names = std::array<std::string_view, 7> {
2807 "BIGINT",
"DOUBLE",
"CHAR",
"WCHAR",
"DATE",
"TIMESTAMP",
"GUID",
2809 return Names.at(
static_cast<std::size_t
>(boundType));
2815 template <
typename T>
2816 [[noreturn]]
inline void ThrowRestrictedPrefetchConversion(RowArrayCursor
const& cursor, SqlColumnIndex column)
2818 throw SqlException(SqlErrorInfo {
2819 .nativeErrorCode = 0,
2820 .sqlState =
"07006",
2821 .message = std::format(
"Restricted data type attribute violation: column {} ({}) cannot be read as {}",
2823 BoundTypeName(cursor.ColumnBoundType(column)),
2824 Reflection::TypeNameOf<T>),
2832 template <
typename T>
2833 [[nodiscard]]
inline T ReadTemporalGuidCell(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
2835 using BoundType = RowArrayCursor::BoundType;
2836 auto const boundType = cursor.ColumnBoundType(column);
2837 if constexpr (std::same_as<T, SqlDate>)
2839 if (boundType == BoundType::Date)
2840 return cursor.GetDate(row, column).value_or(SqlDate {});
2841 if (boundType == BoundType::Timestamp)
2843 auto const timestamp = cursor.GetTimestamp(row, column).value_or(SqlDateTime {}).sqlValue;
2844 auto date = SqlDate {};
2845 date.sqlValue.year = timestamp.year;
2846 date.sqlValue.month = timestamp.month;
2847 date.sqlValue.day = timestamp.day;
2851 else if constexpr (std::same_as<T, SqlDateTime>)
2853 if (boundType == BoundType::Timestamp)
2854 return cursor.GetTimestamp(row, column).value_or(SqlDateTime {});
2855 if (boundType == BoundType::Date)
2857 auto const date = cursor.GetDate(row, column).value_or(SqlDate {}).sqlValue;
2858 auto timestamp = SqlDateTime {};
2859 timestamp.sqlValue.year = date.year;
2860 timestamp.sqlValue.month = date.month;
2861 timestamp.sqlValue.day = date.day;
2867 if (boundType == BoundType::Guid)
2868 return cursor.GetGuid(row, column).value_or(SqlGuid {});
2869 if (boundType == BoundType::Char || boundType == BoundType::WChar)
2870 return SqlGuid::TryParse(cursor.GetString(row, column).value_or(std::string {})).value_or(SqlGuid {});
2872 ThrowRestrictedPrefetchConversion<T>(cursor, column);
2878 template <
typename T>
2879 [[nodiscard]]
inline T ReadNumericCell(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
2881 using BoundType = RowArrayCursor::BoundType;
2882 switch (cursor.ColumnBoundType(column))
2884 case BoundType::Double:
2885 return T { cursor.GetF64(row, column).value_or(0.0) };
2886 case BoundType::Int64:
2887 return T {
static_cast<double>(cursor.GetI64(row, column).value_or(0)) };
2889 ThrowRestrictedPrefetchConversion<T>(cursor, column);
2911 template <
typename DeclaredDigitsOf>
2912 [[nodiscard]] SqlDynamicNumeric ReadDynamicNumericCell(RowArrayCursor
const& cursor,
2914 SqlColumnIndex column,
2915 DeclaredDigitsOf
const& declaredDigitsOf)
2917 using BoundType = RowArrayCursor::BoundType;
2918 if (cursor.IsCellNull(row, column))
2919 return SqlDynamicNumeric {};
2920 switch (cursor.ColumnBoundType(column))
2922 case BoundType::Int64:
2924 case BoundType::Double:
2925 throw SqlException(SqlErrorInfo {
2926 .nativeErrorCode = 0,
2927 .sqlState =
"07006",
2928 .message = std::format(
2929 "Restricted data type attribute violation: column {} (DOUBLE) cannot be read as SqlDynamicNumeric "
2930 "from a block-prefetched result set, since the value is the text the driver renders for it. "
2931 "Read it as double or std::string, or disable block prefetch with "
2932 "SqlConnection::SetDefaultPrefetchDepth(1) to read it as SqlDynamicNumeric.",
2936 ThrowRestrictedPrefetchConversion<SqlDynamicNumeric>(cursor, column);
2938 auto text = std::array<char, 24> {};
2939 auto const*
const end =
2940 std::to_chars(text.data(), text.data() + text.size(), cursor.GetI64(row, column).value_or(0)).ptr;
2941 auto const literal = std::string_view { text.data(), end };
2942 if (
auto value = SqlDataBinder<SqlDynamicNumeric>::FromLiteral(literal, declaredDigitsOf(column)); value)
2944 throw SqlException(SqlErrorInfo {
2945 .nativeErrorCode = 0,
2946 .sqlState =
"22003",
2947 .message = std::format(
"Column {} holds {}, which SqlDynamicNumeric cannot represent exactly: it carries more "
2948 "than {} significant digits. Read the column as an integer or std::string instead.",
2951 SqlMaxDynamicNumericPrecision),
2961 [[nodiscard]]
inline std::string RenderCellAsUtf8(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
2963 switch (cursor.ColumnBoundType(column))
2965 case RowArrayCursor::BoundType::Char:
2966 case RowArrayCursor::BoundType::WChar:
2967 return cursor.GetString(row, column).value_or(std::string {});
2968 case RowArrayCursor::BoundType::Int64:
2969 return std::format(
"{}", cursor.GetI64(row, column).value_or(0));
2970 case RowArrayCursor::BoundType::Double:
2971 return std::format(
"{}", cursor.GetF64(row, column).value_or(0.0));
2972 case RowArrayCursor::BoundType::Date:
2973 return std::format(
"{}", cursor.GetDate(row, column).value_or(SqlDate {}));
2974 case RowArrayCursor::BoundType::Timestamp:
2975 return std::format(
"{}", cursor.GetTimestamp(row, column).value_or(SqlDateTime {}));
2976 case RowArrayCursor::BoundType::Guid:
2977 return std::format(
"{}", cursor.GetGuid(row, column).value_or(SqlGuid {}));
2979 return std::string {};
2987 template <
typename T>
2988 [[nodiscard]]
inline T ReadStringLikeCell(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
2990 auto utf8 = RenderCellAsUtf8(cursor, row, column);
2991 if constexpr (SqlFixedStringCell<T>)
2992 TrimFixedStringBytes<T::PostRetrieveOperation>(utf8);
2993 return T { DecodeUtf8To<typename T::value_type>(utf8) };
3008 template <
typename T>
3009 [[nodiscard]]
inline T IntegerCellAs(std::int64_t value, SqlColumnIndex column, SqlDataBinderCallback
const& cb)
3011 if constexpr (SqlColumnMayStage<T>())
3013 if (!cb.ConvertsNarrowIntegerCTypes())
3014 return SqlDataBinder<T>::NarrowStaged(value, column);
3016 if constexpr (std::same_as<T, bool>)
3017 return BoolFromInteger(value, column, cb.BooleanTrueMayBeMinusOne());
3020 if constexpr (std::is_integral_v<T> &&
sizeof(T) <
sizeof(std::int64_t))
3022 if (!std::in_range<T>(value))
3023 ThrowNumericValueOutOfRange(column, value, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
3025 return static_cast<T
>(value);
3035 template <
typename T>
3036 [[nodiscard]]
inline T FloatingPointCellAs(
double value, SqlColumnIndex column)
3038 if constexpr (std::same_as<T, bool>)
3039 return BoolFromFloatingPoint(value, column);
3042 if constexpr (std::is_integral_v<T>)
3047 constexpr auto lowest =
static_cast<double>(std::numeric_limits<T>::min());
3048 constexpr auto beyond =
3049 static_cast<double>(std::uint64_t { 1 } << (std::numeric_limits<T>::digits - 1)) * 2.0;
3050 auto const truncated = std::trunc(value);
3051 if (!(truncated >= lowest && truncated < beyond))
3052 ThrowNumericValueOutOfRange(column, value, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
3054 return static_cast<T
>(value);
3062 template <
typename T>
3063 [[nodiscard]]
inline T ReadArithmeticCell(RowArrayCursor
const& cursor,
3065 SqlColumnIndex column,
3066 SqlDataBinderCallback
const& cb)
3068 using BoundType = RowArrayCursor::BoundType;
3069 switch (cursor.ColumnBoundType(column))
3071 case BoundType::Int64:
3072 return IntegerCellAs<T>(cursor.GetI64(row, column).value_or(0), column, cb);
3073 case BoundType::Double:
3074 return FloatingPointCellAs<T>(cursor.GetF64(row, column).value_or(0.0), column);
3076 ThrowRestrictedPrefetchConversion<T>(cursor, column);
3082template <
typename T>
3083constexpr bool SqlRowIterator<T>::ColumnsArePrefetchConvertible() noexcept
3085 auto convertible =
true;
3086 EnumerateRecordMembers<T>([&convertible]<
size_t I,
typename FieldType>() {
3087 if constexpr (RecordColumnMember<FieldType>)
3089 if constexpr (FieldWithStorage<FieldType>)
3090 convertible = convertible && detail::PrefetchConvertible<typename FieldType::ValueType>;
3092 convertible = convertible && detail::PrefetchConvertible<FieldType>;
3098template <
typename T>
3099void SqlRowIterator<T>::RecordColumnPrefetchTargets(SqlStatement& stmt)
3101 SqlColumnIndex column = 0;
3102 EnumerateRecordMembers<T>([&stmt, &column]<
size_t I,
typename FieldType>() {
3103 if constexpr (RecordColumnMember<FieldType>)
3106 if constexpr (FieldWithStorage<FieldType>)
3107 stmt.RecordPrefetchColumnTarget(column, SqlStatement::PrefetchTargetOf<typename FieldType::ValueType>());
3109 stmt.RecordPrefetchColumnTarget(column, SqlStatement::PrefetchTargetOf<FieldType>());
3114#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3115template <
typename T>
3116inline T SqlStatement::ConvertCell(RowArrayCursor
const& cursor, std::size_t row, SqlColumnIndex column)
const
3121 if constexpr (std::same_as<T, SqlVariant>)
3122 return MakePrefetchVariantCell(cursor, row, column);
3123 else if constexpr (IsSpecializationOf<std::optional, T>)
3125 if (cursor.IsCellNull(row, column))
3126 return std::nullopt;
3127 return T { ConvertCell<typename T::value_type>(cursor, row, column) };
3129 else if constexpr (std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlGuid>)
3130 return detail::ReadTemporalGuidCell<T>(cursor, row, column);
3131 else if constexpr (std::same_as<T, SqlDateTime::native_type>)
3133 return detail::ReadTemporalGuidCell<SqlDateTime>(cursor, row, column).value();
3134 else if constexpr (detail::SqlNumericCell<T>)
3135 return detail::ReadNumericCell<T>(cursor, row, column);
3136 else if constexpr (std::same_as<T, SqlDynamicNumeric>)
3137 return detail::ReadDynamicNumericCell(
3138 cursor, row, column, [
this](SqlColumnIndex index) {
return DeclaredDynamicNumericDigits(index); });
3139 else if constexpr (detail::StringLikeCell<T>)
3140 return detail::ReadStringLikeCell<T>(cursor, row, column);
3141 else if constexpr (std::is_floating_point_v<T> || (std::is_integral_v<T> && !std::same_as<T, char>) || std::is_enum_v<T>)
3142 return detail::ReadArithmeticCell<T>(cursor, row, column, *
this);
3147 throw SqlException(SqlErrorInfo {
3148 .nativeErrorCode = 0,
3149 .sqlState =
"HY000",
3151 std::format(
"Column {} cannot be read as {} from a block-prefetched result set: the type's binder needs the "
3152 "per-row fetch. Bind it with BindOutputColumns() before the first FetchRow(), or disable "
3153 "block prefetch with SqlConnection::SetDefaultPrefetchDepth(1).",
3155 Reflection::TypeNameOf<T>),
3159template <SqlOutputColumnBinder T>
3160inline void SqlStatement::RecordPrefetchOutputColumn(SqlColumnIndex column, T* arg)
3162 auto deferredBind = [
this, column, arg] {
3163 RequireIndicators();
3164 BindOutputColumnNow<T>(column, arg);
3166 if constexpr (detail::PrefetchConvertible<T>)
3168 RecordPrefetchColumn(
3170 PrefetchTargetOf<T>(),
3171 [
this, column, arg] { *arg = ConvertCell<T>(PrefetchCursorRef(), PrefetchRowInBlock(), column); },
3172 std::move(deferredBind));
3178 RecordPrefetchColumn(column, PrefetchTarget::Any, {}, std::move(deferredBind));
3179 MarkPrefetchBindingUnsupported();
3184template <
typename T>
3185constexpr SqlStatement::PrefetchTarget SqlStatement::PrefetchTargetOf() noexcept
3187 if constexpr (IsSpecializationOf<std::optional, T>)
3188 return PrefetchTargetOf<typename T::value_type>();
3189 else if constexpr (std::same_as<T, SqlVariant>)
3190 return PrefetchTarget::Any;
3191 else if constexpr (std::same_as<T, SqlDate> || std::same_as<T, SqlDateTime> || std::same_as<T, SqlDateTime::native_type>)
3192 return PrefetchTarget::Temporal;
3193 else if constexpr (std::same_as<T, SqlGuid>)
3194 return PrefetchTarget::Guid;
3195 else if constexpr (std::same_as<T, SqlDynamicNumeric>)
3196 return PrefetchTarget::Exact;
3197 else if constexpr (detail::StringLikeCell<T>)
3198 return PrefetchTarget::Text;
3200 return PrefetchTarget::Numeric;
3203template <SqlGetColumnNativeType T>
3204inline T SqlStatement::GetColumn(SqlColumnIndex column)
const
3206#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3207 if (IsPrefetchActive())
3209 auto const& cursor = PrefetchCursorRef();
3210 auto const row = PrefetchRowInBlock();
3211 RequirePrefetchColumnInRange(cursor, column);
3212 if constexpr (!detail::SqlNullableType<T>)
3213 if (cursor.IsCellNull(row, column))
3214 throw std::runtime_error {
"Column value is NULL" };
3215 return ConvertCell<T>(cursor, row, column);
3218 auto result = detail::MakeUninitialized<T>();
3219 SqlIndicator indicator {};
3224 ZoneScopedN(
"SqlStatement::ColumnGetData");
3225 Driver::Visit(m_handle, [&](
auto const& held) {
3227 RequireSuccess(Driver::ReadColumn(stmt, column, &result, &indicator, *
this));
3230 if constexpr (!detail::SqlNullableType<T>)
3231 if (indicator == SqlNullData)
3232 throw std::runtime_error {
"Column value is NULL" };
3236template <SqlGetColumnNativeType T>
3237inline std::optional<T> SqlStatement::GetNullableColumn(SqlColumnIndex column)
const
3239#if defined(LIGHTWEIGHT_DRIVER_ODBC)
3240 if (IsPrefetchActive())
3242 auto const& cursor = PrefetchCursorRef();
3243 auto const row = PrefetchRowInBlock();
3244 RequirePrefetchColumnInRange(cursor, column);
3245 if (cursor.IsCellNull(row, column))
3246 return std::nullopt;
3247 return ConvertCell<T>(cursor, row, column);
3250 auto result = detail::MakeUninitialized<T>();
3251 SqlIndicator indicator {};
3253 ZoneScopedN(
"SqlStatement::ColumnGetData");
3254 Driver::Visit(m_handle, [&](
auto const& held) {
3256 RequireSuccess(Driver::ReadColumn(stmt, column, &result, &indicator, *
this));
3259 if (indicator == SqlNullData)
3260 return std::nullopt;
3261 return { std::move(result) };
3264template <SqlGetColumnNativeType T>
3265T SqlStatement::GetColumnOr(SqlColumnIndex column, T&& defaultValue)
const
3267 return GetNullableColumn<T>(column).value_or(std::forward<T>(defaultValue));
3271 std::source_location location)
3273 auto cursor = ExecuteDirect(query.ToSql(), location);
3275 AdoptProjectedFieldNames(query);
3279template <
typename Callable>
3280 requires std::invocable<Callable, SqlMigrationQueryBuilder&>
3281void SqlStatement::MigrateDirect(Callable
const& callable, std::source_location location)
3283 ZoneScopedN(
"SqlStatement::MigrateDirect");
3285 callable(migration);
3286 auto const queries = migration.GetPlan().ToSql();
3287 ZoneValue(queries.size());
3293 auto const isCommentOnlyGuardScript = [](std::string_view script) {
3294 constexpr std::string_view marker =
"-- LIGHTWEIGHT_SQLITE_GUARD:";
3295 if (!script.starts_with(marker))
3297 auto const newline = script.find(
'\n');
3298 if (newline == std::string_view::npos)
3300 auto const body = script.substr(newline + 1);
3301 auto const bodyStart = body.find_first_not_of(
" \t\r\n");
3302 return bodyStart == std::string_view::npos || body.substr(bodyStart).starts_with(
"--");
3305 for (
auto const& query: queries)
3307 if (isCommentOnlyGuardScript(query))
3308 throw std::runtime_error(
3309 std::format(
"SqlStatement::MigrateDirect cannot apply this SQLite schema change directly because it "
3310 "requires a table rebuild (e.g. ALTER COLUMN or a foreign-key change). Apply it through "
3311 "MigrationManager::ApplyPendingMigrations, which runs the rebuild executor.\n Script: {}",
3313 ExecuteDirect(query, location).ConsumePendingResults(location);
3320template <
typename T>
3321 requires(!std::same_as<T, SqlVariant>)
3322inline std::optional<T> SqlStatement::ExecuteDirectScalar(std::string_view
const& query, std::source_location location)
3324 auto cursor = ExecuteDirect(query, location);
3327 if constexpr (!detail::PrefetchConvertible<T>)
3328 MarkPrefetchBindingUnsupported();
3330 RecordPrefetchColumnTarget(1, PrefetchTargetOf<T>());
3333 return std::nullopt;
3334 return GetNullableColumn<T>(1);
3337template <
typename T>
3338 requires(std::same_as<T, SqlVariant>)
3339inline T SqlStatement::ExecuteDirectScalar(std::string_view
const& query, std::source_location location)
3341 auto cursor = ExecuteDirect(query, location);
3342 KeepVariantReadsPerRow();
3346 .sqlState =
"02000",
3347 .message = std::format(
"The scalar query returned no row: {}", query) },
3349 if (
auto result = GetNullableColumn<T>(1); result.has_value())
3354template <
typename T>
3355 requires(!std::same_as<T, SqlVariant>)
3356inline std::optional<T> SqlStatement::ExecuteDirectScalar(
SqlQueryObject auto const& query, std::source_location location)
3358 return ExecuteDirectScalar<T>(query.ToSql(), location);
3361template <
typename T>
3362 requires(std::same_as<T, SqlVariant>)
3363inline T SqlStatement::ExecuteDirectScalar(
SqlQueryObject auto const& query, std::source_location location)
3365 return ExecuteDirectScalar<T>(query.ToSql(), location);
3368inline LIGHTWEIGHT_FORCE_INLINE
void SqlStatement::CloseCursor() noexcept
3377 ForgetHandleOfEndedSession();
3378 ResetPrefetchState();
3379 if (m_handle.IsEmpty())
3381 SqlLogger::GetLogger().OnFetchEnd();
3396 Driver::DiscardResults(m_handle);
3397 SqlLogger::GetLogger().OnFetchEnd();
void RequireSuccess(StatementHandle const &statement, SqlResult result, std::source_location location=std::source_location::current())
Throws unless result indicates success: std::invalid_argument for a soft failure the caller is expect...
SQLULEN ProcessedCount
The count a driver writes back through a parameter-array or row-array attribute pointer (SQL_ATTR_PAR...
A cursor that fetches result rows in bulk (ODBC row-array binding) for fast column reads.
Represents a connection to a SQL database.
LIGHTWEIGHT_API bool IsAlive() const noexcept
Tests if the connection is still active.
Query builder for building SQL migration queries.
API Entry point for building SQL queries.
LIGHTWEIGHT_FORCE_INLINE T GetColumn(std::string_view name) const
Retrieves the value of the named column for the currently selected row.
T GetColumnOr(SqlColumnIndex column, T &&defaultValue) const
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumnsToRecord(Records *... records)
Binds the given records to the prepared statement to store the fetched data to.
constexpr SqlResultCursor(SqlResultCursor &&other) noexcept
Move constructor.
LIGHTWEIGHT_FORCE_INLINE SqlResultCursor(SqlStatement &stmt) noexcept
Constructs a result cursor for the given SQL statement.
LIGHTWEIGHT_FORCE_INLINE T GetColumn(SqlColumnIndex column) const
LIGHTWEIGHT_FORCE_INLINE void FetchAllRowWise(std::vector< Record > &out, std::size_t arrayDepth, ColumnAccessors const &... accessors)
Fast bulk retrieval: materializes this result set into out via native ODBC row-wise array fetch....
constexpr SqlResultCursor & operator=(SqlResultCursor &&other) noexcept
Move assignment operator.
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumn(SqlColumnIndex columnIndex, T *arg)
Binds a single output column at the given index to store fetched data.
LIGHTWEIGHT_FORCE_INLINE void BindOutputColumns(Args *... args)
T GetColumnOr(std::string_view name, T &&defaultValue) const
Retrieves the value of the named column, or defaultValue if it is NULL.
LIGHTWEIGHT_FORCE_INLINE std::optional< T > GetNullableColumn(std::string_view name) const
Retrieves the value of the named column, or std::nullopt if it is NULL.
LIGHTWEIGHT_FORCE_INLINE std::optional< T > GetNullableColumn(SqlColumnIndex column) const
LIGHTWEIGHT_FORCE_INLINE size_t NumColumnsAffected() const
LIGHTWEIGHT_FORCE_INLINE size_t NumRowsAffected() const
LIGHTWEIGHT_FORCE_INLINE bool GetColumn(SqlColumnIndex column, T *result) const
LIGHTWEIGHT_FORCE_INLINE void ConsumePendingResults(std::source_location location=std::source_location::current())
Steps through every result the last execution still has pending and throws for the first one that fai...
LIGHTWEIGHT_FORCE_INLINE bool FetchRow()
LIGHTWEIGHT_FORCE_INLINE std::expected< bool, SqlErrorInfo > TryFetchRow(std::source_location location=std::source_location::current()) noexcept
Attempts to fetch the next row, returning an error info on failure instead of throwing.
LIGHTWEIGHT_API std::expected< SqlResultColumnType, SqlErrorInfo > ColumnSqlType(SqlColumnIndex column) const
The SQL data type the driver reports for a result column.
detail::NarrowTextBinding NarrowTextBindingMode() const noexcept
SQL query result row iterator.
SqlRowIterator(SqlConnection &conn)
Constructs a row iterator over all rows of the record's table, using the given SQL connection.
SqlRowIterator(SqlConnection &conn, QueryCustomizer queryCustomizer)
std::function< void(SqlSelectQueryBuilder &)> QueryCustomizer
iterator end() noexcept
Returns a sentinel iterator representing the end of the result set.
iterator begin()
Returns an iterator to the first row of the result set.
Query builder for building SELECT ... queries.
High level API for (prepared) raw SQL statements.
LIGHTWEIGHT_API void Prepare(std::string_view query) &
Driver::StatementHandle const & DriverHandle() const noexcept
SqlPreparedStatementCaching PreparedStatementCaching() const noexcept
Whether this statement takes part in its connection's prepared-statement cache.
LIGHTWEIGHT_API SqlQueryBuilder QueryAs(std::string_view const &table, std::string_view const &tableAlias) const
Creates a new query builder for the given table with an alias, compatible with the SQL server being c...
LIGHTWEIGHT_API size_t LastInsertId(std::string_view tableName)
Retrieves the last insert ID of the given table.
LIGHTWEIGHT_API SqlConnection & Connection() noexcept
Retrieves the connection associated with this statement.
LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span< SqlRawColumn const > columns, std::size_t rowCount, std::span< Driver::Odbc::RowStatus > paramStatus, Driver::Odbc::ProcessedCount ¶msProcessed)
SqlDriverId DriverId() const noexcept
LIGHTWEIGHT_API void ConsumePendingResults(std::source_location location=std::source_location::current())
Steps through every result the last execution still has pending and throws for the first one that fai...
LIGHTWEIGHT_API RowArrayCursor ExecuteBatchFetch(std::string_view query, std::size_t arrayDepth)
LIGHTWEIGHT_API SqlStatement(SqlStatement &&other) noexcept
Move constructor.
LIGHTWEIGHT_API SqlStatement()
Construct a new SqlStatement object, using a new connection, and connect to the default database.
LIGHTWEIGHT_API bool IsPrepared() const noexcept
Checks whether the statement has been prepared.
LIGHTWEIGHT_API SqlStatement & operator=(SqlStatement &&other) noexcept
Move assignment operator.
LIGHTWEIGHT_API SqlStatement(std::nullopt_t)
Construct a new empty SqlStatement object. No SqlConnection is associated with this statement.
LIGHTWEIGHT_API SqlResultCursor ExecuteDirect(std::string_view const &query, std::source_location location=std::source_location::current())
Executes the given query directly.
LIGHTWEIGHT_API bool IsAlive() const noexcept
Checks whether the statement's connection is alive and the statement handle is valid.
LIGHTWEIGHT_API SqlResultCursor ExecuteBatch(std::span< SqlRawColumn const > columns, size_t rowCount)
decltype(auto) VisitDriver(std::string_view operation, F &&f)
LIGHTWEIGHT_API SqlStatement(SqlConnection &relatedConnection)
Construct a new SqlStatement object, using the given connection.
Requires that T maps onto a column of its record's table.
Whether SqlDataBinder<T> can read T from a result column on at least one enabled driver.
Whether V's binder provides a row-wise batch entry point (BatchRowWiseInputParameter).
Represents a query object that also knows the name of each column it projects.
A value type that can be bound in a native ODBC row-wise parameter array (fixed-width,...
A std::optional column that can be bound zero-copy in a native row-wise batch: the contained type is ...
Whether SqlDataBinder<T> can bind T as an output column on at least one enabled driver.
Represents an SQL query object, that provides a ToSql() method.
A column value type usable on the native row-wise batch path — either a row-bindable fixed value or a...
A column usable on the native row-wise array-FETCH fast path. Intentionally identical to the write-si...
SqlPreparedStatementCaching
Whether a single SqlStatement takes part in its connection's prepared-statement cache.
@ Execute
The execution of a prepared statement (SqlStatement::Execute).
constexpr void EnumerateRecordMembers(Record &record, Callable &&callable)
Invokes callable as callable<I>(member) for each member of record.
constexpr auto SqlNullValue
std::u16string ToUtf16(std::basic_string_view< T > const u32InputString)
LIGHTWEIGHT_API std::wstring ToStdWideString(std::u8string_view u8InputString)
One column pair of a composite foreign key: "this record's column references that one".
The ODBC driver's statement handle struct.
Represents a SQL error as reported by the database driver.
std::int32_t nativeErrorCode
The driver's native error code.
A step a binder plans to run before every fetch into the output column it binds.
Represents a value that can be any of the supported SQL data types.