Lightweight 0.20260617.0
Loading...
Searching...
No Matches
Lightweight::DataMapper Class Reference

Main API for mapping records to and from the database using high level C++ syntax. More...

#include <DataMapper.hpp>

Public Types

enum class  ModifiedState : uint8_t { Modified , NotModified }
 Enum to set the modified state of a record. More...
 

Public Member Functions

 DataMapper ()
 Constructs a new data mapper, using the default connection.
 
 DataMapper (SqlConnection &&connection)
 Constructs a new data mapper, using the given connection.
 
 DataMapper (std::optional< SqlConnectionString > connectionString)
 Constructs a new data mapper, using the given connection string.
 
 DataMapper (DataMapper const &)=delete
 
DataMapperoperator= (DataMapper const &)=delete
 
 DataMapper (DataMapper &&other) noexcept
 Move constructor.
 
DataMapperoperator= (DataMapper &&other) noexcept
 Move assignment operator.
 
SqlConnection const & Connection () const noexcept
 Returns the connection reference used by this data mapper.
 
SqlConnectionConnection () noexcept
 Returns the mutable connection reference used by this data mapper.
 
template<typename Record >
std::vector< std::string > CreateTableString (SqlServerType serverType)
 Constructs a string list of SQL queries to create the table for the given record type.
 
template<typename FirstRecord , typename... MoreRecords>
std::vector< std::string > CreateTablesString (SqlServerType serverType)
 Constructs a string list of SQL queries to create the tables for the given record types.
 
template<typename Record >
void CreateTable ()
 Creates the table for the given record type.
 
template<typename FirstRecord , typename... MoreRecords>
void CreateTables ()
 Creates the tables for the given record types.
 
template<DataMapperOptions QueryOptions = {}, typename Record >
RecordPrimaryKeyType< Record > Create (Record &record)
 Creates a new record in the database.
 
template<typename Record >
RecordPrimaryKeyType< Record > CreateExplicit (Record const &record)
 Creates a new record in the database.
 
template<std::ranges::range Records>
void CreateAll (Records const &records)
 Batch-inserts a span of records with a single prepared statement.
 
template<DataMapperOptions QueryOptions = {}, typename Record >
RecordPrimaryKeyType< Record > CreateCopyOf (Record const &originalRecord)
 Creates a copy of an existing record in the database.
 
template<typename Record , DataMapperOptions QueryOptions = {}, typename... PrimaryKeyTypes>
std::optional< Record > QuerySingle (PrimaryKeyTypes &&... primaryKeys)
 Queries a single record (based on primary key) from the database.
 
template<typename Record , DataMapperOptions QueryOptions = {}, typename... InputParameters>
std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 
template<typename Record , DataMapperOptions QueryOptions = {}, typename... InputParameters>
std::vector< Record > Query (std::string_view sqlQueryString, InputParameters &&... inputParameters)
 
template<typename ElementMask , typename Record , DataMapperOptions QueryOptions = {}, typename... InputParameters>
std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 
template<typename First , typename Second , typename... Rest, DataMapperOptions QueryOptions = {}>
requires DataMapperRecord<First> && DataMapperRecord<Second> && DataMapperRecords<Rest...>
std::vector< std::tuple< First, Second, Rest... > > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery)
 
template<typename Record , DataMapperOptions QueryOptions = {}>
SqlAllFieldsQueryBuilder< Record, QueryOptions > Query ()
 
template<typename Record , DataMapperOptions QueryOptions = {}>
SqlAllFieldsQueryBuilder< Record, QueryOptions, SqlQueryExecutionMode::Asynchronous > QueryAsync ()
 
SqlQueryBuilder Query ()
 
template<typename Record >
void Update (Record &record)
 
template<std::ranges::range Records>
void UpdateAll (Records const &records)
 Batch-updates a span of records with a single prepared statement.
 
template<typename Record >
std::size_t Delete (Record const &record)
 
SqlQueryBuilder FromTable (std::string_view tableName)
 Constructs an SQL query builder for the given table name.
 
