ORM C++
Loading...
Searching...
No Matches
Backend extension contract

This document defines how contributors add database backends to orm-cxx. It is a source-level extension contract for implementations built with the library. It is not a stable binary plugin ABI, shared-library discovery protocol, or promise that independently compiled backend modules remain compatible across releases.

Backends are registered as source-level BackendProvider implementations. There is deliberately no runtime discovery or binary plugin ABI. New backends remain in-tree source contributions until the project defines a separately versioned plugin interface.

Concrete extension points

The backend boundary is split into focused contracts:

  • BackendProvider owns backend identity, capabilities, and access to the remaining strategies;
  • BackendRuntime owns session initialization, catalog access, runtime limits, canonical value binding, affected-row normalization, and driver-error translation;
  • SqlDialect owns identifier quoting, bind markers, pagination, generated-key syntax, and relation-specific SQL forms;
  • CommandGenerator is the polymorphic interface for the backend's model and query command operations, including the optional batch insert; DefaultCommandGenerator implements them using a SqlDialect;
  • CommandGeneratorFactory is the registry and deterministic selection point.

Database consumes these interfaces and does not branch on individual backend types. A provider is registered once by BackendType. Define a configuration value and specialize its trait to choose the provider without parsing text:

struct MyConfig { std::string endpoint; };
template<> struct orm::db::ConnectionTraits<MyConfig>
{
static constexpr auto backendType = orm::db::BackendType::Oracle;
};
backends.registerBackend(std::make_unique<MyBackend>());
orm::Database database{MyConfig{"endpoint"}, std::move(backends)};
auto registerBackend(std::unique_ptr< BackendProvider > backend) -> void

BackendRuntime::open(soci::session&, db::ConnectionConfigView) borrows the configuration only during synchronous opening. Read view.get<MyConfig>(), which checks type identity using std::type_info equality and throws a sanitized DatabaseError on a mismatch, even for two types mapping to the same backend. Do not cache the view or a reference to its data. Temporary configurations passed to Database remain valid for that synchronous call. Inline trait/view/template definitions are reachable through import orm; and available without clients. onConnect establishes required invariants before the owner publishes the session.

The registry and its providers become owned by the database object. In-tree backends may also be registered by the factory's default construction path.

The CommandGeneratorFactory(std::vector<std::unique_ptr<BackendProvider>>) constructor registers exactly the supplied providers. Pass an empty vector to start an empty registry, or supply your own provider without the default built-in registration.

Migration support is opt-in through BackendCapabilities::migrations.supported and declares migrations.atomicity as Transactional or NonTransactional. A migration-capable runtime supplies migrationTable, migrationHistoryExists, createMigrationHistory, beginMigration and executeMigrationScript to resolve and inspect the history table, acquire the appropriate lock and execute SQL without changing session settings. validateMigrationSession checks any required session invariants before history values are bound; its default is a no-op. Nontransactional engines also supply migrationJournalTable for durable failure tracking and endMigration to release session locks. Default hooks reject unsupported operations. The runner owns history updates and transactional commit/rollback; it never claims that nontransactional DDL can be undone.

An extension translation unit uses import orm;. The command override types are orm::db::SelectSpec, orm::db::UpdateSpec, and orm::db::Predicate. orm::db::ast provides the runtime column, predicate-node, aggregate, ordering, projection, and assignment types needed to inspect those inputs. Endpoint keys use orm::db::PrimaryKey. These names define the backend input contract; application queries continue to use the typed orm::query builders.

Implement the required operations by deriving from CommandGenerator, or derive from DefaultCommandGenerator and override only the operations that differ. Both types are available through import orm;, including builds with no built-in backend enabled. The default generator borrows a const SqlDialect&; the dialect must outlive the generator. A provider storing both should declare its dialect before its generator so destruction occurs in the reverse order.

Batching is opt-in. MutationCapabilities::insertMany defaults to false, and CommandGenerator::insertMany has a default implementation that rejects the operation, so a backend that does not support batches needs no new code. A backend opting in must set the capability to true, override insertMany to render a multi-row INSERT, and honour the declared maximum bind-parameter count when it chooses a chunk. It must reuse the same column qualification, generated-key omission, to-one foreign-key binding, and driver-error translation as single-row insert; a model without bound columns is rejected before SQL. The operation returns no generated keys or row count and promises no row order.

For example, a provider can store this generator and return it from commandGenerator():

