Lightweight 0.20250627.0
Loading...
Searching...
No Matches
DataMapper Class Reference

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

#include <DataMapper.hpp>

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 (SqlConnectionString connectionString)
 Constructs a new data mapper, using the given connection string.
 
 DataMapper (DataMapper const &)=delete
 
 DataMapper (DataMapper &&) noexcept=default
 
DataMapperoperator= (DataMapper const &)=delete
 
DataMapperoperator= (DataMapper &&) noexcept=default
 
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<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<typename Record , typename... Args>
std::optional< Record > QuerySingle (SqlSelectQueryBuilder selectQuery, Args &&... args)
 Queries a single record from the database based on the given query.
 
template<typename Record , typename... PrimaryKeyTypes>
std::optional< Record > QuerySingle (PrimaryKeyTypes &&... primaryKeys)
 Queries a single record (based on primary key) from the database.
 
template<typename Record , typename... PrimaryKeyTypes>
std::optional< Record > QuerySingleWithoutRelationAutoLoading (PrimaryKeyTypes &&... primaryKeys)
 Queries a single record (based on primary key) from the database without auto-loading relations.
 
template<typename Record >
SqlQuerySingleBuilder< Record > QuerySingle ()
 Queries a single record from the database.
 
template<typename Record , typename ColumnName , typename T >
std::optional< Record > QuerySingleBy (ColumnName const &columnName, T const &value)
 Queries a single record by the given column name and value.
 
template<typename Record , typename... InputParameters>
std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 Queries multiple records from the database, based on the given query.
 
template<typename Record , typename... InputParameters>
std::vector< Record > Query (std::string_view sqlQueryString, InputParameters &&... inputParameters)
 Queries multiple records from the database, based on the given query.
 
template<typename ElementMask , typename Record , typename... InputParameters>
std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 
template<typename Record >
SqlAllFieldsQueryBuilder< Record > Query ()
 
template<typename Record , auto... ReferencedFields>
SqlSparseFieldQueryBuilder< Record, ReferencedFields... > QuerySparse ()
 
template<typename Record >
bool IsModified (Record const &record) const noexcept
 Checks if the record has any modified fields.
 
template<typename Record >
void Update (Record &record)
 Updates the record in the database.
 
template<typename Record >
std::size_t Delete (Record const &record)
 Deletes the record from the database.
 
template<typename Record >
std::size_t Count ()
 Counts the total number of records in the database for the given record type.
 
template<typename Record >
std::vector< Record > All ()
 Loads all records from the database for the given record type.
 
template<typename Record >
auto BuildQuery () -> SqlQueryBuilder
 Constructs an SQL query builder for the given record type.
 
SqlQueryBuilder FromTable (std::string_view tableName)
 Constructs an SQL query builder for the given table name.
 
template<typename Record >
void ClearModifiedState (Record &record) noexcept
 Clears the modified state of the record.
 
template<typename Record >
void LoadRelations (Record &record)
 Loads all direct relations to this record.
 
template<typename Record >
void ConfigureRelationAutoLoading (Record &record)
 
template<typename Record >
size_t Count ()
 
template<typename Record , typename... InputParameters>
LIGHTWEIGHT_FORCE_INLINE std::vector< Record > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 
template<typename FirstRecord , typename SecondRecord , typename... InputParameters>
requires DataMapperRecord<FirstRecord> && DataMapperRecord<SecondRecord>
std::vector< std::tuple< FirstRecord, SecondRecord > > Query (SqlSelectQueryBuilder::ComposedQuery const &selectQuery, InputParameters &&... inputParameters)
 
template<typename Record , typename ValueType >
LIGHTWEIGHT_FORCE_INLINE void SetId (Record &record, ValueType &&id)
 
template<typename Record , size_t InitialOffset>
LIGHTWEIGHT_FORCE_INLINE Record & BindOutputColumns (Record &record)
 
template<typename ElementMask , typename Record , size_t InitialOffset>
LIGHTWEIGHT_FORCE_INLINE Record & BindOutputColumns (Record &record)
 

Static Public Member Functions

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

Definition at line 558 of file DataMapper.hpp.

Constructor & Destructor Documentation

◆ DataMapper() [1/3]

DataMapper::DataMapper ( )
inline

Constructs a new data mapper, using the default connection.

Definition at line 562 of file DataMapper.hpp.

◆ DataMapper() [2/3]

DataMapper::DataMapper ( SqlConnection &&  connection)
inlineexplicit

Constructs a new data mapper, using the given connection.

Definition at line 569 of file DataMapper.hpp.

◆ DataMapper() [3/3]

DataMapper::DataMapper ( SqlConnectionString  connectionString)
inlineexplicit

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

Definition at line 576 of file DataMapper.hpp.

Member Function Documentation

◆ Connection() [1/2]

SqlConnection const & DataMapper::Connection ( ) const
inlinenoexcept

Returns the connection reference used by this data mapper.

Definition at line 589 of file DataMapper.hpp.

◆ Connection() [2/2]

SqlConnection & DataMapper::Connection ( )
inlinenoexcept

Returns the mutable connection reference used by this data mapper.

