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

  1. Create a model
  2. Static schema
  3. Supported field types
  4. Optional fields
  5. Table name
  6. Column names
  7. Primary key
  8. Auto-increment primary key
  9. One-to-one relations
  10. Collection relations
  11. Current limitations

Create a model

A model is a reflected C++ struct whose fields can be mapped to database columns.

struct User {
int id;
std::string name;
std::string email;
};

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 _.

Static schema

Each ORM context is bound to a closed set of complete model types and borrows an independent database connection:

import orm;
using AppSchema = orm::Schema<User>;
auto context = database.orm<AppSchema>();
auto orm() &noexcept -> OrmContext< SchemaType >
model::Schema< Models... > Schema
Definition schema.cppm:504

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.

Supported field types

The bundled SQLite, PostgreSQL, MySQL and MariaDB backends support these scalar C++ field types:

  • bool
  • char, signed char, unsigned char
  • short, short int, unsigned short, short unsigned int
  • int
  • long, long int, unsigned int, unsigned long, long unsigned int
  • long long, long long int, __int64 (MSVC)
  • unsigned long long, long long unsigned int, unsigned __int64 (MSVC)
  • float
  • double
  • std::string

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.

Bounded strings

String bounds are model metadata, independent of the selected backend:

struct Account {
std::string code;
std::string name;
inline static constexpr auto id_columns = orm::primaryKey<&Account::code>();
inline static constexpr auto string_lengths = orm::stringLengths(
};
consteval auto stringLength()
Definition mapping.cppm:583
consteval auto stringLengths(Definitions... definitions)
Definition mapping.cppm:589
consteval auto primaryKey()
Definition mapping.cppm:576

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.

Optional fields

Wrap a supported scalar type in std::optional<T> to make the column nullable.

struct User {
int id;
std::optional<std::string> email;
};

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.

Table name

Override the generated table name with a static table_name field:

struct User {
int id;
std::string name;
inline static constexpr orm::reflection::FixedString table_name{"users"};
};

table_name must be a structural FixedString; runtime std::string and std::string_view metadata are no longer accepted.

Column names

Override database column names with orm::columnNames and typed member pointers. Fields omitted from the mapping keep their reflected C++ names.

struct User {
int id;
std::string displayName;
inline static constexpr auto columns_names =
};
consteval auto columnName()
Definition mapping.cppm:563
consteval auto columnNames(Definitions... definitions)
Definition mapping.cppm:569

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.

Primary key

If a model has an id field, it is used as the default primary key.

struct User {
int id;
std::string name;
};

Override the primary key with orm::primaryKey and member pointers. The order of the pointers is the order of a composite key.

struct User {
int id;
int tenantId;
std::string name;
inline static constexpr auto id_columns =
};

To create a model without a primary key, omit id or define an empty primaryKey definition.

struct LogEntry {
std::string message;
inline static constexpr auto id_columns = orm::primaryKey<>();
};

Auto-increment primary key

Integer primary keys can be generated by any bundled database backend. To enable this, define auto_increment_columns with orm::autoIncrement:

struct User {
int id;
std::string name;
inline static constexpr auto auto_increment_columns =
};
consteval auto autoIncrement()
Definition mapping.cppm:596

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:

  • The auto-increment column must be the only primary-key column.
  • The column must have type int.
  • The column cannot be std::optional.
  • The column cannot be a related model field.

Column mappings and auto-increment declarations refer to the same C++ member independently:

struct User {
int id;
std::string name;
inline static constexpr auto auto_increment_columns =
inline static constexpr auto columns_names =
};

This applies the mapped user_id name to the backend's corresponding auto-generated integer primary-key declaration.

One-to-one relations

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).

struct Profile {
int id;
std::string city;
};
struct User {
int id;
Profile profile;
};

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:

struct User {
int id;
std::optional<Profile> profile;
};

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.

Collection relations

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:

struct Book;
struct Author
{
int id;
std::string name;
inline static constexpr auto relations =
};
struct Book
{
int id;
std::string title;
Author author;
};
consteval auto relations(Descriptors... descriptors)
consteval auto oneToMany() -> OneToManyDescriptor< Member >

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:

struct Role;
struct User
{
int id;
inline static constexpr auto relations =
.through<"user_roles">()
.ownerColumns<"user_id">()
.targetColumns<"role_id">());
};
struct Role
{
int id;
inline static constexpr auto relations =
orm::relations(orm::manyToMany<&Role::users>().mappedBy<&User::roles>());
};
consteval auto manyToMany() -> ManyToManyDescriptor< Member >

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:

auto context = database.orm<AppSchema>();

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.

Current limitations

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.