template<typename Record >
bool IsModified (Record const &record) const noexcept
 
template<ModifiedState state, typename Record >
void SetModifiedState (Record &record) noexcept
 
template<typename Record >
void LoadRelations (Record &record)
 
template<typename Record >
void ConfigureRelationAutoLoading (Record &record)
 
template<typename T >
std::optional< T > Execute (std::string_view sqlQueryString)
 
template<DataMapperOptions QueryOptions = {}, typename Record >
Async::Task< RecordPrimaryKeyType< Record > > CreateAsync (Record &record)
 Asynchronously inserts record, updating its primary key in place.
 
template<typename Record , DataMapperOptions QueryOptions = {}, typename... PrimaryKeyTypes>
Async::Task< std::optional< Record > > QuerySingleAsync (PrimaryKeyTypes... primaryKeys)
 
template<typename Record >
Async::Task< void > UpdateAsync (Record &record)
 Asynchronously updates record's modified fields.
 
template<typename Record >
Async::Task< std::size_t > DeleteAsync (Record const &record)
 Asynchronously deletes record.
 
template<typename Record >
Async::Task< void > LoadRelationsAsync (Record &record)
 Asynchronously loads record's relations.
 
template<typename Record , DataMapperOptions QueryOptions, typename... InputParameters>
LIGHTWEIGHT_FORCE_INLINE std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 Queries multiple records from the database using a composed query and optional input parameters.
 
template<typename Record , typename ValueType >
LIGHTWEIGHT_FORCE_INLINE void SetId (Record &record, ValueType &&id)
 Sets the primary key field(s) of the given record to the specified id value.
 
template<typename Record , size_t InitialOffset>
LIGHTWEIGHT_FORCE_INLINE Record & BindOutputColumns (Record &record, SqlResultCursor &cursor)
 Binds all output columns of the record via the given cursor.
 

Static Public Member Functions

static LIGHTWEIGHT_API DataMapperAcquireThreadLocal ()
 Acquires a thread-local DataMapper instance that is safe for reuse within that thread.
 
template<typename Record >
static std::string Inspect (Record const &record)
 Constructs a human readable string representation of the given record.
 

Detailed Description

Main API for mapping records to and from the database using high level C++ syntax.

A DataMapper instances operates on a single SQL connection and provides methods to create, read, update and delete records in the database.

See also
Field, BelongsTo, HasMany, HasManyThrough, HasOneThrough
struct Person
{
};
auto dm = DataMapper {};
// Create a new person record
auto person = Person { .id = SqlGuid::Create(), .name = "John Doe", .email = "johnt@doe.com" };
// Create the record in the database and set the primary key on the record
auto const personId = dm.Create(person);
// Query the person record from the database
auto const queriedPerson = dm.Query<Person>(personId)
.Where(FieldNameOf<&Person::id>, "=", personId)
.First();
if (queriedPerson.has_value())
std::println("Queried Person: {}", DataMapper::Inspect(queriedPerson.value()));
// Update the person record in the database
person.email = "alt@doe.com";
dm.Update(person);
// Delete the person record from the database
dm.Delete(person);
Main API for mapping records to and from the database using high level C++ syntax.
static std::string Inspect(Record const &record)
Constructs a human readable string representation of the given record.
Represents a single column in a table.
Definition Field.hpp:84
static SqlGuid Create() noexcept
Creates a new non-empty GUID.

Definition at line 91 of file DataMapper.hpp.

Member Enumeration Documentation

◆ ModifiedState

enum class Lightweight::DataMapper::ModifiedState : uint8_t
strong

Enum to set the modified state of a record.

Definition at line 495 of file DataMapper.hpp.

Constructor & Destructor Documentation

◆ DataMapper() [1/4]

Lightweight::DataMapper::DataMapper ( )
inline

Constructs a new data mapper, using the default connection.

Definition at line 98 of file DataMapper.hpp.

◆ DataMapper() [2/4]

Lightweight::DataMapper::DataMapper ( SqlConnection &&  connection)
inlineexplicit

Constructs a new data mapper, using the given connection.

