ORM C++
Loading...
Searching...
No Matches
Database

  1. Connect
  2. Capabilities and errors
  3. Create table
  4. Delete table
  5. Create and delete relation tables
  6. Insert objects
  7. Insert objects in batches
  8. Link and unlink relations
  9. Query objects
  10. Update objects
  11. Remove objects
  12. Transactions

Connect

Create a database connection independently of model schemas. Obtain a borrowed ORM context for each closed compile-time schema:

struct User
{
int id;
};
using AppSchema = orm::Schema<User>;
orm::Database database{orm::SqliteConfig{.database = std::filesystem::path{"test.db"}}};
auto context = database.orm<AppSchema>();
auto orm() &noexcept -> OrmContext< SchemaType >
model::Schema< Models... > Schema
Definition schema.cppm:504

Every model used by select, insert, schema operations, or relation operations must belong to AppSchema. All relation targets must be listed as well. Missing models and invalid mappings fail during compilation.

Database owns the connection and transaction. OrmContext<Schema> borrows that database; it does not own a connection or cache a backend. Creating or copying a context requires no allocation. A context can be copied, moved, or assigned to another database's context of the same schema. Model operations require a connected database.

The database must outlive every context that refers to it. Contexts cannot be default constructed or obtained from a temporary or const database. Destroying a context leaves the connection and transaction open. Disconnecting rolls back the transaction; existing contexts work again after reconnecting, using the current backend. The session is shared, so contexts do not enable concurrent access to a database.

orm::Schema<...> describes a closed set of C++ models and their relations. It does not select a PostgreSQL namespace or verify the physical database layout.

The remaining fragments are independent examples. In each case, the context object's schema must contain every model named by that operation.

Constructing Database{config} synchronously opens and initializes the session, or throws DatabaseError with operation connect. There is no empty constructor. The four owned configuration values are available even in core-only builds:

Configuration Backend Source
SqliteConfig SQLite std::filesystem::path or explicit SqliteMemory{}
PostgresConfig PostgreSQL Optional libpq connection fields
MysqlConfig MySQL Optional Oracle MySQL client connection fields
MariadbConfig MariaDB Optional Oracle MySQL client connection fields

All adapters default to disabled at build time. Using a configuration whose adapter is not registered throws UnsupportedBackend. Selection uses db::ConnectionTraits<Config>::backendType; it does not inspect parameter text.

.host = "localhost", .port = 5432, .database = "application",
.user = "application", .password = password,
}};
server.disconnect();
server.connect(orm::PostgresConfig{.database = "application"});
auto connect(const Config &config) -> void
Connects to a database.
auto disconnect() -> void
Disconnects from the database.

Server strings, port and connection timeout are optional. Omitted fields are not sent, preserving client and environment defaults. An explicitly empty string is preserved as a distinct value; the native client decides its meaning. Omitting credentials does not imply anonymous login. PostgreSQL still authenticates a role; MySQL/MariaDB may match an anonymous account according to server rules. There is no anonymous flag, authentication fallback, automatic retry, or reconnect.

SQLite requires a nonempty path or explicit memory tag. Paths use UTF-8. openMode optionally selects ReadWriteCreate, ReadWrite, or ReadOnly; busyTimeout is milliseconds. Server connectTimeout is seconds (PostgreSQL 0..INT_MAX; MySQL/MariaDB 1..UINT_MAX). Invalid ranges are rejected before opening without silent truncation; these timeouts do not promise a common bound on the whole startup operation. Embedded NUL is rejected. Whitespace, quotes, backslashes, equals signs and Unicode remain parameter data.

PostgresTls provides optional PostgresSslMode and CA, client certificate and key paths. MysqlTls provides corresponding MysqlSslMode and paths for both MySQL-family configurations. Empty TLS fields preserve native policy; specifying a CA does not implicitly choose a verification mode. PostgreSQL also exposes passfile; MySQL-family configurations expose socket. See Backends.

connect(config) on an active owner throws AlreadyConnected. Call disconnect() first; it rolls back an active transaction and reports rollback errors after closing. Failed construction releases opened resources; failed reconnect leaves the owner disconnected and ready for another explicit attempt. Cleanup depends on resource ownership, including when a health check fails. The destructor never propagates exceptions.

Database is neither copyable nor movable. Existing contexts use the current session after reconnect; transactions and migration locks are not restored. The owner does not retain configurations for a parameterless reconnect. SOCI and native clients may retain internal copies of connection parameters. Diagnostics exclude configuration values and passwords. No URI parser is provided.

