Aegon

ORM Schema Definition

Compile-time C++23 entity schema mapping with zero reflection overhead, member pointers, foreign keys, composite indexes, and optimistic locking.

Aegon's Object-Relational Mapper (ORM) provides a compile-time, zero-overhead schema mapping system.

Unlike traditional C++ ORMs that rely on external code generation tools, runtime dynamic reflection, or intrusive macros, Aegon declares entity schemas directly in C++ using typesafe member pointers (&Entity::member). The compiler validates all column types, member byte offsets, nullability rules, and foreign key relationships at compile time.


Defining an Entity

To map a C++ struct to a database table, define a static schema() method that returns aegon::data::orm::sql::TableDef<Entity> using the table<Entity>("table_name") helper:

User.h
#include <aegon/data/orm/sql/Sql.h>
#include <aegon/data/types/Types.h>

using namespace aegon::data;
using namespace aegon::data::orm::sql;

struct User {
    UUID id;
    std::string email;
    std::string username;
    std::optional<std::string> bio;
    Decimal128 balance;
    Json preferences;
    IpAddress last_login_ip;
    int64_t version{1}; // Optimistic Concurrency Control
    DateTime created_at;
    DateTime updated_at;

    static auto schema() {
        return table<User>("users")
            .id(&User::id)
            .column(&User::email, "email").unique().not_null().length(255)
            .column(&User::username, "username").indexed().not_null().length(50)
            .column(&User::bio, "bio").nullable()
            .column(&User::balance, "balance").default_value("0.0000")
            .column(&User::preferences, "preferences")
            .column(&User::last_login_ip, "last_login_ip")
            .version(&User::version, "version")
            .created_at(&User::created_at)
            .updated_at(&User::updated_at);
    }
};

Zero Runtime Overhead The schema definition runs purely at compile time to construct member-offset hydrators and parameter extractors. Hydrating database rows into C++ structs executes with direct memory pointer writes—completely avoiding string lookups or dictionary allocations.


Primary Key Configurations

1. Single Primary Key (.id)

Use .id(&Entity::member, [name]) to designate the table's primary key:

// 1. UUID Primary Key (RFC 9562 v7 or v4)
table<User>("users")
    .id(&User::id);

// 2. Auto-Incrementing Integer Primary Key
struct Article {
    int64_t id{0};
    std::string title;

    static auto schema() {
        return table<Article>("articles")
            .id(&Article::id, "id")
            .column(&Article::title, "title");
    }
};
  • Auto-Increment: Integral fields (int64_t, uint64_t, int32_t) are automatically mapped to identity auto-increment columns (BIGSERIAL in PostgreSQL, INTEGER PRIMARY KEY AUTOINCREMENT in SQLite).
  • Auto-Population: When inserting new records with db.insert(entity), Aegon automatically extracts the database-generated key (via RETURNING id or last_insert_rowid) and updates the struct field in-place.

2. Composite Primary Keys

For junction tables or multi-tenant partition tables, declare composite primary keys using .composite_primary_key(...):

struct TenantUser {
    UUID tenant_id;
    UUID user_id;
    std::string role;

    static auto schema() {
        return table<TenantUser>("tenant_users")
            .column(&TenantUser::tenant_id, "tenant_id")
            .column(&TenantUser::user_id, "user_id")
            .column(&TenantUser::role, "role")
            .composite_primary_key(&TenantUser::tenant_id, &TenantUser::user_id);
    }
};

Column Modifiers & Constraints

Column attributes are chained fluently onto .column(&Entity::member, "column_name"):

ModifierDescriptionGenerated SQL (PostgreSQL / SQLite)
.not_null()Disallows NULL values. Enforced automatically for non-optional types.NOT NULL
.nullable()Allows NULL values. Default for std::optional<T>.NULL
.unique()Creates a unique column constraint.UNIQUE
.indexed()Generates a secondary B-Tree index on this column.CREATE INDEX idx_table_col ON table(col);
.length(N)Restricts string length to VARCHAR(N).VARCHAR(N)
.default_value(val)Specifies column default value in generated DDL.DEFAULT 'val' / DEFAULT 0
table<Product>("products")
    .id(&Product::id)
    .column(&Product::sku, "sku").unique().not_null().length(32)
    .column(&Product::name, "name").not_null().length(100)
    .column(&Product::description, "description").nullable()
    .column(&Product::price, "price").not_null().default_value("0.0000")
    .column(&Product::is_active, "is_active").default_value(true);

Automatic Nullability Deduction

Aegon inspects member types via C++ template specialization:

  • Non-optional types (std::string, int64_t, UUID) are automatically treated as NOT NULL.
  • std::optional<T> types are automatically treated as nullable and hydrated as std::nullopt when database rows contain SQL NULL.

Foreign Keys & Referential Actions

Establish referential integrity between tables using .references<TargetEntity>(&TargetEntity::pk_member):

struct Order {
    UUID id;
    UUID user_id;
    Decimal128 total;
    std::string status;