Definition at line 105 of file DataMapper.hpp.

◆ DataMapper() [3/4]

Lightweight::DataMapper::DataMapper ( std::optional< SqlConnectionString connectionString)
inlineexplicit

Constructs a new data mapper, using the given connection string.

Definition at line 112 of file DataMapper.hpp.

◆ DataMapper() [4/4]

Lightweight::DataMapper::DataMapper ( DataMapper &&  other)
inlinenoexcept

Move constructor.

Definition at line 122 of file DataMapper.hpp.

Member Function Documentation

◆ operator=()

DataMapper & Lightweight::DataMapper::operator= ( DataMapper &&  other)
inlinenoexcept

Move assignment operator.

Definition at line 130 of file DataMapper.hpp.

◆ Connection() [1/2]

SqlConnection const & Lightweight::DataMapper::Connection ( ) const
inlinenoexcept

Returns the connection reference used by this data mapper.

Definition at line 145 of file DataMapper.hpp.

◆ Connection() [2/2]

SqlConnection & Lightweight::DataMapper::Connection ( )
inlinenoexcept

Returns the mutable connection reference used by this data mapper.

Definition at line 151 of file DataMapper.hpp.

◆ Inspect()

template<typename Record >
std::string Lightweight::DataMapper::Inspect ( Record const &  record)
static

Constructs a human readable string representation of the given record.

Definition at line 1564 of file DataMapper.hpp.

◆ CreateTableString()

template<typename Record >
std::vector< std::string > Lightweight::DataMapper::CreateTableString ( SqlServerType  serverType)

Constructs a string list of SQL queries to create the table for the given record type.

Definition at line 1605 of file DataMapper.hpp.

References Lightweight::SqlMigrationQueryBuilder::CreateTable(), Lightweight::SqlQueryFormatter::Get(), and Lightweight::SqlQueryBuilder::Migration().

◆ CreateTablesString()

template<typename FirstRecord , typename... MoreRecords>
std::vector< std::string > Lightweight::DataMapper::CreateTablesString ( SqlServerType  serverType)

Constructs a string list of SQL queries to create the tables for the given record types.

Definition at line 1616 of file DataMapper.hpp.

◆ CreateTable()

template<typename Record >
void Lightweight::DataMapper::CreateTable ( )

Creates the table for the given record type.

Definition at line 1628 of file DataMapper.hpp.

References Lightweight::SqlStatement::ExecuteDirect(), and Lightweight::SqlConnection::ServerType().

◆ CreateTables()

template<typename FirstRecord , typename... MoreRecords>
void Lightweight::DataMapper::CreateTables ( )

Creates the tables for the given record types.

Definition at line 1641 of file DataMapper.hpp.

◆ Create()

template<DataMapperOptions QueryOptions, typename Record >
RecordPrimaryKeyType< Record > Lightweight::DataMapper::Create ( Record &  record)

Creates a new record in the database.

The record is inserted into the database and the primary key is set on this record.

Template Parameters
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
RecordThe record type to insert.
Parameters
recordThe record to insert. The primary key field is updated in-place after the insert.
Returns
The primary key of the newly created record.

Definition at line 1866 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), and Lightweight::GetPrimaryKeyField().

◆ CreateExplicit()

template<typename Record >
RecordPrimaryKeyType< Record > Lightweight::DataMapper::CreateExplicit ( Record const &  record)

Creates a new record in the database.

Note
This is a variation of the Create() method and does not update the record's primary key.
Template Parameters
RecordThe record type to insert.
Parameters
recordThe record to insert. Unlike Create(), the primary key field is NOT updated in-place.
Returns
The primary key of the newly created record.

Definition at line 1749 of file DataMapper.hpp.

◆ CreateAll()

template<std::ranges::range Records>
void Lightweight::DataMapper::CreateAll ( Records const &  records)

Batch-inserts a span of records with a single prepared statement.

