|
ORM C++
|
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.
The backend boundary is split into focused contracts:
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:
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():
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.
A backend implementation owns the following responsibilities behind one centrally selected adapter or equivalent contract:
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.
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:
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:
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 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 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.
Backend work must preserve the DatabaseErrorCode categories:
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.
Every backend must execute the same conformance test sources. Those tests use only public ORM APIs and cover:
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.
A backend contribution must provide:
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.
A backend can move from experimental to supported only when:
The broader project milestone criteria are listed in Backend portability.