class CustomCommands final : public orm::db::DefaultCommandGenerator
{
public:
using DefaultCommandGenerator::DefaultCommandGenerator;
auto select(orm::model::ModelView model, const orm::db::SelectSpec& spec) const
{
auto statement = DefaultCommandGenerator::select(model, spec);
statement.sql.insert(0, "/* custom select */ ");
return statement;
}
};
auto select(model::ModelView model, const SelectSpec &spec) const -> SelectStatement override
query::detail::SelectSpec SelectSpec
Statement SelectStatement
Definition commands.cppm:20
Trivially-copyable handle to one model in immutable Schema storage.
Definition views.cppm:181

BackendProvider::compiledSqlFlavor() defaults to CompiledSqlFlavor::None. With that default, static plans also use the runtime generator. Advertising a known flavor opts eligible static plans into precompiled SQL that bypasses CommandGenerator; dynamic queries and unsupported static shapes still use the generator. A provider changing generated SQL must leave the flavor as None unless that precompiled SQL implements the intended behavior too.

The external import compile control verifies complete and partial generator overrides, predicate-node inspection, and registration of a provider owning the custom generator without joining the library's module implementation. External consumer execution also exercises inherited operations and partial overrides.

Built-in provider and dialect declarations are exported only when their backend is enabled in the library build. orm::config::sqliteBackendEnabled, orm::config::mysqlBackendEnabled, orm::config::mariadbBackendEnabled and orm::config::postgresqlBackendEnabled report that build configuration.

Required backend responsibilities

A backend implementation owns the following responsibilities behind one centrally selected adapter or equivalent contract:

  1. Identity and selection
    • provide a stable backend name and type;
    • specialize ConnectionTraits<Config> and read the checked configuration;
    • reject unknown or disabled backends before generating SQL.
  2. Session lifecycle
    • open and close the appropriate SOCI session;
    • apply required per-session configuration;
    • support begin, commit, and rollback or reject the backend as incomplete.
  3. Command generation
    • render create/drop table, insert, select, update, and remove operations;
    • opt into MutationCapabilities::insertMany, override CommandGenerator::insertMany, and honour the bind limit when batching is advertised;
    • render joins, predicates, ordering, grouping, projection, and pagination;
    • render collection-relation DDL, loading, and mutations when that capability is advertised.
  4. Types and values
    • map supported model column types to database types;
    • bind and hydrate the ORM's canonical C++ value representations;
    • preserve nullable values and detect unsupported or lossy conversions.
  5. Execution semantics
    • report exact affected rows for public APIs returning a count;
    • provide catalog or introspection operations required by ORM behavior;
    • honor the declared maximum bind-parameter count when batching statements.
  6. Errors
    • translate driver failures into stable ORM error categories;
    • retain useful native error information without exposing credentials;
    • reject unsupported capabilities before sending SQL.

Transaction support and exact mutation counts are part of the current public API and therefore required for a supported backend. A backend that cannot provide them may be developed experimentally but must not be listed as supported.

Capabilities versus dialect

Do not use capabilities to expose every syntax difference to applications.

A capability is user-visible behavior that may be unavailable or have semantics that cannot be emulated reliably, for example:

  • database-generated integer primary keys;
  • full-model grouping;
  • enforced foreign keys;
  • collection relations;
  • native UUID, date, or time values.

A limit is backend data, such as maximum bind parameters per statement or the largest numeric value a driver can exchange without loss. query.maxOrderedStringLength requires typed string ordering to use a declared column bound no greater than that limit; an empty value imposes no such restriction.

supportedColumnTypes governs native Date, TimeOfDay, LocalDateTime, UtcTimestamp and Uuid too. Advertise real native types without implicit text, binary or epoch-number fallback. Explicit Binary16 and Text36 UUID storage is a separate per-field/backend mapping and is not a claim of native UUID support. Static temporal bounds belong to BackendValueLimits; connection/version-dependent bounds belong to BackendRuntimeLimits. Execution applies their intersection without mutating shared providers, including standalone parameters, related keys and static plans.

Preserve all six microsecond digits in binding and hydration. The bundled adapters use stable text result buffers for native temporal and UUID values and explicit SOCI into(storage, indicator) followed by logical-type decoding. Avoid dynamic db_date/std::tm, which loses fractions, and result-formatting casts that change DISTINCT or grouping semantics. Preserve aliases, positions, lifetime and null indicators across model/DTO/collection results. Invalid native values give Conversion; unavailable types give UnsupportedFeature before SQL. Binary16 uses session-bound binary buffers with stable lifetimes; Text36 uses canonical text. SQLite must validate the actual storage class, and Binary16 also requires the exact byte length. MySQL's fixed-width binary column may pad an external short write before it can be read.