    static auto schema() {
        return table<Order>("orders")
            .id(&Order::id)
            .column(&Order::user_id, "user_id")
                .references<User>(&User::id)
                .on_delete_cascade()
                .on_update_cascade()
            .column(&Order::total, "total")
            .column(&Order::status, "status").default_value("'PENDING'");
    }
};

Supported Referential Actions

ActionMethodBehavior
Cascade.on_delete_cascade()Deletes dependent rows automatically when the parent row is deleted.
Set Null.on_delete_set_null()Sets the foreign key column to NULL when the parent row is deleted (requires nullable column).
Restrict.on_delete_restrict()Prevents parent deletion if matching child rows exist.
Cascade Update.on_update_cascade()Propagates primary key changes downstream to dependent rows.

Multi-Column & Composite Indexes

In addition to single-column .indexed() flags, you can declare composite multi-column indexes and composite unique constraints directly on the table definition:

struct UserRole {
    int64_t user_id{0};
    int64_t role_id{0};
    DateTime assigned_at;

    static auto schema() {
        return table<UserRole>("user_roles")
            .column(&UserRole::user_id, "user_id")
            .column(&UserRole::role_id, "role_id")
            .created_at(&UserRole::assigned_at, "assigned_at")
            // Composite Primary Key
            .composite_primary_key(&UserRole::user_id, &UserRole::role_id)
            // Multi-Column Performance Index
            .add_index("idx_user_roles_composite", &UserRole::role_id, &UserRole::assigned_at)
            // Composite Unique Constraint
            .add_unique_index("uq_user_roles_pair", &UserRole::user_id, &UserRole::role_id);
    }
};

When running db.sync_schema<UserRole>(), Aegon automatically generates:

CREATE INDEX idx_user_roles_composite ON "user_roles" ("role_id", "assigned_at");
CREATE UNIQUE INDEX uq_user_roles_pair ON "user_roles" ("user_id", "role_id");

Automatic Audit Timestamps

Aegon natively tracks entity lifecycle timestamps without requiring manual triggers or timestamp assignment in application logic:

table<User>("users")
    .id(&User::id)
    .created_at(&User::created_at, "created_at")
    .updated_at(&User::updated_at, "updated_at");
  • created_at: Set to the current UTC timestamp (DateTime::now()) during db.insert(entity).
  • updated_at: Bumped to the current UTC timestamp automatically during any db.update(entity) or UPDATE query.

Optimistic Concurrency Control (OCC)

To prevent race conditions, lost updates, and overwrite hazards under concurrent traffic without resorting to heavy database locks, declare a version column:

struct Account {
    UUID id;
    Decimal128 balance;
    int64_t version{1}; // Version token

    static auto schema() {
        return table<Account>("accounts")
            .id(&Account::id)
            .column(&Account::balance, "balance")
            .version(&Account::version, "version");
    }
};

How OCC Works Under the Hood

  1. When reading an entity, Aegon captures its current version (e.g. version = 1).
  2. When executing co_await db.update(account), Aegon generates:
    UPDATE "accounts" 
    SET "balance" = $1, "version" = 2 
    WHERE "id" = $2 AND "version" = 1;
  3. If another worker thread modified the record in the interim, 0 rows are affected.
  4. Aegon detects the conflict and immediately throws an OptimisticLockException:
try {
    account.balance = account.balance + 100.00;
    co_await db.update(account);
} catch (const aegon::data::orm::sql::OptimisticLockException& ex) {
    // Conflict detected: re-fetch latest entity and retry transaction
}

Smart L2 Entity & Query Caching Declarations

Aegon allows you to declare caching policies directly on the table definition, orchestrating transparent L2 entity and query caching:

static auto schema() {
    return table<User>("users")
        .id(&User::id)
        .column(&User::email, "email").unique()
        .column(&User::tenant_id, "tenant_id")
        // Cache primary key lookups for 5 minutes
        .cache_by_id(std::chrono::seconds(300))
        // Secondary pointer cache by unique column (e.g. email -> id)
        .by_unique(&User::email)
        // Partition-scoped invalidation (invalidation affects only this tenant)
        .by_partition(&User::tenant_id)
        // Invalidation policy
        .invalidation_mode(InvalidationMode::StrictEpoch)
        // Sync policy: evict cached entity on update
        .mutation_sync(MutationSync::EvictOnWrite);
}

Invalidation Modes

ModeEnum ValueDescription
Strict EpochInvalidationMode::StrictEpochO(1) epoch increment on write, atomically invalidating query results for the table.
PartitionedInvalidationMode::PartitionedIncrements tenant/partition-specific epochs without invalidating unrelated tenant data.
Predicate AwareInvalidationMode::PredicateAwareEvaluates write mutations against cached query filter conditions.
TTL OnlyInvalidationMode::TtlOnlyDecays strictly by elapsed time; writes do not invalidate cached reads.

Mutation Sync Policies

  • MutationSync::EvictOnWrite: Deletes the cached entity key on update. The fresh value is populated on the next read.
  • MutationSync::UpdateOnWrite: Atomically rewrites the cached entity key with the updated struct data upon successful write.