All four supported backends enforce generated foreign keys. SQLite connections automatically enable PRAGMA foreign_keys=ON; PostgreSQL requires no equivalent session setup. Foreign-key violations therefore fail immediately, and deleting a many-to-many endpoint removes its junction rows through the generated ON DELETE CASCADE rules. PostgreSQL uses the session's active search_path; schema-qualified model names are not a public API in this release.

Capabilities and errors

getBackendCapabilities() returns the selected backend's centralized schema, query, mutation, relation, type, value-limit, and transaction feature profile. Unsupported optional behavior is rejected before SQL execution with DatabaseErrorCode::UnsupportedFeature.

Operations crossing the backend boundary throw orm::DatabaseError. Inspect getCode(), getBackendType(), getOperation(), and the optional getNativeCode() instead of parsing vendor message text. Diagnostics are sanitized and do not contain connection strings or bound values.

Native date/time and UUID values share the CRUD, nullable, projection, manual/composite-key and relation paths. supportedColumnTypes reports availability, and valueLimits reports static temporal bounds. Execution also applies connection-specific limits, including the actual MariaDB server's timestamp range. Unsupported native types give UnsupportedFeature; invalid calendars, storage representations and ranges give Conversion before binding or when decoding a result.

PostgreSQL sessions establish ISO/YMD date formatting and UTC. MySQL/MariaDB establish UTC, strict mode and explicit timestamp defaults. Reconnect repeats this initialization. Applications must preserve these settings; in particular, changing the MySQL-family session zone changes native TIMESTAMP interpretation. LocalDateTime and UtcTimestamp remain distinct even when the host uses a different time zone. The ORM does not add automatic timestamp defaults or UUID generation.

Create table

To create a table in the database, use createTable method and pass model as template argument:

struct ObjectModel
{
int id;
std::string name;
std::optional<std::string> email;
std::string password;
std::string created_at;
std::string updated_at;
};
context.createTable<ObjectModel>();

Delete table

To delete a table from the database, use deleteTable method and pass model as template argument:

context.deleteTable<ObjectModel>();

Create and delete relation tables

Base model tables and many-to-many junction tables have an explicit lifecycle. Create both endpoint tables first, then create junction tables from the owning model:

context.createTable<User>();
context.createTable<Role>();
context.createRelationTables<User>();

createRelationTables<T>() creates only junction tables owned by T. It is a no-op for one-to-many mappings and inverse many-to-many mappings. Repeated calls are safe. Endpoint tables must already exist.

Drop junction tables before either endpoint table:

context.deleteRelationTables<User>();
context.deleteTable<Role>();
context.deleteTable<User>();

deleteRelationTables<T>() is also idempotent and affects only junction tables owned by T. createTable, deleteTable, insert, and row deletion never recursively create, drop, or synchronize relation tables.

Insert objects

To insert objects into the database, use insert method and pass vector of objects as argument:

std::vector<ObjectModel> objects{
{1, "name", "email", "password", "created_at", "updated_at"},
{2, "name2", "email2", "password2", "created_at2", "updated_at2"}
};
context.insert(objects);

You can also insert single object:

ObjectModel object{1, "name", "email", "password", "created_at", "updated_at"};
context.insert(object);

For models with an auto-increment primary key, the generated INSERT statement omits that primary-key column and the selected database assigns the value:

struct User
{
int id;
std::string name;
inline static constexpr auto auto_increment_columns =
};
context.createTable<User>();
context.insert(User{0, "Ann"});
consteval auto autoIncrement()
Definition mapping.cppm:596

insert does not mutate the passed object. Select the row after insertion if you need the generated id.

Optional fields and optional one-to-one relations store std::nullopt as SQL NULL:

struct Profile
{
int id;
std::string city;
};
struct User
{
int id;
std::optional<Profile> profile;
};
context.insert(User{1, std::nullopt});

OneToMany and ManyToMany wrapper fields are ignored by insert. Endpoint objects must be inserted separately, followed by explicit link calls where a stored relation is needed. There is no cascade-save.

Insert objects in batches

insertMany inserts a borrowed sequence of objects atomically on backends that advertise the capability. The primary overload accepts std::span<const T>; a narrow forwarding overload accepts const std::vector<T>&:

std::vector<ObjectModel> objects{
{1, "name", "email", "password", "created_at", "updated_at"},
{2, "name2", "email2", "password2", "created_at2", "updated_at2"}
};
context.insertMany(objects);
context.insertMany(std::span<const ObjectModel>{objects});