Establish temporal session invariants in onConnect, repeat them after reconnect, and check them in migration hooks before binding history values and accepting script success. The bundled profiles use ISO/YMD and UTC for PostgreSQL, and UTC/strict mode/explicit timestamp defaults for MySQL/MariaDB. UUID equality and keys are supported; typed ordering, range operations and MIN/MAX are intentionally unavailable. See Value types.

Adapter implementation details include, for example:

  • identifier quoting and qualification;
  • placeholder, pagination, and generated-column syntax;
  • IF EXISTS or IF NOT EXISTS forms;
  • conflict handling used for idempotent relation links;
  • runtime catalog access used to determine whether a table exists.

Dialect and runtime differences must remain behind the adapter. Shared ORM code should ask for behavior or a declared limit, not branch on individual backend enum values.

SOCI boundary

SOCI is the transport and driver abstraction used by the project. A backend may use SOCI to open sessions, prepare statements, exchange values, and obtain native driver information. SOCI does not define the ORM's model contract, command semantics, capabilities, batching policy, or error categories.

An adapter must verify the actual SOCI backend behavior through live tests. Merely enabling a SOCI build target is insufficient. Backend-specific SOCI objects should not be exposed through public model or query APIs.

Raw SQL

Raw predicates and ordering fragments are passed through as backend-specific SQL. The adapter is not required to translate them between dialects. Their explicit values must continue to use prepared bind parameters, and documentation must not describe a raw fragment as portable unless the relevant dialects are verified.

Error contract

Backend work must preserve the DatabaseErrorCode categories:

  • NotConnected — operation requires an active connection;
  • AlreadyConnected — duplicate connect call;
  • UnsupportedBackend — requested backend type is not registered;
  • UnsupportedFeature — the backend does not implement the requested capability;
  • Connection — connection failure;
  • Statement — statement execution failure;
  • Constraint — constraint violation;
  • Transaction — invalid transaction state;
  • Conversion — type conversion or hydration failure;
  • AffectedRowsUnavailable — affected-row count is not supported.

Errors should identify the backend and logical operation. Native codes may be attached, and the driver exception may be retained as a nested cause. Tests must assert categories and state changes rather than vendor-specific English text. Connection strings, passwords, and tokens must not be included in diagnostics.

Conformance tests

Every backend must execute the same conformance test sources. Those tests use only public ORM APIs and cover:

  • lifecycle and backend selection;
  • schema creation and removal;
  • scalar, nullable, mapped-name, manual-key, and composite-key round trips;
  • CRUD, binding safety, affected rows, transactions, and pagination;
  • full-model and projection query behavior advertised by the backend;
  • to-one and collection relation behavior advertised by the backend;
  • stable errors for unsupported optional capabilities.

The backend test harness supplies a connection, declared capabilities and limits, an isolated schema or database, and reliable cleanup. Server credentials come from the test environment and must never be committed. Tests must not rely on implicit row order or assume that generated integer keys start at one.

Exact SQL snapshots, catalog queries, session pragmas, and driver instrumentation belong in backend-specific integration or dialect tests.

Build and CI integration

A backend contribution must provide:

  • its implementation sources and dependency target;
  • an explicit build option or feature controlling the driver dependency;
  • registration with backend selection;
  • a test harness using the common conformance sources;
  • backend-specific dialect and session integration tests;
  • a real database service in CI for server backends;
  • updates to Backends, public documentation, and examples where relevant.

The minimum new-backend CI job uses Ubuntu, one supported compiler, the real database service, and both dialect and conformance tests. Additional compiler, operating-system, and server-version jobs are required only for combinations the documentation claims to support. The existing SQLite GCC, Clang coverage, and MSVC jobs remain the core portability guard.

Backend Definition of Done

A backend can move from experimental to supported only when:

  • no public operation selects it through a scattered backend-specific enum branch;
  • all required operations and advertised capabilities are implemented;
  • unsupported optional behavior fails before SQL execution with the documented category;
  • the common conformance suite passes against a real database in CI;
  • backend-specific type mapping, session setup, catalog access, and dialect SQL have focused tests;
  • local setup, connection format, capabilities, limits, supported server versions, and known exclusions are documented;
  • build dependencies remain optional for consumers that do not enable the backend;
  • Backends and the CI matrix accurately reflect the verified support claim.

The broader project milestone criteria are listed in Backend portability.