Definition at line 595 of file DataMapper.hpp.

◆ Inspect()

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

Constructs a human readable string representation of the given record.

Definition at line 932 of file DataMapper.hpp.

◆ CreateTableString()

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

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

Definition at line 973 of file DataMapper.hpp.

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

◆ CreateTablesString()

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

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

Definition at line 1022 of file DataMapper.hpp.

◆ CreateTable()

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

Creates the table for the given record type.

Definition at line 1034 of file DataMapper.hpp.

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

◆ CreateTables()

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

Creates the tables for the given record types.

Definition at line 1044 of file DataMapper.hpp.

◆ Create()

template<typename Record >
RecordPrimaryKeyType< Record > 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.

Returns
The primary key of the newly created record.

Definition at line 1092 of file DataMapper.hpp.

References ClearModifiedState(), ConfigureRelationAutoLoading(), SqlGuid::Create(), CreateExplicit(), GetPrimaryKeyField(), and SqlStatement::LastInsertId().

◆ CreateExplicit()

template<typename Record >
RecordPrimaryKeyType< Record > 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.
Returns
The primary key of the newly created record.

Definition at line 1051 of file DataMapper.hpp.

References SqlStatement::Execute(), SqlQueryBuilder::Insert(), SqlStatement::LastInsertId(), SqlStatement::Prepare(), and SqlConnection::Query().

Referenced by Create().

◆ QuerySingle() [1/3]

template<typename Record , typename... Args>
std::optional< Record > DataMapper::QuerySingle ( SqlSelectQueryBuilder  selectQuery,
Args &&...  args 
)

Queries a single record from the database based on the given query.

Parameters
selectQueryThe SQL select query to execute.
argsThe input parameters for the query.
Returns
The record if found, otherwise std::nullopt.

Definition at line 1272 of file DataMapper.hpp.

References SqlStatement::Connection(), SqlStatement::Execute(), SqlSelectQueryBuilder::Field(), SqlSelectQueryBuilder::First(), SqlStatement::GetResultCursor(), SqlStatement::Prepare(), and SqlConnection::ServerType().

◆ QuerySingle() [2/3]

template<typename Record , typename... PrimaryKeyTypes>
std::optional< Record > 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.

Definition at line 1263 of file DataMapper.hpp.

References ConfigureRelationAutoLoading().

◆ QuerySingleWithoutRelationAutoLoading()

template<typename Record , typename... PrimaryKeyTypes>
std::optional< Record > DataMapper::QuerySingleWithoutRelationAutoLoading ( PrimaryKeyTypes &&...  primaryKeys)

Queries a single record (based on primary key) from the database without auto-loading relations.

The primary key(s) are used to identify the record to load.

Main goal of this function is to load record without relationships to decrease compilation time and work around some limitations of template instantiation depth on MSVC compiler.

Definition at line 1235 of file DataMapper.hpp.

References SqlStatement::Connection(), SqlStatement::Execute(), SqlStatement::GetResultCursor(), SqlStatement::Prepare(), SqlConnection::Query(), SqlQueryBuilder::Select(), and SqlConnection::ServerType().

◆ QuerySingle() [3/3]

template<typename Record >
SqlQuerySingleBuilder< Record > DataMapper::QuerySingle ( )
inline

Queries a single record from the database.

Returns
A query builder for the given Record type that will also allow executing the query.
auto const record = dm.QuerySingle<Person>(personId)
.Where(FieldNameOf<&Person::id>, "=", 42)
.Get();
if (record.has_value())
std::println("Person: {}", DataMapper::Inspect(record.value()));
static std::string Inspect(Record const &record)
Constructs a human readable string representation of the given record.

Definition at line 674 of file DataMapper.hpp.

◆ QuerySingleBy()

template<typename Record , typename ColumnName , typename T >
std::optional< Record > DataMapper::QuerySingleBy ( ColumnName const &  columnName,
T const &  value 
)

Queries a single record by the given column name and value.

Parameters
columnNameThe name of the column to search.
valueThe value to search for.
Returns
The record if found, otherwise std::nullopt.

◆ Query() [1/5]

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

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

Definition at line 1302 of file DataMapper.hpp.

References ConfigureRelationAutoLoading(), SqlStatement::Execute(), SqlStatement::FetchRow(), SqlStatement::GetColumn(), SqlStatement::NumColumnsAffected(), and SqlStatement::Prepare().

◆ Query() [2/5]

template<typename ElementMask , typename Record , typename... InputParameters>
std::vector< Record > 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.

example:

struct Person
{
int id;
std::string name;
std::string email;
std::string phone;
std::string address;
std::string city;
std::string country;
};
auto infos = dm.Query<SqlElements<1,5>(RecordTableName<Person>.Fields({"name"sv, "city"sv}));
for(auto const& info : infos)
{
// only info.name and info.city are loaded
}
std::integer_sequence< size_t, Ints... > SqlElements
Represents a sequence of indexes that can be used alongside Query() to retrieve only part of the reco...
Definition Record.hpp:17

Definition at line 1374 of file DataMapper.hpp.

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

◆ Query() [3/5]

