|
Lightweight 0.20260617.0
|
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 | |
| DataMapper & | operator= (DataMapper const &)=delete |
| DataMapper (DataMapper &&other) noexcept | |
| Move constructor. | |
| DataMapper & | operator= (DataMapper &&other) noexcept |
| Move assignment operator. | |
| SqlConnection const & | Connection () const noexcept |
| Returns the connection reference used by this data mapper. | |
| SqlConnection & | Connection () 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 DataMapper & | AcquireThreadLocal () |
| 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. | |
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.
Definition at line 91 of file DataMapper.hpp.
|
strong |
Enum to set the modified state of a record.
Definition at line 495 of file DataMapper.hpp.
|
inline |
Constructs a new data mapper, using the default connection.
Definition at line 98 of file DataMapper.hpp.
|
inlineexplicit |
Constructs a new data mapper, using the given connection.
Definition at line 105 of file DataMapper.hpp.
|
inlineexplicit |
Constructs a new data mapper, using the given connection string.
Definition at line 112 of file DataMapper.hpp.
|
inlinenoexcept |
Move constructor.
Definition at line 122 of file DataMapper.hpp.
|
inlinenoexcept |
Move assignment operator.
Definition at line 130 of file DataMapper.hpp.
|
inlinenoexcept |
Returns the connection reference used by this data mapper.
Definition at line 145 of file DataMapper.hpp.
|
inlinenoexcept |
Returns the mutable connection reference used by this data mapper.
Definition at line 151 of file DataMapper.hpp.
|
static |
Constructs a human readable string representation of the given record.
Definition at line 1564 of file DataMapper.hpp.
| 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().
| 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.
| 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().
| void Lightweight::DataMapper::CreateTables | ( | ) |
Creates the tables for the given record types.
Definition at line 1641 of file DataMapper.hpp.
| 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.
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
| Record | The record type to insert. |
| record | The record to insert. The primary key field is updated in-place after the insert. |
Definition at line 1866 of file DataMapper.hpp.
References ConfigureRelationAutoLoading(), and Lightweight::GetPrimaryKeyField().
| RecordPrimaryKeyType< Record > Lightweight::DataMapper::CreateExplicit | ( | Record const & | record | ) |
Creates a new record in the database.
| Record | The record type to insert. |
| record | The record to insert. Unlike Create(), the primary key field is NOT updated in-place. |
Definition at line 1749 of file DataMapper.hpp.
| 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).
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).
| Records | A contiguous range whose element type is the record type to insert. |
| records | The 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().
| 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).
| originalRecord | The record to copy. |
Definition at line 1850 of file DataMapper.hpp.
| 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.
| Record | The record type to query and materialize. |
| QueryOptions | A 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. |
| PrimaryKeyTypes | The type(s) of the primary key value(s) used to look up the record. |
| primaryKeys | The primary key value(s) identifying the record to load. |
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().
| std::vector< Record > Lightweight::DataMapper::Query | ( | SqlSelectQueryBuilder::ComposedQuery const & | selectQuery, |
| InputParameters &&... | inputParameters | ||
| ) |
Queries multiple records from the database, based on the given query.
| Record | The record type to query and materialize. |
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
| InputParameters | The types of the input parameters to bind before executing the query. |
| selectQuery | The composed SQL select query to execute. |
| inputParameters | Zero or more values to bind as positional parameters in the query. |
Referenced by ConfigureRelationAutoLoading().
| std::vector< Record > Lightweight::DataMapper::Query | ( | std::string_view | sqlQueryString, |
| InputParameters &&... | inputParameters | ||
| ) |
Queries multiple records from the database, based on the given query.
| sqlQueryString | The SQL query string to execute. |
| inputParameters | The input parameters for the query to be bound before executing. |
example:
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().
| 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.
| ElementMask | A SqlElements<Idx...> specialization specifying the zero-based field indices to populate. |
| Record | The record type to query and materialize. |
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
| InputParameters | The types of the input parameters to bind before executing the query. |
| selectQuery | The 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. |
| inputParameters | Zero or more values to bind as positional parameters in the query. |
Definition at line 2307 of file DataMapper.hpp.
References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::ServerType().
| 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
| First | The first record type to materialize from each result row. |
| Second | The second record type to materialize from each result row. |
| Rest | Zero or more additional record types to materialize from each result row. |
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
| selectQuery | The composed SQL select query whose column list covers all fields of First, Second, and Rest. |
Definition at line 2225 of file DataMapper.hpp.
References ConfigureRelationAutoLoading(), Lightweight::SqlStatement::Connection(), Lightweight::SqlStatement::Execute(), Lightweight::SqlStatement::Prepare(), and Lightweight::SqlConnection::ServerType().
|
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.
| Record | The record type to query and materialize. |
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
Definition at line 399 of file DataMapper.hpp.
|
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.
co_await full-expression (e.g. co_await dm.QueryAsync<Person>().Where(...).All();) so it outlives the awaited task.| Record | The record type to query and materialize. |
| QueryOptions | A specialization of DataMapperOptions that controls query behavior. |
Definition at line 424 of file DataMapper.hpp.
|
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.
Definition at line 436 of file DataMapper.hpp.
References Lightweight::SqlConnection::QueryFormatter().
| 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.
| Record | The record type to update. |
| record | The 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().
| 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.
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.
| Records | A contiguous range whose element type is the record type to update (with a primary key). |
| records | The 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().
| 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.
| Record | The record type to delete. |
| record | The record to delete. Its primary key field(s) identify the row to remove. |
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().
|
inline |
Constructs an SQL query builder for the given table name.
Definition at line 481 of file DataMapper.hpp.
References Lightweight::SqlConnection::Query().
|
noexcept |
Checks if the record has any modified fields.
| Record | The record type to inspect. |
| record | The record to check. |
Definition at line 1893 of file DataMapper.hpp.
|
noexcept |
Sets the modified state of the record after receiving from the database. This marks all fields as not modified.
| state | The target modified state for all fields (Modified or NotModified). |
| Record | The record type whose fields are to be updated. |
| record | The record whose field modification flags are set to state. |
Definition at line 2352 of file DataMapper.hpp.
References Lightweight::EnumerateRecordMembers().
| void Lightweight::DataMapper::LoadRelations | ( | Record & | record | ) |
Loads all direct relations to this record.
| Record | The record type whose relation fields are to be populated. |
| record | The record whose BelongsTo, HasMany, HasOneThrough, and HasManyThrough fields are loaded. |
Definition at line 2729 of file DataMapper.hpp.
References Lightweight::EnumerateRecordMembers().
| 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.
| Record | The record type to configure auto-loading for. |
| record | The 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().
| 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
| T | The scalar type of the expected result value. |
| sqlQueryString | The SQL query string to execute. |
Definition at line 3008 of file DataMapper.hpp.
References Lightweight::SqlStatement::ExecuteDirectScalar().
| Async::Task< RecordPrimaryKeyType< Record > > Lightweight::DataMapper::CreateAsync | ( | Record & | record | ) |
Asynchronously inserts record, updating its primary key in place.
Definition at line 24 of file DataMapperAsync.hpp.
References Lightweight::SqlConnection::AsyncBackend().
| Async::Task< std::optional< Record > > Lightweight::DataMapper::QuerySingleAsync | ( | PrimaryKeyTypes... | primaryKeys | ) |
Asynchronously queries a single record by its primary key(s).
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().
| Async::Task< void > Lightweight::DataMapper::UpdateAsync | ( | Record & | record | ) |
Asynchronously updates record's modified fields.
Definition at line 40 of file DataMapperAsync.hpp.
References Lightweight::SqlConnection::AsyncBackend().
| Async::Task< std::size_t > Lightweight::DataMapper::DeleteAsync | ( | Record const & | record | ) |
Asynchronously deletes record.
Definition at line 46 of file DataMapperAsync.hpp.
References Lightweight::SqlConnection::AsyncBackend().
| Async::Task< void > Lightweight::DataMapper::LoadRelationsAsync | ( | Record & | record | ) |
Asynchronously loads record's relations.
Definition at line 52 of file DataMapperAsync.hpp.
References Lightweight::SqlConnection::AsyncBackend().
|
inline |
Queries multiple records from the database using a composed query and optional input parameters.
Definition at line 2157 of file DataMapper.hpp.
|
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().
|
inline |
Binds all output columns of the record via the given cursor.
Definition at line 2818 of file DataMapper.hpp.