|
ORM C++
|
A model is a reflected C++ struct whose fields can be mapped to database columns.
Models must be C++ aggregates. Their field names and types are reflected during compilation; unions, raw C-array fields, bit-fields, and non-aggregate classes are rejected. Inherited aggregates are outside the supported contract and must use composition instead, even if a compiler happens to accept a particular structured binding. By default the table name is derived from the C++ type name and :: is replaced with _.
Each ORM context is bound to a closed set of complete model types and borrows an independent database connection:
The schema validates each model and the complete relation graph at compile time. A model operation fails to compile when its type is absent from the ORM context's schema. Include every to-one and collection relation target in the same schema, even when only one endpoint is queried directly.
The bundled SQLite, PostgreSQL, MySQL and MariaDB backends support these scalar C++ field types:
Each backend maps these types to its native SQL types. SQLite uses its integer, real, and text affinities. PostgreSQL uses BOOLEAN, width-appropriate SMALLINT/INTEGER/BIGINT, DOUBLE PRECISION, and TEXT. MySQL and MariaDB use native signed/unsigned integer types, DOUBLE, and LONGTEXT or bounded VARCHAR. See the backend matrix for backend-specific limits and semantics.
The date, time and UUID types are additional scalars: orm::Date, orm::TimeOfDay, orm::LocalDateTime and orm::UtcTimestamp are supported by PostgreSQL, MySQL and MariaDB. orm::Uuid defaults to native UUID on PostgreSQL and MariaDB; SQLite and MySQL require an explicit Binary16 or Text36 mapping for each UUID field. An application can specialize UuidAdapter<T> or ValueConverter<T> to use its own UUID type. Optional fields, manual/composite primary keys and foreign keys retain the logical UUID type, while related keys inherit their target key's physical mapping. SQLite does not provide the native temporal types. Unsupported mappings are rejected before SQL. Temporal precision is fixed at six fractional digits. Values outside the calendar, time-of-day or effective backend range give Conversion. Other types are not supported as scalar columns.
SQLite and PostgreSQL exchange the widest integer values through signed 64-bit storage. Consequently, unsigned long long and 64-bit unsigned long values are supported through INT64_MAX; larger values fail with DatabaseErrorCode::Conversion instead of being silently wrapped. The selected backend reports this bound in BackendCapabilities::valueLimits.
String bounds are model metadata, independent of the selected backend:
Bounds describe a maximum number of characters. Definitions must refer to unique std::string or nullable string members of the same model and use a positive length. MySQL and MariaDB require bounds on string primary and foreign keys so indexes have a predictable width. Related foreign-key columns inherit the referenced key's bound. Index width is validated against the active InnoDB page size before table creation. MySQL-family bounded strings become VARCHAR(n); ordinary unbounded strings become LONGTEXT. SQLite and PostgreSQL retain their native text types. MySQL-family VARCHAR supports lengths from 1 through 16,383; a table must also fit the server's row limits. MariaDB typed string ordering also requires an explicit bound within that range to avoid native prefix sorting of unbounded text; see Backends.
MySQL and MariaDB support the full unsigned long long range through BIGINT UNSIGNED. Consult the selected adapter's value limits when portable application values must also fit SQLite or PostgreSQL.
Wrap a supported scalar type in std::optional<T> to make the column nullable.
Non-optional fields are generated as NOT NULL. Optional fields are nullable, and std::nullopt is stored and read back as SQL NULL. Nullable timestamp declarations in MySQL/MariaDB explicitly retain nullability; NULL is never interpreted as the current time.
Override the generated table name with a static table_name field:
table_name must be a structural FixedString; runtime std::string and std::string_view metadata are no longer accepted.
Override database column names with orm::columnNames and typed member pointers. Fields omitted from the mapping keep their reflected C++ names.
Query and update builders use member pointers such as orm::query::col<&User::displayName>(); the renderer maps them to database column names.
Physical non-identity column names are also used as prepared-statement bind names by the bundled adapters. Keep those mapped names to ASCII letters, digits, and _; unsupported names are rejected during model validation rather than being passed to a database driver. Table names and all identifiers must be non-empty and cannot contain an embedded NUL byte. PostgreSQL additionally enforces its 63-byte identifier limit.
If a model has an id field, it is used as the default primary key.
Override the primary key with orm::primaryKey and member pointers. The order of the pointers is the order of a composite key.
To create a model without a primary key, omit id or define an empty primaryKey definition.
Integer primary keys can be generated by any bundled database backend. To enable this, define auto_increment_columns with orm::autoIncrement:
SQLite creates id INTEGER PRIMARY KEY AUTOINCREMENT; PostgreSQL creates id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY; MySQL and MariaDB use AUTO_INCREMENT. All adapters omit the field from generated INSERT statements. Existing models are unchanged unless they define auto_increment_columns.
Auto-increment support has these limitations:
Column mappings and auto-increment declarations refer to the same C++ member independently:
This applies the mapped user_id name to the backend's corresponding auto-generated integer primary-key declaration.
A field whose type is another model with a primary key is treated as a one-to-one relation. The owning table stores the related model primary key as local foreign key column(s).
For this model, User stores profile_id and references Profile(id). Selecting a model joins one-to-one relations by default. Use call disableJoining() on the query object to read only related primary-key values.
Relations can also be nullable:
Nullable relations generate nullable foreign-key columns, store std::nullopt as SQL NULL, and read SQL NULL back as std::nullopt.
These fields are represented by separate to-one relation metadata rather than by a scalar ColumnType. The ORM does not add a UNIQUE constraint to their foreign-key columns.
Use orm::OneToMany<T> and orm::ManyToMany<T> for fields that contain multiple related models. A collection field must have exactly one matching entry in the model's static relations metadata:
The collection itself is selected with the typed member pointer &Author::books. mappedBy names the existing to-one field on the child. When the target type is complete, use the typed form .mappedBy<&Book::author>(). The FixedString form shown above is the supported fallback for this common forward-declaration cycle. OneToMany does not add a column to the parent or create a hidden child foreign key.
The owning side of a many-to-many relation declares its junction table:
The inverse mappedBy side is optional. Endpoint models must have non-empty primary keys. optional<OneToMany<T>> and optional<ManyToMany<T>> are not valid mappings; the wrapper already represents an unloaded or loaded-empty collection.
Declare the complete relation graph in one schema:
Collection fields are omitted from base-table DDL, insert statements, and ordinary row binding. Inserting a model never traverses or saves a collection. See Collection relations for wrapper behavior, junction naming, schema lifecycle, explicit mutations, includes, predicates, composite keys, and validation rules.
Model metadata supports to-one fields and explicitly mapped OneToMany and ManyToMany collection fields. Mapping definitions are compile-time values; the old runtime string/string_view, vector, and map metadata forms are not accepted. It does not support nested collection loading, junction models with payload fields, ordered relations, or other mapping extensions. Opt-in value converters and nullable wrappers for third-party types, including boost::uuids::uuid and boost::optional, are described in Value types. Native date/time and UUID fields follow the capability and range contract in Value types.