|
Database System 0.1.0
Advanced C++20 Database System with Multi-Backend Support
|
The database_system ORM lets you describe a table as a C++ class using two macros, ENTITY_FIELD and ENTITY_METADATA. The result is a type-safe entity that can generate its own CREATE TABLE statement, expose typed field accessors, and integrate with the query builders.
This tutorial walks through defining an entity, attaching constraints, modelling relationships, and feeding entity metadata into a query.
| Concept | Description |
|---|---|
entity_base | Abstract base class with virtual table_name(), save(), load(), update(), remove() |
ENTITY_FIELD(type, name, constraints) | Declares a typed field with metadata |
ENTITY_METADATA() | Hooks initialize_metadata() into the entity |
entity_metadata | Runtime container for fields, used to generate SQL |
field_constraint | Bitset enum: primary_key, auto_increment, not_null, unique, index, default_value |
ENTITY_FIELD macro plus a manual table_name() override. The optional ENTITY_TABLE() form simply wraps the same idiom.The example below defines a user_entity with a primary key, a unique username and email, and a not-null age. The ENTITY_FIELD macro creates a typed accessor (e.g. user.username.get(), user.username = "alice") and registers a field_metadata entry.
Once defined, you can ask the entity to generate its own DDL:
Constraints are bitwise OR'd onto each field. The most common combinations are summarized below.
| Constraint | Effect |
|---|---|
primary_key | Marks the column as PRIMARY KEY |
auto_increment | Backend-specific auto-increment (SERIAL, AUTOINCREMENT, AUTO_INCREMENT) |
not_null | Adds NOT NULL |
unique | Adds UNIQUE |
index | Generates a secondary index in create_indexes_sql() |
default_value | Field uses its default expression |
The ORM models relationships through foreign-key columns plus indexes; join logic lives in the query builder. The example below pairs a post_entity with the user_entity from above using author_id.
You can then materialize both schemas in dependency order:
index constraint on author_id triggers create_indexes_sql() to emit CREATE INDEX statements that accelerate join lookups.Entity metadata pairs naturally with the query_builder to construct type-safe queries without hard-coded column lists.
To join posts and users:
Iterating over entity_metadata::fields() is useful for diagnostics, schema migration tools, and serialization helpers.