Lightweight 0.20261105.1
Loading...
Searching...
No Matches
DataMapper.hpp
1// SPDX-License-Identifier: Apache-2.0
2#pragma once
3
4#include "../Async/Backend.hpp"
5#include "../SqlConnection.hpp"
6#include "../SqlDataBinder.hpp"
7#include "../SqlLogger.hpp"
8#include "../SqlRealName.hpp"
9#include "../SqlStatement.hpp"
10#include "../Utils.hpp"
11#include "BelongsTo.hpp"
12#include "CollectDifferences.hpp"
13#include "CompositeForeignKey.hpp"
14#include "Field.hpp"
15#include "HasMany.hpp"
16#include "HasManyThrough.hpp"
17#include "HasOneThrough.hpp"
18#include "QueryBuilders.hpp"
19#include "Record.hpp"
20#include "RelationLoadSource.hpp"
21
22#include <reflection-cpp/reflection.hpp>
23
24#include <cassert>
25#include <chrono>
26#include <concepts>
27#include <cstdint>
28#include <exception>
29#include <expected>
30#include <format>
31#include <functional>
32#include <memory>
33#include <optional>
34#include <ranges>
35#include <span>
36#include <tuple>
37#include <type_traits>
38#include <utility>
39#include <vector>
40
41namespace Lightweight
42{
43
44/// @defgroup DataMapper Data Mapper
45///
46/// @brief The data mapper is a high level API for mapping records to and from the database using high level C++ syntax.
47
48namespace detail
49{
50 /// The first element of a non-empty pack of relation members, i.e. the head of a relation path.
51 ///
52 /// Declared up here because `With<>()` names it, and a non-dependent name inside a template is
53 /// looked up where the template is defined, not where it is instantiated.
54 template <auto First, auto...>
55 inline constexpr auto FirstOf = First;
56
57 // Converts a container of T to a container of std::shared_ptr<T>.
58 template <template <typename> class Allocator, template <typename, typename> class Container, typename Object>
59 auto ToSharedPtrList(Container<Object, Allocator<Object>> container)
60 {
61 using SharedPtrRecord = std::shared_ptr<Object>;
62 auto sharedPtrContainer = Container<SharedPtrRecord, Allocator<SharedPtrRecord>> {};
63 for (auto& object: container)
64 sharedPtrContainer.emplace_back(std::make_shared<Object>(std::move(object)));
65 return sharedPtrContainer;
66 }
67} // namespace detail
68
69/// @brief Main API for mapping records to and from the database using high level C++ syntax.
70///
71/// A DataMapper instances operates on a single SQL connection and provides methods to
72/// create, read, update and delete records in the database.
73///
74/// @see Field, BelongsTo, HasMany, HasManyThrough, HasOneThrough
75/// @ingroup DataMapper
76///
77/// @code
78/// struct Person
79/// {
80/// Field<SqlGuid, PrimaryKey::AutoAssign> id;
81/// Field<SqlAnsiString<30>> name;
82/// Field<SqlAnsiString<40>> email;
83/// };
84///
85/// auto dm = DataMapper {};
86///
87/// // Create a new person record
88/// auto person = Person { .id = SqlGuid::Create(), .name = "John Doe", .email = "johnt@doe.com" };
89///
90/// // Create the record in the database and set the primary key on the record
91/// auto const personId = dm.Create(person);
92///
93/// // Query the person record from the database
94/// auto const queriedPerson = dm.Query<Person>(personId)
95/// .Where(FieldNameOf<&Person::id>, "=", personId)
96/// .First();
97///
98/// if (queriedPerson.has_value())
99/// std::println("Queried Person: {}", DataMapper::Inspect(queriedPerson.value()));
100///
101/// // Update the person record in the database
102/// person.email = "alt@doe.com";
103/// dm.Update(person);
104///
105/// // Delete the person record from the database
106/// dm.Delete(person);
107/// @endcode
110 public:
111 /// Constructs a new data mapper, using the default connection.
112 /// @throws SqlException if connecting to the default connection fails, as the default @c SqlConnection
113 /// constructor does (in a build without ODBC also when no default connect info is set: SQLSTATE @c 08001).
115 _connection {},
116 _stmt { _connection }
117 {
118 }
119
120 /// Constructs a new data mapper, using the given connection.
121 explicit DataMapper(SqlConnection&& connection):
122 _connection { std::move(connection) },
123 _stmt { _connection }
124 {
125 }
126
127 /// Constructs a new data mapper, connected from @p connectInfo (an ODBC connection string or data source, or a
128 /// SQLite database for the native SQLite3 driver); std::nullopt leaves it unconnected.
129 /// @param connectInfo What to connect from.
130 explicit DataMapper(std::optional<SqlConnectInfo> connectInfo):
131 _connection { std::move(connectInfo) },
132 _stmt { _connection }
133 {
134 }
135
136 DataMapper(DataMapper const&) = delete;
137 DataMapper& operator=(DataMapper const&) = delete;
138
139 /// Move constructor.
140 DataMapper(DataMapper&& other) noexcept:
141 _connection(TakeConnection(other)),
142 _stmt(_connection),
143 _relationLoadSource(std::move(other._relationLoadSource)),
144 _timestampClock(std::move(other._timestampClock))
145 {
146 }
147
148 /// Move assignment operator.
149 DataMapper& operator=(DataMapper&& other) noexcept
150 {
151 if (this == &other)
152 return *this;
153
154 // Release our statement while the connection it belongs to is still ours to release it on.
155 _stmt = SqlStatement(std::nullopt);
156 _connection = TakeConnection(other);
157 _stmt = SqlStatement(_connection);
158 _relationLoadSource = std::move(other._relationLoadSource);
159 _timestampClock = std::move(other._timestampClock);
160
161 return *this;
162 }
163
164 ~DataMapper() = default;
165
166 /// Returns the connection reference used by this data mapper.
167 [[nodiscard]] SqlConnection const& Connection() const noexcept
168 {
169 return _connection;
170 }
171
172 /// Returns the mutable connection reference used by this data mapper.
173 [[nodiscard]] SqlConnection& Connection() noexcept
174 {
175 return _connection;
176 }
177
178 /// A source of the current time, used to fill fields marked with a @ref FieldTimestamp.
179 using TimestampClock = std::function<SqlDateTime()>;
180
181 /// @brief Sets the clock that fills the auto-maintained timestamp fields (see @ref FieldTimestamp).
182 ///
183 /// The clock is the client's: the time is taken here, not by the database server. It is read once
184 /// per write operation, so every timestamp written by one Create(), Update(), CreateAll(), ... carries
185 /// the same value. Asynchronous methods read it on the worker thread that runs the operation.
186 ///
187 /// @param clock The clock to use. An empty function restores the default, the system clock in UTC.
189 {
190 _timestampClock = std::move(clock);
191 }
192
193 /// @brief Reads the clock that fills the auto-maintained timestamp fields.
194 ///
195 /// @return The time from the clock set by SetTimestampClock(), or the current UTC system time if none is set.
196 [[nodiscard]] SqlDateTime CurrentTimestamp() const
197 {
198 if (_timestampClock)
199 return _timestampClock();
200 // std::chrono::system_clock is Unix time, i.e. UTC (see SqlDateTime::NowUTC()).
201 return SqlDateTime { std::chrono::system_clock::now() };
202 }
203
204#if defined(BUILD_TESTS)
205
206 [[nodiscard]] SqlStatement& Statement(this auto&& self) noexcept
207 {
208 return self._stmt;
209 }
210
211#endif
212
213 /// Constructs a human readable string representation of the given record.
214 template <typename Record>
215 static std::string Inspect(Record const& record);
216
217 /// Constructs a string list of SQL queries to create the table for the given record type.
218 template <typename Record>
219 std::vector<std::string> CreateTableString(SqlServerType serverType);
220
221 /// Constructs a string list of SQL queries to create the tables for the given record types.
222 template <typename FirstRecord, typename... MoreRecords>
223 std::vector<std::string> CreateTablesString(SqlServerType serverType);
224
225 /// Creates the table for the given record type.
226 template <typename Record>
227 void CreateTable();
228
229 /// Creates the tables for the given record types.
230 template <typename FirstRecord, typename... MoreRecords>
231 void CreateTables();
232
233 /// @brief Creates a new record in the database.
234 ///
235 /// The record is inserted into the database and the primary key is set on this record.
236 ///
237 /// Every auto-maintained timestamp field (see @ref FieldTimestamp) that holds no value is set to the
238 /// current time of the timestamp clock (see SetTimestampClock()) on this record and inserted with it; a
239 /// timestamp the caller set is inserted as given.
240 ///
241 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
242 /// @tparam Record The record type to insert.
243 /// @param record The record to insert. The primary key field is updated in-place after the insert.
244 /// @return The primary key of the newly created record.
245 template <DataMapperOptions QueryOptions = {}, typename Record>
246 RecordPrimaryKeyType<Record> Create(Record& record);
247
248 /// @brief Creates a new record in the database.
249 ///
250 /// @note This is a variation of the Create() method and does not update the record's primary key.
251 ///
252 /// Auto-maintained timestamp fields (see @ref FieldTimestamp) that hold no value are inserted with the
253 /// current time of the timestamp clock, as Create() does, but the record itself is left untouched.
254 ///
255 /// @tparam Record The record type to insert.
256 /// @param record The record to insert. Unlike Create(), the primary key field is NOT updated in-place.
257 /// @return The primary key of the newly created record.
258 template <typename Record>
259 RecordPrimaryKeyType<Record> CreateExplicit(Record const& record);
260
261 /// @brief Batch-inserts a span of records with a single prepared statement.
262 ///
263 /// The INSERT is prepared once and the whole batch is submitted via
264 /// SqlStatement::ExecuteBatch(rows, accessors...), which uses native zero-copy row-wise array
265 /// binding when every inserted column is row-bindable (primitives, date/time/datetime, numeric, or
266 /// std::optional of a fixed non-numeric type) and the driver supports parameter arrays, otherwise a
267 /// prepare-once + per-row execute. This is dramatically faster than calling CreateExplicit() in a
268 /// loop (which re-prepares per row).
269 ///
270 /// @note Like CreateExplicit(), this does not write back primary keys, relations, or modified-state
271 /// onto the records; callers should treat the inserted records as write-only inputs. Auto-increment
272 /// primary keys are not retrieved.
273 ///
274 /// Auto-maintained timestamp fields (see @ref FieldTimestamp) that hold no value are inserted with the
275 /// current time of the timestamp clock, read once for the whole batch. For such a record type the batch
276 /// is copied to carry the timestamps, so the record type must then be copy-constructible.
277 ///
278 /// Accepts any contiguous, sized range of records (e.g. std::vector, std::array, std::span, or a C
279 /// array), so `dm.CreateAll(records)` works without an explicit std::span wrapper. Non-contiguous
280 /// ranges are rejected at compile time via static_assert (no implicit copy is made).
281 ///
282 /// @tparam Records A contiguous range whose element type is the record type to insert.
283 /// @param records The records to insert. An empty range is a no-op.
284 template <std::ranges::range Records>
285 void CreateAll(Records const& records);
286
287 /// @brief Creates a copy of an existing record in the database.
288 ///
289 /// This method is useful for duplicating a database record while assigning a new primary key.
290 /// All fields except primary key(s) are copied from the original record.
291 /// The primary key is automatically generated (auto-incremented or auto-assigned).
292 /// Auto-maintained timestamp fields (see @ref FieldTimestamp) are not copied either: the copy is a new
293 /// row, so they are inserted with the current time of the timestamp clock.
294 ///
295 /// @param originalRecord The record to copy.
296 /// @return The primary key of the newly created record.
297 template <DataMapperOptions QueryOptions = {}, typename Record>
298 [[nodiscard]] RecordPrimaryKeyType<Record> CreateCopyOf(Record const& originalRecord);
299
300 /// @brief Queries a single record (based on primary key) from the database.
301 ///
302 /// The primary key(s) are used to identify the record to load.
303 /// If the record is not found, std::nullopt is returned.
304 ///
305 /// @tparam Record The record type to query and materialize.
306 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior,
307 /// such as whether related records should be auto-loaded. For example,
308 /// set the relation loading option to false to disable auto-loading of
309 /// relations when reading a single record.
310 /// @tparam PrimaryKeyTypes The type(s) of the primary key value(s) used to look up the record.
311 /// @param primaryKeys The primary key value(s) identifying the record to load.
312 /// @return An initialized Record if found; otherwise std::nullopt.
313 ///
314 /// @code
315 /// // Example: disable auto-loading of relations when querying a single record
316 /// auto result = dataMapper
317 /// .QuerySingle<MyRecord, DataMapperOptions{ .loadRelations = false }>(primaryKeyValue);
318 /// if (result)
319 /// {
320 /// // use *result; relations have not been auto-loaded
321 /// }
322 /// @endcode
323 template <typename Record, DataMapperOptions QueryOptions = {}, typename... PrimaryKeyTypes>
324 std::optional<Record> QuerySingle(PrimaryKeyTypes&&... primaryKeys);
325
326 /// Queries multiple records from the database, based on the given query.
327 ///
328 /// @tparam Record The record type to query and materialize.
329 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
330 /// @tparam InputParameters The types of the input parameters to bind before executing the query.
331 /// @param selectQuery The composed SQL select query to execute.
332 /// @param inputParameters Zero or more values to bind as positional parameters in the query.
333 /// @return A vector of records populated from the query results.
334 template <typename Record, DataMapperOptions QueryOptions = {}, typename... InputParameters>
335 std::vector<Record> Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery, InputParameters&&... inputParameters);
336
337 /// Queries multiple records from the database, based on the given query.
338 ///
339 /// @param sqlQueryString The SQL query string to execute.
340 /// @param inputParameters The input parameters for the query to be bound before executing.
341 /// @return A vector of records of the given type that were found via the query.
342 ///
343 /// example:
344 /// @code
345 /// struct Person
346 /// {
347 /// int id;
348 /// std::string name;
349 /// std::string email;
350 /// std::string phone;
351 /// std::string address;
352 /// std::string city;
353 /// std::string country;
354 /// };
355 ///
356 /// void example(DataMapper& dm)
357 /// {
358 /// auto const sqlQueryString = R"(SELECT * FROM "Person" WHERE "city" = ? AND "country" = ?)";
359 /// auto const records = dm.Query<Person>(sqlQueryString, "Berlin", "Germany");
360 /// for (auto const& record: records)
361 /// {
362 /// std::println("Person: {}", DataMapper::Inspect(record));
363 /// }
364 /// }
365 /// @endcode
366 template <typename Record, DataMapperOptions QueryOptions = {}, typename... InputParameters>
367 std::vector<Record> Query(std::string_view sqlQueryString, InputParameters&&... inputParameters);
368
369 /// Queries records from the database, based on the given query and can be used to retrieve only part of the record
370 /// by specifying the ElementMask.
371 ///
372 /// @tparam ElementMask A SqlElements<Idx...> specialization specifying the zero-based field indices to populate.
373 /// @tparam Record The record type to query and materialize.
374 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
375 /// @tparam InputParameters The types of the input parameters to bind before executing the query.
376 /// @param selectQuery The composed SQL select query to execute. Only the columns listed in the SELECT clause
377 /// are bound; the remaining fields of Record are left at their default values.
378 /// @param inputParameters Zero or more values to bind as positional parameters in the query.
379 /// @return A vector of partially populated records; only fields at the specified indices are filled in.
380 ///
381 /// @code
382 ///
383 /// struct Person
384 /// {
385 /// Field<int> id;
386 /// Field<std::string> name; // index 1
387 /// Field<std::string> email;
388 /// Field<std::string> phone;
389 /// Field<std::string> address;
390 /// Field<std::string> city; // index 5
391 /// Field<std::string> country;
392 /// };
393 ///
394 /// void example(DataMapper& dm)
395 /// {
396 /// auto const query = dm.FromTable(RecordTableName<Person>)
397 /// .Select()
398 /// .Fields({ "name"sv, "city"sv })
399 /// .All();
400 /// auto const infos = dm.Query<SqlElements<1, 5>, Person>(query);
401 /// for (auto const& info : infos)
402 /// {
403 /// // only info.name and info.city are populated
404 /// }
405 /// }
406 /// @endcode
407 template <typename ElementMask, typename Record, DataMapperOptions QueryOptions = {}, typename... InputParameters>
408 std::vector<Record> Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery, InputParameters&&... inputParameters);
409
410 /// Queries records of different types from the database, based on the given query.
411 /// User can constructed query that selects columns from the multiple tables
412 /// this function is used to get result of the query
413 ///
414 /// @tparam First The first record type to materialize from each result row.
415 /// @tparam Second The second record type to materialize from each result row.
416 /// @tparam Rest Zero or more additional record types to materialize from each result row.
417 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
418 /// @param selectQuery The composed SQL select query whose column list covers all fields of First, Second, and Rest.
419 /// @return A vector of tuples, each containing one instance of every requested record type per result row.
420 ///
421 /// @code
422 ///
423 /// struct JointA{};
424 /// struct JointB{};
425 /// struct JointC{};
426 ///
427 /// // the following query will construct statement to fetch all elements of JointA and JointC types
428 /// auto dm = DataMapper {};
429 /// auto const query = dm.FromTable(RecordTableName<JoinTestA>)
430 /// .Select()
431 /// .Fields<JointA, JointC>()
432 /// .InnerJoin<&JointB::a_id, &JointA::id>()
433 /// .InnerJoin<&JointC::id, &JointB::c_id>()
434 /// .All();
435 /// auto const records = dm.Query<JointA, JointC>(query);
436 /// for(const auto [elementA, elementC] : records)
437 /// {
438 /// // do something with elementA and elementC
439 /// }
440 /// @endcode
441 template <typename First, typename Second, typename... Rest, DataMapperOptions QueryOptions = {}>
442 requires DataMapperRecord<First> && DataMapperRecord<Second> && DataMapperRecords<Rest...>
443 std::vector<std::tuple<First, Second, Rest...>> Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery);
444
445 /// Queries records of given Record type.
446 ///
447 /// The query builder can be used to further refine the query.
448 /// The query builder will execute the query when a method like All(), First(n), etc. is called.
449 ///
450 /// @tparam Record The record type to query and materialize.
451 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
452 /// @return A query builder for the given Record type.
453 ///
454 /// @code
455 /// auto const records = dm.Query<Person>()
456 /// .Where(FieldNameOf<&Person::is_active>, "=", true)
457 /// .All();
458 /// @endcode
459 template <typename Record, DataMapperOptions QueryOptions = {}>
461 {
462 return SqlAllFieldsQueryBuilder<Record, QueryOptions>(*this, BuildFullyQualifiedFieldList<Record>());
463 }
464
465 /// Asynchronous counterpart of @c Query — returns an async query builder for @p Record.
466 ///
467 /// The builder offers the exact same fluent DSL (`Where`, `OrderBy`, `GroupBy`, joins, …) as the
468 /// synchronous one; its finisher methods (`All()`, `First()`, `First(n)`, `Range()`, `Count()`,
469 /// `Exist()`, `Delete()`) return an @c Async::Task instead of the plain result, to be @c co_await -ed.
470 /// The connection must have been put into async mode via @c SqlConnection::EnableAsync first.
471 ///
472 /// @note The returned builder is a temporary; keep the whole chain in the @c co_await full-expression
473 /// (e.g. `co_await dm.QueryAsync<Person>().Where(...).All();`) so it outlives the awaited task.
474 ///
475 /// @tparam Record The record type to query and materialize.
476 /// @tparam QueryOptions A specialization of DataMapperOptions that controls query behavior.
477 /// @return An asynchronous query builder for the given Record type.
478 ///
479 /// @code
480 /// auto const records = co_await dm.QueryAsync<Person>()
481 /// .Where(FieldNameOf<&Person::is_active>, "=", true)
482 /// .All();
483 /// @endcode
484 template <typename Record, DataMapperOptions QueryOptions = {}>
490
491 /// Returns a SqlQueryBuilder using the default query formatter.
492 ///
493 /// This can be used to build custom queries separately from the DataMapper
494 /// and execute them via the DataMapper's typed Query() overloads that accept a SqlSelectQueryBuilder.
495 ///
496 /// @return A SqlQueryBuilder bound to the connection's query formatter.
498 {
499 return SqlQueryBuilder(_connection.QueryFormatter());
500 }
501
502 /// Updates the record in the database.
503 ///
504 /// Only fields that have been modified since the record was last loaded or saved are written.
505 /// Fields that were not changed are excluded from the UPDATE statement. If no field is
506 /// modified, the call is a no-op and no statement is executed.
507 ///
508 /// When at least one field other than an UpdatedAt timestamp (see @ref FieldTimestamp) is written, every
509 /// UpdatedAt field is set to the current time of the timestamp clock on this record and written with it,
510 /// unless the caller assigned it a value in this change. CreatedAt fields are never touched.
511 ///
512 /// The record type must have a primary key: the WHERE clause is built exclusively from the
513 /// primary-key fields, so a record without one would produce an UPDATE with no WHERE clause
514 /// and rewrite every row of the table. Use the query builder's Update() with an explicit
515 /// WHERE clause when you need to update a table that has no primary key. UpdateAll() carries
516 /// the same requirement.
517 ///
518 /// @tparam Record The record type to update. Must have a primary key.
519 /// @param record The record to update. Only its modified fields are written to the database.
520 template <typename Record>
521 requires HasPrimaryKey<Record>
522 void Update(Record& record);
523
524 /// @brief Batch-updates a span of records with a single prepared statement.
525 ///
526 /// One UPDATE is prepared that writes **all** storable non-primary-key columns of the record,
527 /// matched on the primary key(s) (`UPDATE … SET <all non-PK columns> WHERE <pk> = ?`), and the whole
528 /// batch is submitted via SqlStatement::ExecuteBatch(rows, accessors...) — natively row-wise when
529 /// possible, otherwise prepare-once + per-row execute.
530 ///
531 /// @note Unlike Update(), which writes only the modified fields of a single record, this writes a
532 /// uniform set of columns for every row, because a single prepared statement must bind the same
533 /// columns for the whole batch. Per-row modified-state is therefore not consulted, and is not reset.
534 ///
535 /// Every UpdatedAt timestamp field (see @ref FieldTimestamp) is written with the current time of the
536 /// timestamp clock, read once for the whole batch; the records themselves are left untouched. For such a
537 /// record type the batch is copied to carry the timestamps, so the record type must then be
538 /// copy-constructible.
539 ///
540 /// Accepts any contiguous, sized range of records (see CreateAll), so `dm.UpdateAll(records)` works
541 /// without an explicit std::span wrapper. Non-contiguous ranges are rejected at compile time.
542 ///
543 /// @tparam Records A contiguous range whose element type is the record type to update (with a primary key).
544 /// @param records The records to update. An empty range is a no-op.
545 template <std::ranges::range Records>
546 void UpdateAll(Records const& records);
547
548 /// Deletes the record from the database.
549 ///
550 /// The record is identified by its primary key(s). The row is removed from the backing table.
551 ///
552 /// @tparam Record The record type to delete.
553 /// @param record The record to delete. Its primary key field(s) identify the row to remove.
554 /// @return The number of rows deleted (typically 1 if the record was found, 0 otherwise).
555 template <typename Record>
556 std::size_t Delete(Record const& record);
557
558 /// Constructs an SQL query builder for the given table name.
559 SqlQueryBuilder FromTable(std::string_view tableName)
560 {
561 return _connection.Query(tableName);
562 }
563
564 /// Checks if the record has any modified fields.
565 ///
566 /// @tparam Record The record type to inspect.
567 /// @param record The record to check.
568 /// @return True if at least one field has been modified since the record was last loaded or saved.
569 template <typename Record>
570 bool IsModified(Record const& record) const noexcept;
571
572 /// Enum to set the modified state of a record.
573 enum class ModifiedState : uint8_t
574 {
575 Modified,
576 NotModified
577 };
578
579 /// Sets the modified state of the record after receiving from the database.
580 /// This marks all fields as not modified.
581 ///
582 /// @tparam state The target modified state for all fields (Modified or NotModified).
583 /// @tparam Record The record type whose fields are to be updated.
584 /// @param record The record whose field modification flags are set to @p state.
585 template <ModifiedState state, typename Record>
586 void SetModifiedState(Record& record) noexcept;
587
588 /// Loads all direct relations to this record.
589 ///
590 /// @tparam Record The record type whose relation fields are to be populated.
591 /// @param record The record whose BelongsTo, HasMany, HasOneThrough, and HasManyThrough fields are loaded.
592 template <typename Record>
593 void LoadRelations(Record& record);
594
595 /// Configures the auto loading of relations for the given record.
596 ///
597 /// This means, that no explicit loading of relations is required.
598 /// The relations are automatically loaded when accessed.
599 ///
600 /// @tparam Record The record type to configure auto-loading for.
601 /// @param record The record whose relation fields are set up to load lazily on first access.
602 template <typename Record>
603 void ConfigureRelationAutoLoading(Record& record);
604
605 /// Helper function that allow to execute query directly via data mapper
606 /// and get scalar result without need to create SqlStatement manually
607 ///
608 /// @tparam T The scalar type of the expected result value.
609 /// @param sqlQueryString The SQL query string to execute.
610 /// @return The first column of the first result row cast to T, or std::nullopt if the query returns no rows.
611 template <typename T>
612 [[nodiscard]] std::optional<T> Execute(std::string_view sqlQueryString);
613
614 // --------------------------------------------------------------------------------------------
615 // Asynchronous (C++23 coroutine) API.
616 //
617 // Each method offloads its synchronous counterpart to the connection's async backend — a
618 // worker thread, serialized per connection — and resumes the awaiting coroutine on the app's
619 // resume scheduler. Call SqlConnection::EnableAsync(...) on the underlying connection (or use a
620 // pool that stamps it) before invoking any of these. Definitions live in
621 // Async/DataMapperAsync.hpp (included at the end of this header).
622 //
623 // Methods taking a Record& / Record const& capture the record BY REFERENCE, and dereference it
624 // on a worker thread when the returned Task is awaited. The caller must keep the record alive —
625 // and must not mutate or move it — for the entire duration of the co_await (i.e. until the
626 // awaiting coroutine resumes), not merely until the call returns. Destroying, moving, or mutating
627 // it before the co_await resumes is a use-after-free / data race. The idiomatic, safe form keeps
628 // the whole expression in the co_await: `co_await dm.UpdateAsync(record);`.
629
630 /// Asynchronously inserts @p record, updating its primary key in place. @see Create.
631 template <DataMapperOptions QueryOptions = {}, typename Record>
632 [[nodiscard]] Async::Task<RecordPrimaryKeyType<Record>> CreateAsync(Record& record);
633
634 /// Asynchronously queries a single record by its primary key(s). @see QuerySingle.
635 ///
636 /// This is the asynchronous shorthand for a primary-key lookup; for anything else use the fluent
637 /// builder returned by QueryAsync<Record>() (whose finishers also return an Async::Task). Note there
638 /// is deliberately no QueryAsync(string)/QueryAsync(ComposedQuery) — that is what the builder is for.
639 template <typename Record, DataMapperOptions QueryOptions = {}, typename... PrimaryKeyTypes>
640 [[nodiscard]] Async::Task<std::optional<Record>> QuerySingleAsync(PrimaryKeyTypes... primaryKeys);
641
642 /// Asynchronously updates @p record's modified fields. @see Update.
643 template <typename Record>
644 [[nodiscard]] Async::Task<void> UpdateAsync(Record& record);
645
646 /// Asynchronously deletes @p record. @see Delete.
647 template <typename Record>
648 [[nodiscard]] Async::Task<std::size_t> DeleteAsync(Record const& record);
649
650 /// Asynchronously loads @p record's relations. @see LoadRelations.
651 template <typename Record>
652 [[nodiscard]] Async::Task<void> LoadRelationsAsync(Record& record);
653
654 private:
655 // The fluent query builders drive the batched relation preloading (`With<>()`), which is an
656 // internal entry point rather than part of the mapper's public surface.
657 template <typename BuilderRecord, typename Derived, DataMapperOptions BuilderQueryOptions>
658 friend class SqlCoreDataMapperQueryBuilder;
659
660 friend void detail::AdoptRelationLoadSource(DataMapper& dataMapper,
661 std::shared_ptr<detail::RelationLoadSource> source) noexcept;
662
663 /// The source this mapper's relation auto-loaders borrow from (see @ref detail::RelationLoadSource).
664 ///
665 /// Chosen on first use unless adopted from a pool: the process-wide pool when this mapper is
666 /// connected from the current default connect info, otherwise a source that reconnects from
667 /// this mapper's own connect info, so that relations load from the database the record was
668 /// read from. A mapper on a private in-memory SQLite database, which no other connection reaches,
669 /// gets a source that refuses every load.
670 ///
671 /// @return The source; never null.
672 [[nodiscard]] LIGHTWEIGHT_API std::shared_ptr<detail::RelationLoadSource> const& RelationLoadSourceForLoaders();
673
674 /// Runs @p query and hands each row to @p each as an auto-loading @p Record, reusing one instance.
675 ///
676 /// Backs the streaming @c Each() of the relation loaders. Runs on this mapper's own statement,
677 /// which is safe because the loaders only ever call it on a mapper borrowed for that one load.
678 ///
679 /// @param query The query to run.
680 /// @param each Called once per row.
681 /// @param inputParameters Bound to the query's parameters.
682 template <typename Record, typename QueryText, typename Callable, typename... InputParameters>
683 void StreamRecords(QueryText const& query, Callable const& each, InputParameters const&... inputParameters);
684
685 /// Runs one relation load on a mapper borrowed from @p source, reporting every failure as a
686 /// @ref RelationError rather than an exception: an unusable source as whatever @c Borrow() reports,
687 /// a failing query as @ref RelationError::QueryFailed (its diagnostic goes to @c SqlLogger).
688 ///
689 /// @param source Where the load borrows its mapper from.
690 /// @param load Runs the query on the borrowed mapper and returns its result.
691 /// @return What @p load returned, or why the load did not happen.
692 template <typename Load>
693 static auto RunRelationLoad(detail::RelationLoadSource& source, Load const& load)
694 -> RelationResult<std::invoke_result_t<Load const&, DataMapper&>>;
695
696 /// @ref RunRelationLoad for the streaming @c Each() loaders. An exception thrown by the caller's
697 /// @p each callback is not a failed load: it propagates unchanged instead of being reported.
698 ///
699 /// @param source Where the load borrows its mapper from.
700 /// @param each The caller's per-record callback.
701 /// @param stream Runs the query on the borrowed mapper, calling the callback it is given per row.
702 /// @return Nothing, or why the load did not happen.
703 template <typename Each, typename Stream>
704 static RelationResult<void> RunRelationStream(detail::RelationLoadSource& source,
705 Each const& each,
706 Stream const& stream);
707
708 /// @return @p record, or @ref RelationError::NotFound for a null one.
709 template <typename Record>
710 static RelationResult<std::shared_ptr<Record>> NotFoundIfNull(std::shared_ptr<Record> record)
711 {
712 if (!record)
713 return std::unexpected { RelationError::NotFound };
714 return record;
715 }
716
717 /// Builds the comma-separated, fully-qualified (`"Table"."Column"`) field list for @p Record.
718 ///
719 /// Shared by @c Query and @c QueryAsync so the SELECT projection is produced in exactly one place.
720 ///
721 /// @tparam Record The record type whose members are enumerated.
722 /// @return The field list usable as the projection of a SELECT statement.
723 template <typename Record>
724 [[nodiscard]] static std::string BuildFullyQualifiedFieldList()
725 {
726 std::string fields;
727 EnumerateRecordMembers<Record>([&fields]<size_t I, typename FieldType>() {
728 // Relations (HasMany, HasManyThrough, HasOneThrough, ...) have no column of their own.
729 if constexpr (RecordColumnMember<FieldType>)
730 {
731 if (!fields.empty())
732 fields += ", ";
733 SqlQueryFormatter::AppendQuotedIdentifier(fields, RecordTableName<Record>);
734 fields += '.';
735 SqlQueryFormatter::AppendQuotedIdentifier(fields, FieldNameAt<I, Record>);
736 }
737 });
738 return fields;
739 }
740
741 /// @brief Queries a single record from the database based on the given query.
742 ///
743 /// @param selectQuery The SQL select query to execute.
744 /// @param args The input parameters for the query.
745 ///
746 /// @return The record if found, otherwise std::nullopt.
747 template <typename Record, typename... Args>
748 std::optional<Record> QuerySingle(SqlSelectQueryBuilder selectQuery, Args&&... args);
749
750 template <typename Record, typename ValueType>
751 void SetId(Record& record, ValueType&& id);
752
753 template <typename Record, size_t InitialOffset = 1>
754 Record& BindOutputColumns(Record& record, SqlResultCursor& cursor);
755
756 template <typename ElementMask, typename Record, size_t InitialOffset = 1>
757 Record& BindOutputColumns(Record& record, SqlResultCursor& cursor);
758
759 template <typename FieldType>
760 std::optional<typename FieldType::ReferencedRecord> LoadBelongsTo(FieldType::ValueType value);
761
762 /// Queries the record referenced by a composite foreign key, without touching the relation itself.
763 ///
764 /// Shared by the eager path (`LoadCompositeForeignKey`) and the lazy loader installed by
765 /// `ConfigureRelationAutoLoading`, so both resolve a missing target row and wrap a found one the
766 /// same way instead of maintaining two copies of that logic.
767 ///
768 /// Takes the already-permuted key values rather than the owning record itself: the lazy loader
769 /// must evaluate `FieldType::OrderedValuesOf()` while the record is known to be live (at
770 /// `ConfigureRelationAutoLoading` time) and capture the resulting values by value, not a pointer to
771 /// the record - a `std::optional<Record>` returned by value from a query method is not guaranteed to
772 /// stay at the same address (NRVO is not mandated by the standard, and does not reliably apply to
773 /// every such function in practice), so a captured pointer can dangle by the time the loader runs.
774 ///
775 /// @param keys The foreign key values, in the referenced record's member order.
776 /// @return The referenced record, or `nullptr` if no matching row exists.
777 template <typename FieldType>
778 std::shared_ptr<typename FieldType::ReferencedRecord> LoadCompositeForeignKeyRecord(
779 FieldType::OrderedValueType const& keys);
780
781 /// Eagerly loads the record referenced by a composite foreign key.
782 ///
783 /// @param record The record holding the foreign key.
784 /// @param field The relation to fill.
785 template <typename Record, typename FieldType>
786 void LoadCompositeForeignKey(Record const& record, FieldType& field);
787
788 template <typename Record, typename OtherRecord, auto InverseSelector>
789 void LoadHasMany(Record& record, HasMany<OtherRecord, InverseSelector>& field);
790
791 /// @brief Eagerly resolves one relation for a whole batch of records, in a bounded number of queries.
792 ///
793 /// This is the engine behind `Query<Record>().With<&Record::relation>()`. Where the lazy loaders
794 /// installed by `ConfigureRelationAutoLoading()` issue one query per record touched - the N+1 - this
795 /// issues one query per chunk of the batch (see `SqlQueryFormatter::MaxInPredicateValues()`) and
796 /// distributes the resulting rows into the records in memory.
797 ///
798 /// The batch is addressed by pointer rather than as a contiguous range: past the first level of
799 /// a relation path the targets are not contiguous - every owner holds its own copy of a
800 /// `BelongsTo` target, and a `HasMany` list holds `shared_ptr`s - so only their addresses can be
801 /// gathered. `SqlCoreDataMapperQueryBuilder::RunRelationPreloaders()` adapts a freshly
802 /// materialized result set onto this.
803 ///
804 /// @tparam Record The record type owning the relation.
805 /// @tparam FieldIndex Member index, within @p Record, of the relation to load.
806 /// @param records The batch to resolve the relation for.
807 template <typename Record, size_t FieldIndex>
808 void PreloadRelation(std::span<Record* const> records);
809
810 /// Batch counterpart of `LoadBelongsTo`: one query per chunk of distinct foreign keys.
811 /// @see PreloadRelation
812 template <typename Record, size_t FieldIndex>
813 void PreloadBelongsTo(std::span<Record* const> records);
814
815 /// Batch counterpart of `LoadHasMany`: one query per chunk of owner primary keys, then the rows
816 /// are grouped by the inverse foreign key and handed to each owner.
817 /// @see PreloadRelation
818 template <typename Record, size_t FieldIndex>
819 void PreloadHasMany(std::span<Record* const> records);
820
821 /// @brief Eagerly resolves a *path* of relations, one bounded set of queries per level.
822 ///
823 /// Backs `Query<Record>().With<&Track::album, &Album::artist>()`: the first relation is resolved
824 /// for the whole batch, the loaded targets are then gathered and the next relation resolved for
825 /// all of them at once, and so on. Every level costs a constant number of queries, so a two-level
826 /// path over any number of records is three queries in total.
827 ///
828 /// @tparam Record The record type owning the first relation of the path.
829 /// @tparam FieldIndex Member index, within @p Record, of the first relation.
830 /// @tparam RestOfPath The remaining relations, each a member of the preceding target type.
831 /// @param records The batch to resolve the path for.
832 template <typename Record, size_t FieldIndex, auto... RestOfPath>
833 void PreloadRelationPath(std::span<Record* const> records);
834
835 /// @brief Eagerly resolves *every* supported relation reachable within @p Depth levels.
836 ///
837 /// Backs `DataMapperOptions { .eagerLoadDepth = N }`. Each level costs a bounded number of
838 /// queries per relation, never one per record. `HasOneThrough`, `HasManyThrough` and
839 /// `CompositeForeignKey` are skipped and keep loading on demand.
840 ///
841 /// @tparam Record The record type whose relations are resolved.
842 /// @tparam Depth Remaining levels to descend; `0` stops the recursion, which is what keeps a
843 /// cyclic relation graph (a self-referencing record, or A -> B -> A) from
844 /// instantiating forever.
845 /// @param records The batch to resolve the relations for.
846 template <typename Record, size_t Depth>
847 void PreloadAllRelations(std::span<Record* const> records);
848
849 /// Appends the addresses of the records loaded into relation @p FieldIndex of every record in
850 /// @p records, so the next level of a path can be resolved for all of them at once.
851 ///
852 /// @tparam Record The record type owning the relation.
853 /// @tparam FieldIndex Member index, within @p Record, of the relation to walk into.
854 /// @param records The batch to collect from.
855 /// @return The loaded targets; records whose relation is unloaded or NULL contribute nothing.
856 template <typename Record, size_t FieldIndex>
857 [[nodiscard]] static auto CollectRelationTargets(std::span<Record* const> records);
858
859 template <typename ReferencedRecord, typename ThroughSpec, typename Record, auto OwnerSelector, auto ThroughSelector>
860 void LoadHasOneThrough(Record& record,
861 HasOneThrough<ReferencedRecord, ThroughSpec, OwnerSelector, ThroughSelector>& field);
862
863 template <typename ReferencedRecord, typename ThroughSpec, typename Record, auto OwnerSelector, auto ReferencedSelector>
864 void LoadHasManyThrough(Record& record,
865 HasManyThrough<ReferencedRecord, ThroughSpec, OwnerSelector, ReferencedSelector>& field);
866
867 template <typename Record, typename OtherRecord, auto InverseSelector, typename Callable>
868 void CallOnHasMany(Record& record, Callable const& callback);
869
870 template <typename OwnerRecord, typename OtherRecord, auto InverseSelector>
871 SqlSelectQueryBuilder BuildHasManySelectQuery();
872
873 /// @brief Builds a `SELECT <all storage columns> FROM <table of @p Record>`, without any predicate.
874 ///
875 /// The starting point for the batched relation queries, which add their own `WHERE ... IN (...)`.
876 ///
877 /// @tparam Record The record type whose table and columns are selected.
878 /// @return The select query builder, ready for further clauses.
879 template <typename Record>
880 SqlSelectQueryBuilder BuildRecordSelectQuery();
881
882 template <typename ReferencedRecord, typename ThroughRecord, typename Record, auto OwnerSelector, auto ThroughSelector>
883 SqlSelectQueryBuilder BuildHasOneThroughSelectQuery();
884
885 template <typename ReferencedRecord,
886 typename ThroughRecord,
887 typename Record,
888 auto OwnerSelector,
889 auto ReferencedSelector>
890 SqlSelectQueryBuilder BuildHasManyThroughSelectQuery();
891
892 template <typename ReferencedRecord,
893 typename ThroughRecord,
894 typename Record,
895 auto OwnerSelector,
896 auto ReferencedSelector,
897 typename Callable>
898 void CallOnHasManyThrough(Record& record, Callable const& callback);
899
900 template <typename ReferencedRecord,
901 typename ThroughRecord,
902 typename Record,
903 auto OwnerSelector,
904 auto ReferencedSelector,
905 typename PKValue,
906 typename Callable>
907 void CallOnHasManyThroughByPK(PKValue const& pkValue, Callable const& callback);
908
909 template <typename ReferencedRecord,
910 typename ThroughRecord,
911 typename Record,
912 auto OwnerSelector,
913 auto ThroughSelector,
914 typename PKValue>
915 std::shared_ptr<ReferencedRecord> LoadHasOneThroughByPK(PKValue const& pkValue);
916
917 enum class PrimaryKeySource : std::uint8_t
918 {
919 Record,
920 Override,
921 };
922
923 /// Which auto-maintained timestamp fields (see @ref FieldTimestamp) a write sets to the current time.
924 enum class TimestampFill : std::uint8_t
925 {
926 /// No field: the record's own values are written (e.g. Create() already stamped the record).
927 None,
928 /// Every timestamp field that holds no value (inserts).
929 Unset,
930 /// Every timestamp field, whatever it holds (CreateCopyOf(): the copy is a new row).
931 All,
932 /// Every UpdatedAt field, whatever it holds (UpdateAll()).
933 UpdatedAt,
934 };
935
936 /// Whether a write that fills timestamps as @p Fill says writes the current time into @p field.
937 template <TimestampFill Fill, typename FieldType>
938 [[nodiscard]] static constexpr bool FillsTimestamp(FieldType const& field) noexcept;
939
940 /// Sets the timestamp fields of @p record that @p Fill selects to @p now.
941 template <TimestampFill Fill, typename Record>
942 static void StampTimestamps(Record& record, SqlDateTime const& now);
943
944 /// Sets the UpdatedAt fields of @p record to the current time, for an update, if the update writes anything else.
945 template <typename Record>
946 void StampTimestampsForUpdate(Record& record) const;
947
948 /// Returns a copy of @p records whose timestamp fields selected by @p Fill hold the current time.
949 template <TimestampFill Fill, typename Record>
950 [[nodiscard]] std::vector<Record> CopyWithTimestamps(std::span<Record const> records) const;
951
952 /// Batch-inserts @p records as given (the body of CreateAll()).
953 template <typename Record>
954 void InsertBatch(std::span<Record const> records);
955
956 /// Batch-updates @p records as given (the body of UpdateAll()).
957 template <typename Record>
958 void UpdateBatch(std::span<Record const> records);
959
960 template <typename Record>
961 std::optional<RecordPrimaryKeyType<Record>> GenerateAutoAssignPrimaryKey(Record const& record);
962
963 template <PrimaryKeySource UsePkOverride, TimestampFill Fill, typename Record>
964 RecordPrimaryKeyType<Record> CreateInternal(
965 Record const& record,
966 std::optional<std::conditional_t<std::is_void_v<RecordPrimaryKeyType<Record>>, int, RecordPrimaryKeyType<Record>>>
967 pkOverride = std::nullopt);
968
969 /// Moves @p other's connection out, after releasing @p other's statement: its handle lives on that
970 /// connection, and once the connection has moved, the moved-from statement can no longer free it.
971 static SqlConnection TakeConnection(DataMapper& other) noexcept
972 {
973 other._stmt = SqlStatement(std::nullopt);
974 return std::move(other._connection);
975 }
976
977 SqlConnection _connection;
978 SqlStatement _stmt;
979 std::shared_ptr<detail::RelationLoadSource> _relationLoadSource;
980 TimestampClock _timestampClock;
981};
982
983inline void detail::AdoptRelationLoadSource(DataMapper& dataMapper, std::shared_ptr<RelationLoadSource> source) noexcept
984{
985 dataMapper._relationLoadSource = std::move(source);
986}
987
988// ------------------------------------------------------------------------------------------------
989
990namespace detail
991{
992 /// Whether @p T is a column type whose buffer may have to grow while fetching (e.g. a string long
993 /// enough to be truncated into the initially bound buffer): every string and binary type whose
994 /// binder binds a growable buffer, and a @c std::optional of one.
995 ///
996 /// @tparam T The *value* type of the column, i.e. `Field<...>::ValueType`, never the `Field<...>`
997 /// wrapper itself.
998 template <typename T>
999 inline constexpr bool IsGrowableColumnType =
1000 detail::OneOf<T, std::string, std::wstring, std::u8string, std::u16string, std::u32string, SqlText, SqlBinary>
1001 || IsSqlDynamicString<T> || IsSqlDynamicBinary<T>;
1002
1003 template <typename T>
1004 inline constexpr bool IsGrowableColumnType<std::optional<T>> = IsGrowableColumnType<T>;
1005
1006 /// Whether a single output column of value type @p T can safely be bound up front.
1007 ///
1008 /// Takes the column's *value* type, not a `Field<...>` wrapper: the sole caller projects a single
1009 /// field and only has `ReferencedFieldTypeOf<Field>` (the ValueType) to hand. This previously
1010 /// took the wrapper and gated its whole body on `if constexpr (IsField<FieldType>)`, which a
1011 /// ValueType never satisfies - so it silently answered "safe to bind" for every type, including
1012 /// the growable ones it exists to exclude.
1013 ///
1014 /// @tparam T The column's value type.
1015 /// @param readsBoundColumnsAgain The connection's SqlConnection::ReadsBoundColumnsAgain().
1016 /// @return `true` if the column may be bound with `BindOutputColumn`, `false` if it has to be read
1017 /// per row with `GetColumn` instead.
1018 template <typename T>
1019 constexpr bool CanSafelyBindOutputColumn(bool readsBoundColumnsAgain) noexcept
1020 {
1021 // A growable column's value can be longer than its bound buffer, and the binder then reads it again
1022 // with SQLGetData. A driver without SQL_GD_BOUND (MS SQL Server) refuses that, so such a value would
1023 // fail the fetch, and a buffer of the column's declared length would be kept per record: read these
1024 // columns per row instead, which sizes each value to itself.
1025 return readsBoundColumnsAgain || !IsGrowableColumnType<T>;
1026 }
1027
1028 /// Whether every output column of @p Record can safely be bound up front.
1029 ///
1030 /// The record-wide counterpart of @ref CanSafelyBindOutputColumn: one growable member is enough to
1031 /// force the whole record onto the per-row `GetColumn` path.
1032 ///
1033 /// @tparam Record The record being fetched.
1034 /// @param readsBoundColumnsAgain The connection's SqlConnection::ReadsBoundColumnsAgain().
1035 /// @return `true` if the columns may be bound with `BindOutputColumns`.
1036 template <DataMapperRecord Record>
1037 constexpr bool CanSafelyBindOutputColumns(bool readsBoundColumnsAgain) noexcept
1038 {
1039 if (readsBoundColumnsAgain)
1040 return true;
1041
1042 bool result = true;
1043 EnumerateRecordMembers<Record>([&result]<size_t I, typename Field>() {
1044 if constexpr (IsField<Field>)
1045 if constexpr (IsGrowableColumnType<typename Field::ValueType>)
1046 // Known types that MAY require growing due to truncation.
1047 result = false;
1048 });
1049 return result;
1050 }
1051
1052 template <typename Record>
1053 void BindAllOutputColumnsWithOffset(SqlResultCursor& reader, Record& record, SqlColumnIndex startOffset)
1054 {
1055 EnumerateRecordMembers(record, [reader = &reader, i = startOffset]<size_t I, typename Field>(Field& field) mutable {
1056 if constexpr (IsField<Field>)
1057 {
1058 reader->BindOutputColumn(i++, &field.MutableValue());
1059 }
1060 else if constexpr (IsBelongsTo<Field>)
1061 {
1062 reader->BindOutputColumn(i++, &field.MutableValue());
1063 }
1064 else if constexpr (SqlOutputColumnBinder<Field>)
1065 {
1066 reader->BindOutputColumn(i++, &field);
1067 }
1068 });
1069 }
1070
1071 template <typename Record>
1072 void BindAllOutputColumns(SqlResultCursor& reader, Record& record)
1073 {
1074 BindAllOutputColumnsWithOffset(reader, record, 1);
1075 }
1076
1077 /// @brief Requested rows per SQLFetchScroll round-trip for the native row-wise fetch fast path. The
1078 /// statement clamps this to a memory budget, so it is an upper bound, not a guarantee.
1079 inline constexpr std::size_t kDefaultRowArrayFetchDepth = 1024;
1080
1081 /// @brief Mutable-reference output accessor for member @p I that is a Field/BelongsTo: yields the
1082 /// field's mutable value so the row-wise fetch path binds the result column in place. The read-side
1083 /// counterpart of @ref FieldValueAccessor.
1084 template <std::size_t I>
1085 struct MutableFieldValueAccessor
1086 {
1087 template <typename Record>
1088 decltype(auto) operator()(Record& record) const
1089 {
1090 return GetRecordMemberAt<I>(record).MutableValue();
1091 }
1092 };
1093
1094 /// @brief The mutable value type bound for member @p FieldType on the row-wise fetch path (the type
1095 /// the result column materializes into).
1096 template <typename FieldType>
1097 using RowWiseColumnValueType = std::remove_cvref_t<decltype(std::declval<FieldType&>().MutableValue())>;
1098
1099 /// @return Whether @p FieldType maps to a result column on the bound-output path (Field, BelongsTo, or
1100 /// a directly-bindable member) — mirrors the classification in @ref BindAllOutputColumnsWithOffset.
1101 template <typename FieldType>
1102 constexpr bool RowWiseIsColumn()
1103 {
1104 return IsField<FieldType> || IsBelongsTo<FieldType> || SqlOutputColumnBinder<FieldType>;
1105 }
1106
1107 /// @return Whether @p FieldType is acceptable on the row-wise fetch path: either it is not a result
1108 /// column (a relation member, which is not bound) or it is a column whose value type is
1109 /// @ref SqlRowWiseFetchableColumn. Directly-bindable non-Field members are conservatively rejected
1110 /// (their value would need a separate accessor shape) so such records fall back to the per-row path.
1111 template <typename FieldType>
1112 constexpr bool RowWiseColumnAcceptable()
1113 {
1114 if constexpr (IsField<FieldType> || IsBelongsTo<FieldType>)
1115 return SqlRowWiseFetchableColumn<RowWiseColumnValueType<FieldType>>;
1116 else if constexpr (SqlOutputColumnBinder<FieldType>)
1117 return false;
1118 else
1119 return true; // relation / non-column member: not bound, imposes no constraint
1120 }
1121
1122 template <typename Record, std::size_t... Is>
1123 constexpr bool CanRowWiseFetchRecordImpl(std::index_sequence<Is...> /*indices*/)
1124 {
1125 // The row-strided indicator slots are addressed at i * sizeof(Record); they must stay SqlIndicator
1126 // aligned, so sizeof(Record) must be a multiple of alignof(SqlIndicator) (mirrors the write-side
1127 // indicatorAlignmentSatisfied precondition).
1128 return (sizeof(Record) % alignof(SqlIndicator) == 0)
1129 && (RowWiseColumnAcceptable<RecordMemberTypeOf<Is, Record>>() && ...)
1130 && (RowWiseIsColumn<RecordMemberTypeOf<Is, Record>>() || ...);
1131 }
1132
1133 /// @brief Whether @p Record can be materialized via the native row-wise array-fetch fast path: every
1134 /// result column is a Field/BelongsTo of a @ref SqlRowWiseFetchableColumn type, there is at least one
1135 /// column, and the record size keeps the row-strided indicators aligned. Records that fail this fall
1136 /// back to the per-row @c SQLFetch path, with identical results.
1137 template <typename Record>
1138 constexpr bool CanRowWiseFetchRecord()
1139 {
1140 return CanRowWiseFetchRecordImpl<Record>(std::make_index_sequence<RecordMemberCount<Record>> {});
1141 }
1142
1143 /// Returns a one-element accessor tuple for member @p I when it is a bound result column, else an empty
1144 /// tuple — flattened via tuple_cat so the accessor pack matches the bound column set and order exactly.
1145 template <std::size_t I, typename Record>
1146 auto MakeOutputColumnAccessor()
1147 {
1148 using FieldType = RecordMemberTypeOf<I, Record>;
1149 if constexpr (IsField<FieldType> || IsBelongsTo<FieldType>)
1150 return std::tuple<MutableFieldValueAccessor<I>> {};
1151 else
1152 return std::tuple<> {};
1153 }
1154
1155 /// @brief Materializes the whole result set into @p records via @ref SqlStatement::FetchAllRowWise,
1156 /// building one mutable value accessor per bound result column (same set and order as
1157 /// @ref BindAllOutputColumnsWithOffset). Precondition: @ref CanRowWiseFetchRecord<Record>().
1158 template <typename Record>
1159 void ReadAllRowWise(SqlResultCursor& reader, std::vector<Record>* records)
1160 {
1161 [&]<std::size_t... Is>(std::index_sequence<Is...>) {
1162 std::apply(
1163 [&](auto const&... accessors) {
1164 reader.FetchAllRowWise(*records, kDefaultRowArrayFetchDepth, accessors...);
1165 },
1166 std::tuple_cat(MakeOutputColumnAccessor<Is, Record>()...));
1167 }(std::make_index_sequence<RecordMemberCount<Record>> {});
1168 }
1169
1170 /// @return Whether @p FieldType is a result column whose value is a char fixed-capacity string (or a
1171 /// @c std::optional of one). Such columns are array-bound narrow (SQL_C_CHAR), which only round-trips
1172 /// byte-exact where @ref SqlConnection::RoundTripsNarrowTextByteExact holds.
1173 template <typename FieldType>
1174 constexpr bool ColumnIsNarrowFixedString()
1175 {
1176 if constexpr (IsField<FieldType> || IsBelongsTo<FieldType>)
1177 {
1178 using V = RowWiseColumnValueType<FieldType>;
1179 if constexpr (SqlIsStdOptional<V>)
1180 return IsSqlFixedString<typename V::value_type>;
1181 else
1182 return IsSqlFixedString<V>;
1183 }
1184 else
1185 return false;
1186 }
1187
1188 template <typename Record, std::size_t... Is>
1189 constexpr bool RecordHasNarrowFixedStringColumnImpl(std::index_sequence<Is...> /*indices*/)
1190 {
1191 return (ColumnIsNarrowFixedString<RecordMemberTypeOf<Is, Record>>() || ...);
1192 }
1193
1194 /// @brief Whether @p Record has any char fixed-capacity-string result column. Such records take the
1195 /// row-wise fetch fast path only on backends that round-trip narrow text byte-exact; elsewhere they
1196 /// fall back to the per-row (wide) path. See @ref SqlConnection::RoundTripsNarrowTextByteExact.
1197 template <typename Record>
1198 constexpr bool RecordHasNarrowFixedStringColumn()
1199 {
1200 return RecordHasNarrowFixedStringColumnImpl<Record>(std::make_index_sequence<RecordMemberCount<Record>> {});
1201 }
1202
1203 /// @brief Whether narrow text array-bound as @c SQL_C_CHAR round-trips byte-exact on @p serverType with
1204 /// @p narrowTextBinding (see @ref SqlConnection::RoundTripsNarrowTextByteExact).
1205 inline bool NarrowTextBindsInPlace(SqlServerType serverType, NarrowTextBinding narrowTextBinding) noexcept
1206 {
1207 return SqlConnection::RoundTripsNarrowTextByteExact(serverType) && narrowTextBinding == NarrowTextBinding::Narrow;
1208 }
1209
1210 /// @return Whether @p FieldType is a result column whose binder stages its value on a driver that does
1211 /// not convert its C type over the full range (see @ref SqlColumnMayStage).
1212 template <typename FieldType>
1213 constexpr bool ColumnMayStage()
1214 {
1215 if constexpr (IsField<FieldType> || IsBelongsTo<FieldType>)
1216 return SqlColumnMayStage<RowWiseColumnValueType<FieldType>>();
1217 else
1218 return false;
1219 }
1220
1221 /// @brief Whether any of @p Record's members @p Is is a column whose binder may stage (see ColumnMayStage()).
1222 template <typename Record, std::size_t... Is>
1223 constexpr bool RecordHasStagedColumnImpl(std::index_sequence<Is...> /*indices*/)
1224 {
1225 return (ColumnMayStage<RecordMemberTypeOf<Is, Record>>() || ...);
1226 }
1227
1228 /// @brief Whether @p Record has a result column whose binder stages its value on some drivers. The
1229 /// row-wise fetch binds such a column in place, so on such a driver the record is read per row.
1230 template <typename Record>
1231 constexpr bool RecordHasStagedColumn()
1232 {
1233 return RecordHasStagedColumnImpl<Record>(std::make_index_sequence<RecordMemberCount<Record>> {});
1234 }
1235
1236 /// @brief Whether @p Record may use the row-wise fetch fast path on @p driver and @p serverType: it is row-wise
1237 /// fetchable, the driver supports row-array fetch (the native SQLite3 driver has none), and any narrow fixed-string
1238 /// column round-trips byte-exact there. Single runtime gate composed from connection capabilities + the compile-time
1239 /// record shape, so business logic never branches on the server type directly.
1240 template <typename Record>
1241 bool CanRowWiseFetchOn(SqlDriverId driver, SqlServerType serverType, NarrowTextBinding narrowTextBinding)
1242 {
1243 if constexpr (!CanRowWiseFetchRecord<Record>())
1244 return false;
1245 else
1246 return SqlConnection::SupportsNativeRowArrayFetch(driver, serverType)
1247 && (!RecordHasNarrowFixedStringColumn<Record>() || NarrowTextBindsInPlace(serverType, narrowTextBinding))
1248 && (!RecordHasStagedColumn<Record>() || ConvertsNarrowIntegerCTypes(serverType));
1249 }
1250
1251 // --- Two-record tuple (JOIN) fast path ----------------------------------------------------------
1252
1253 /// @brief Mutable-reference output accessor for member @p I of the @p TupleIndex-th sub-record of a
1254 /// @c std::tuple result row; yields that field's mutable value so a JOIN result binds in place.
1255 template <std::size_t TupleIndex, std::size_t I>
1256 struct MutableTupleFieldAccessor
1257 {
1258 template <typename TupleType>
1259 decltype(auto) operator()(TupleType& row) const
1260 {
1261 return GetRecordMemberAt<I>(std::get<TupleIndex>(row)).MutableValue();
1262 }
1263 };
1264
1265 template <typename First, typename Second, std::size_t... Fs, std::size_t... Ss>
1266 constexpr bool CanRowWiseFetchTupleImpl(std::index_sequence<Fs...> /*firstIndices*/,
1267 std::index_sequence<Ss...> /*secondIndices*/)
1268 {
1269 return (sizeof(std::tuple<First, Second>) % alignof(SqlIndicator) == 0)
1270 && (RowWiseColumnAcceptable<RecordMemberTypeOf<Fs, First>>() && ...)
1271 && (RowWiseColumnAcceptable<RecordMemberTypeOf<Ss, Second>>() && ...)
1272 && ((RowWiseIsColumn<RecordMemberTypeOf<Fs, First>>() || ...)
1273 || (RowWiseIsColumn<RecordMemberTypeOf<Ss, Second>>() || ...));
1274 }
1275
1276 /// @brief Whether a @c std::tuple<First,Second> JOIN row can be materialized via the row-wise fetch
1277 /// fast path: both sub-records' columns are row-bindable and the combined row size keeps the
1278 /// row-strided indicators aligned.
1279 template <typename First, typename Second>
1280 constexpr bool CanRowWiseFetchTuple()
1281 {
1282 return CanRowWiseFetchTupleImpl<First, Second>(std::make_index_sequence<RecordMemberCount<First>> {},
1283 std::make_index_sequence<RecordMemberCount<Second>> {});
1284 }
1285
1286 /// @brief Whether a @c std::tuple<First,Second> JOIN row may use the row-wise fetch fast path on
1287 /// @p serverType (row-wise fetchable + driver supports row-array fetch + any narrow fixed-string
1288 /// column round-trips byte-exact there). The tuple counterpart of @ref CanRowWiseFetchOn.
1289 template <typename First, typename Second>
1290 bool CanRowWiseFetchTupleOn(SqlDriverId driver, SqlServerType serverType, NarrowTextBinding narrowTextBinding)
1291 {
1292 if constexpr (!CanRowWiseFetchTuple<First, Second>())
1293 return false;
1294 else
1295 return SqlConnection::SupportsNativeRowArrayFetch(driver, serverType)
1296 && ((!RecordHasNarrowFixedStringColumn<First>() && !RecordHasNarrowFixedStringColumn<Second>())
1297 || NarrowTextBindsInPlace(serverType, narrowTextBinding))
1298 && ((!RecordHasStagedColumn<First>() && !RecordHasStagedColumn<Second>())
1299 || ConvertsNarrowIntegerCTypes(serverType));
1300 }
1301
1302 /// Accessor tuple for member @p I of the @p TupleIndex-th sub-record, or empty for non-columns.
1303 template <std::size_t TupleIndex, std::size_t I, typename SubRecord>
1304 auto MakeTupleColumnAccessor()
1305 {
1306 using FieldType = RecordMemberTypeOf<I, SubRecord>;
1307 if constexpr (IsField<FieldType> || IsBelongsTo<FieldType>)
1308 return std::tuple<MutableTupleFieldAccessor<TupleIndex, I>> {};
1309 else
1310 return std::tuple<> {};
1311 }
1312
1313 /// @brief Materializes a two-record JOIN result set into @p records via row-wise array fetch. The
1314 /// accessor pack is First's columns followed by Second's, matching the column order of
1315 /// @ref BindAllOutputColumnsWithOffset's offset scheme. Precondition: @ref CanRowWiseFetchTuple.
1316 template <typename First, typename Second>
1317 void ReadAllRowWiseTuple(SqlResultCursor& reader, std::vector<std::tuple<First, Second>>* records)
1318 {
1319 [&]<std::size_t... Fs, std::size_t... Ss>(std::index_sequence<Fs...>, std::index_sequence<Ss...>) {
1320 std::apply(
1321 [&](auto const&... accessors) {
1322 reader.FetchAllRowWise(*records, kDefaultRowArrayFetchDepth, accessors...);
1323 },
1324 std::tuple_cat(MakeTupleColumnAccessor<0, Fs, First>()..., MakeTupleColumnAccessor<1, Ss, Second>()...));
1325 }(std::make_index_sequence<RecordMemberCount<First>> {}, std::make_index_sequence<RecordMemberCount<Second>> {});
1326 }
1327
1328 // when we iterate over all columns using element mask
1329 // indexes of the mask corresponds to the indexe of the field
1330 // inside the structure, not inside the SQL result set
1331 template <typename ElementMask, typename Record>
1332 void GetAllColumns(SqlResultCursor& reader, Record& record, SqlColumnIndex indexFromQuery = 0)
1333 {
1334 EnumerateRecordMembers<ElementMask>(
1335 record, [reader = &reader, &indexFromQuery]<size_t I, typename Field>(Field& field) mutable {
1336 // Only members that map onto a column consume a result set index — relations
1337 // (HasMany, HasManyThrough, HasOneThrough, ...) are not part of the projection.
1338 //
1339 // The projection side (RecordColumnMember, see SqlSelectQueryBuilder::Fields and
1340 // DataMapper::BuildFullyQualifiedFieldList) and this read side must classify every
1341 // member identically; a member that only one of them counts silently shifts the index
1342 // of every column following it. Both predicates ultimately ask whether SqlDataBinder<T>
1343 // is usable as a column, so pin them together here rather than letting them drift.
1344 static_assert(RecordColumnMember<Field> == (IsField<Field> || SqlGetColumnNativeType<Field>),
1345 "Record member is projected but not readable (or readable but not projected). "
1346 "A SqlDataBinder<T> used as a record member must provide both OutputColumn() "
1347 "and GetColumn().");
1348 if constexpr (IsField<Field>)
1349 {
1350 ++indexFromQuery;
1351 if constexpr (Field::IsOptional)
1352 field.MutableValue() =
1353 reader->GetNullableColumn<typename Field::ValueType::value_type>(indexFromQuery);
1354 else
1355 field.MutableValue() = reader->GetColumn<typename Field::ValueType>(indexFromQuery);
1356 }
1357 else if constexpr (SqlGetColumnNativeType<Field>)
1358 {
1359 ++indexFromQuery;
1360 if constexpr (IsOptionalBelongsTo<Field>)
1361 field = reader->GetNullableColumn<typename Field::BaseType>(indexFromQuery);
1362 else
1363 field = reader->GetColumn<Field>(indexFromQuery);
1364 }
1365 });
1366 }
1367
1368 template <typename Record>
1369 void GetAllColumns(SqlResultCursor& reader, Record& record, SqlColumnIndex indexFromQuery = 0)
1370 {
1371 return GetAllColumns<std::make_integer_sequence<size_t, RecordMemberCount<Record>>, Record>(
1372 reader, record, indexFromQuery);
1373 }
1374
1375 template <typename FirstRecord, typename SecondRecord>
1376 // TODO we need to remove this at some points and provide generic bindings for tuples
1377 void GetAllColumns(SqlResultCursor& reader, std::tuple<FirstRecord, SecondRecord>& record)
1378 {
1379 auto& [firstRecord, secondRecord] = record;
1380
1381 // Both sub-records are read through the single-record overload, so relation members are skipped
1382 // (rather than indexed by member position) on both sides. The second sub-record starts after the
1383 // *columns* the first one projects, which is RecordColumnCount, not RecordMemberCount.
1384 GetAllColumns(reader, firstRecord, 0);
1385 GetAllColumns(reader, secondRecord, static_cast<SqlColumnIndex>(RecordColumnCount<FirstRecord>));
1386 }
1387
1388 template <typename Record>
1389 bool ReadSingleResult(SqlConnection const& connection, SqlResultCursor& reader, Record& record)
1390 {
1391 auto const outputColumnsBound = CanSafelyBindOutputColumns<Record>(connection.ReadsBoundColumnsAgain());
1392
1393 if (outputColumnsBound)
1394 BindAllOutputColumns(reader, record);
1395
1396 if (!reader.FetchRow())
1397 return false;
1398
1399 if (!outputColumnsBound)
1400 GetAllColumns(reader, record);
1401
1402 return true;
1403 }
1404} // namespace detail
1405
1406template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1407template <typename Finisher>
1408auto SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::RunFinisher(Finisher finisher)
1409{
1410 if constexpr (Derived::QueryExecution == SqlQueryExecutionMode::Asynchronous)
1411 return Async::RunAsync(_dm.Connection().AsyncBackend(), std::move(finisher));
1412 else
1413 return finisher();
1414}
1415
1416template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1418 DataMapper& dm, std::string fields) noexcept:
1419 _dm { dm },
1420 _formatter { dm.Connection().QueryFormatter() },
1421 _fields { std::move(fields) }
1422{
1423 this->_query.searchCondition.inputBindings = &_boundInputs;
1424}
1425
1426template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1428 SqlCoreDataMapperQueryBuilder const& other):
1429 SqlBasicSelectQueryBuilder<Derived> { other },
1430 _dm { other._dm },
1431 _formatter { other._formatter },
1432 _fields { other._fields },
1433 _boundInputs { other._boundInputs },
1434 _relationPreloaders { other._relationPreloaders }
1435{
1436 this->_query.searchCondition.inputBindings = &_boundInputs;
1437}
1438
1439template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1441 SqlCoreDataMapperQueryBuilder&& other) noexcept:
1442 // Moves only the base subobject; the members below are still intact in `other`.
1443 SqlBasicSelectQueryBuilder<Derived> { std::move(static_cast<SqlBasicSelectQueryBuilder<Derived>&>(other)) },
1444 _dm { other._dm },
1445 _formatter { other._formatter },
1446 _fields { std::move(other._fields) },
1447 _boundInputs { std::move(other._boundInputs) },
1448 _relationPreloaders { std::move(other._relationPreloaders) }
1449{
1450 this->_query.searchCondition.inputBindings = &_boundInputs;
1451}
1452
1453template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1454size_t SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::CountImpl()
1455{
1456 auto stmt = SqlStatement { _dm.Connection() };
1457 stmt.Prepare(_formatter.SelectCount(this->_query.distinct,
1458 RecordTableName<Record>,
1459 this->_query.searchCondition.tableAlias,
1460 this->_query.searchCondition.tableJoins,
1461 this->_query.searchCondition.condition,
1462 this->_query.groupBy));
1463 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1464 if (reader.FetchRow())
1465 return reader.template GetColumn<size_t>(1);
1466 return 0;
1467}
1468
1469template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1470template <auto... RelationPath>
1471 requires DataMapperRecord<Record> && (sizeof...(RelationPath) >= 1)
1472Derived& SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::With()
1473{
1474 constexpr auto FirstField = detail::FirstOf<RelationPath...>;
1475
1476#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1477 static_assert(std::same_as<typename[:std::meta::parent_of(FirstField):], Record>,
1478 "The first relation named by With<>() must be a member of the record being queried");
1479#else
1480 // remove_cv_t: FirstField is a constexpr variable, so decltype() yields a *const* member pointer
1481 // type, which MemberClassType is not specialized for.
1482 static_assert(std::same_as<MemberClassType<std::remove_cv_t<decltype(FirstField)>>, Record>,
1483 "The first relation named by With<>() must be a member of the record being queried");
1484#endif
1485
1486 // A capture-less lambda, so this decays to a plain function pointer: the whole path is known at
1487 // compile time, so nothing has to be carried at run time beyond which instantiation to call.
1488 _relationPreloaders.emplace_back(+[](DataMapper& dm, std::span<Record* const> records) {
1489 [&]<auto Head, auto... Tail>() {
1490 dm.template PreloadRelationPath<Record, MemberIndexOf<Head>, Tail...>(records);
1491 }.template operator()<RelationPath...>();
1492 });
1493
1494 return static_cast<Derived&>(*this);
1495}
1496
1497template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1499{
1500 if constexpr (QueryOptions.eagerLoadDepth == 0)
1501 if (_relationPreloaders.empty())
1502 return;
1503
1504 if (records.empty())
1505 return;
1506
1507 auto pointers = std::vector<Record*> {};
1508 pointers.reserve(records.size());
1509 for (auto& record: records)
1510 pointers.emplace_back(&record);
1511 auto const batch = std::span<Record* const> { pointers };
1512
1513 // The named paths run first: the batched loaders skip a relation that is already loaded, so a
1514 // relation this query asked for by name is not fetched a second time by the depth walk below.
1515 for (auto const preloader: _relationPreloaders)
1516 preloader(_dm, batch);
1517
1518 if constexpr (QueryOptions.eagerLoadDepth > 0)
1519 _dm.template PreloadAllRelations<Record, QueryOptions.eagerLoadDepth>(batch);
1520}
1521
1522template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1523bool SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::ExistImpl()
1524{
1525 auto stmt = SqlStatement { _dm.Connection() };
1526
1527 auto const query = _formatter.SelectFirst(this->_query.distinct,
1528 _fields,
1529 RecordTableName<Record>,
1530 this->_query.searchCondition.tableAlias,
1531 this->_query.searchCondition.tableJoins,
1532 this->_query.searchCondition.condition,
1533 this->_query.orderBy,
1534 this->_query.groupBy,
1535 1);
1536
1537 stmt.Prepare(query);
1538 if (auto reader = stmt.ExecuteWithVariants(_boundInputs); reader.FetchRow())
1539 return true;
1540 return false;
1541}
1542
1543template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1544void SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::DeleteImpl()
1545{
1546 // DELETE has no HAVING clause. Dropping the filter would delete more rows than the caller asked for.
1547 if (this->HasHavingClause())
1548 throw std::logic_error { "Delete() cannot honor Having(): a DELETE statement has no HAVING clause." };
1549
1550 auto stmt = SqlStatement { _dm.Connection() };
1551
1552 auto const query = _formatter.Delete(RecordTableName<Record>,
1553 this->_query.searchCondition.tableAlias,
1554 this->_query.searchCondition.tableJoins,
1555 this->_query.searchCondition.condition);
1556
1557 stmt.Prepare(query);
1558 [[maybe_unused]] auto cursor = stmt.ExecuteWithVariants(_boundInputs);
1559}
1560
1561template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1562std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::AllImpl()
1563{
1564
1565 auto records = std::vector<Record> {};
1566 auto stmt = SqlStatement { _dm.Connection() };
1567 stmt.Prepare(_formatter.SelectAll(this->_query.distinct,
1568 _fields,
1569 RecordTableName<Record>,
1570 this->_query.searchCondition.tableAlias,
1571 this->_query.searchCondition.tableJoins,
1572 this->_query.searchCondition.condition,
1573 this->_query.orderBy,
1574 this->_query.groupBy));
1575 Derived::ReadResults(stmt.Connection(), stmt.ExecuteWithVariants(_boundInputs), &records);
1576 if constexpr (DataMapperRecord<Record>)
1577 {
1578 // This can be called when record type is not plain aggregate type
1579 // but more complex tuple, like std::tuple<A, B>
1580 // for now we do not unwrap this type and just skip auto-loading configuration
1581 if constexpr (QueryOptions.loadRelations)
1582 {
1583 for (auto& record: records)
1584 {
1585 _dm.ConfigureRelationAutoLoading(record);
1586 }
1587 }
1588 RunRelationPreloaders(records);
1589 }
1590 return records;
1591}
1592
1593template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1594template <auto Field>
1595#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1596 requires(is_aggregate_type(parent_of(Field)))
1597#else
1598 requires std::is_member_object_pointer_v<decltype(Field)>
1599#endif
1600auto SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::AllImpl() -> std::vector<ReferencedFieldTypeOf<Field>>
1601{
1602 using value_type = ReferencedFieldTypeOf<Field>;
1603 auto result = std::vector<value_type> {};
1604
1605 auto stmt = SqlStatement { _dm.Connection() };
1606 stmt.Prepare(_formatter.SelectAll(this->_query.distinct,
1607 detail::FullyQualifiedNamesOf<Field>,
1608 RecordTableName<Record>,
1609 this->_query.searchCondition.tableAlias,
1610 this->_query.searchCondition.tableJoins,
1611 this->_query.searchCondition.condition,
1612 this->_query.orderBy,
1613 this->_query.groupBy));
1614 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1615 auto const outputColumnsBound =
1616 detail::CanSafelyBindOutputColumn<value_type>(stmt.Connection().ReadsBoundColumnsAgain());
1617 while (true)
1618 {
1619 auto& value = result.emplace_back();
1620 if (outputColumnsBound)
1621 reader.BindOutputColumn(1, &value);
1622
1623 if (!reader.FetchRow())
1624 {
1625 result.pop_back();
1626 break;
1627 }
1628
1629 if (!outputColumnsBound)
1630 value = reader.template GetColumn<value_type>(1);
1631 }
1632
1633 return result;
1634}
1635
1636template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1637template <auto... ReferencedFields>
1638 requires(sizeof...(ReferencedFields) >= 2)
1639auto SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::AllImpl() -> std::vector<Record>
1640{
1641 auto records = std::vector<Record> {};
1642 auto stmt = SqlStatement { _dm.Connection() };
1643
1644 stmt.Prepare(_formatter.SelectAll(this->_query.distinct,
1645 detail::FullyQualifiedNamesOf<ReferencedFields...>,
1646 RecordTableName<Record>,
1647 this->_query.searchCondition.tableAlias,
1648 this->_query.searchCondition.tableJoins,
1649 this->_query.searchCondition.condition,
1650 this->_query.orderBy,
1651 this->_query.groupBy));
1652
1653 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1654 auto const outputColumnsBound = detail::CanSafelyBindOutputColumns<Record>(stmt.Connection().ReadsBoundColumnsAgain());
1655 while (true)
1656 {
1657 auto& record = detail::EmplaceBackUninitialized(records);
1658 if (outputColumnsBound)
1659#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1660 reader.BindOutputColumns(&(record.[:ReferencedFields:])...);
1661#else
1662 reader.BindOutputColumns(&(record.*ReferencedFields)...);
1663#endif
1664 if (!reader.FetchRow())
1665 {
1666 records.pop_back();
1667 break;
1668 }
1669 if (!outputColumnsBound)
1670 {
1671 using ElementMask = std::integer_sequence<size_t, MemberIndexOf<ReferencedFields>...>;
1672 detail::GetAllColumns<ElementMask>(reader, record);
1673 }
1674 }
1675
1676 return records;
1677}
1678
1679template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1680std::optional<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::FirstImpl()
1681{
1682 std::optional<Record> record {};
1683 auto stmt = SqlStatement { _dm.Connection() };
1684 stmt.Prepare(_formatter.SelectFirst(this->_query.distinct,
1685 _fields,
1686 RecordTableName<Record>,
1687 this->_query.searchCondition.tableAlias,
1688 this->_query.searchCondition.tableJoins,
1689 this->_query.searchCondition.condition,
1690 this->_query.orderBy,
1691 this->_query.groupBy,
1692 1));
1693 Derived::ReadResult(stmt.Connection(), stmt.ExecuteWithVariants(_boundInputs), &record);
1694 if constexpr (QueryOptions.loadRelations)
1695 {
1696 if (record)
1697 _dm.ConfigureRelationAutoLoading(record.value());
1698 }
1699 if constexpr (DataMapperRecord<Record>)
1700 if (record)
1701 RunRelationPreloaders(std::span<Record> { &record.value(), 1 });
1702 return record;
1703}
1704
1705template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1706template <auto Field>
1707#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1708 requires(is_aggregate_type(parent_of(Field)))
1709#else
1710 requires std::is_member_object_pointer_v<decltype(Field)>
1711#endif
1712auto SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::FirstImpl() -> std::optional<ReferencedFieldTypeOf<Field>>
1713{
1714 auto constexpr count = 1;
1715 auto stmt = SqlStatement { _dm.Connection() };
1716 stmt.Prepare(_formatter.SelectFirst(this->_query.distinct,
1717 detail::FullyQualifiedNamesOf<Field>,
1718 RecordTableName<Record>,
1719 this->_query.searchCondition.tableAlias,
1720 this->_query.searchCondition.tableJoins,
1721 this->_query.searchCondition.condition,
1722 this->_query.orderBy,
1723 this->_query.groupBy,
1724 count));
1725 if (auto reader = stmt.ExecuteWithVariants(_boundInputs); reader.FetchRow())
1726 return reader.template GetColumn<ReferencedFieldTypeOf<Field>>(1);
1727 return std::nullopt;
1728}
1729
1730template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1731template <auto... ReferencedFields>
1732 requires(sizeof...(ReferencedFields) >= 2)
1733auto SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::FirstImpl() -> std::optional<Record>
1734{
1735 auto optionalRecord = std::optional<Record> {};
1736
1737 auto stmt = SqlStatement { _dm.Connection() };
1738 stmt.Prepare(_formatter.SelectFirst(this->_query.distinct,
1739 detail::FullyQualifiedNamesOf<ReferencedFields...>,
1740 RecordTableName<Record>,
1741 this->_query.searchCondition.tableAlias,
1742 this->_query.searchCondition.tableJoins,
1743 this->_query.searchCondition.condition,
1744 this->_query.orderBy,
1745 this->_query.groupBy,
1746 1));
1747
1748 auto& record = detail::EmplaceUninitialized(optionalRecord);
1749 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1750 auto const outputColumnsBound = detail::CanSafelyBindOutputColumns<Record>(stmt.Connection().ReadsBoundColumnsAgain());
1751 if (outputColumnsBound)
1752#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1753 reader.BindOutputColumns(&(record.[:ReferencedFields:])...);
1754#else
1755 reader.BindOutputColumns(&(record.*ReferencedFields)...);
1756#endif
1757
1758 // A single return statement at the end is deliberate, not stylistic: a composite foreign key
1759 // configured below (ConfigureRelationAutoLoading) captures a pointer to *optionalRecord. An earlier
1760 // `return std::nullopt;` here defeats NRVO in both GCC and Clang (verified: it forces a
1761 // move-construct into the caller's storage at a new address), which would leave that captured
1762 // pointer dangling.
1763 if (reader.FetchRow())
1764 {
1765 if (!outputColumnsBound)
1766 {
1767 using ElementMask = std::integer_sequence<size_t, MemberIndexOf<ReferencedFields>...>;
1768 detail::GetAllColumns<ElementMask>(reader, record);
1769 }
1770
1771 if constexpr (QueryOptions.loadRelations)
1772 _dm.ConfigureRelationAutoLoading(record);
1773 }
1774 else
1775 {
1776 optionalRecord.reset();
1777 }
1778
1779 return optionalRecord;
1780}
1781
1782template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1783std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::FirstImpl(size_t n)
1784{
1785 auto records = std::vector<Record> {};
1786 auto stmt = SqlStatement { _dm.Connection() };
1787 records.reserve(n);
1788 stmt.Prepare(_formatter.SelectFirst(this->_query.distinct,
1789 _fields,
1790 RecordTableName<Record>,
1791 this->_query.searchCondition.tableAlias,
1792 this->_query.searchCondition.tableJoins,
1793 this->_query.searchCondition.condition,
1794 this->_query.orderBy,
1795 this->_query.groupBy,
1796 n));
1797 Derived::ReadResults(stmt.Connection(), stmt.ExecuteWithVariants(_boundInputs), &records);
1798
1799 if constexpr (QueryOptions.loadRelations)
1800 {
1801 for (auto& record: records)
1802 _dm.ConfigureRelationAutoLoading(record);
1803 }
1804 if constexpr (DataMapperRecord<Record>)
1805 RunRelationPreloaders(records);
1806 return records;
1807}
1808
1809template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1810std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::RangeImpl(size_t offset, size_t limit)
1811{
1812 auto records = std::vector<Record> {};
1813 auto stmt = SqlStatement { _dm.Connection() };
1814 records.reserve(limit);
1815 stmt.Prepare(_formatter.SelectRange(
1816 this->_query.distinct,
1817 _fields,
1818 RecordTableName<Record>,
1819 this->_query.searchCondition.tableAlias,
1820 this->_query.searchCondition.tableJoins,
1821 this->_query.searchCondition.condition,
1822 !this->_query.orderBy.empty()
1823 ? this->_query.orderBy
1824 : std::format(" ORDER BY {} ASC",
1825 SqlQueryFormatter::QuoteIdentifier(FieldNameAt<RecordPrimaryKeyIndex<Record>, Record>)),
1826 this->_query.groupBy,
1827 offset,
1828 limit));
1829 Derived::ReadResults(stmt.Connection(), stmt.ExecuteWithVariants(_boundInputs), &records);
1830 if constexpr (QueryOptions.loadRelations)
1831 {
1832 for (auto& record: records)
1833 _dm.ConfigureRelationAutoLoading(record);
1834 }
1835 if constexpr (DataMapperRecord<Record>)
1836 RunRelationPreloaders(records);
1837 return records;
1838}
1839
1840template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1841template <auto... ReferencedFields>
1842std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::RangeImpl(size_t offset, size_t limit)
1843{
1844 auto records = std::vector<Record> {};
1845 auto stmt = SqlStatement { _dm.Connection() };
1846 records.reserve(limit);
1847 stmt.Prepare(_formatter.SelectRange(
1848 this->_query.distinct,
1849 detail::FullyQualifiedNamesOf<ReferencedFields...>,
1850 RecordTableName<Record>,
1851 this->_query.searchCondition.tableAlias,
1852 this->_query.searchCondition.tableJoins,
1853 this->_query.searchCondition.condition,
1854 !this->_query.orderBy.empty()
1855 ? this->_query.orderBy
1856 : std::format(" ORDER BY {} ASC",
1857 SqlQueryFormatter::QuoteIdentifier(FieldNameAt<RecordPrimaryKeyIndex<Record>, Record>)),
1858 this->_query.groupBy,
1859 offset,
1860 limit));
1861
1862 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1863 auto const outputColumnsBound = detail::CanSafelyBindOutputColumns<Record>(stmt.Connection().ReadsBoundColumnsAgain());
1864 while (true)
1865 {
1866 auto& record = detail::EmplaceBackUninitialized(records);
1867 if (outputColumnsBound)
1868#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1869 reader.BindOutputColumns(&(record.[:ReferencedFields:])...);
1870#else
1871 reader.BindOutputColumns(&(record.*ReferencedFields)...);
1872#endif
1873 if (!reader.FetchRow())
1874 {
1875 records.pop_back();
1876 break;
1877 }
1878 if (!outputColumnsBound)
1879 {
1880 using ElementMask = std::integer_sequence<size_t, MemberIndexOf<ReferencedFields>...>;
1881 detail::GetAllColumns<ElementMask>(reader, record);
1882 }
1883 }
1884
1885 if constexpr (QueryOptions.loadRelations)
1886 {
1887 for (auto& record: records)
1888 _dm.ConfigureRelationAutoLoading(record);
1889 }
1890
1891 return records;
1892}
1893
1894template <typename Record, typename Derived, DataMapperOptions QueryOptions>
1895template <auto... ReferencedFields>
1896[[nodiscard]] std::vector<Record> SqlCoreDataMapperQueryBuilder<Record, Derived, QueryOptions>::FirstImpl(size_t n)
1897{
1898 auto records = std::vector<Record> {};
1899 auto stmt = SqlStatement { _dm.Connection() };
1900 records.reserve(n);
1901 stmt.Prepare(_formatter.SelectFirst(this->_query.distinct,
1902 detail::FullyQualifiedNamesOf<ReferencedFields...>,
1903 RecordTableName<Record>,
1904 this->_query.searchCondition.tableAlias,
1905 this->_query.searchCondition.tableJoins,
1906 this->_query.searchCondition.condition,
1907 this->_query.orderBy,
1908 this->_query.groupBy,
1909 n));
1910
1911 auto reader = stmt.ExecuteWithVariants(_boundInputs);
1912 auto const outputColumnsBound = detail::CanSafelyBindOutputColumns<Record>(stmt.Connection().ReadsBoundColumnsAgain());
1913 while (true)
1914 {
1915 auto& record = detail::EmplaceBackUninitialized(records);
1916 if (outputColumnsBound)
1917#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
1918 reader.BindOutputColumns(&(record.[:ReferencedFields:])...);
1919#else
1920 reader.BindOutputColumns(&(record.*ReferencedFields)...);
1921#endif
1922 if (!reader.FetchRow())
1923 {
1924 records.pop_back();
1925 break;
1926 }
1927 if (!outputColumnsBound)
1928 {
1929 using ElementMask = std::integer_sequence<size_t, MemberIndexOf<ReferencedFields>...>;
1930 detail::GetAllColumns<ElementMask>(reader, record);
1931 }
1932 }
1933
1934 if constexpr (QueryOptions.loadRelations)
1935 {
1936 for (auto& record: records)
1937 _dm.ConfigureRelationAutoLoading(record);
1938 }
1939
1940 return records;
1941}
1942
1943template <typename Record, DataMapperOptions QueryOptions, SqlQueryExecutionMode Execution>
1944void SqlAllFieldsQueryBuilder<Record, QueryOptions, Execution>::ReadResults(SqlConnection const& connection,
1945 SqlResultCursor reader,
1946 std::vector<Record>* records)
1947{
1948 // Fast path: when every result column is a fixed-width row-bindable field and the driver honours
1949 // native row-array fetching, materialize the whole result set in row blocks (one SQLFetchScroll per
1950 // block) directly into records, instead of one SQLFetch round-trip per row. Results are identical to
1951 // the per-row path below; this only collapses ODBC round-trips (the win on high-latency links).
1952 if constexpr (detail::CanRowWiseFetchRecord<Record>())
1953 {
1954 if (detail::CanRowWiseFetchOn<Record>(
1955 connection.DriverId(), connection.ServerType(), reader.NarrowTextBindingMode()))
1956 {
1957 detail::ReadAllRowWise(reader, records);
1958 return;
1959 }
1960 }
1961
1962 while (true)
1963 {
1964 Record& record = detail::EmplaceBackUninitialized(*records);
1965 if (!detail::ReadSingleResult(connection, reader, record))
1966 {
1967 records->pop_back();
1968 break;
1969 }
1970 }
1971}
1972
1973template <typename Record, DataMapperOptions QueryOptions, SqlQueryExecutionMode Execution>
1974void SqlAllFieldsQueryBuilder<Record, QueryOptions, Execution>::ReadResult(SqlConnection const& connection,
1975 SqlResultCursor reader,
1976 std::optional<Record>* optionalRecord)
1977{
1978 Record& record = detail::EmplaceUninitialized(*optionalRecord);
1979 if (!detail::ReadSingleResult(connection, reader, record))
1980 optionalRecord->reset();
1981}
1982
1983template <typename FirstRecord, typename SecondRecord, DataMapperOptions QueryOptions, SqlQueryExecutionMode Execution>
1984void SqlAllFieldsQueryBuilder<std::tuple<FirstRecord, SecondRecord>, QueryOptions, Execution>::ReadResults(
1985 SqlConnection const& connection, SqlResultCursor reader, std::vector<RecordType>* records)
1986{
1987 // Fast path: a JOIN row of two row-bindable records is bound row-wise over the tuple and fetched in
1988 // blocks (one SQLFetchScroll per block) instead of one SQLFetch per row. Identical results.
1989 if constexpr (detail::CanRowWiseFetchTuple<FirstRecord, SecondRecord>())
1990 {
1991 if (detail::CanRowWiseFetchTupleOn<FirstRecord, SecondRecord>(
1992 connection.DriverId(), connection.ServerType(), reader.NarrowTextBindingMode()))
1993 {
1994 detail::ReadAllRowWiseTuple<FirstRecord, SecondRecord>(reader, records);
1995 return;
1996 }
1997 }
1998
1999 while (true)
2000 {
2001 auto& record = detail::EmplaceBackUninitialized(*records);
2002 auto& [firstRecord, secondRecord] = record;
2003
2004 using FirstRecordType = std::remove_cvref_t<decltype(firstRecord)>;
2005 using SecondRecordType = std::remove_cvref_t<decltype(secondRecord)>;
2006
2007 auto const outputColumnsBoundFirst =
2008 detail::CanSafelyBindOutputColumns<FirstRecordType>(connection.ReadsBoundColumnsAgain());
2009 auto const outputColumnsBoundSecond =
2010 detail::CanSafelyBindOutputColumns<SecondRecordType>(connection.ReadsBoundColumnsAgain());
2011 auto const canSafelyBindAll = outputColumnsBoundFirst && outputColumnsBoundSecond;
2012
2013 if (canSafelyBindAll)
2014 {
2015 detail::BindAllOutputColumnsWithOffset(reader, firstRecord, 1);
2016 // The second sub-record starts after the *columns* projected for the first one; relation
2017 // members are not projected, so RecordMemberCount would over-count here.
2018 detail::BindAllOutputColumnsWithOffset(
2019 reader, secondRecord, static_cast<SqlColumnIndex>(1 + RecordColumnCount<FirstRecord>));
2020 }
2021
2022 if (!reader.FetchRow())
2023 {
2024 records->pop_back();
2025 break;
2026 }
2027
2028 if (!canSafelyBindAll)
2029 detail::GetAllColumns(reader, record);
2030 }
2031}
2032
2033template <typename Record>
2034std::string DataMapper::Inspect(Record const& record)
2035{
2036 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2037
2038 std::string str;
2039 Reflection::CallOnMembers(record, [&str]<typename Name, typename Value>(Name const& name, Value const& value) {
2040 if (!str.empty())
2041 str += '\n';
2042
2043 if constexpr (FieldWithStorage<Value>)
2044 {
2045 if constexpr (Value::IsOptional)
2046 {
2047 if (!value.Value().has_value())
2048 {
2049 str += std::format("{} {} := <nullopt>", Reflection::TypeNameOf<Value>, name);
2050 }
2051 else
2052 {
2053 str += std::format("{} {} := {}", Reflection::TypeNameOf<Value>, name, value.Value().value());
2054 }
2055 }
2056 else if constexpr (IsBelongsTo<Value>)
2057 {
2058 str += std::format("{} {} := {}", Reflection::TypeNameOf<Value>, name, value.Value());
2059 }
2060 else if constexpr (std::same_as<typename Value::ValueType, char>)
2061 {
2062 }
2063 else
2064 {
2065 str += std::format("{} {} := {}", Reflection::TypeNameOf<Value>, name, value.InspectValue());
2066 }
2067 }
2068 else if constexpr (!IsHasMany<Value> && !IsHasManyThrough<Value> && !IsHasOneThrough<Value> && !IsBelongsTo<Value>
2069 && !IsCompositeForeignKey<Value>)
2070 str += std::format("{} {} := {}", Reflection::TypeNameOf<Value>, name, value);
2071 });
2072 return "{\n" + std::move(str) + "\n}";
2073}
2074
2075template <typename Record>
2076std::vector<std::string> DataMapper::CreateTableString(SqlServerType serverType)
2077{
2078 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2079
2080 auto migration = SqlQueryBuilder(*SqlQueryFormatter::Get(serverType)).Migration();
2081 auto createTable = migration.CreateTable(RecordTableName<Record>);
2082 detail::PopulateCreateTableBuilder<Record>(createTable);
2083 return migration.GetPlan().ToSql();
2084}
2085
2086template <typename FirstRecord, typename... MoreRecords>
2087std::vector<std::string> DataMapper::CreateTablesString(SqlServerType serverType)
2088{
2089 std::vector<std::string> output;
2090 auto const append = [&output](auto const& sql) {
2091 output.insert(output.end(), sql.begin(), sql.end());
2092 };
2093 append(CreateTableString<FirstRecord>(serverType));
2094 (append(CreateTableString<MoreRecords>(serverType)), ...);
2095 return output;
2096}
2097
2098template <typename Record>
2100{
2101 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2102
2103 ZoneScopedN("DataMapper::CreateTable");
2104 ZoneTextObject(RecordTableName<Record>);
2105
2106 auto const sqlQueryStrings = CreateTableString<Record>(_connection.ServerType());
2107 for (auto const& sqlQueryString: sqlQueryStrings) [[maybe_unused]]
2108 auto cursor = _stmt.ExecuteDirect(sqlQueryString);
2109}
2110
2111template <typename FirstRecord, typename... MoreRecords>
2113{
2114 CreateTable<FirstRecord>();
2115 (CreateTable<MoreRecords>(), ...);
2116}
2117
2118namespace detail
2119{
2120 /// Whether @p Record has at least one auto-maintained timestamp field (see @ref FieldTimestamp).
2121 template <typename Record>
2122 inline constexpr bool HasAutoTimestampFields =
2123 CheckFieldProperty<[]<typename FieldType>() { return IsAutoTimestampField<FieldType>; }, Record>;
2124
2125 /// Whether @p Record has at least one UpdatedAt timestamp field (see @ref FieldTimestamp).
2126 template <typename Record>
2127 inline constexpr bool HasUpdatedAtTimestampFields =
2128 CheckFieldProperty<[]<typename FieldType>() { return FieldTimestampOf<FieldType> == FieldTimestamp::UpdatedAt; },
2129 Record>;
2130} // namespace detail
2131
2132template <DataMapper::TimestampFill Fill, typename FieldType>
2133constexpr bool DataMapper::FillsTimestamp(FieldType const& field) noexcept
2134{
2135 if constexpr (!IsAutoTimestampField<FieldType>)
2136 return false;
2137 else if constexpr (Fill == TimestampFill::Unset)
2138 return detail::IsUnsetTimestamp(field.Value());
2139 else if constexpr (Fill == TimestampFill::All)
2140 return true;
2141 else if constexpr (Fill == TimestampFill::UpdatedAt)
2142 return FieldTimestampOf<FieldType> == FieldTimestamp::UpdatedAt;
2143 else
2144 return false;
2145}
2146
2147template <DataMapper::TimestampFill Fill, typename Record>
2148void DataMapper::StampTimestamps(Record& record, SqlDateTime const& now)
2149{
2150 EnumerateRecordMembers(record, [&now]<size_t I>(auto& field) {
2151 using MemberType = RecordMemberTypeOf<I, Record>;
2152 if constexpr (IsAutoTimestampField<MemberType>)
2153 {
2154 if (FillsTimestamp<Fill>(field))
2155 field = now;
2156 }
2157 });
2158}
2159
2160template <typename Record>
2161void DataMapper::StampTimestampsForUpdate(Record& record) const
2162{
2163 if constexpr (detail::HasUpdatedAtTimestampFields<Record>)
2164 {
2165 // An UpdatedAt field records a change to the row, so it only moves when something else is written.
2166 bool writesOtherColumn = false;
2167 EnumerateRecordMembers(record, [&writesOtherColumn]<size_t I>(auto const& field) {
2168 using MemberType = RecordMemberTypeOf<I, Record>;
2169 if constexpr (FieldWithStorage<MemberType> && FieldTimestampOf<MemberType> != FieldTimestamp::UpdatedAt)
2170 writesOtherColumn = writesOtherColumn || field.IsModified();
2171 });
2172
2173 auto const now = writesOtherColumn ? std::optional { CurrentTimestamp() } : std::nullopt;
2174 EnumerateRecordMembers(record, [&now]<size_t I>(auto& field) {
2175 using MemberType = RecordMemberTypeOf<I, Record>;
2176 if constexpr (FieldTimestampOf<MemberType> == FieldTimestamp::UpdatedAt)
2177 {
2178 // A value the caller assigned in this change is theirs to keep.
2179 if (field.IsModified() && !detail::IsUnsetTimestamp(field.Value()))
2180 return;
2181 if (now.has_value())
2182 field = *now;
2183 else
2184 field.SetModified(false); // Never write an unset timestamp, and keep a no-op update a no-op.
2185 }
2186 });
2187 }
2188}
2189
2190template <DataMapper::TimestampFill Fill, typename Record>
2191std::vector<Record> DataMapper::CopyWithTimestamps(std::span<Record const> records) const
2192{
2193 static_assert(std::copy_constructible<Record>,
2194 "Batch writes of a record with FieldTimestamp fields copy the batch to carry the generated "
2195 "timestamps, so the record type must be copy-constructible.");
2196
2197 auto copies = std::vector<Record>(records.begin(), records.end());
2198 auto const now = CurrentTimestamp();
2199 for (auto& copy: copies)
2200 StampTimestamps<Fill>(copy, now);
2201 return copies;
2202}
2203
2204template <typename Record>
2205std::optional<RecordPrimaryKeyType<Record>> DataMapper::GenerateAutoAssignPrimaryKey(Record const& record)
2206{
2207 // Auto-assignment produces exactly one value, and SetId() writes it into every generated primary
2208 // key member - so a record with several auto-assigned key members would silently receive the same
2209 // value in all of them. A composite key is declared PrimaryKey::Manual instead; see that enumerator.
2210 static_assert(detail::AutoAssignPrimaryKeyFieldCount<Record> <= 1,
2211 "A record may declare at most one auto-assigned primary key member. Auto-assignment yields a "
2212 "single value that would be written into every generated key member, so a composite key cannot "
2213 "be generated - declare its members PrimaryKey::Manual and set their values yourself before "
2214 "calling Create().");
2215
2216 std::optional<RecordPrimaryKeyType<Record>> result;
2218 record, [this, &result]<size_t PrimaryKeyIndex, typename PrimaryKeyType>(PrimaryKeyType const& primaryKeyField) {
2219 if constexpr (IsField<PrimaryKeyType> && IsPrimaryKey<PrimaryKeyType>
2220 && detail::IsAutoAssignPrimaryKeyField<PrimaryKeyType>::value)
2221 {
2222 using ValueType = PrimaryKeyType::ValueType;
2223 if constexpr (std::same_as<ValueType, SqlGuid>)
2224 {
2225 if (!primaryKeyField.Value())
2226 [&](auto& res) {
2227 res.emplace(SqlGuid::Create());
2228 }(result);
2229 }
2230 else if constexpr (requires { ValueType {} + 1; })
2231 {
2232 if (primaryKeyField.Value() == ValueType {})
2233 {
2234 auto maxId = SqlStatement { _connection }.ExecuteDirectScalar<ValueType>(
2235 std::format("SELECT MAX({}) FROM {}",
2236 SqlQueryFormatter::QuoteIdentifier(FieldNameAt<PrimaryKeyIndex, Record>),
2237 SqlQueryFormatter::QuoteIdentifier(RecordTableName<Record>)));
2238 result = maxId.value_or(ValueType {}) + 1;
2239 }
2240 }
2241 }
2242 });
2243 return result;
2244}
2245
2246template <DataMapper::PrimaryKeySource UsePkOverride, DataMapper::TimestampFill Fill, typename Record>
2247RecordPrimaryKeyType<Record> DataMapper::CreateInternal(
2248 Record const& record,
2249 std::optional<std::conditional_t<std::is_void_v<RecordPrimaryKeyType<Record>>, int, RecordPrimaryKeyType<Record>>>
2250 pkOverride)
2251{
2252 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2253
2254 auto query = _connection.Query(RecordTableName<Record>).Insert(nullptr);
2255
2256#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2257 constexpr auto ctx = std::meta::access_context::current();
2258 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2259 {
2260 using FieldType = typename[:std::meta::type_of(el):];
2261 if constexpr (SqlInputParameterBinder<FieldType> && !IsAutoIncrementPrimaryKey<FieldType>)
2262 query.Set(FieldNameOf<el>, SqlWildcard);
2263 }
2264#else
2265 EnumerateRecordMembers(record, [&query]<auto I, typename FieldType>(FieldType const& /*field*/) {
2266 if constexpr (SqlInputParameterBinder<FieldType> && !IsAutoIncrementPrimaryKey<FieldType>)
2267 query.Set(FieldNameAt<I, Record>, SqlWildcard);
2268 });
2269#endif
2270
2271 _stmt.Prepare(query);
2272
2273 // The time generated timestamps are inserted with: read once, and alive until the statement has run,
2274 // as the driver reads the bound parameter on execution.
2275 auto const now =
2276 Fill != TimestampFill::None && detail::HasAutoTimestampFields<Record> ? CurrentTimestamp() : SqlDateTime {};
2277
2278#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2279 int i = 1;
2280 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2281 {
2282 using FieldType = typename[:std::meta::type_of(el):];
2283 if constexpr (SqlInputParameterBinder<FieldType> && !IsAutoIncrementPrimaryKey<FieldType>)
2284 {
2285 // The override replaces the generated member only; a PrimaryKey::Manual member is the caller's.
2286 if constexpr (detail::IsAutoAssignPrimaryKeyField<FieldType>::value
2287 && UsePkOverride == PrimaryKeySource::Override)
2288 _stmt.BindInputParameter(i++, *pkOverride, std::meta::identifier_of(el));
2289 else if (FillsTimestamp<Fill>(record.[:el:]))
2290 _stmt.BindInputParameter(i++, now, std::meta::identifier_of(el));
2291 else
2292 _stmt.BindInputParameter(i++, record.[:el:], std::meta::identifier_of(el));
2293 }
2294 }
2295#else
2296 Reflection::CallOnMembers(record,
2297 [this, &pkOverride, &now, i = std::int16_t { 1 }]<typename Name, typename FieldType>(
2298 Name const& name, FieldType const& field) mutable {
2299 if constexpr (SqlInputParameterBinder<FieldType> && !IsAutoIncrementPrimaryKey<FieldType>)
2300 {
2301 // The override replaces the generated member only; a Manual member is the caller's.
2302 if constexpr (detail::IsAutoAssignPrimaryKeyField<FieldType>::value
2303 && UsePkOverride == PrimaryKeySource::Override)
2304 _stmt.BindInputParameter(i++, *pkOverride, name);
2305 else if (FillsTimestamp<Fill>(field))
2306 _stmt.BindInputParameter(i++, now, name);
2307 else
2308 _stmt.BindInputParameter(i++, field, name);
2309 }
2310 });
2311#endif
2312 [[maybe_unused]] auto cursor = _stmt.Execute();
2313
2314 if constexpr (HasAutoIncrementPrimaryKey<Record>)
2315 // LastInsertId() returns size_t; a record whose auto-increment primary key is declared
2316 // narrower (e.g. int32_t, the common SQL Server `int IDENTITY` mapping) would otherwise hit
2317 // a narrowing conversion in brace-init, which is ill-formed and fails under warnings-as-errors
2318 // (MSVC C2397). The narrowing is deliberate here: the caller already chose that column's
2319 // width when declaring the record.
2320 return static_cast<RecordPrimaryKeyType<Record>>(_stmt.LastInsertId(RecordTableName<Record>));
2321 else if constexpr (HasPrimaryKey<Record>)
2322 {
2323 if constexpr (UsePkOverride == PrimaryKeySource::Override)
2324 return *pkOverride; // NOLINT(bugprone-unchecked-optional-access)
2325 else
2326 return RecordPrimaryKeyOf(record).Value();
2327 }
2328 else
2329 return {};
2330}
2331
2332template <typename Record>
2333RecordPrimaryKeyType<Record> DataMapper::CreateExplicit(Record const& record)
2334{
2335 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2336 return CreateInternal<PrimaryKeySource::Record, TimestampFill::Unset>(record);
2337}
2338
2339namespace detail
2340{
2341 /// @brief Whether member field type @p FieldType is an insertable column for a batched CREATE
2342 /// (bindable and not an auto-increment primary key). Single source of truth shared by the INSERT
2343 /// column-list builder and the value-accessor builder, so the bound `?` count and the accessor count
2344 /// cannot drift apart.
2345 template <typename FieldType>
2346 constexpr bool IsBatchInsertColumn = SqlInputParameterBinder<FieldType> && !IsAutoIncrementPrimaryKey<FieldType>;
2347
2348 /// @brief Whether @p FieldType is a SET column for a batched UPDATE (storable, non-primary-key).
2349 template <typename FieldType>
2350 constexpr bool IsBatchUpdateSetColumn = FieldWithStorage<FieldType> && !IsPrimaryKey<FieldType>;
2351
2352 /// @brief Whether @p FieldType is a WHERE (key) column for a batched UPDATE (a primary key).
2353 template <typename FieldType>
2354 constexpr bool IsBatchUpdateWhereColumn = IsPrimaryKey<FieldType>;
2355
2356 /// @brief Column accessor for batched DataMapper operations: maps a record to the value of its
2357 /// I-th member field, returning a reference so the native row-wise batch path binds it in place.
2358 template <std::size_t I>
2359 struct FieldValueAccessor
2360 {
2361 template <typename Record>
2362 decltype(auto) operator()(Record const& record) const
2363 {
2364 return GetRecordMemberAt<I>(record).Value();
2365 }
2366 };
2367
2368 /// Returns a one-element accessor tuple for member I when it is an insertable column (bindable and
2369 /// not an auto-increment primary key), or an empty tuple otherwise — to be flattened via tuple_cat.
2370 template <std::size_t I, typename Record>
2371 auto MakeCreateColumnAccessor()
2372 {
2373 using FieldType = RecordMemberTypeOf<I, Record>;
2374 if constexpr (IsBatchInsertColumn<FieldType>)
2375 return std::tuple<FieldValueAccessor<I>> {};
2376 else
2377 return std::tuple<> {};
2378 }
2379
2380 /// Accessor tuple for the SET clause of a batched UPDATE: storable, non-primary-key columns.
2381 template <std::size_t I, typename Record>
2382 auto MakeUpdateSetAccessor()
2383 {
2384 using FieldType = RecordMemberTypeOf<I, Record>;
2385 if constexpr (IsBatchUpdateSetColumn<FieldType>)
2386 return std::tuple<FieldValueAccessor<I>> {};
2387 else
2388 return std::tuple<> {};
2389 }
2390
2391 /// Accessor tuple for the WHERE clause of a batched UPDATE: primary-key columns.
2392 template <std::size_t I, typename Record>
2393 auto MakeUpdateWhereAccessor()
2394 {
2395 using FieldType = RecordMemberTypeOf<I, Record>;
2396 if constexpr (IsBatchUpdateWhereColumn<FieldType>)
2397 return std::tuple<FieldValueAccessor<I>> {};
2398 else
2399 return std::tuple<> {};
2400 }
2401} // namespace detail
2402
2403template <std::ranges::range Records>
2404void DataMapper::CreateAll(Records const& records)
2405{
2406 static_assert(std::ranges::contiguous_range<Records> && std::ranges::sized_range<Records>,
2407 "CreateAll requires a contiguous, sized range of records (e.g. std::vector, std::array, "
2408 "std::span, or a C array); native row-wise array binding needs the records laid out contiguously.");
2409 using Record = std::remove_cvref_t<std::ranges::range_value_t<Records>>;
2410 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2411
2412 ZoneScopedN("DataMapper::CreateAll");
2413 ZoneTextObject(RecordTableName<Record>);
2414
2415 if (std::ranges::empty(records))
2416 return;
2417
2418 auto const rows = std::span<Record const> { std::ranges::data(records), std::ranges::size(records) };
2419 if constexpr (detail::HasAutoTimestampFields<Record>)
2420 InsertBatch(std::span<Record const> { CopyWithTimestamps<TimestampFill::Unset>(rows) });
2421 else
2422 InsertBatch(rows);
2423}
2424
2425template <typename Record>
2426void DataMapper::InsertBatch(std::span<Record const> records)
2427{
2428 // Build the INSERT once, with the same column set and order as CreateInternal().
2429 auto query = _connection.Query(RecordTableName<Record>).Insert(nullptr);
2430 EnumerateRecordMembers<Record>([&query]<auto I, typename FieldType>() {
2431 if constexpr (detail::IsBatchInsertColumn<FieldType>)
2432 query.Set(FieldNameAt<I, Record>, SqlWildcard);
2433 });
2434 _stmt.Prepare(query);
2435
2436 // Build one value accessor per bound column (same filter/order) and submit the whole batch.
2437 [&]<std::size_t... Is>(std::index_sequence<Is...>) {
2438 std::apply([&](auto const&... accessors) { std::ignore = _stmt.ExecuteBatch(records, accessors...); },
2439 std::tuple_cat(detail::MakeCreateColumnAccessor<Is, Record>()...));
2440 }(std::make_index_sequence<RecordMemberCount<Record>> {});
2441}
2442
2443template <DataMapperOptions QueryOptions, typename Record>
2444RecordPrimaryKeyType<Record> DataMapper::CreateCopyOf(Record const& originalRecord)
2445{
2446 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2447 static_assert(HasPrimaryKey<Record>, "CreateCopyOf requires a record type with a primary key");
2448 static_assert(
2449 HasAutoIncrementPrimaryKey<Record>
2450 || detail::CheckFieldProperty<[]<typename Field>() { return detail::IsAutoAssignPrimaryKeyField<Field>::value; },
2451 Record>,
2452 "CreateCopyOf() needs a primary key the mapper generates (AutoAssign or ServerSideAutoIncrement). A "
2453 "record keyed by PrimaryKey::Manual members only has no key to give the copy - set one on a copy "
2454 "of your own and call Create() instead.");
2455
2456 auto generatedKey = GenerateAutoAssignPrimaryKey(originalRecord);
2457 if (generatedKey)
2458 return CreateInternal<PrimaryKeySource::Override, TimestampFill::All>(originalRecord, generatedKey);
2459
2460 if constexpr (HasAutoIncrementPrimaryKey<Record>)
2461 return CreateInternal<PrimaryKeySource::Record, TimestampFill::All>(originalRecord);
2462
2463 return CreateInternal<PrimaryKeySource::Override, TimestampFill::All>(originalRecord, RecordPrimaryKeyType<Record> {});
2464}
2465
2466template <DataMapperOptions QueryOptions, typename Record>
2467RecordPrimaryKeyType<Record> DataMapper::Create(Record& record)
2468{
2469 static_assert(!std::is_const_v<Record>);
2470 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2471
2472 ZoneScopedN("DataMapper::Create");
2473 ZoneTextObject(RecordTableName<Record>);
2474
2475 auto generatedKey = GenerateAutoAssignPrimaryKey(record);
2476 if (generatedKey)
2477 SetId(record, *generatedKey);
2478
2479 // Stamp the record itself, so the caller sees the timestamps that were inserted.
2480 if constexpr (detail::HasAutoTimestampFields<Record>)
2481 StampTimestamps<TimestampFill::Unset>(record, CurrentTimestamp());
2482
2483 auto pk = CreateInternal<PrimaryKeySource::Record, TimestampFill::None>(record);
2484
2485 if constexpr (HasAutoIncrementPrimaryKey<Record>)
2486 SetId(record, pk);
2487
2488 SetModifiedState<ModifiedState::NotModified>(record);
2489
2490 if constexpr (QueryOptions.loadRelations)
2492
2493 if constexpr (HasPrimaryKey<Record>)
2494 return GetPrimaryKeyField(record);
2495}
2496
2497template <typename Record>
2498bool DataMapper::IsModified(Record const& record) const noexcept
2499{
2500 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2501
2502 bool modified = false;
2503
2504#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2505 auto constexpr ctx = std::meta::access_context::current();
2506 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2507 {
2508 if constexpr (requires { record.[:el:].IsModified(); })
2509 {
2510 modified = modified || record.[:el:].IsModified();
2511 }
2512 }
2513#else
2514 Reflection::CallOnMembers(record, [&modified](auto const& /*name*/, auto const& field) {
2515 if constexpr (requires { field.IsModified(); })
2516 {
2517 modified = modified || field.IsModified();
2518 }
2519 });
2520#endif
2521
2522 return modified;
2523}
2524
2525template <typename Record>
2526 requires HasPrimaryKey<Record>
2527void DataMapper::Update(Record& record)
2528{
2529 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2530
2531 ZoneScopedN("DataMapper::Update");
2532 ZoneTextObject(RecordTableName<Record>);
2533
2534 // Mark the UpdatedAt fields modified with the current time, so the SET clause below writes them.
2535 StampTimestampsForUpdate(record);
2536
2537 auto query = _connection.Query(RecordTableName<Record>).Update();
2538
2539 // Tracks whether the fold below contributed at least one assignment to the SET clause.
2540 // With no assignments the formatter would emit `UPDATE "T" SET WHERE ...`, which every
2541 // driver rejects as a syntax error, so we skip the statement entirely instead.
2542 bool anyFieldModified = false;
2543
2544#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2545 auto constexpr ctx = std::meta::access_context::current();
2546 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2547 {
2548 using FieldType = typename[:std::meta::type_of(el):];
2549 if constexpr (FieldWithStorage<FieldType>)
2550 {
2551 if (record.[:el:].IsModified())
2552 {
2553 query.Set(FieldNameOf<el>, SqlWildcard);
2554 anyFieldModified = true;
2555 }
2556 if constexpr (IsPrimaryKey<FieldType>)
2557 std::ignore = query.Where(FieldNameOf<el>, SqlWildcard);
2558 }
2559 }
2560#else
2561 EnumerateRecordMembers(record, [&query, &anyFieldModified]<size_t I, typename FieldType>(FieldType const& field) {
2562 // for some reason compiler do not want to properly deduce FieldType, so here we
2563 // directly infer the type from the Record type and index
2564 using MemberType = RecordMemberTypeOf<I, Record>;
2565 // Relations (HasMany, HasManyThrough, HasOneThrough, ...) have no column of their own.
2566 if constexpr (FieldWithStorage<MemberType>)
2567 {
2568 if (field.IsModified())
2569 {
2570 query.Set(FieldNameAt<I, Record>, SqlWildcard);
2571 anyFieldModified = true;
2572 }
2573 if constexpr (IsPrimaryKey<MemberType>)
2574 std::ignore = query.Where(FieldNameAt<I, Record>, SqlWildcard);
2575 }
2576 });
2577#endif
2578
2579 // Nothing to write: an UPDATE with an empty SET clause is a no-op by definition.
2580 if (!anyFieldModified)
2581 return;
2582
2583 _stmt.Prepare(query);
2584
2585 std::int16_t i = 1;
2586
2587#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2588 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2589 {
2590 using FieldType = typename[:std::meta::type_of(el):];
2591 // Relations (HasMany, HasManyThrough, HasOneThrough, ...) have no column of their own.
2592 if constexpr (FieldWithStorage<FieldType>)
2593 {
2594 if (record.[:el:].IsModified())
2595 {
2596 _stmt.BindInputParameter(i++, record.[:el:].Value(), FieldNameOf<el>);
2597 }
2598 }
2599 }
2600
2601 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2602 {
2603 using FieldType = typename[:std::meta::type_of(el):];
2604 if constexpr (FieldWithStorage<FieldType>)
2605 {
2606 if constexpr (FieldType::IsPrimaryKey)
2607 {
2608 _stmt.BindInputParameter(i++, record.[:el:].Value(), FieldNameOf<el>);
2609 }
2610 }
2611 }
2612#else
2613 // Bind the SET clause
2614 EnumerateRecordMembers(record, [this, &i]<size_t I, typename FieldType>(FieldType const& field) {
2615 // Relations (HasMany, HasManyThrough, HasOneThrough, ...) have no column of their own.
2617 {
2618 if (field.IsModified())
2619 _stmt.BindInputParameter(i++, field.Value(), FieldNameAt<I, Record>);
2620 }
2621 });
2622
2623 // Bind the WHERE clause
2624 EnumerateRecordMembers(record, [this, &i]<size_t I, typename FieldType>(FieldType const& field) {
2625 if constexpr (IsPrimaryKey<RecordMemberTypeOf<I, Record>>)
2626 _stmt.BindInputParameter(i++, field.Value(), FieldNameAt<I, Record>);
2627 });
2628#endif
2629
2630 [[maybe_unused]] auto cursor = _stmt.Execute();
2631
2632 SetModifiedState<ModifiedState::NotModified>(record);
2633}
2634
2635template <std::ranges::range Records>
2636void DataMapper::UpdateAll(Records const& records)
2637{
2638 static_assert(std::ranges::contiguous_range<Records> && std::ranges::sized_range<Records>,
2639 "UpdateAll requires a contiguous, sized range of records (e.g. std::vector, std::array, "
2640 "std::span, or a C array); native row-wise array binding needs the records laid out contiguously.");
2641 using Record = std::remove_cvref_t<std::ranges::range_value_t<Records>>;
2642 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2643 static_assert(HasPrimaryKey<Record>, "UpdateAll requires a record type with a primary key");
2644
2645 ZoneScopedN("DataMapper::UpdateAll");
2646 ZoneTextObject(RecordTableName<Record>);
2647
2648 if (std::ranges::empty(records))
2649 return;
2650
2651 auto const rows = std::span<Record const> { std::ranges::data(records), std::ranges::size(records) };
2652 if constexpr (detail::HasUpdatedAtTimestampFields<Record>)
2653 UpdateBatch(std::span<Record const> { CopyWithTimestamps<TimestampFill::UpdatedAt>(rows) });
2654 else
2655 UpdateBatch(rows);
2656}
2657
2658template <typename Record>
2659void DataMapper::UpdateBatch(std::span<Record const> records)
2660{
2661 // Build one UPDATE that writes all storable non-primary-key columns, matched on the primary key(s).
2662 auto query = _connection.Query(RecordTableName<Record>).Update();
2663 EnumerateRecordMembers<Record>([&query]<auto I, typename FieldType>() {
2664 if constexpr (detail::IsBatchUpdateSetColumn<FieldType>)
2665 query.Set(FieldNameAt<I, Record>, SqlWildcard);
2666 });
2667 EnumerateRecordMembers<Record>([&query]<auto I, typename FieldType>() {
2668 if constexpr (detail::IsBatchUpdateWhereColumn<FieldType>)
2669 std::ignore = query.Where(FieldNameAt<I, Record>, SqlWildcard);
2670 });
2671 _stmt.Prepare(query);
2672
2673 // Accessor order must match the SQL parameter order: SET columns first, then the WHERE key(s).
2674 [&]<std::size_t... Is>(std::index_sequence<Is...>) {
2675 std::apply([&](auto const&... accessors) { std::ignore = _stmt.ExecuteBatch(records, accessors...); },
2676 std::tuple_cat(detail::MakeUpdateSetAccessor<Is, Record>()...,
2677 detail::MakeUpdateWhereAccessor<Is, Record>()...));
2678 }(std::make_index_sequence<RecordMemberCount<Record>> {});
2679}
2680
2681template <typename Record>
2682std::size_t DataMapper::Delete(Record const& record)
2683{
2684 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2685
2686 ZoneScopedN("DataMapper::Delete");
2687 ZoneTextObject(RecordTableName<Record>);
2688
2689 auto query = _connection.Query(RecordTableName<Record>).Delete();
2690
2691#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2692 auto constexpr ctx = std::meta::access_context::current();
2693 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2694 {
2695 using FieldType = typename[:std::meta::type_of(el):];
2696 // Relations (HasMany, HasManyThrough, HasOneThrough, ...) have no column of their own.
2697 if constexpr (FieldWithStorage<FieldType>)
2698 if constexpr (FieldType::IsPrimaryKey)
2699 std::ignore = query.Where(FieldNameOf<el>, SqlWildcard);
2700 }
2701#else
2702 EnumerateRecordMembers(record, [&query]<size_t I, typename FieldType>(FieldType const& /*field*/) {
2703 if constexpr (IsPrimaryKey<RecordMemberTypeOf<I, Record>>)
2704 std::ignore = query.Where(FieldNameAt<I, Record>, SqlWildcard);
2705 });
2706#endif
2707
2708 _stmt.Prepare(query);
2709
2710#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
2711 std::int16_t i = 1;
2712 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
2713 {
2714 using FieldType = typename[:std::meta::type_of(el):];
2715 if constexpr (FieldWithStorage<FieldType>)
2716 {
2717 if constexpr (FieldType::IsPrimaryKey)
2718 {
2719 _stmt.BindInputParameter(i++, record.[:el:].Value(), FieldNameOf<el>);
2720 }
2721 }
2722 }
2723#else
2724 // Bind the WHERE clause
2726 [this, i = std::int16_t { 1 }]<size_t I, typename FieldType>(FieldType const& field) mutable {
2727 if constexpr (IsPrimaryKey<RecordMemberTypeOf<I, Record>>)
2728 _stmt.BindInputParameter(i++, field.Value(), FieldNameAt<I, Record>);
2729 });
2730#endif
2731
2732 auto cursor = _stmt.Execute();
2733
2734 return cursor.NumRowsAffected();
2735}
2736
2737template <typename Record, DataMapperOptions QueryOptions, typename... PrimaryKeyTypes>
2738std::optional<Record> DataMapper::QuerySingle(PrimaryKeyTypes&&... primaryKeys)
2739{
2740 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2741
2742 ZoneScopedN("DataMapper::QuerySingle(PK)");
2743 ZoneTextObject(RecordTableName<Record>);
2744
2745 // Starter doesn't expose finalizers / Where until at least one column is
2746 // projected. The reflection enumeration below is constexpr-conditional, so
2747 // which iteration adds the first column isn't known up front — promote on the
2748 // first storage field via the returned Builder&, then reuse that pointer.
2749 auto selectStarter = _connection.Query(RecordTableName<Record>).Select();
2750 SqlSelectQueryBuilder* queryBuilder = nullptr;
2751 // Project exactly the members the read side (detail::ReadSingleResult) consumes as columns —
2752 // FieldWithStorage alone would drop plain bindable members such as `std::string note;`.
2753 EnumerateRecordMembers<Record>([&]<size_t I, typename FieldType>() {
2754 if constexpr (RecordColumnMember<FieldType>)
2755 {
2756 if (queryBuilder == nullptr)
2757 queryBuilder = &selectStarter.Field(FieldNameAt<I, Record>);
2758 else
2759 queryBuilder->Field(FieldNameAt<I, Record>);
2760
2761 if constexpr (FieldWithStorage<FieldType>)
2762 {
2763 if constexpr (FieldType::IsPrimaryKey)
2764 std::ignore = queryBuilder->Where(FieldNameAt<I, Record>, SqlWildcard);
2765 }
2766 }
2767 });
2768
2769 _stmt.Prepare(queryBuilder->First());
2770 auto reader = _stmt.Execute(std::forward<PrimaryKeyTypes>(primaryKeys)...);
2771
2772 // A single return statement at the end is deliberate, not stylistic: a composite foreign key
2773 // configured below (ConfigureRelationAutoLoading) captures a pointer to *resultRecord. An earlier
2774 // `return std::nullopt;` here defeats NRVO in both GCC and Clang (verified: it forces a move-construct
2775 // into the caller's storage at a new address), which would leave that captured pointer dangling.
2776 auto resultRecord = std::optional<Record> { detail::MakeUninitialized<Record>() };
2777 if (detail::ReadSingleResult(_stmt.Connection(), reader, *resultRecord))
2778 {
2779 SetModifiedState<ModifiedState::NotModified>(resultRecord.value());
2780
2781 if constexpr (QueryOptions.loadRelations)
2782 ConfigureRelationAutoLoading(*resultRecord);
2783 }
2784 else
2785 {
2786 resultRecord.reset();
2787 }
2788
2789 return resultRecord;
2790}
2791
2792template <typename Record, typename... Args>
2793std::optional<Record> DataMapper::QuerySingle(SqlSelectQueryBuilder selectQuery, Args&&... args)
2794{
2795 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2796
2797 ZoneScopedN("DataMapper::QuerySingle(Builder)");
2798 ZoneTextObject(RecordTableName<Record>);
2799
2800 // Same projection predicate as the read side; see the note in QuerySingle(PrimaryKeyTypes...).
2801 EnumerateRecordMembers<Record>([&]<size_t I, typename FieldType>() {
2802 if constexpr (RecordColumnMember<FieldType>)
2803 selectQuery.Field(SqlQualifiedTableColumnName { RecordTableName<Record>, FieldNameAt<I, Record> });
2804 });
2805 auto const composedSql = selectQuery.First().ToSql();
2806 ZoneTextObject(composedSql);
2807 _stmt.Prepare(composedSql);
2808 auto reader = _stmt.Execute(std::forward<Args>(args)...);
2809
2810 auto resultRecord = std::optional<Record> { detail::MakeUninitialized<Record>() };
2811 if (!detail::ReadSingleResult(_stmt.Connection(), reader, *resultRecord))
2812 return std::nullopt;
2813
2814 if (resultRecord)
2815 SetModifiedState<ModifiedState::NotModified>(resultRecord.value());
2816
2817 return resultRecord;
2818}
2819
2820// TODO: Provide Query(QueryBuilder, ...) method variant
2821
2822/// Queries multiple records from the database using a composed query and optional input parameters.
2823template <typename Record, DataMapperOptions QueryOptions, typename... InputParameters>
2824inline LIGHTWEIGHT_FORCE_INLINE std::vector<Record> DataMapper::Query(
2825 SqlSelectQueryBuilder::ComposedQuery const& selectQuery, InputParameters&&... inputParameters)
2826{
2827 static_assert(DataMapperRecord<Record> || std::same_as<Record, SqlVariantRow>, "Record must satisfy DataMapperRecord");
2828
2829 ZoneScopedN("DataMapper::Query(ComposedQuery)");
2830 return Query<Record, QueryOptions>(selectQuery.ToSql(), std::forward<InputParameters>(inputParameters)...);
2831}
2832
2833template <typename Record, DataMapperOptions QueryOptions, typename... InputParameters>
2834std::vector<Record> DataMapper::Query(std::string_view sqlQueryString, InputParameters&&... inputParameters)
2835{
2836 ZoneScopedN("DataMapper::Query(string)");
2837 ZoneTextObject(sqlQueryString);
2838
2839 auto result = std::vector<Record> {};
2840 if constexpr (std::same_as<Record, SqlVariantRow>)
2841 {
2842 _stmt.Prepare(sqlQueryString);
2843 // Through the variant row cursor, which keeps the result set on the per-row path where a typed read
2844 // reports a cell not of its column's type as NULL (SQLite): the cell's text comes back, not NULL.
2845 for (auto& row: SqlVariantRowCursor { _stmt.Execute(std::forward<InputParameters>(inputParameters)...) })
2846 result.emplace_back(std::move(row));
2847 }
2848 else
2849 {
2850 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2851
2852 bool const canSafelyBindOutputColumns =
2853 detail::CanSafelyBindOutputColumns<Record>(_stmt.Connection().ReadsBoundColumnsAgain());
2854
2855 _stmt.Prepare(sqlQueryString);
2856 auto reader = _stmt.Execute(std::forward<InputParameters>(inputParameters)...);
2857
2858 for (;;)
2859 {
2860 auto& record = detail::EmplaceBackUninitialized(result);
2861
2862 if (canSafelyBindOutputColumns)
2863 BindOutputColumns(record, reader);
2864
2865 if (!reader.FetchRow())
2866 break;
2867
2868 if (!canSafelyBindOutputColumns)
2869 detail::GetAllColumns(reader, record);
2870 }
2871
2872 // Drop the last record, which we failed to fetch (End of result set).
2873 result.pop_back();
2874
2875 for (auto& record: result)
2876 {
2877 SetModifiedState<ModifiedState::NotModified>(record);
2878 if constexpr (QueryOptions.loadRelations)
2880 }
2881 }
2882
2883 return result;
2884}
2885
2886template <typename First, typename Second, typename... Rest, DataMapperOptions QueryOptions>
2887 requires DataMapperRecord<First> && DataMapperRecord<Second> && DataMapperRecords<Rest...>
2888std::vector<std::tuple<First, Second, Rest...>> DataMapper::Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery)
2889{
2890 using value_type = std::tuple<First, Second, Rest...>;
2891 auto result = std::vector<value_type> {};
2892
2893 ZoneScopedN("DataMapper::Query(ComposedQuery -> tuple)");
2894 auto const tupleSql = selectQuery.ToSql();
2895 ZoneTextObject(tupleSql);
2896 _stmt.Prepare(tupleSql);
2897 auto reader = _stmt.Execute();
2898
2899 // The 1-based result set index of the first column belonging to the I-th sub-record. The projection
2900 // (SqlSelectQueryBuilder::Fields<Records...>) emits one entry per RecordColumnMember, so relation
2901 // members contribute no column and RecordMemberCount would over-count the preceding sub-records.
2902 constexpr auto calculateOffset = []<size_t I, typename Tuple>() {
2903 size_t offset = 1;
2904
2905 if constexpr (I > 0)
2906 {
2907 [&]<size_t... Indices>(std::index_sequence<Indices...>) {
2908 ((Indices < I ? (offset += RecordColumnCount<std::tuple_element_t<Indices, Tuple>>) : 0), ...);
2909 }(std::make_index_sequence<I> {});
2910 }
2911 return offset;
2912 };
2913
2914 auto const BindElements = [&](auto& record) {
2915 Reflection::template_for<0, std::tuple_size_v<value_type>>([&]<auto I>() {
2916 using TupleElement = std::decay_t<std::tuple_element_t<I, value_type>>;
2917 auto& element = std::get<I>(record);
2918 constexpr size_t offset = calculateOffset.template operator()<I, value_type>();
2919 this->BindOutputColumns<TupleElement, offset>(element, reader);
2920 });
2921 };
2922
2923 auto const GetElements = [&](auto& record) {
2924 Reflection::template_for<0, std::tuple_size_v<value_type>>([&]<auto I>() {
2925 auto& element = std::get<I>(record);
2926 constexpr size_t offset = calculateOffset.template operator()<I, value_type>();
2927 detail::GetAllColumns(reader, element, offset - 1);
2928 });
2929 };
2930
2931 bool const canSafelyBindOutputColumns = [&]() {
2932 bool result = true;
2933 Reflection::template_for<0, std::tuple_size_v<value_type>>([&]<auto I>() {
2934 using TupleElement = std::decay_t<std::tuple_element_t<I, value_type>>;
2935 result &= detail::CanSafelyBindOutputColumns<TupleElement>(_stmt.Connection().ReadsBoundColumnsAgain());
2936 });
2937 return result;
2938 }();
2939
2940 for (;;)
2941 {
2942 auto& record = detail::EmplaceBackUninitialized(result);
2943
2944 if (canSafelyBindOutputColumns)
2945 BindElements(record);
2946
2947 if (!reader.FetchRow())
2948 break;
2949
2950 if (!canSafelyBindOutputColumns)
2951 GetElements(record);
2952 }
2953
2954 // Drop the last record, which we failed to fetch (End of result set).
2955 result.pop_back();
2956
2957 for (auto& record: result)
2958 {
2959 Reflection::template_for<0, std::tuple_size_v<value_type>>([&]<auto I>() {
2960 auto& element = std::get<I>(record);
2961 SetModifiedState<ModifiedState::NotModified>(element);
2962 if constexpr (QueryOptions.loadRelations)
2963 {
2965 }
2966 });
2967 }
2968
2969 return result;
2970}
2971
2972template <typename ElementMask, typename Record, DataMapperOptions QueryOptions, typename... InputParameters>
2973std::vector<Record> DataMapper::Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery,
2974 InputParameters&&... inputParameters)
2975{
2976 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
2977
2978 ZoneScopedN("DataMapper::Query(ComposedQuery, ElementMask)");
2979 auto const maskedSql = selectQuery.ToSql();
2980 ZoneTextObject(maskedSql);
2981 _stmt.Prepare(maskedSql);
2982
2983 auto records = std::vector<Record> {};
2984
2985 // TODO: We could optimize this further by only considering ElementMask fields in Record.
2986 bool const canSafelyBindOutputColumns =
2987 detail::CanSafelyBindOutputColumns<Record>(_stmt.Connection().ReadsBoundColumnsAgain());
2988
2989 auto reader = _stmt.Execute(std::forward<InputParameters>(inputParameters)...);
2990
2991 for (;;)
2992 {
2993 auto& record = detail::EmplaceBackUninitialized(records);
2994
2995 if (canSafelyBindOutputColumns)
2996 BindOutputColumns<ElementMask>(record, reader);
2997
2998 if (!reader.FetchRow())
2999 break;
3000
3001 if (!canSafelyBindOutputColumns)
3002 detail::GetAllColumns<ElementMask>(reader, record);
3003 }
3004
3005 // Drop the last record, which we failed to fetch (End of result set).
3006 records.pop_back();
3007
3008 for (auto& record: records)
3009 {
3010 SetModifiedState<ModifiedState::NotModified>(record);
3011 if constexpr (QueryOptions.loadRelations)
3013 }
3014
3015 return records;
3016}
3017
3018template <DataMapper::ModifiedState state, typename Record>
3019void DataMapper::SetModifiedState(Record& record) noexcept
3020{
3021 static_assert(!std::is_const_v<Record>);
3022 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3023
3024 EnumerateRecordMembers(record, []<size_t I, typename FieldType>(FieldType& field) {
3025 if constexpr (requires { field.SetModified(false); })
3026 {
3027 if constexpr (state == ModifiedState::Modified)
3028 field.SetModified(true);
3029 else
3030 field.SetModified(false);
3031 }
3032 });
3033}
3034
3035template <typename Record, typename Callable>
3036inline LIGHTWEIGHT_FORCE_INLINE void CallOnPrimaryKey(Record& record, Callable const& callable)
3037{
3038 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3039
3040 EnumerateRecordMembers(record, [&]<size_t I, typename FieldType>(FieldType& field) {
3041 if constexpr (IsField<FieldType>)
3042 {
3043 if constexpr (FieldType::IsPrimaryKey)
3044 {
3045 return callable.template operator()<I, FieldType>(field);
3046 }
3047 }
3048 });
3049}
3050
3051template <typename Record, typename Callable>
3052inline LIGHTWEIGHT_FORCE_INLINE void CallOnPrimaryKey(Callable const& callable)
3053{
3054 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3055
3056 EnumerateRecordMembers<Record>([&]<size_t I, typename FieldType>() {
3057 if constexpr (IsField<FieldType>)
3058 {
3059 if constexpr (FieldType::IsPrimaryKey)
3060 {
3061 return callable.template operator()<I, FieldType>();
3062 }
3063 }
3064 });
3065}
3066
3067template <typename Record, typename Callable>
3068inline LIGHTWEIGHT_FORCE_INLINE void CallOnBelongsTo(Callable const& callable)
3069{
3070 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3071
3072 EnumerateRecordMembers<Record>([&]<size_t I, typename FieldType>() {
3073 if constexpr (IsBelongsTo<FieldType>)
3074 {
3075 return callable.template operator()<I, FieldType>();
3076 }
3077 });
3078}
3079
3080template <typename FieldType>
3081std::shared_ptr<typename FieldType::ReferencedRecord> DataMapper::LoadCompositeForeignKeyRecord(
3082 FieldType::OrderedValueType const& keys)
3083{
3084 using ReferencedRecord = FieldType::ReferencedRecord;
3085
3086 auto loaded =
3087 std::apply([this](auto const&... key) { return this->template QuerySingle<ReferencedRecord>(key...); }, keys);
3088 if (!loaded)
3089 return {};
3090 return std::make_shared<ReferencedRecord>(std::move(*loaded));
3091}
3092
3093template <typename Record, typename FieldType>
3094void DataMapper::LoadCompositeForeignKey(Record const& record, FieldType& field)
3095{
3096 using ReferencedRecord = FieldType::ReferencedRecord;
3097
3098 ZoneScopedN("DataMapper::LoadCompositeForeignKey");
3099 ZoneTextObject(RecordTableName<ReferencedRecord>);
3100
3101 // OrderedValuesOf() rather than ValuesOf(): QuerySingle emits one WHERE predicate per primary key
3102 // member of the referenced record, in that record's member declaration order, and binds its
3103 // arguments positionally - so the values have to be permuted into that order first. See
3104 // CompositeKeyOrderingTests.cpp.
3105 auto loaded = LoadCompositeForeignKeyRecord<FieldType>(FieldType::OrderedValuesOf(record));
3106
3107 // A missing target row leaves the relation unloaded rather than throwing here: eagerly loading a
3108 // dangling foreign key is a data-integrity problem to surface at the accessor, which is where the
3109 // lazy path reports it too.
3110 if (!loaded)
3111 {
3113 std::format("Loading composite foreign key failed for {}", RecordTableName<ReferencedRecord>));
3114 return;
3115 }
3116
3117 field.EmplaceRecord(std::move(loaded));
3118}
3119
3120template <typename FieldType>
3121std::optional<typename FieldType::ReferencedRecord> DataMapper::LoadBelongsTo(FieldType::ValueType value)
3122{
3123 using ReferencedRecord = FieldType::ReferencedRecord;
3124
3125 ZoneScopedN("DataMapper::LoadBelongsTo");
3126 ZoneTextObject(RecordTableName<ReferencedRecord>);
3127
3128 std::optional<ReferencedRecord> record { std::nullopt };
3129
3130 // A NULL foreign key references nothing - that is the relation being empty, not a failed load.
3131 if constexpr (FieldType::IsOptional)
3132 if (!value.has_value())
3133 return record;
3134
3135#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
3136 auto constexpr ctx = std::meta::access_context::current();
3137 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^ReferencedRecord, ctx)))
3138 {
3139 using BelongsToFieldType = typename[:std::meta::type_of(el):];
3140 if constexpr (IsField<BelongsToFieldType>)
3141 if constexpr (BelongsToFieldType::IsPrimaryKey)
3142 {
3143 if (auto result = QuerySingle<ReferencedRecord>(value); result)
3144 record = std::move(result);
3145 else
3147 std::format("Loading BelongsTo failed for {}", RecordTableName<ReferencedRecord>));
3148 }
3149 }
3150#else
3151 CallOnPrimaryKey<ReferencedRecord>([&]<size_t PrimaryKeyIndex, typename PrimaryKeyType>() {
3152 if (auto result = QuerySingle<ReferencedRecord>(value); result)
3153 record = std::move(result);
3154 else
3156 std::format("Loading BelongsTo failed for {}", RecordTableName<ReferencedRecord>));
3157 });
3158#endif
3159 return record;
3160}
3161
3162template <typename Record, typename OtherRecord, auto InverseSelector, typename Callable>
3163void DataMapper::CallOnHasMany(Record& record, Callable const& callback)
3164{
3165 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3166 static_assert(DataMapperRecord<OtherRecord>, "OtherRecord must satisfy DataMapperRecord");
3167
3168 using FieldType = HasMany<OtherRecord, InverseSelector>;
3169 using ReferencedRecord = FieldType::ReferencedRecord;
3170
3171 CallOnPrimaryKey(record, [&]<size_t PrimaryKeyIndex, typename PrimaryKeyType>(PrimaryKeyType const& primaryKeyField) {
3172 auto query = BuildHasManySelectQuery<Record, ReferencedRecord, InverseSelector>();
3173 callback(query, primaryKeyField);
3174 });
3175}
3176
3177template <typename OwnerRecord, typename OtherRecord, auto InverseSelector>
3178SqlSelectQueryBuilder DataMapper::BuildHasManySelectQuery()
3179{
3180 return BuildRecordSelectQuery<OtherRecord>()
3181 .Where(InverseBelongsToFieldNameOf<OwnerRecord, OtherRecord, InverseSelector>, SqlWildcard)
3182 .OrderBy(FieldNameAt<RecordPrimaryKeyIndex<OtherRecord>, OtherRecord>);
3183}
3184
3185template <typename Record, typename OtherRecord, auto InverseSelector>
3186void DataMapper::LoadHasMany(Record& record, HasMany<OtherRecord, InverseSelector>& field)
3187{
3188 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3189 static_assert(DataMapperRecord<OtherRecord>, "OtherRecord must satisfy DataMapperRecord");
3190
3191 ZoneScopedN("DataMapper::LoadHasMany");
3192 ZoneTextObject(RecordTableName<OtherRecord>);
3193
3194 CallOnHasMany<Record, OtherRecord, InverseSelector>(
3195 record, [&](SqlSelectQueryBuilder selectQuery, auto& primaryKeyField) {
3196 field.Emplace(detail::ToSharedPtrList(Query<OtherRecord>(selectQuery.All(), primaryKeyField.Value())));
3197 });
3198}
3199
3200namespace detail
3201{
3202 /// @brief Invokes @p callable once per chunk of at most @p chunkSize consecutive elements of @p values.
3203 ///
3204 /// Used to keep a generated `WHERE ... IN (...)` predicate inside what the dialect accepts (see
3205 /// @ref SqlQueryFormatter::MaxInPredicateValues) while still resolving a whole batch in a number of
3206 /// queries that depends on the chunk size, not on the number of records.
3207 ///
3208 /// @param values The values to split.
3209 /// @param chunkSize Maximum number of values per chunk; zero is treated as "all in one chunk".
3210 /// @param callable Invoked with a `std::span` over each chunk, in order.
3211 template <typename T, typename Callable>
3212 void ForEachChunk(std::span<T const> values, size_t chunkSize, Callable const& callable)
3213 {
3214 auto const stride = chunkSize == 0 ? values.size() : chunkSize;
3215 for (size_t offset = 0; offset < values.size(); offset += stride)
3216 callable(values.subspan(offset, (std::min) (stride, values.size() - offset)));
3217 }
3218} // namespace detail
3219
3220template <typename Record>
3221SqlSelectQueryBuilder DataMapper::BuildRecordSelectQuery()
3222{
3223 return _connection.Query(RecordTableName<Record>).Select().Build([](auto& query) {
3224 EnumerateRecordMembers<Record>([&query]<size_t I, typename FieldType>() {
3225 if constexpr (FieldWithStorage<FieldType>)
3226 query.Field(FieldNameAt<I, Record>);
3227 });
3228 });
3229}
3230
3231template <typename Record, size_t FieldIndex>
3232void DataMapper::PreloadRelation(std::span<Record* const> records)
3233{
3234 using FieldType = RecordMemberTypeOf<FieldIndex, Record>;
3235
3236 static_assert(IsBelongsTo<FieldType> || IsHasMany<FieldType>,
3237 "Eager loading via With<>() is supported for BelongsTo and HasMany relations. "
3238 "HasOneThrough, HasManyThrough and CompositeForeignKey still load on demand.");
3239
3240 // Defensive rather than reachable: every caller already returns on an empty batch
3241 // (RunRelationPreloaders, PreloadAllRelations, and the `targets.empty()` guards in
3242 // PreloadRelationPath / PreloadAllRelations). Kept so a future caller cannot trip over it, which
3243 // is also why coverage reports never mark this line.
3244 if (records.empty())
3245 return;
3246
3247 if constexpr (IsBelongsTo<FieldType>)
3248 PreloadBelongsTo<Record, FieldIndex>(records);
3249 else if constexpr (IsHasMany<FieldType>)
3250 PreloadHasMany<Record, FieldIndex>(records);
3251}
3252
3253template <typename Record, size_t FieldIndex>
3254auto DataMapper::CollectRelationTargets(std::span<Record* const> records)
3255{
3256 using FieldType = RecordMemberTypeOf<FieldIndex, Record>;
3257 using TargetRecord = FieldType::ReferencedRecord;
3258
3259 auto targets = std::vector<TargetRecord*> {};
3260 targets.reserve(records.size());
3261
3262 for (auto* record: records)
3263 {
3264 auto& field = GetRecordMemberAt<FieldIndex>(*record);
3265 if constexpr (IsBelongsTo<FieldType>)
3266 {
3267 // LoadedRecord(), not Record(): asking through the accessor would run the on-demand
3268 // loader for exactly the rows the batch failed to resolve, one query at a time.
3269 if (auto* target = field.LoadedRecord(); target != nullptr)
3270 targets.emplace_back(target);
3271 }
3272 else if constexpr (IsHasMany<FieldType>)
3273 {
3274 if (auto* loaded = field.LoadedRecords(); loaded != nullptr)
3275 for (auto& element: *loaded)
3276 targets.emplace_back(element.get());
3277 }
3278 }
3279
3280 return targets;
3281}
3282
3283template <typename Record, size_t FieldIndex, auto... RestOfPath>
3284void DataMapper::PreloadRelationPath(std::span<Record* const> records)
3285{
3286 PreloadRelation<Record, FieldIndex>(records);
3287
3288 if constexpr (sizeof...(RestOfPath) > 0)
3289 {
3290 using FieldType = RecordMemberTypeOf<FieldIndex, Record>;
3291 using TargetRecord = FieldType::ReferencedRecord;
3292
3293 auto targets = CollectRelationTargets<Record, FieldIndex>(records);
3294 if (targets.empty())
3295 return;
3296
3297 // Every owner holds its own copy of a BelongsTo target, so the same underlying row can
3298 // appear many times here. That is not wasted work: the level below deduplicates the keys
3299 // before querying, so the row is still fetched once and then handed to each copy.
3300 // The static_assert below is what keeps the path honest: without it, a path element naming a
3301 // member of some *other* record still compiles, because MemberIndexOf<> yields that member's
3302 // index within its own class, which is then read as an index into TargetRecord - silently
3303 // eager-loading whatever relation happens to sit at the same position (say
3304 // `With<&Track::album, &Track::genre>()` resolving Album's member 2).
3305 [&]<auto NextField, auto... Rest>() {
3306#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
3307 static_assert(std::same_as<typename[:std::meta::parent_of(NextField):], TargetRecord>,
3308 "Each relation named after the first in With<>() must be a member of the "
3309 "preceding relation's referenced record");
3310#else
3311 static_assert(std::same_as<MemberClassType<std::remove_cv_t<decltype(NextField)>>, TargetRecord>,
3312 "Each relation named after the first in With<>() must be a member of the "
3313 "preceding relation's referenced record");
3314#endif
3315 PreloadRelationPath<TargetRecord, MemberIndexOf<NextField>, Rest...>(std::span<TargetRecord* const> { targets });
3316 }.template operator()<RestOfPath...>();
3317 }
3318}
3319
3320template <typename Record, size_t Depth>
3321void DataMapper::PreloadAllRelations(std::span<Record* const> records)
3322{
3323 if constexpr (Depth == 0)
3324 return;
3325 else
3326 {
3327 // As in PreloadRelation: both callers (RunRelationPreloaders and the recursive descent below)
3328 // already guard against an empty batch, so this is belt-and-braces and stays uncovered.
3329 if (records.empty())
3330 return;
3331
3332 Reflection::template_for<0, RecordMemberCount<Record>>([&]<auto I>() {
3333 using FieldType = RecordMemberTypeOf<I, Record>;
3334 // Relations the batched loaders do not cover are left to their on-demand loaders rather
3335 // than failing the whole query: this option means "load what can be loaded in bulk".
3336 if constexpr (IsBelongsTo<FieldType> || IsHasMany<FieldType>)
3337 {
3338 PreloadRelation<Record, I>(records);
3339
3340 if constexpr (Depth > 1)
3341 {
3342 using TargetRecord = FieldType::ReferencedRecord;
3343 auto targets = CollectRelationTargets<Record, I>(records);
3344 if (!targets.empty())
3345 PreloadAllRelations<TargetRecord, Depth - 1>(std::span<TargetRecord* const> { targets });
3346 }
3347 }
3348 });
3349 }
3350}
3351
3352template <typename Record, size_t FieldIndex>
3353void DataMapper::PreloadBelongsTo(std::span<Record* const> records)
3354{
3355 using FieldType = RecordMemberTypeOf<FieldIndex, Record>;
3356 using ReferencedRecord = FieldType::ReferencedRecord;
3357 using KeyType = RecordPrimaryKeyType<ReferencedRecord>;
3358
3359 static_assert(HasPrimaryKey<ReferencedRecord>,
3360 "Eager loading a BelongsTo requires the referenced record to have a primary key");
3361
3362 ZoneScopedN("DataMapper::PreloadBelongsTo");
3363 ZoneTextObject(RecordTableName<ReferencedRecord>);
3364
3365 auto const primaryKeyOf = [](ReferencedRecord const& record) {
3366 return GetPrimaryKeyField(record);
3367 };
3368
3369 // The distinct, non-NULL foreign keys of the batch. Sorted and deduplicated rather than hashed:
3370 // ordering is all a key column type has to provide, while std::hash is not specialized for every
3371 // one of them. The deduplication is what makes this cheaper than the row count - many rows
3372 // commonly point at the same parent, which is then fetched once instead of once per row.
3373 auto keys = std::vector<KeyType> {};
3374 keys.reserve(records.size());
3375 for (auto const* record: records)
3376 {
3377 auto const& field = GetRecordMemberAt<FieldIndex>(*record);
3378 // Already resolved - by a named With<>() path, or by an outer level of the depth walk. Asking
3379 // again would be a second query for a row that is already in memory.
3380 if (field.LoadedRecord() != nullptr)
3381 continue;
3382
3383 auto const& value = field.Value();
3384 if constexpr (FieldType::IsOptional)
3385 {
3386 if (value.has_value())
3387 keys.emplace_back(*value);
3388 }
3389 else
3390 keys.emplace_back(value);
3391 }
3392 std::ranges::sort(keys);
3393 keys.erase(std::ranges::unique(keys).begin(), keys.end());
3394 if (keys.empty())
3395 return;
3396
3397 auto loaded = std::vector<ReferencedRecord> {};
3398 loaded.reserve(keys.size());
3399 detail::ForEachChunk(std::span<KeyType const> { keys },
3400 _connection.QueryFormatter().MaxInPredicateValues(),
3401 [&](std::span<KeyType const> chunk) {
3402 auto selectQuery = BuildRecordSelectQuery<ReferencedRecord>().WhereIn(
3403 FieldNameAt<RecordPrimaryKeyIndex<ReferencedRecord>, ReferencedRecord>, chunk);
3404 auto rows = Query<ReferencedRecord>(selectQuery.All());
3405 loaded.insert(
3406 loaded.end(), std::make_move_iterator(rows.begin()), std::make_move_iterator(rows.end()));
3407 });
3408
3409 std::ranges::sort(loaded, {}, primaryKeyOf);
3410
3411 for (auto* record: records)
3412 {
3413 auto& field = GetRecordMemberAt<FieldIndex>(*record);
3414 // Only reachable from a batch mixing already-loaded and unloaded records: the key-collection
3415 // loop above skips the loaded ones, and a batch in which *every* record is loaded has already
3416 // returned at the `keys.empty()` check. No current call path builds such a mix, so this arm is
3417 // not covered by the suite.
3418 if (field.LoadedRecord() != nullptr)
3419 continue;
3420
3421 auto const& value = field.Value();
3422 if constexpr (FieldType::IsOptional)
3423 if (!value.has_value())
3424 continue;
3425
3426 auto const key = [&] {
3427 if constexpr (FieldType::IsOptional)
3428 return *value;
3429 else
3430 return value;
3431 }();
3432
3433 auto const it = std::ranges::lower_bound(loaded, key, {}, primaryKeyOf);
3434 // A foreign key pointing at a row that is not there is left unloaded rather than adopted as
3435 // empty: a missing target row is a data-integrity problem for the accessor to surface, which
3436 // is also what the on-demand path does.
3437 if (it != loaded.end() && primaryKeyOf(*it) == key)
3438 field.AdoptFetchedRecord(*it);
3439 }
3440}
3441
3442template <typename Record, size_t FieldIndex>
3443void DataMapper::PreloadHasMany(std::span<Record* const> records)
3444{
3445 using FieldType = RecordMemberTypeOf<FieldIndex, Record>;
3446 using ReferencedRecord = FieldType::ReferencedRecord;
3447 using ReferencedRecordList = FieldType::ReferencedRecordList;
3448 using KeyType = RecordPrimaryKeyType<Record>;
3449
3450 static_assert(HasPrimaryKey<Record>, "Eager loading a HasMany requires the owning record to have a primary key");
3451
3452 ZoneScopedN("DataMapper::PreloadHasMany");
3453 ZoneTextObject(RecordTableName<ReferencedRecord>);
3454
3455 // Every fetched child carries its owner's key in the BelongsTo that backs this relation; that is
3456 // what assigns the row to an owner below, without a second query to find out.
3457 constexpr size_t InverseIndex = InverseBelongsToIndexOf<Record, ReferencedRecord, FieldType::InverseSelector>;
3458
3459 auto keys = std::vector<KeyType> {};
3460 keys.reserve(records.size());
3461 for (auto* record: records)
3462 // See PreloadBelongsTo: a list already in memory is not fetched again.
3463 if (GetRecordMemberAt<FieldIndex>(*record).LoadedRecords() == nullptr)
3464 keys.emplace_back(GetPrimaryKeyField(*record));
3465 std::ranges::sort(keys);
3466 keys.erase(std::ranges::unique(keys).begin(), keys.end());
3467 if (keys.empty())
3468 return;
3469
3470 // One bucket per distinct owner key, in the same sorted order, so a child row finds its owner by
3471 // binary search rather than by scanning the batch (which would be quadratic in the row count).
3472 auto buckets = std::vector<ReferencedRecordList> {};
3473 buckets.resize(keys.size());
3474
3475 detail::ForEachChunk(
3476 std::span<KeyType const> { keys },
3477 _connection.QueryFormatter().MaxInPredicateValues(),
3478 [&](std::span<KeyType const> chunk) {
3479 auto selectQuery =
3480 BuildRecordSelectQuery<ReferencedRecord>()
3481 .WhereIn(InverseBelongsToFieldNameOf<Record, ReferencedRecord, FieldType::InverseSelector>, chunk)
3482 .OrderBy(FieldNameAt<RecordPrimaryKeyIndex<ReferencedRecord>, ReferencedRecord>);
3483 for (auto& child: Query<ReferencedRecord>(selectQuery.All()))
3484 {
3485 // The inverse BelongsTo holds the owner's key, or an optional of it when the foreign
3486 // key is nullable; a NULL there is a child no owner in the batch can claim.
3487 std::optional<KeyType> const ownerKey = GetRecordMemberAt<InverseIndex>(child).Value();
3488 if (!ownerKey.has_value())
3489 continue;
3490
3491 auto const it = std::ranges::lower_bound(keys, *ownerKey);
3492 if (it != keys.end() && *it == *ownerKey)
3493 buckets[static_cast<size_t>(std::distance(keys.begin(), it))].emplace_back(
3494 std::make_shared<ReferencedRecord>(std::move(child)));
3495 }
3496 });
3497
3498 for (auto* record: records)
3499 {
3500 auto& field = GetRecordMemberAt<FieldIndex>(*record);
3501 // See PreloadBelongsTo: reachable only from a batch mixing loaded and unloaded records, which
3502 // no current call path produces - a wholly-loaded batch returns at the `keys.empty()` check.
3503 if (field.LoadedRecords() != nullptr)
3504 continue;
3505
3506 // Likewise unreachable today: every record that got past the check above contributed its key
3507 // to `keys` in the collection loop, so the lookup cannot miss. Kept as a guard for a future
3508 // caller that hands in a batch whose keys were filtered elsewhere.
3509 auto const it = std::ranges::lower_bound(keys, GetPrimaryKeyField(*record));
3510 if (it == keys.end() || !(*it == GetPrimaryKeyField(*record)))
3511 continue;
3512
3513 // Owners with no children are emplaced empty on purpose: leaving the relation unloaded would
3514 // send the very first access back to the database for a result already known to be empty.
3515 auto& bucket = buckets[static_cast<size_t>(std::distance(keys.begin(), it))];
3516 field.Emplace(ReferencedRecordList { bucket });
3517 }
3518}
3519
3520template <typename ReferencedRecord, typename ThroughRecord, typename Record, auto OwnerSelector, auto ThroughSelector>
3521SqlSelectQueryBuilder DataMapper::BuildHasOneThroughSelectQuery()
3522{
3523 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3524 static_assert(DataMapperRecord<ThroughRecord>, "ThroughRecord must satisfy DataMapperRecord");
3525
3526 // The foreign key of ThroughRecord pointing at the record owning this relationship.
3527 constexpr size_t ThroughToOwnerIndex = InverseBelongsToIndexOf<Record, ThroughRecord, OwnerSelector>;
3528
3529 // The foreign key of ReferencedRecord pointing at ThroughRecord.
3530 constexpr size_t ReferencedToThroughIndex = InverseBelongsToIndexOf<ThroughRecord, ReferencedRecord, ThroughSelector>;
3531
3532 // Filtering on the join record's foreign key is equivalent to joining the owning table back in and
3533 // filtering on its primary key - the caller already holds that primary key - and it keeps the owning
3534 // table out of the query, which matters when it is the same table as one already joined.
3535 return _connection.Query(RecordTableName<ReferencedRecord>)
3536 .Select()
3537 .Build([&](auto& query) {
3538 EnumerateRecordMembers<ReferencedRecord>([&]<size_t ReferencedFieldIndex, typename ReferencedFieldType>() {
3539 if constexpr (FieldWithStorage<ReferencedFieldType>)
3540 {
3541 query.Field(SqlQualifiedTableColumnName { RecordTableName<ReferencedRecord>,
3542 FieldNameAt<ReferencedFieldIndex, ReferencedRecord> });
3543 }
3544 });
3545 })
3546 .InnerJoin(RecordTableName<ThroughRecord>,
3547 FieldNameAt<RecordPrimaryKeyIndex<ThroughRecord>, ThroughRecord>,
3548 FieldNameAt<ReferencedToThroughIndex, ReferencedRecord>)
3549 .Where(
3550 SqlQualifiedTableColumnName {
3551 RecordTableName<ThroughRecord>,
3552 FieldNameAt<ThroughToOwnerIndex, ThroughRecord>,
3553 },
3554 SqlWildcard);
3555}
3556
3557template <typename ReferencedRecord, typename ThroughSpec, typename Record, auto OwnerSelector, auto ThroughSelector>
3558void DataMapper::LoadHasOneThrough(Record& record,
3559 HasOneThrough<ReferencedRecord, ThroughSpec, OwnerSelector, ThroughSelector>& field)
3560{
3561 using ThroughRecord = ThroughRecordOf<ThroughSpec>;
3562
3563 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3564 static_assert(DataMapperRecord<ThroughRecord>, "ThroughRecord must satisfy DataMapperRecord");
3565
3566 ZoneScopedN("DataMapper::LoadHasOneThrough");
3567 ZoneTextObject(RecordTableName<ReferencedRecord>);
3568
3569 CallOnPrimaryKey(record, [&]<size_t PrimaryKeyIndex, typename PrimaryKeyType>(PrimaryKeyType const& primaryKeyField) {
3570 auto query =
3571 BuildHasOneThroughSelectQuery<ReferencedRecord, ThroughRecord, Record, OwnerSelector, ThroughSelector>();
3572 if (auto link = QuerySingle<ReferencedRecord>(std::move(query), primaryKeyField.Value()); link)
3573 field.EmplaceRecord(std::make_shared<ReferencedRecord>(std::move(*link)));
3574 });
3575}
3576
3577template <typename ReferencedRecord,
3578 typename ThroughRecord,
3579 typename Record,
3580 auto OwnerSelector,
3581 auto ThroughSelector,
3582 typename PKValue>
3583std::shared_ptr<ReferencedRecord> DataMapper::LoadHasOneThroughByPK(PKValue const& pkValue)
3584{
3585 static_assert(DataMapperRecord<ThroughRecord>, "ThroughRecord must satisfy DataMapperRecord");
3586
3587 auto query = BuildHasOneThroughSelectQuery<ReferencedRecord, ThroughRecord, Record, OwnerSelector, ThroughSelector>();
3588
3589 if (auto link = QuerySingle<ReferencedRecord>(std::move(query), pkValue); link)
3590 return std::make_shared<ReferencedRecord>(std::move(*link));
3591
3592 return {};
3593}
3594
3595template <typename ReferencedRecord, typename ThroughRecord, typename Record, auto OwnerSelector, auto ReferencedSelector>
3596SqlSelectQueryBuilder DataMapper::BuildHasManyThroughSelectQuery()
3597{
3598 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3599 static_assert(DataMapperRecord<ThroughRecord>, "ThroughRecord must satisfy DataMapperRecord");
3600
3601 // The join record's foreign key pointing at the record owning this relationship.
3602 constexpr size_t ThroughToOwnerIndex = InverseBelongsToIndexOf<Record, ThroughRecord, OwnerSelector>;
3603
3604 // The join record's foreign key pointing at the referenced record.
3605 constexpr size_t ThroughToReferencedIndex = InverseBelongsToIndexOf<ReferencedRecord, ThroughRecord, ReferencedSelector>;
3606
3607 return _connection.Query(RecordTableName<ReferencedRecord>)
3608 .Select()
3609 .Build([&](auto& query) {
3610 EnumerateRecordMembers<ReferencedRecord>([&]<size_t ReferencedFieldIndex, typename ReferencedFieldType>() {
3611 if constexpr (FieldWithStorage<ReferencedFieldType>)
3612 {
3613 query.Field(SqlQualifiedTableColumnName { RecordTableName<ReferencedRecord>,
3614 FieldNameAt<ReferencedFieldIndex, ReferencedRecord> });
3615 }
3616 });
3617 })
3618 .InnerJoin(RecordTableName<ThroughRecord>,
3619 FieldNameAt<ThroughToReferencedIndex, ThroughRecord>,
3620 SqlQualifiedTableColumnName { RecordTableName<ReferencedRecord>,
3621 FieldNameAt<RecordPrimaryKeyIndex<ReferencedRecord>, ReferencedRecord> })
3622 .Where(
3623 SqlQualifiedTableColumnName {
3624 RecordTableName<ThroughRecord>,
3625 FieldNameAt<ThroughToOwnerIndex, ThroughRecord>,
3626 },
3627 SqlWildcard);
3628}
3629
3630template <typename ReferencedRecord,
3631 typename ThroughRecord,
3632 typename Record,
3633 auto OwnerSelector,
3634 auto ReferencedSelector,
3635 typename Callable>
3636void DataMapper::CallOnHasManyThrough(Record& record, Callable const& callback)
3637{
3638 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3639
3640 CallOnPrimaryKey(record, [&]<size_t PrimaryKeyIndex, typename PrimaryKeyType>(PrimaryKeyType const& primaryKeyField) {
3641 auto query =
3642 BuildHasManyThroughSelectQuery<ReferencedRecord, ThroughRecord, Record, OwnerSelector, ReferencedSelector>();
3643 callback(query, primaryKeyField);
3644 });
3645}
3646
3647template <typename ReferencedRecord,
3648 typename ThroughRecord,
3649 typename Record,
3650 auto OwnerSelector,
3651 auto ReferencedSelector,
3652 typename PKValue,
3653 typename Callable>
3654void DataMapper::CallOnHasManyThroughByPK(PKValue const& pkValue, Callable const& callback)
3655{
3656 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3657
3658 auto query =
3659 BuildHasManyThroughSelectQuery<ReferencedRecord, ThroughRecord, Record, OwnerSelector, ReferencedSelector>();
3660 callback(query, pkValue);
3661}
3662
3663template <typename ReferencedRecord, typename ThroughSpec, typename Record, auto OwnerSelector, auto ReferencedSelector>
3664void DataMapper::LoadHasManyThrough(Record& record,
3665 HasManyThrough<ReferencedRecord, ThroughSpec, OwnerSelector, ReferencedSelector>& field)
3666{
3667 using ThroughRecord = ThroughRecordOf<ThroughSpec>;
3668
3669 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3670
3671 ZoneScopedN("DataMapper::LoadHasManyThrough");
3672 ZoneTextObject(RecordTableName<ReferencedRecord>);
3673
3674 CallOnHasManyThrough<ReferencedRecord, ThroughRecord, Record, OwnerSelector, ReferencedSelector>(
3675 record, [&](SqlSelectQueryBuilder& selectQuery, auto& primaryKeyField) {
3676 field.Emplace(detail::ToSharedPtrList(Query<ReferencedRecord>(selectQuery.All(), primaryKeyField.Value())));
3677 });
3678}
3679
3680template <typename Record>
3681void DataMapper::LoadRelations(Record& record)
3682{
3683 static_assert(!std::is_const_v<Record>);
3684 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3685
3686 ZoneScopedN("DataMapper::LoadRelations");
3687 ZoneTextObject(RecordTableName<Record>);
3688
3689#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
3690 constexpr auto ctx = std::meta::access_context::current();
3691 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
3692 {
3693 using FieldType = typename[:std::meta::type_of(el):];
3694 if constexpr (IsBelongsTo<FieldType>)
3695 {
3696 auto& field = record.[:el:];
3697 field.AdoptFetchedRecord(LoadBelongsTo<FieldType>(field.Value()));
3698 }
3699 else if constexpr (IsCompositeForeignKey<FieldType>)
3700 {
3701 LoadCompositeForeignKey(record, record.[:el:]);
3702 }
3703 else if constexpr (IsHasMany<FieldType>)
3704 {
3705 LoadHasMany(record, record.[:el:]);
3706 }
3707 else if constexpr (IsHasOneThrough<FieldType>)
3708 {
3709 LoadHasOneThrough(record, record.[:el:]);
3710 }
3711 else if constexpr (IsHasManyThrough<FieldType>)
3712 {
3713 LoadHasManyThrough(record, record.[:el:]);
3714 }
3715 }
3716#else
3717 EnumerateRecordMembers(record, [&]<size_t FieldIndex, typename FieldType>(FieldType& field) {
3718 if constexpr (IsBelongsTo<FieldType>)
3719 {
3720 field.AdoptFetchedRecord(LoadBelongsTo<FieldType>(field.Value()));
3721 }
3722 else if constexpr (IsCompositeForeignKey<FieldType>)
3723 {
3724 LoadCompositeForeignKey(record, field);
3725 }
3726 else if constexpr (IsHasMany<FieldType>)
3727 {
3728 LoadHasMany(record, field);
3729 }
3730 else if constexpr (IsHasOneThrough<FieldType>)
3731 {
3732 LoadHasOneThrough(record, field);
3733 }
3734 else if constexpr (IsHasManyThrough<FieldType>)
3735 {
3736 LoadHasManyThrough(record, field);
3737 }
3738 });
3739#endif
3740}
3741
3742/// Sets the primary key field(s) of the given record to the specified id value.
3743template <typename Record, typename ValueType>
3744inline LIGHTWEIGHT_FORCE_INLINE void DataMapper::SetId(Record& record, ValueType&& id)
3745{
3746 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3747 // static_assert(HasPrimaryKey<Record>);
3748
3749#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
3750
3751 auto constexpr ctx = std::meta::access_context::current();
3752 template for (constexpr auto el: define_static_array(nonstatic_data_members_of(^^Record, ctx)))
3753 {
3754 using FieldType = typename[:std::meta::type_of(el):];
3755 if constexpr (IsField<FieldType>)
3756 {
3757 // Only a generated key member receives the value; a PrimaryKey::Manual member is the caller's.
3758 if constexpr (FieldType::IsAutoAssignPrimaryKey || FieldType::IsAutoIncrementPrimaryKey)
3759 {
3760 record.[:el:] = std::forward<ValueType>(id);
3761 }
3762 }
3763 }
3764#else
3765 EnumerateRecordMembers(record, [&]<size_t I, typename FieldType>(FieldType& field) {
3766 if constexpr (IsField<FieldType>)
3767 {
3768 // Only a generated key member receives the value; a PrimaryKey::Manual member is the caller's.
3769 if constexpr (FieldType::IsAutoAssignPrimaryKey || FieldType::IsAutoIncrementPrimaryKey)
3770 {
3771 field = std::forward<FieldType>(id);
3772 }
3773 }
3774 });
3775#endif
3776}
3777
3778/// Binds all output columns of the record via the given cursor.
3779template <typename Record, size_t InitialOffset>
3780inline LIGHTWEIGHT_FORCE_INLINE Record& DataMapper::BindOutputColumns(Record& record, SqlResultCursor& cursor)
3781{
3782 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3783 return BindOutputColumns<std::make_integer_sequence<size_t, RecordMemberCount<Record>>, Record, InitialOffset>(record,
3784 cursor);
3785}
3786
3787template <typename ElementMask, typename Record, size_t InitialOffset>
3788Record& DataMapper::BindOutputColumns(Record& record, SqlResultCursor& cursor)
3789{
3790 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3791 static_assert(!std::is_const_v<Record>);
3792
3793#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
3794 auto constexpr ctx = std::meta::access_context::current();
3795 std::int16_t i = std::int16_t { InitialOffset };
3796 template for (constexpr auto index: define_static_array(template_arguments_of(^^ElementMask)) | std::views::drop(1))
3797 {
3798 constexpr auto el = nonstatic_data_members_of(^^Record, ctx)[[:index:]];
3799 using FieldType = typename[:std::meta::type_of(el):];
3800 if constexpr (IsField<FieldType>)
3801 {
3802 cursor.BindOutputColumn(i++, &record.[:el:].MutableValue());
3803 }
3804 else if constexpr (SqlOutputColumnBinder<FieldType>)
3805 {
3806 cursor.BindOutputColumn(i++, &record.[:el:]);
3807 }
3808 }
3809#else
3810 EnumerateRecordMembers<ElementMask>(
3811 record, [&cursor, i = SqlColumnIndex { InitialOffset }]<size_t I, typename Field>(Field& field) mutable {
3812 if constexpr (IsField<Field>)
3813 {
3814 cursor.BindOutputColumn(i++, &field.MutableValue());
3815 }
3816 else if constexpr (SqlOutputColumnBinder<Field>)
3817 {
3818 cursor.BindOutputColumn(i++, &field);
3819 }
3820 });
3821#endif
3822
3823 return record;
3824}
3825template <typename Load>
3826auto DataMapper::RunRelationLoad(detail::RelationLoadSource& source, Load const& load)
3827 -> RelationResult<std::invoke_result_t<Load const&, DataMapper&>>
3828{
3829 using Result = std::invoke_result_t<Load const&, DataMapper&>;
3830 return source.Borrow().and_then([&load](std::shared_ptr<DataMapper> const& borrowed) -> RelationResult<Result> {
3831 try
3832 {
3833 if constexpr (std::is_void_v<Result>)
3834 {
3835 load(*borrowed);
3836 return {};
3837 }
3838 else
3839 return load(*borrowed);
3840 }
3841 catch (std::exception const& error)
3842 {
3843 SqlLogger::GetLogger().OnWarning(std::format("Loading a relation failed: {}", error.what()));
3844 return std::unexpected { RelationError::QueryFailed };
3845 }
3846 });
3847}
3848
3849template <typename Each, typename Stream>
3850RelationResult<void> DataMapper::RunRelationStream(detail::RelationLoadSource& source,
3851 Each const& each,
3852 Stream const& stream)
3853{
3854 auto callbackError = std::exception_ptr {};
3855 auto const guarded = [&each, &callbackError](auto const& row) {
3856 try
3857 {
3858 each(row);
3859 }
3860 catch (...)
3861 {
3862 callbackError = std::current_exception();
3863 throw;
3864 }
3865 };
3866 auto result = RunRelationLoad(source, [&](DataMapper& dm) { stream(dm, guarded); });
3867 if (callbackError)
3868 std::rethrow_exception(callbackError);
3869 return result;
3870}
3871
3872template <typename Record, typename QueryText, typename Callable, typename... InputParameters>
3873void DataMapper::StreamRecords(QueryText const& query, Callable const& each, InputParameters const&... inputParameters)
3874{
3875 _stmt.Prepare(query);
3876 auto cursor = _stmt.Execute(inputParameters...);
3877
3878 auto record = detail::MakeUninitialized<Record>();
3879 BindOutputColumns(record, cursor);
3880 while (cursor.FetchRow())
3881 {
3882 // Installed only now that the row is fetched: the loaders capture the record's key values when
3883 // installed, and before the fetch those are still default-constructed.
3885 each(record);
3886
3887 // Reset before rebinding for the next row. The same record instance is reused across rows, and a
3888 // fetch does not necessarily overwrite the whole of a variable-width buffer: a shorter value
3889 // leaves the tail of the previous one in place, so a string column can come back as a blend of
3890 // two rows. Assigning a fresh record clears every field's buffer and indicator first.
3891 record = detail::MakeUninitialized<Record>();
3892 BindOutputColumns(record, cursor);
3893 }
3894}
3895
3896template <typename Record>
3897// NOLINTNEXTLINE(readability-function-cognitive-complexity)
3899{
3900 static_assert(DataMapperRecord<Record>, "Record must satisfy DataMapperRecord");
3901
3902 // Every loader below borrows a mapper of its own from this source for the duration of one load,
3903 // rather than running on this mapper (which a record may outlive) or on a shared thread-local one:
3904 // no two loads - nor a load nested inside a streaming Each() - share a statement or connection.
3905 auto const& source = RelationLoadSourceForLoaders();
3906
3907 auto const callback = [&]<size_t FieldIndex, typename FieldType>(FieldType& field) {
3908 if constexpr (IsBelongsTo<FieldType>)
3909 {
3910 using ReferencedRecord = FieldType::ReferencedRecord;
3911 field.SetAutoLoader(typename FieldType::Loader {
3912 .loadReference = [source, value = field.Value()]() -> RelationResult<ReferencedRecord> {
3913 return RunRelationLoad(*source, [&](DataMapper& dm) { return dm.LoadBelongsTo<FieldType>(value); })
3914 .and_then([](std::optional<ReferencedRecord> loaded) -> RelationResult<ReferencedRecord> {
3915 if (!loaded)
3916 return std::unexpected { RelationError::NotFound };
3917 return std::move(*loaded);
3918 });
3919 },
3920 });
3921 }
3922 if constexpr (IsCompositeForeignKey<FieldType>)
3923 {
3924 using ReferencedRecord = FieldType::ReferencedRecord;
3925
3926 // Captured by value, evaluated now while `record` is known to be live - not a pointer to
3927 // `record` read later from inside the closure. A `std::optional<Record>` returned by value
3928 // from a query method (QuerySingle, First, ...) is not guaranteed to keep its address: NRVO
3929 // is not mandated by the standard, and - verified - does not reliably apply to the fuller
3930 // body of those functions in at least one real build configuration, so a captured pointer
3931 // can end up pointing at stack memory already reused for something else by the time the
3932 // loader runs. The trade-off is the same one HasMany/BelongsTo already make: repointing the
3933 // foreign key after this point does not change what the relation resolves to.
3934 //
3935 // OrderedValuesOf() - not ValuesOf() - because QuerySingle emits one WHERE predicate per
3936 // primary key member in the *referenced record's* member declaration order and binds its
3937 // arguments positionally. Passing them in connection-declaration order would bind each
3938 // value to the wrong predicate whenever the two orders differ, which with same-typed key
3939 // columns fetches a wrong row rather than failing. See CompositeKeyOrderingTests.cpp.
3940 field.SetAutoLoader(typename FieldType::Loader {
3941 .loadReference = [source, keys = FieldType::OrderedValuesOf(record)]()
3942 -> RelationResult<std::shared_ptr<ReferencedRecord>> {
3943 return RunRelationLoad(*source,
3944 [&](DataMapper& dm) { return dm.LoadCompositeForeignKeyRecord<FieldType>(keys); })
3945 .and_then(NotFoundIfNull<ReferencedRecord>);
3946 },
3947 });
3948 }
3949 if constexpr (IsHasMany<FieldType>)
3950 {
3951 if constexpr (HasPrimaryKey<Record>)
3952 {
3953 using ReferencedRecord = FieldType::ReferencedRecord;
3955 // Capture the PK value by value to avoid dangling references if the record is moved.
3956 auto pkValue = GetPrimaryKeyField(record);
3957 hasMany.SetAutoLoader(typename FieldType::Loader {
3958 .count = [source, pkValue]() -> RelationResult<size_t> {
3959 return RunRelationLoad(*source, [&](DataMapper& dm) {
3960 auto selectQuery =
3961 dm.BuildHasManySelectQuery<Record, ReferencedRecord, FieldType::InverseSelector>();
3962 dm._stmt.Prepare(selectQuery.Count());
3963 SqlResultCursor cursor = dm._stmt.Execute(pkValue);
3964 size_t count = 0;
3965 if (cursor.FetchRow())
3966 count = cursor.GetColumn<size_t>(1);
3967 return count;
3968 });
3969 },
3970 .all = [source, pkValue]() -> RelationResult<typename FieldType::ReferencedRecordList> {
3971 return RunRelationLoad(*source, [&](DataMapper& dm) {
3972 auto selectQuery =
3973 dm.BuildHasManySelectQuery<Record, ReferencedRecord, FieldType::InverseSelector>();
3974 return detail::ToSharedPtrList(dm.Query<ReferencedRecord>(selectQuery.All(), pkValue));
3975 });
3976 },
3977 .each = [source, pkValue](auto const& each) -> RelationResult<void> {
3978 return RunRelationStream(*source, each, [&](DataMapper& dm, auto const& guarded) {
3979 auto selectQuery =
3980 dm.BuildHasManySelectQuery<Record, ReferencedRecord, FieldType::InverseSelector>();
3981 dm.StreamRecords<ReferencedRecord>(selectQuery.All(), guarded, pkValue);
3982 });
3983 },
3984 });
3985 }
3986 }
3987 if constexpr (IsHasOneThrough<FieldType> && HasPrimaryKey<Record>)
3988 {
3989 using ReferencedRecord = FieldType::ReferencedRecord;
3990 using ThroughRecord = FieldType::ThroughRecord;
3991 // Capture the PK value by value to avoid dangling references if the record is moved.
3992 auto pkValue = GetPrimaryKeyField(record);
3993 field.SetAutoLoader(typename FieldType::Loader {
3994 .loadReference = [source, pkValue]() -> RelationResult<std::shared_ptr<ReferencedRecord>> {
3995 return RunRelationLoad(*source,
3996 [&](DataMapper& dm) {
3997 return dm.LoadHasOneThroughByPK<ReferencedRecord,
3998 ThroughRecord,
3999 Record,
4000 FieldType::OwnerSelector,
4001 FieldType::ThroughSelector>(pkValue);
4002 })
4003 .and_then(NotFoundIfNull<ReferencedRecord>);
4004 },
4005 });
4006 }
4007 if constexpr (IsHasManyThrough<FieldType> && HasPrimaryKey<Record>)
4008 {
4009 using ReferencedRecord = FieldType::ReferencedRecord;
4010 using ThroughRecord = FieldType::ThroughRecord;
4011 // Capture the PK value by value to avoid dangling references if the record is moved.
4012 auto pkValue = GetPrimaryKeyField(record);
4013 field.SetAutoLoader(typename FieldType::Loader {
4014 .count = [source, pkValue]() -> RelationResult<size_t> {
4015 return RunRelationLoad(*source, [&](DataMapper& dm) {
4016 size_t count = 0;
4017 dm.CallOnHasManyThroughByPK<ReferencedRecord,
4018 ThroughRecord,
4019 Record,
4020 FieldType::OwnerSelector,
4021 FieldType::ReferencedSelector>(
4022 pkValue, [&](SqlSelectQueryBuilder& selectQuery, auto const& pk) {
4023 dm._stmt.Prepare(selectQuery.Count());
4024 SqlResultCursor cursor = dm._stmt.Execute(pk);
4025 if (cursor.FetchRow())
4026 count = cursor.GetColumn<size_t>(1);
4027 });
4028 return count;
4029 });
4030 },
4031 .all = [source, pkValue]() -> RelationResult<typename FieldType::ReferencedRecordList> {
4032 return RunRelationLoad(*source, [&](DataMapper& dm) {
4033 typename FieldType::ReferencedRecordList result;
4034 dm.CallOnHasManyThroughByPK<ReferencedRecord,
4035 ThroughRecord,
4036 Record,
4037 FieldType::OwnerSelector,
4038 FieldType::ReferencedSelector>(
4039 pkValue, [&](SqlSelectQueryBuilder& selectQuery, auto const& pk) {
4040 result = detail::ToSharedPtrList(dm.Query<ReferencedRecord>(selectQuery.All(), pk));
4041 });
4042 return result;
4043 });
4044 },
4045 .each = [source, pkValue](auto const& each) -> RelationResult<void> {
4046 return RunRelationStream(*source, each, [&](DataMapper& dm, auto const& guarded) {
4047 dm.CallOnHasManyThroughByPK<ReferencedRecord,
4048 ThroughRecord,
4049 Record,
4050 FieldType::OwnerSelector,
4051 FieldType::ReferencedSelector>(
4052 pkValue, [&](SqlSelectQueryBuilder& selectQuery, auto const& pk) {
4053 dm.StreamRecords<ReferencedRecord>(selectQuery.All(), guarded, pk);
4054 });
4055 });
4056 },
4057 });
4058 }
4059 };
4060
4061#if defined(LIGHTWEIGHT_CXX26_REFLECTION)
4062 constexpr auto ctx = std::meta::access_context::current();
4063
4064 Reflection::template_for<0, nonstatic_data_members_of(^^Record, ctx).size()>([&callback, &record]<auto I>() {
4065 constexpr auto localctx = std::meta::access_context::current();
4066 constexpr auto members = define_static_array(nonstatic_data_members_of(^^Record, localctx));
4067 using FieldType = typename[:std::meta::type_of(members[I]):];
4068 callback.template operator()<I, FieldType>(record.[:members[I]:]);
4069 });
4070#else
4071 EnumerateRecordMembers(record, callback);
4072#endif
4073}
4074
4075template <typename T>
4076std::optional<T> DataMapper::Execute(std::string_view sqlQueryString)
4077{
4078 ZoneScopedN("DataMapper::Execute(string)");
4079 ZoneTextObject(sqlQueryString);
4080 return _stmt.ExecuteDirectScalar<T>(sqlQueryString);
4081}
4082
4083} // namespace Lightweight
4084
4085#include "../Async/DataMapperAsync.hpp"
Main API for mapping records to and from the database using high level C++ syntax.
DataMapper(DataMapper &&other) noexcept
Move constructor.
SqlConnection const & Connection() const noexcept
Returns the connection reference used by this data mapper.
bool IsModified(Record const &record) const noexcept
Async::Task< void > LoadRelationsAsync(Record &record)
Asynchronously loads record's relations.
std::vector< std::string > CreateTableString(SqlServerType serverType)
Constructs a string list of SQL queries to create the table for the given record type.
SqlQueryBuilder Query()
void LoadRelations(Record &record)
DataMapper & operator=(DataMapper &&other) noexcept
Move assignment operator.
void SetModifiedState(Record &record) noexcept
void UpdateAll(Records const &records)
Batch-updates a span of records with a single prepared statement.
Async::Task< std::optional< Record > > QuerySingleAsync(PrimaryKeyTypes... primaryKeys)
Async::Task< void > UpdateAsync(Record &record)
Asynchronously updates record's modified fields.
std::optional< T > Execute(std::string_view sqlQueryString)
void CreateAll(Records const &records)
Batch-inserts a span of records with a single prepared statement.
std::size_t Delete(Record const &record)
RecordPrimaryKeyType< Record > CreateCopyOf(Record const &originalRecord)
Creates a copy of an existing record in the database.
DataMapper(SqlConnection &&connection)
Constructs a new data mapper, using the given connection.
void CreateTable()
Creates the table for the given record type.
std::function< SqlDateTime()> TimestampClock
A source of the current time, used to fill fields marked with a FieldTimestamp.
SqlAllFieldsQueryBuilder< Record, QueryOptions > Query()
std::optional< Record > QuerySingle(PrimaryKeyTypes &&... primaryKeys)
Queries a single record (based on primary key) from the database.
void SetTimestampClock(TimestampClock clock) noexcept
Sets the clock that fills the auto-maintained timestamp fields (see FieldTimestamp).
SqlConnection & Connection() noexcept
Returns the mutable connection reference used by this data mapper.
void CreateTables()
Creates the tables for the given record types.
static std::string Inspect(Record const &record)
Constructs a human readable string representation of the given record.
RecordPrimaryKeyType< Record > CreateExplicit(Record const &record)
Creates a new record in the database.
std::vector< std::string > CreateTablesString(SqlServerType serverType)
Constructs a string list of SQL queries to create the tables for the given record types.
SqlDateTime CurrentTimestamp() const
Reads the clock that fills the auto-maintained timestamp fields.
Async::Task< RecordPrimaryKeyType< Record > > CreateAsync(Record &record)
Asynchronously inserts record, updating its primary key in place.
void ConfigureRelationAutoLoading(Record &record)
SqlAllFieldsQueryBuilder< Record, QueryOptions, SqlQueryExecutionMode::Asynchronous > QueryAsync()
void Update(Record &record)
SqlQueryBuilder FromTable(std::string_view tableName)
Constructs an SQL query builder for the given table name.
DataMapper(std::optional< SqlConnectInfo > connectInfo)
ModifiedState
Enum to set the modified state of a record.
RecordPrimaryKeyType< Record > Create(Record &record)
Creates a new record in the database.
Async::Task< std::size_t > DeleteAsync(Record const &record)
Asynchronously deletes record.
std::vector< Record > Query(SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
This HasMany<OtherRecord> represents a simple one-to-many relationship between two records.
Definition HasMany.hpp:67
void SetAutoLoader(Loader loader) noexcept
Used internally to configure on-demand loading of the records.
Definition HasMany.hpp:228
Represents a query builder that retrieves all fields of a record.
Represents a connection to a SQL database.
bool RoundTripsNarrowTextByteExact() const noexcept
Whether narrow character data round-trips byte-exact on this connection.
SqlServerType ServerType() const noexcept
Retrieves the type of the server.
LIGHTWEIGHT_API SqlQueryBuilder Query(std::string_view const &table={}) const
SqlQueryFormatter const & QueryFormatter() const noexcept
Retrieves a query formatter suitable for the SQL server being connected.
bool SupportsNativeRowArrayFetch() const noexcept
Whether this connection's driver supports native row-array fetching (SQL_ATTR_ROW_ARRAY_SIZE > 1 with...
bool ReadsBoundColumnsAgain() const noexcept
auto Delete()
Executes a DELETE query.
LIGHTWEIGHT_FORCE_INLINE SqlCoreDataMapperQueryBuilder(DataMapper &dm, std::string fields) noexcept
Constructs a query builder with the given data mapper and field list.
static LIGHTWEIGHT_API SqlLogger & GetLogger()
Retrieves the currently configured logger.
virtual void OnWarning(std::string_view const &message)=0
Invoked on a warning.
LIGHTWEIGHT_API SqlCreateTableQueryBuilder CreateTable(std::string_view tableName)
Creates a new table.
API Entry point for building SQL queries.
Definition SqlQuery.hpp:32
LIGHTWEIGHT_API SqlDeleteQueryBuilder Delete(std::vector< SqlVariant > *boundInputs=nullptr) noexcept
LIGHTWEIGHT_API SqlInsertQueryBuilder Insert(std::vector< SqlVariant > *boundInputs=nullptr) noexcept
LIGHTWEIGHT_API SqlSelectQueryStarter Select(std::vector< SqlVariant > *boundInputs=nullptr) noexcept
LIGHTWEIGHT_API SqlMigrationQueryBuilder Migration()
Initiates query for building database migrations.
LIGHTWEIGHT_API SqlUpdateQueryBuilder Update(std::vector< SqlVariant > *boundInputs=nullptr) noexcept
static std::string QuoteIdentifier(std::string_view name)
static SqlQueryFormatter const * Get(SqlServerType serverType) noexcept
Retrieves the SQL query formatter for the given SqlServerType.
static void AppendQuotedIdentifier(std::string &out, std::string_view name)
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 size_t NumRowsAffected() const
LIGHTWEIGHT_FORCE_INLINE bool GetColumn(SqlColumnIndex column, T *result) const
LIGHTWEIGHT_FORCE_INLINE bool FetchRow()
Query builder for building SELECT ... queries.
Definition Select.hpp:100
SqlSelectQueryBuilder & Build(Callable const &callable)
Builds the query using a callable.
LIGHTWEIGHT_API ComposedQuery First(size_t count=1)
Finalizes building the query as SELECT TOP n field names FROM ... query.
LIGHTWEIGHT_API SqlSelectQueryBuilder & Field(std::string_view const &fieldName)
Adds a single column to the SELECT clause.
High level API for (prepared) raw SQL statements.
LIGHTWEIGHT_API void Prepare(std::string_view query) &
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.
SqlResultCursor Execute(Args const &... args)
SqlResultCursor ExecuteBatch(FirstColumnBatch const &firstColumnBatch, MoreColumnBatches const &... moreColumnBatches)
LIGHTWEIGHT_API SqlResultCursor ExecuteDirect(std::string_view const &query, std::source_location location=std::source_location::current())
Executes the given query directly.
std::optional< T > ExecuteDirectScalar(std::string_view const &query, std::source_location location=std::source_location::current())
void BindInputParameter(std::int16_t columnIndex, Arg const &arg)
Derived & Where(ColumnName const &columnName, std::string_view binaryOp, T const &value)
Constructs or extends a WHERE clause to test for a binary operation.
Represents a record type that can be used with the DataMapper.
Definition Record.hpp:52
Requires that T maps onto a column of its record's table.
Definition Record.hpp:419
Whether SqlDataBinder<T> can bind T as an input parameter on at least one enabled driver.
Definition Core.hpp:786
@ Execute
The execution of a prepared statement (SqlStatement::Execute).
@ Create
Create the database if it does not exist (together with ReadWrite).
LIGHTWEIGHT_FORCE_INLINE RecordPrimaryKeyType< Record > GetPrimaryKeyField(Record const &record) noexcept
Definition Record.hpp:615
constexpr decltype(auto) GetRecordMemberAt(Record &&record)
Returns a reference to the member at index I — from the descriptor if present, else via reflection.
std::expected< T, RelationError > RelationResult
The outcome of a relation access: the requested value, or why it is unavailable.
Definition Error.hpp:44
constexpr std::string_view FieldNameAt
Returns the SQL field name of the given field index in the record.
Definition Utils.hpp:403
constexpr void EnumerateRecordMembers(Record &record, Callable &&callable)
Invokes callable as callable<I>(member) for each member of record.
detail::RecordMemberTypeOfDispatch< I, std::remove_cvref_t< Record >, HasDescription< Record > >::type RecordMemberTypeOf
Type of the member at index I — from the descriptor if present, else via reflection.
@ UpdatedAt
The field holds the time the record was last written.
@ None
The field is not maintained by the data mapper.
@ NotFound
There is nothing to load: the foreign key is NULL, or the referenced row does not exist.
T ValueType
The underlying value type of this field.
Definition Field.hpp:156
static constexpr auto IsOptional
Indicates if the field is optional, i.e., it can be NULL.
Definition Field.hpp:179
static SqlGuid Create() noexcept
Creates a new non-empty GUID.
SqlQualifiedTableColumnName represents a column name qualified with a table name.
Definition Utils.hpp:460