template<typename Record >
SqlAllFieldsQueryBuilder< Record > DataMapper::Query ( )
inline

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 uset to get result of the

example:

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
}
template <typename FirstRecord, typename NextRecord, typename... InputParameters>
std::vector<std::tuple<FirstRecord, NextRecord>> Query(SqlSelectQueryBuilder::ComposedQuery const& selectQuery,
InputParameters&&... inputParameters);
Similar to previous one but quiery is builded from the object return by the quiery
template <typename FirstRecord, typename NextRecord>
{
std::string fields;
auto const emplaceRecordsFrom = [&fields]<typename Record>() {
Reflection::EnumerateMembers<Record>([&fields]<size_t I, typename Field>() {
if (!fields.empty())
fields += ", ";
fields += std::format(R"("{}"."{}")", RecordTableName<Record>, FieldNameAt<I, Record>);
});
};
emplaceRecordsFrom.template operator()<FirstRecord>();
emplaceRecordsFrom.template operator()<NextRecord>();
}
Queries records of given Record type.
@returns A query builder for the 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.
@code
auto const records = dm.Query<Person>()
.Where(FieldNameOf<&Person::is_active>, "=", true)
.All();
Main API for mapping records to and from the database using high level C++ syntax.
std::vector< Record > All()
Loads all records from the database for the given record type.
SqlQueryBuilder FromTable(std::string_view tableName)
Constructs an SQL query builder for the given table name.
SqlAllFieldsQueryBuilder< Record > Query()
Represents a query builder that retrieves all fields of a record.
LIGHTWEIGHT_API SqlSelectQueryBuilder Select() noexcept
Initiates SELECT query building.
SqlSelectQueryBuilder & Fields(std::string_view const &firstField, MoreFields &&... moreFields)
Adds a sequence of columns to the SELECT clause.
Definition Select.hpp:173
Represents a record type that can be used with the DataMapper.
Definition Record.hpp:44
Represents a single column in a table.
Definition Field.hpp:80

Definition at line 796 of file DataMapper.hpp.

◆ QuerySparse()

template<typename Record , auto... ReferencedFields>
SqlSparseFieldQueryBuilder< Record, ReferencedFields... > DataMapper::QuerySparse ( )
inline

Queries select fields from the given Record type.

The fields are given in form of &Record::field1, &Record::field2, ...

Returns
A query builder for the 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.
auto const records = dm.QuerySparse<Person, &Person::id, &Person::name, &Person::age>()
.Where(FieldNameOf<&Person::is_active>, "=", true)
.All();

Definition at line 825 of file DataMapper.hpp.

◆ IsModified()

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

Checks if the record has any modified fields.

Definition at line 1133 of file DataMapper.hpp.

References Field< T, P1, P2 >::IsModified().

◆ Update()

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

Updates the record in the database.

Definition at line 1150 of file DataMapper.hpp.

References ClearModifiedState(), SqlStatement::Execute(), SqlStatement::Prepare(), SqlConnection::Query(), and SqlQueryBuilder::Update().

◆ Delete()

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

◆ All()

template<typename Record >
std::vector< Record > DataMapper::All ( )

Loads all records from the database for the given record type.

Definition at line 1229 of file DataMapper.hpp.

References SqlSelectQueryBuilder::All(), SqlConnection::Query(), and SqlQueryBuilder::Select().

◆ BuildQuery()

template<typename Record >
auto DataMapper::BuildQuery ( ) -> SqlQueryBuilder
inline

Constructs an SQL query builder for the given record type.

Definition at line 865 of file DataMapper.hpp.

References SqlConnection::Query().

◆ FromTable()

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

Constructs an SQL query builder for the given table name.

Definition at line 871 of file DataMapper.hpp.

References SqlConnection::Query().

◆ ClearModifiedState()

template<typename Record >
void DataMapper::ClearModifiedState ( Record &  record)
noexcept

Clears the modified state of the record.

Definition at line 1413 of file DataMapper.hpp.

Referenced by Create(), and Update().

◆ LoadRelations()

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

Loads all direct relations to this record.

Definition at line 1641 of file DataMapper.hpp.

◆ ConfigureRelationAutoLoading()

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

◆ Count()

template<typename Record >
size_t DataMapper::Count ( )

Definition at line 1216 of file DataMapper.hpp.

◆ Query() [4/5]

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

Definition at line 1293 of file DataMapper.hpp.

◆ Query() [5/5]

template<typename FirstRecord , typename SecondRecord , typename... InputParameters>
requires DataMapperRecord<FirstRecord> && DataMapperRecord<SecondRecord>
std::vector< std::tuple< FirstRecord, SecondRecord > > DataMapper::Query ( SqlSelectQueryBuilder::ComposedQuery const &  selectQuery,
InputParameters &&...  inputParameters 
)

Definition at line 1343 of file DataMapper.hpp.

◆ SetId()

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

Definition at line 1667 of file DataMapper.hpp.

◆ BindOutputColumns() [1/2]

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

Definition at line 1684 of file DataMapper.hpp.

◆ BindOutputColumns() [2/2]

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

Definition at line 1699 of file DataMapper.hpp.


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