|
ORM C++
|
Create a database connection independently of model schemas. Obtain a borrowed ORM context for each closed compile-time schema:
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.
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.
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.
To create a table in the database, use createTable method and pass model as template argument:
To delete a table from the database, use deleteTable method and pass model as template argument:
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:
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:
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.
To insert objects into the database, use insert method and pass vector of objects as argument:
You can also insert single 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:
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:
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.
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::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.
Many-to-many mutations add or remove one junction row:
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:
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.
To select objects from database use select method and pass query as argument:
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.
To update rows, build an orm::Update<Model> with one or more assignments and a required predicate:
Use std::nullopt to store NULL in nullable columns:
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.
To delete rows, call remove with the model type and a required predicate:
remove returns the number of affected rows. There is no unfiltered public delete-row API.
Start a transaction with beginTransaction, then call commitTransaction or rollbackTransaction on the database. All contexts obtained from that database participate in the same transaction:
For a single context:
or:
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.
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.
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.
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.