std::array and other contiguous ranges participate through an explicit std::span. The input is borrowed for the duration of the call and is not retained. An empty input returns before any backend work, capability check, or SQL on every backend.

Batching is PostgreSQL-only in v1. PostgreSQL reports getBackendCapabilities().mutations.insertMany == true; SQLite, MySQL and MariaDB report false, and a non-empty call is rejected with DatabaseErrorCode::UnsupportedFeature before the first write. Empty input is still a no-op there.

Each row is mapped like a single insert: model and column names follow the existing qualification rules, auto-increment primary-key columns are omitted so the database generates them, to-one foreign-key columns are bound from the related model's primary key, and std::nullopt is stored as SQL NULL, distinct from an empty string. Generated SQL contains only quoted identifiers and bind placeholders; values are never formatted into SQL text. The operation returns void and exposes no generated keys, inserted-row count, physical row order, upsert, chunk control, or RETURNING.

Without an active caller transaction, insertMany owns one transaction and sends a single COMMIT after the last chunk; any failure rolls the whole batch back. Inside a healthy caller transaction it uses one internal savepoint, releases it on success, and never commits the caller's transaction. A caller transaction that already contains a failed statement rejects the batch before the first write instead of being reset. Because deferred constraints may fail at commit time, a successful insertMany inside a caller transaction does not guarantee that the caller's later COMMIT succeeds.

The legacy insert(const std::vector<T>&) remains unchanged: it executes one INSERT per element, is not atomic, stops at the first failure, and keeps rows written before that failure.

Link and unlink relations

Many-to-many mutations add or remove one junction row:

User user{1, "Ada"};
Role admin{10, "admin"};
std::size_t linked = context.link<&User::roles>(user, admin);
std::size_t unlinked = context.unlink<&User::roles>(user, admin);

Each operation is idempotent: it returns 1 when the relation changed and 0 when the database was already in the requested state. The same operations can be called through an inverse many-to-many field.

For one-to-many, select the collection member in the template argument and pass the parent and child:

std::size_t assigned = context.link<&Author::books>(author, book);
std::size_t detached = context.unlink<&Author::books>(author, book);

link updates the child's mapped foreign key, including moving it from another parent. unlink writes SQL NULL; it throws std::invalid_argument when the child's mapped to-one field is not optional. They return 1 only when the stored foreign key changed and 0 when it was already in the requested state.

link and unlink read only endpoint primary keys. They do not persist either object, and all components of a simple or composite key must be present and non-null. A model with a database-generated key must be selected after insert before it is used as an endpoint. Missing endpoint rows are rejected by foreign-key enforcement on all four supported backends.

See Collection relations for mapping declarations, generated junction schemas, delete behavior, and self-referencing mappings.

Query objects

To select objects from database use select method and pass query as argument:

using namespace orm::query;
query.where(col<&ObjectModel::name>().like("name%"))
.limit(10);
auto queriedObjects = context.select(query);
A template class representing a select query in the ORM framework.
Definition select.cppm:39
constexpr auto asc(TypedColumn< Members... > column)
constexpr auto col() -> TypedColumn< Members... >
Definition columns.cppm:336

PostgreSQL rejects full-model GROUP BY/HAVING queries before SQL execution, because selecting arbitrary non-grouped model fields has no portable meaning. Use ProjectionQuery and explicitly project grouped columns and aggregates.

Update objects

To update rows, build an orm::Update<Model> with one or more assignments and a required predicate:

using namespace orm::query;
update.set(col<&ObjectModel::email>(), "new-email@example.com")
.set(col<&ObjectModel::updated_at>(), "updated_at")
.where(col<&ObjectModel::id>() == 1);
std::size_t updatedRows = context.update(update);
constexpr auto update()

Use std::nullopt to store NULL in nullable columns:

clearEmail.set(col<&ObjectModel::email>(), std::nullopt)
.where(col<&ObjectModel::id>() == 1);
auto set(query::TypedColumn< Members... > column, Value &&value) -> Update< T > &
Definition update.cppm:36

update returns the number of affected rows. Calling it without a where predicate, or without assignments throws std::invalid_argument. Assigning NULL or an optional value to a non-nullable column fails to compile. Assignments accept only type-compatible values with safe numeric widening. Nullable assignments also accept std::optional<T> when T satisfies the same value rule; an empty optional stores SQL NULL. Filter values do not accept optionals: test nullability explicitly in the predicate.

Remove objects

To delete rows, call remove with the model type and a required predicate:

using namespace orm::query;
std::size_t removedRows = context.remove<ObjectModel>(col<&ObjectModel::id>() == 1);

remove returns the number of affected rows. There is no unfiltered public delete-row API.

Transactions

Start a transaction with beginTransaction, then call commitTransaction or rollbackTransaction on the database. All contexts obtained from that database participate in the same transaction:

struct AuditEntry
{
int id;
std::string action;
};
using AuditSchema = orm::Schema<AuditEntry>;
auto audit = database.orm<AuditSchema>();
context.createTable<User>();
audit.createTable<AuditEntry>();
database.beginTransaction();
context.insert(User{1});
audit.insert(AuditEntry{1, "created user"});
database.commitTransaction();
auto beginTransaction() -> void
Starts a transaction.
auto commitTransaction() -> void
Commits a transaction.

For a single context:

database.beginTransaction();
context.insert(objects);
database.commitTransaction();

or:

database.beginTransaction();
context.insert(objects);
auto rollbackTransaction() -> void
Rollbacks a transaction.

PostgreSQL marks a transaction failed after a statement error. commitTransaction() then throws orm::DatabaseError with getCode() == DatabaseErrorCode::Transaction without sending a misleading commit; catch the exception and call rollbackTransaction() before starting another transaction. The function returns void on success.

Scoped transactions

database.scopedTransaction() starts one application transaction and returns a noncopyable, nonmovable RAII guard. The method is [[nodiscard]], so keep the result in a named local variable. The database must outlive the guard.

{
auto transaction = database.scopedTransaction();
context.insert(User{1, "Ada"});
transaction.commit(); // or transaction.rollback()
}
auto scopedTransaction() &-> ScopedTransaction

Leaving the scope without an explicit call attempts to roll back. The guard commits or rolls back only its own transaction. Its destructor never throws: it attempts rollback when the guard is still the owner and does nothing when it is already finished or retired. If rollback fails, the session is closed; call rollback() explicitly if the caller needs to observe that error. Calling commit() or rollback() on a completed or retired guard throws DatabaseErrorCode::Transaction before any session check.

The database still permits only one application transaction at a time. Every context obtained from that database participates in the scoped transaction. Scoped guards cannot be nested. beginTransaction() is rejected while a scoped guard is active, and commitTransaction() or rollbackTransaction() are rejected while the guard owns the transaction. A scoped transaction cannot start while a manual transaction or a migration is active. disconnect() rolls back an active scoped transaction, closes the session, reports the first error, and retires the guard; the retired guard's destructor is a no-op. After reconnecting, a new scoped transaction can start.

A driver error during scoped BEGIN closes the session and propagates the sanitized translated error. A known failed statement, such as the PostgreSQL aborted-transaction state, is rejected by scoped commit() with DatabaseErrorCode::Transaction before the driver commit; the guard stays active so it can still be rolled back. If the driver rejects COMMIT itself, the error code is DatabaseErrorCode::CommitUncertain: the commit outcome is unknown, the local session is closed, and the guard is retired without retrying the commit. A NotConnected error while committing or rolling back retires the guard and closes local session state; the ORM does not reconnect or retry. Schema operations inside a scoped transaction require the backend's transactional DDL capability: SQLite and PostgreSQL allow them, while MySQL and MariaDB reject them with UnsupportedFeature.

Batched inserts and transactions

Without a caller transaction, insertMany starts and commits its own. If rolling back that private transaction fails, it closes the session. Inside a healthy manual or scoped transaction, it creates one internal savepoint named orm_insert_many_<n> for the whole call and releases it after the last chunk. On a chunk failure it issues ROLLBACK TO SAVEPOINT, then RELEASE SAVEPOINT, and restores the healthy state only after both succeed. The original DatabaseError category, operation and native SQLSTATE are preserved. A cleanup failure appends ; savepoint cleanup failed: <cause> and requires the caller to roll back the transaction rather than reuse it. A caller transaction that is already marked failed or whose session state is unknown is rejected before the first chunk.

Relation-table operations, link, unlink, and included selects participate in the current explicit transaction and never start a private transaction. Because an included select uses the parent query plus one or more batched queries per included collection, a consistent snapshot requires both an explicit transaction and a backend isolation level that preserves that snapshot across statements. beginTransaction() does not select or strengthen the isolation level. In PostgreSQL's default READ COMMITTED, consecutive queries can still observe commits from other connections. Configure the required isolation through the database's connection defaults before connecting; this API has no isolation setter. See transactions and consistency.