This document provides a set of best practices for using the API.
These best practices are based on the experience of the API team and feedback from API users, as well as learnings from
the underlying technologies.
The DataMapper API provides a high-level abstraction for working with database tables.
It simplifies the process of querying, inserting, updating, and deleting data from the database while retaining
performance and flexibility.
Keep the data model and business logic separate to improve the maintainability and scalability of your application.
Remember to also keep frontend (e.g., GUI) and backend (e.g., API) separate.
Declare a column as Field<T> only when it is NOT NULL, and as Field<std::optional<T>> when it
is nullable. A NOT NULL column that has no default member initializer is a
required field: the compiler rejects every place that creates the record
without it, so adding such a column to a table points you at all the code that has to supply it.
Reach for a default member initializer only when the default is a real business value, not to make
the error go away.
Use transactions to group multiple database operations into a single unit of work.
This ensures that all operations are either committed or rolled back together.
However, be careful when using transactions, as they can affect performance severely if not used properly.
First things first, always favor using the DataMapper API over manual querying and binding of columns.
However, when not using the DataMapper API, you need to retrieve the result manually, either via
SqlStatement::BindOutputColumns() or afterwards by fetching the columns individually.
It is always highly recommended to pre-bind to avoid unnecessary memory allocations and copying.
With this, it is sufficient to call SqlStatement::BindOutputColumns() once, and then you can reuse the result
throughout many SqlStatement::FetchRow() calls of that result set. Every fetched row sets each bound variable to
that row's value: strings and binaries get the row's own length, and a std::optional<T> is reset to std::nullopt
on a NULL row and engaged again on the next non-NULL one. The bound variables must outlive the fetch loop; moving a
value out of one between two fetches is fine, the column follows the variable's new storage.
The binding lasts as long as the statement's query: it outlives the end of the result set and the closing of the cursor, so executing the prepared statement again fetches into the same variables, which must therefore stay alive as long as the statement may fetch into them. Preparing or directly executing another query on the statement drops the binding; bind again for it.
A string or binary variable is bound with a buffer of at least 255 units, or its own size if that is larger. A
value longer than the bound buffer is read again with SQLGetData and the buffer grows to it. MS SQL Server's
driver cannot read a bound column again (it lacks SQL_GD_BOUND, see SqlConnection::ReadsBoundColumnsAgain()),
so there the buffer is at least the column's declared length (up to 8000 units, asked once per result set), and a
value that is still longer, such as one in a MAX column, fails FetchRow() with a SqlException instead of
coming back truncated. On SQL Server, read a MAX column with GetColumn() or size the variable to the longest
value before binding it. For this reason the DataMapper does not bind a record with a growable member (any string or
binary type whose size is not fixed, SqlText, or a std::optional of one) on a driver that cannot read a bound
column again: it reads that record per row with GetColumn(), which sizes every value to itself.
struct MixedNullRow
{
Field<SqlGuid, PrimaryKey::AutoAssign> id {};
Field<std::optional<SqlAnsiString<30>>> name {};
Field<std::optional<int>> age {};
};
void ForEachData(SqlStatement& stmt, auto&& onRow)
{
stmt.ExecuteDirect(stmt.Query(RecordTableName<MixedNullRow>)
.Select()
.Fields({ "id"sv, "name"sv, "age"sv })
.All());
auto currentRow = MixedNullRow {};
// Bind the output columns once for the whole result set
stmt.BindOutputColumns(¤tRow.id, ¤tRow.name, ¤tRow.age);
while (stmt.FetchRow())
onRow(currentRow);
}When querying the result set, always access the columns in the order they are returned by the query.
At least the MS SQL Server driver has issues when accessing columns out of order.
Carefully check the driver documentation for the specific behavior of the driver you are using.
This can be avoided when using the DataMapper API, which always maps the result in order and as efficiently as
possible.
Use the native column types provided by the API for the columns in your tables.
This will help to improve the performance of your application by reducing the overhead of data conversion.
The existence of SqlVariant in the API allows you to store any type of data in a single column, but it is recommended
to use the native column types whenever possible.
Prepared statements are precompiled SQL statements that can be executed multiple times with different parameters.
Using prepared statements can improve the performance of your application by reducing the overhead of parsing,
analyzing, and compiling SQL queries.
When querying large result sets, use pagination or infinite scrolling to limit the number of results returned in a
single response.
This will help to reduce the response time and the load on the server, and improve the performance of your
application.
Touching a relation on each record of a result set issues one query per record — the N+1 problem. Name the relation on the query instead, and it is resolved for the entire batch in a constant number of queries:
auto albums = dm.Query<Album>().With<&Album::tracks>().All(); // 2 queries, not 1 + NA nested relation needs the whole path named — .With<&Track::album, &Album::artist>() — because
each record holds its own copy of the target, so one level of eager loading leaves the level below it
loading per record. DataMapperOptions { .eagerLoadDepth = N } loads everything reachable instead,
at the cost of fetching more than you asked for.
See Eager loading of relations. Two things compound with it:
- Index your foreign keys.
CreateTable<Record>()emits an index for everyBelongsTocolumn, because no supported engine indexes a foreign key implicitly. Tables created by hand, or by an older version of Lightweight, need that index added — without it every relation query is a full table scan. - Prove the absence of N+1 in tests. A
SqlLoggersubclass countingOnPrepare/OnExecuteDirectturns "this endpoint issues two queries" into an assertion instead of an assumption.
Per-row fetch loops issue one SQLFetch (one network round-trip) per row. Lightweight transparently
fetches rows in blocks (ODBC row-array binding) so a large result set costs ceil(rows / depth)
round-trips instead of one per row — see Transparent block-prefetch. It is on by default
(Lightweight::PrefetchDepthDefault, 1000 rows) and tuned per connection:
connection.SetDefaultPrefetchDepth(1000); // rows per SQLFetchScroll round-trip; <= 1 disablesKeep in mind:
- It engages only for fixed-width numeric/temporal result sets; result sets with character,
GUID,NUMERIC,TIME, binary or LOB columns transparently stay on the per-row path. - An active cursor reads ahead up to one block and holds a few MB of buffers, so set the depth to
1on a connection used for cursors you intend to abandon early or where memory is tight. - It does not change results — values are identical to the per-row path.
Every fresh prepare costs a server-side parse and plan on Microsoft SQL Server and PostgreSQL — charged
at the statement's first execute, not inside SQLPrepare — and the DataMapper / query-builder layers
re-prepare the same handful of statements on every call because each call site builds a fresh
SqlStatement. A connection can pool the already-prepared handles so repeats re-execute one instead —
see Prepared-statement cache:
connection.SetPreparedStatementCacheCapacity(Lightweight::PreparedStatementCacheCapacitySuggested);Measured against Docker-local servers, this is worth 4.2x on PostgreSQL, 1.7x on MS SQL Server and
1.4x on SQLite for a repeatedly re-prepared single-row read, and 3.8x / 1.3x / 1.1x for the same
query driven through DataMapper::Query<>(). What it removes is network round-trips — about 2.8 per
query on PostgreSQL and exactly one on MS SQL Server — so the further away the server, the more it
is worth: across a 50 ms link the same PostgreSQL read goes from 202 ms to 61 ms. The full tables, the
latency sweep and the workloads that gain nothing are in usage.md.
Keep in mind:
- It is opt-in (default capacity
0), and transparent once enabled — no call-site changes. - It pays off where a short-lived statement re-prepares a text the connection has seen — the shape the
query builders produce. Code that already drives one long-lived
SqlStatementthrough one query text (asDataMapper::QuerySingle()does) reuses its own handle regardless and gains nothing. - On SQLite it is roughly break-even: with no network there is no round-trip to save, and
DataMapper::Create()measures ~8% slower because its last-insert-idExecuteDirect()has to park the prepared handle. Enable it for the network-backed engines. - Size it to your working set of distinct query texts. Too small and the LRU thrashes; too large and you risk the server-side cap on live prepared statements per session.
- With a connection pool, set it once via
PoolConfig::preparedStatementCacheCapacity(or theLIGHTWEIGHT_POOL_PREPARED_STATEMENT_CACHE_CAPACITYCMake option forGlobalDataMapperPool()) instead of per acquired connection. Budget for the whole pool: handles cannot be shared between connections, so a warmed pool holds up tomaxSize * preparedStatementCacheCapacityof them, and every connection pays its own warm-up — measured, exactlyconnections * distinct query textsprepares, paid once. Pool size does not dilute the steady-state win (one connection and four reach the same speed-up), but short-lived work does: at six operations per connection the PostgreSQL gain fell from 2.35x to 1.69x. - Anything that retires a connection discards its warmed cache. Under
GrowthStrategy::BoundedOverflowa connection created past the idle set is destroyed when returned, so the pool never stops re-preparing: the PostgreSQL gain drops from 2.5x to 1.4x and SQLite's to nothing. RaisingmaxSizeto cover the real concurrency is worth more than any cache capacity. The same applies toPoolConfig::maxIdleTimeMs,maxLifetimeMsand a failedvalidateOnBorrowcheck — worth keeping in mind when picking a recycle window, though a stale connection is still worse than a cold one. - A pooled handle carries the plan derived from the schema at preparation time. Call
ClearPreparedStatementCache()after raw DDL; migrations andMigrateDirect()already do. - Statements whose plan must be re-derived opt out via
SqlStatement::SetPreparedStatementCaching(SqlPreparedStatementCaching::Disabled).
Oracle database does not support 64-bit integers natively.
When working with 64-bit integers in Oracle database, you need to use the SqlNumeric column types.