The INSERT is prepared once and the whole batch is submitted via SqlStatement::ExecuteBatch(rows, accessors...), which uses native zero-copy row-wise array binding when every inserted column is row-bindable (primitives, date/time/datetime, numeric, or std::optional of a fixed non-numeric type) and the driver supports parameter arrays, otherwise a prepare-once + per-row execute. This is dramatically faster than calling CreateExplicit() in a loop (which re-prepares per row).

Note
Like CreateExplicit(), this does not write back primary keys, relations, or modified-state onto the records; callers should treat the inserted records as write-only inputs. Auto-increment primary keys are not retrieved.

Accepts any contiguous, sized range of records (e.g. std::vector, std::array, std::span, or a C array), so dm.CreateAll(records) works without an explicit std::span wrapper. Non-contiguous ranges are rejected at compile time via static_assert (no implicit copy is made).

Template Parameters
RecordsA contiguous range whose element type is the record type to insert.
Parameters
recordsThe records to insert. An empty range is a no-op.

Definition at line 1820 of file DataMapper.hpp.

References Lightweight::SqlStatement::ExecuteBatch(), Lightweight::SqlQueryBuilder::Insert(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::Query().

◆ CreateCopyOf()

template<DataMapperOptions QueryOptions, typename Record >
RecordPrimaryKeyType< Record > Lightweight::DataMapper::CreateCopyOf ( Record const &  originalRecord)

Creates a copy of an existing record in the database.

This method is useful for duplicating a database record while assigning a new primary key. All fields except primary key(s) are copied from the original record. The primary key is automatically generated (auto-incremented or auto-assigned).

Parameters
originalRecordThe record to copy.
Returns
The primary key of the newly created record.

Definition at line 1850 of file DataMapper.hpp.

◆ QuerySingle()

template<typename Record , DataMapperOptions QueryOptions, typename... PrimaryKeyTypes>
std::optional< Record > Lightweight::DataMapper::QuerySingle ( PrimaryKeyTypes &&...  primaryKeys)

Queries a single record (based on primary key) from the database.

The primary key(s) are used to identify the record to load. If the record is not found, std::nullopt is returned.

Template Parameters
RecordThe record type to query and materialize.
QueryOptionsA specialization of DataMapperOptions that controls query behavior, such as whether related records should be auto-loaded. For example, set the relation loading option to false to disable auto-loading of relations when reading a single record.
PrimaryKeyTypesThe type(s) of the primary key value(s) used to look up the record.
Parameters
primaryKeysThe primary key value(s) identifying the record to load.
Returns
An initialized Record if found; otherwise std::nullopt.
// Example: disable auto-loading of relations when querying a single record
auto result = dataMapper
.QuerySingle<MyRecord, DataMapperOptions{ .loadRelations = false }>(primaryKeyValue);
if (result)
{
// use *result; relations have not been auto-loaded
}
bool loadRelations
Whether to automatically load relations when querying records.

Definition at line 2081 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlSelectQueryBuilder::Field(), Lightweight::SqlSelectQueryBuilder::First(), Lightweight::SqlStatement::Prepare(), Lightweight::SqlConnection::Query(), Lightweight::SqlQueryBuilder::Select(), Lightweight::SqlConnection::ServerType(), and Lightweight::SqlWhereClauseBuilder< Derived >::Where().

◆ Query() [1/7]

template<typename Record , DataMapperOptions QueryOptions = {}, typename... InputParameters>
std::vector< Record > Lightweight::DataMapper::Query ( SqlSelectQueryBuilder::ComposedQuery const &  selectQuery,
InputParameters &&...  inputParameters 
)

Queries multiple records from the database, based on the given query.

Template Parameters
RecordThe record type to query and materialize.
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
InputParametersThe types of the input parameters to bind before executing the query.
Parameters
selectQueryThe composed SQL select query to execute.
inputParametersZero or more values to bind as positional parameters in the query.
Returns
A vector of records populated from the query results.

Referenced by ConfigureRelationAutoLoading().

◆ Query() [2/7]

template<typename Record , DataMapperOptions QueryOptions, typename... InputParameters>
std::vector< Record > Lightweight::DataMapper::Query ( std::string_view  sqlQueryString,
InputParameters &&...  inputParameters 
)

Queries multiple records from the database, based on the given query.

Parameters
sqlQueryStringThe SQL query string to execute.
inputParametersThe input parameters for the query to be bound before executing.
Returns
A vector of records of the given type that were found via the query.

example:

struct Person
{
int id;
std::string name;
std::string email;
std::string phone;
std::string address;
std::string city;
std::string country;
};
void example(DataMapper& dm)
{
auto const sqlQueryString = R"(SELECT * FROM "Person" WHERE "city" = ? AND "country" = ?)";
auto const records = dm.Query<Person>(sqlQueryString, "Berlin", "Germany");
for (auto const& record: records)
{
std::println("Person: {}", DataMapper::Inspect(record));
}
}
std::vector< Record > Query(SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)

Definition at line 2167 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlResultCursor::FetchRow(), Lightweight::SqlResultCursor::GetColumn(), Lightweight::SqlResultCursor::NumColumnsAffected(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::ServerType().

◆ Query() [3/7]

template<typename ElementMask , typename Record , DataMapperOptions QueryOptions, typename... InputParameters>
std::vector< Record > Lightweight::DataMapper::Query ( SqlSelectQueryBuilder::ComposedQuery const &  selectQuery,
InputParameters &&...  inputParameters 
)

Queries records from the database, based on the given query and can be used to retrieve only part of the record by specifying the ElementMask.

Template Parameters
ElementMaskA SqlElements<Idx...> specialization specifying the zero-based field indices to populate.
RecordThe record type to query and materialize.
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
InputParametersThe types of the input parameters to bind before executing the query.
Parameters
selectQueryThe composed SQL select query to execute. Only the columns listed in the SELECT clause are bound; the remaining fields of Record are left at their default values.
inputParametersZero or more values to bind as positional parameters in the query.
Returns
A vector of partially populated records; only fields at the specified indices are filled in.
struct Person
{
Field<std::string> name; // index 1
Field<std::string> city; // index 5
};
void example(DataMapper& dm)
{
auto const query = dm.FromTable(RecordTableName<Person>)
.Select()
.Fields({ "name"sv, "city"sv })
.All();
auto const infos = dm.Query<SqlElements<1, 5>, Person>(query);
for (auto const& info : infos)
{
// only info.name and info.city are populated
}
}
SqlQueryBuilder FromTable(std::string_view tableName)
Constructs an SQL query builder for the given table name.
LIGHTWEIGHT_API SqlSelectQueryStarter Select() noexcept
SqlSelectQueryBuilder & Fields(std::string_view const &firstField, MoreFields &&... moreFields)
Adds a sequence of columns to the SELECT clause.
Definition Select.hpp:268

Definition at line 2307 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::ServerType().

◆ Query() [4/7]

template<typename First , typename Second , typename... Rest, DataMapperOptions QueryOptions>
requires DataMapperRecord<First> && DataMapperRecord<Second> && DataMapperRecords<Rest...>
std::vector< std::tuple< First, Second, Rest... > > Lightweight::DataMapper::Query ( SqlSelectQueryBuilder::ComposedQuery const &  selectQuery)

Queries records of different types from the database, based on the given query. User can constructed query that selects columns from the multiple tables this function is used to get result of the query

Template Parameters
FirstThe first record type to materialize from each result row.
SecondThe second record type to materialize from each result row.
RestZero or more additional record types to materialize from each result row.
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
Parameters
selectQueryThe composed SQL select query whose column list covers all fields of First, Second, and Rest.
Returns
A vector of tuples, each containing one instance of every requested record type per result row.
struct JointA{};
struct JointB{};
struct JointC{};
// the following query will construct statement to fetch all elements of JointA and JointC types
auto dm = DataMapper {};
auto const query = dm.FromTable(RecordTableName<JoinTestA>)
.Select()
.Fields<JointA, JointC>()
.InnerJoin<&JointB::a_id, &JointA::id>()
.InnerJoin<&JointC::id, &JointB::c_id>()
.All();
auto const records = dm.Query<JointA, JointC>(query);
for(const auto [elementA, elementC] : records)
{
// do something with elementA and elementC
}
DataMapper()
Constructs a new data mapper, using the default connection.

Definition at line 2225 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::ServerType().

◆ Query() [5/7]

template<typename Record , DataMapperOptions QueryOptions = {}>
SqlAllFieldsQueryBuilder< Record, QueryOptions > Lightweight::DataMapper::Query ( )
inline

Queries records of given Record type.

The query builder can be used to further refine the query. The query builder will execute the query when a method like All(), First(n), etc. is called.

Template Parameters
RecordThe record type to query and materialize.
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
Returns
A query builder for the given Record type.
auto const records = dm.Query<Person>()
.Where(FieldNameOf<&Person::is_active>, "=", true)
.All();

Definition at line 399 of file DataMapper.hpp.

◆ QueryAsync()

template<typename Record , DataMapperOptions QueryOptions = {}>
SqlAllFieldsQueryBuilder< Record, QueryOptions, SqlQueryExecutionMode::Asynchronous > Lightweight::DataMapper::QueryAsync ( )
inline

Asynchronous counterpart of Query — returns an async query builder for Record.

The builder offers the exact same fluent DSL (Where, OrderBy, GroupBy, joins, …) as the synchronous one; its finisher methods (All(), First(), First(n), Range(), Count(), Exist(), Delete()) return an Async::Task instead of the plain result, to be co_await -ed. The connection must have been put into async mode via SqlConnection::EnableAsync first.

Note
The returned builder is a temporary; keep the whole chain in the co_await full-expression (e.g. co_await dm.QueryAsync<Person>().Where(...).All();) so it outlives the awaited task.
Template Parameters
RecordThe record type to query and materialize.
QueryOptionsA specialization of DataMapperOptions that controls query behavior.
Returns
An asynchronous query builder for the given Record type.
auto const records = co_await dm.QueryAsync<Person>()
.Where(FieldNameOf<&Person::is_active>, "=", true)
.All();

Definition at line 424 of file DataMapper.hpp.

◆ Query() [6/7]

SqlQueryBuilder Lightweight::DataMapper::Query ( )
inline

Returns a SqlQueryBuilder using the default query formatter.

This can be used to build custom queries separately from the DataMapper and execute them via the DataMapper's typed Query() overloads that accept a SqlSelectQueryBuilder.

Returns
A SqlQueryBuilder bound to the connection's query formatter.

Definition at line 436 of file DataMapper.hpp.

References Lightweight::SqlConnection::QueryFormatter().

◆ Update()

template<typename Record >
void Lightweight::DataMapper::Update ( Record &  record)

Updates the record in the database.

Only fields that have been modified since the record was last loaded or saved are written. Fields that were not changed are excluded from the UPDATE statement.

Template Parameters
RecordThe record type to update.
Parameters
recordThe record to update. Only its modified fields are written to the database.

Definition at line 1921 of file DataMapper.hpp.

References Lightweight::SqlStatement::BindInputParameter(), Lightweight::EnumerateRecordMembers(), Lightweight::SqlStatement::Execute(), Lightweight::SqlStatement::Prepare(), Lightweight::SqlConnection::Query(), and Lightweight::SqlQueryBuilder::Update().

◆ UpdateAll()

template<std::ranges::range Records>
void Lightweight::DataMapper::UpdateAll ( Records const &  records)

Batch-updates a span of records with a single prepared statement.

One UPDATE is prepared that writes all storable non-primary-key columns of the record, matched on the primary key(s) (UPDATE … SET <all non-PK columns> WHERE <pk> = ?), and the whole batch is submitted via SqlStatement::ExecuteBatch(rows, accessors...) — natively row-wise when possible, otherwise prepare-once + per-row execute.

Note
Unlike Update(), which writes only the modified fields of a single record, this writes a uniform set of columns for every row, because a single prepared statement must bind the same columns for the whole batch. Per-row modified-state is therefore not consulted, and is not reset.

Accepts any contiguous, sized range of records (see CreateAll), so dm.UpdateAll(records) works without an explicit std::span wrapper. Non-contiguous ranges are rejected at compile time.

Template Parameters
RecordsA contiguous range whose element type is the record type to update (with a primary key).
Parameters
recordsThe records to update. An empty range is a no-op.

Definition at line 1994 of file DataMapper.hpp.

References Lightweight::SqlStatement::ExecuteBatch(), Lightweight::SqlStatement::Prepare(), Lightweight::SqlConnection::Query(), and Lightweight::SqlQueryBuilder::Update().

◆ Delete()

template<typename Record >
std::size_t Lightweight::DataMapper::Delete ( Record const &  record)

Deletes the record from the database.

The record is identified by its primary key(s). The row is removed from the backing table.

Template Parameters
RecordThe record type to delete.
Parameters
recordThe record to delete. Its primary key field(s) identify the row to remove.
Returns
The number of rows deleted (typically 1 if the record was found, 0 otherwise).

Definition at line 2030 of file DataMapper.hpp.

References Lightweight::SqlStatement::BindInputParameter(), Lightweight::SqlQueryBuilder::Delete(), Lightweight::EnumerateRecordMembers(), Lightweight::SqlStatement::Execute(), Lightweight::SqlResultCursor::NumRowsAffected(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::Query().

◆ FromTable()

SqlQueryBuilder Lightweight::DataMapper::FromTable ( std::string_view  tableName)
inline

Constructs an SQL query builder for the given table name.

Definition at line 481 of file DataMapper.hpp.

References Lightweight::SqlConnection::Query().

◆ IsModified()

template<typename Record >
bool Lightweight::DataMapper::IsModified ( Record const &  record) const
noexcept

Checks if the record has any modified fields.

Template Parameters
RecordThe record type to inspect.
Parameters
recordThe record to check.
Returns
True if at least one field has been modified since the record was last loaded or saved.

Definition at line 1893 of file DataMapper.hpp.

◆ SetModifiedState()

template<DataMapper::ModifiedState state, typename Record >
void Lightweight::DataMapper::SetModifiedState ( Record &  record)
noexcept

Sets the modified state of the record after receiving from the database. This marks all fields as not modified.

Template Parameters
stateThe target modified state for all fields (Modified or NotModified).
RecordThe record type whose fields are to be updated.
Parameters
recordThe record whose field modification flags are set to state.

Definition at line 2352 of file DataMapper.hpp.

References Lightweight::EnumerateRecordMembers().

◆ LoadRelations()

template<typename Record >
void Lightweight::DataMapper::LoadRelations ( Record &  record)

Loads all direct relations to this record.

Template Parameters
RecordThe record type whose relation fields are to be populated.
Parameters
recordThe record whose BelongsTo, HasMany, HasOneThrough, and HasManyThrough fields are loaded.

Definition at line 2729 of file DataMapper.hpp.

References Lightweight::EnumerateRecordMembers().

◆ ConfigureRelationAutoLoading()

template<typename Record >
void Lightweight::DataMapper::ConfigureRelationAutoLoading ( Record &  record)

Configures the auto loading of relations for the given record.

This means, that no explicit loading of relations is required. The relations are automatically loaded when accessed.

Template Parameters
RecordThe record type to configure auto-loading for.
Parameters
recordThe record whose relation fields are set up to load lazily on first access.

Definition at line 2865 of file DataMapper.hpp.

References AcquireThreadLocal(), ConfigureRelationAutoLoading(), Lightweight::EnumerateRecordMembers(), Lightweight::SqlStatement::Execute(), Lightweight::SqlResultCursor::FetchRow(), Lightweight::SqlResultCursor::GetColumn(), Lightweight::GetPrimaryKeyField(), Lightweight::SqlStatement::Prepare(), Query(), Lightweight::HasOneThrough< OtherTable, ThroughTable >::SetAutoLoader(), Lightweight::HasMany< OtherRecord >::SetAutoLoader(), and Lightweight::HasManyThrough< ReferencedRecordT, ThroughRecordT >::SetAutoLoader().

Referenced by ConfigureRelationAutoLoading(), Create(), Query(), Query(), Query(), and QuerySingle().

◆ Execute()

template<typename T >
std::optional< T > Lightweight::DataMapper::Execute ( std::string_view  sqlQueryString)

Helper function that allow to execute query directly via data mapper and get scalar result without need to create SqlStatement manually

Template Parameters
TThe scalar type of the expected result value.
Parameters
sqlQueryStringThe SQL query string to execute.
Returns
The first column of the first result row cast to T, or std::nullopt if the query returns no rows.

Definition at line 3008 of file DataMapper.hpp.

References Lightweight::SqlStatement::ExecuteDirectScalar().

◆ CreateAsync()

template<DataMapperOptions QueryOptions, typename Record >
Async::Task< RecordPrimaryKeyType< Record > > Lightweight::DataMapper::CreateAsync ( Record &  record)

Asynchronously inserts record, updating its primary key in place.

See also
Create.

Definition at line 24 of file DataMapperAsync.hpp.

References Lightweight::SqlConnection::AsyncBackend().

◆ QuerySingleAsync()

template<typename Record , DataMapperOptions QueryOptions, typename... PrimaryKeyTypes>
Async::Task< std::optional< Record > > Lightweight::DataMapper::QuerySingleAsync ( PrimaryKeyTypes...  primaryKeys)

Asynchronously queries a single record by its primary key(s).

See also
QuerySingle.

This is the asynchronous shorthand for a primary-key lookup; for anything else use the fluent builder returned by QueryAsync<Record>() (whose finishers also return an Async::Task). Note there is deliberately no QueryAsync(string)/QueryAsync(ComposedQuery) — that is what the builder is for.

Definition at line 31 of file DataMapperAsync.hpp.

References Lightweight::SqlConnection::AsyncBackend().

◆ UpdateAsync()

template<typename Record >
Async::Task< void > Lightweight::DataMapper::UpdateAsync ( Record &  record)

Asynchronously updates record's modified fields.

See also
Update.

Definition at line 40 of file DataMapperAsync.hpp.

References Lightweight::SqlConnection::AsyncBackend().

◆ DeleteAsync()

template<typename Record >
Async::Task< std::size_t > Lightweight::DataMapper::DeleteAsync ( Record const &  record)

Asynchronously deletes record.

See also
Delete.

Definition at line 46 of file DataMapperAsync.hpp.

References Lightweight::SqlConnection::AsyncBackend().

◆ LoadRelationsAsync()

template<typename Record >
Async::Task< void > Lightweight::DataMapper::LoadRelationsAsync ( Record &  record)

Asynchronously loads record's relations.

See also
LoadRelations.

Definition at line 52 of file DataMapperAsync.hpp.

References Lightweight::SqlConnection::AsyncBackend().

◆ Query() [7/7]

template<typename Record , DataMapperOptions QueryOptions, typename... InputParameters>
LIGHTWEIGHT_FORCE_INLINE std::vector< Record > Lightweight::DataMapper::Query ( SqlSelectQueryBuilder::ComposedQuery const &  selectQuery,
InputParameters &&...  inputParameters 
)
inline

Queries multiple records from the database using a composed query and optional input parameters.

Definition at line 2157 of file DataMapper.hpp.

◆ SetId()

template<typename Record , typename ValueType >
LIGHTWEIGHT_FORCE_INLINE void Lightweight::DataMapper::SetId ( Record &  record,
ValueType &&  id 
)
inline

Sets the primary key field(s) of the given record to the specified id value.

Definition at line 2784 of file DataMapper.hpp.

References Lightweight::EnumerateRecordMembers().

◆ BindOutputColumns()

template<typename Record , size_t InitialOffset>
LIGHTWEIGHT_FORCE_INLINE Record & Lightweight::DataMapper::BindOutputColumns ( Record &  record,
SqlResultCursor cursor 
)
inline

Binds all output columns of the record via the given cursor.

Definition at line 2818 of file DataMapper.hpp.


The documentation for this class was generated from the following files: