Contents
orm-c is a small ORM for C with Django-style model definitions. It is an early project. SQLite is the only backend with code, and the save and get functions it generates are still stubs. The part worth reading is the macro layer, which shows how much a C struct can tell you at runtime using only offsetof, sizeof and the preprocessor.
One thing up front: the macros do not generate your struct. You write the struct, and the macros describe it.
Describe the struct, do not generate it
You declare an ordinary typedef struct, then list its fields in a model definition.
typedef struct {
int id;
char username[50];
char email[100];
int age;
} User;
#undef ORM_CURRENT_MODEL
#define ORM_CURRENT_MODEL User
ORM_MODEL_DEFINE(User, "users",
ORM_FIELD_INT(id, ORM_PRIMARY_KEY | ORM_AUTO_INCREMENT),
ORM_FIELD_STRING(username, 50, ORM_NOT_NULL | ORM_UNIQUE),
ORM_FIELD_STRING(email, 100, ORM_NOT_NULL),
ORM_FIELD_INT(age, 0)
);Each field macro expands to one designated initializer for an ORM_FieldMeta. This is the string field from src/core/model.h:
#define ORM_FIELD_STRING(name, max_size, field_flags) \
{ \
.field_name = #name, \
.column_name = #name, \
.type = ORM_TYPE_STRING, \
.offset = offsetof(ORM_CURRENT_MODEL, name), \
.size = (max_size), \
.flags = (field_flags), \
.default_value = NULL \
}#name turns the member name you passed into a string, so the field and column name are written once. offsetof asks the compiler where that member sits. The flags are plain bits, so ORM_PRIMARY_KEY | ORM_AUTO_INCREMENT is a single integer.
offsetof needs a struct type, but a field macro only receives a member name. The workaround is ORM_CURRENT_MODEL, a macro that stands in for the struct type. You redefine it before every model, which is why #undef and #define appear above each definition.
What ORM_MODEL_DEFINE expands to
The model macro receives the type name, the table name and then every field macro through __VA_ARGS__. Trimmed to the metadata part:
#define ORM_MODEL_DEFINE(ModelType, table_name_str, ...) \
void* ModelType##_new(void); \
void ModelType##_free(void* obj); \
ORM_FieldMeta ModelType##_fields[] = { __VA_ARGS__ }; \
ORM_ModelMeta ModelType##_meta = { \
#ModelType, \
table_name_str, \
sizeof(ModelType), \
sizeof(ModelType##_fields) / sizeof(ORM_FieldMeta), \
ModelType##_fields, \
ModelType##_new, \
ModelType##_free \
}; \
/* constructor, destructor and CRUD stubs follow */Because every field macro is already a braced initializer, the commas you typed between them become the commas between array elements. ## pastes the type name into User_fields, User_meta and User_new. sizeof(User_fields) / sizeof(ORM_FieldMeta) gives the field count, and #ModelType becomes the registry key. The result is an ordinary global, User_meta, with no allocation.
A registry and pointer arithmetic
ORM_Init allocates a global ORM_Registry, which is an array of pointers to ORM_ModelMeta. It starts with 16 slots and doubles with realloc when full. ORM_RegisterModel(&User_meta) rejects a duplicate model_name and appends the pointer, and ORM_GetModel("User") finds it with a linear strcmp scan. Nothing is copied. ORM_Shutdown frees the pointer array and leaves the metadata alone, because it is static.
I kept registration explicit. The header says models must be registered by hand after ORM_Init(), and the tests do the same, with a comment that a constructor attribute may not work in every context.
With offsets stored, any field of any model can be reached without knowing the struct type:
void* ORM_GetFieldValue(void* obj, ORM_FieldMeta* field) {
char* obj_ptr = (char*)obj;
return (void*)(obj_ptr + field->offset);
}That is why the SQL layer can stay generic.
From metadata to SQL
The builder in src/core/sql_builder.c takes an ORM_ModelMeta* and a dialect. It never sees the User type. ORM_BuildCreateTableSQL loops over fields, and ORM_BuildColumnDefinition adds the quoted column name, a dialect-specific type name and the constraint flags. ORM_BuildInsertSQL skips auto-increment columns and binds every other field by pointer:
field_count = 0;
for (int i = 0; i < model->field_count; i++) {
if (model->fields[i].flags & ORM_AUTO_INCREMENT) {
continue;
}
if (field_count > 0) {
ORM_StringBufferAppend(builder->sql, ", ");
}
void* field_ptr = (char*)instance + model->fields[i].offset;
int param_idx = ORM_AddParameter(builder, field_ptr, model->fields[i].type, model->fields[i].size);
ORM_StringBufferAppend(builder->sql, ORM_GetPlaceholder(builder, param_idx));
field_count++;
}Values are never pasted into the SQL text. ORM_AddParameter stores the pointer into the live struct, not a copy, so the instance has to outlive the statement. The placeholder, the quoting and the type names depend on the dialect:
| Dialect | Identifier quoting | Placeholder | Auto-increment | BOOLEAN column |
|---|---|---|---|---|
| SQLite | double quotes | ? | AUTOINCREMENT | INTEGER |
| PostgreSQL | double quotes | $1, $2 | nothing emitted | BOOLEAN |
| MySQL | backticks | ? | AUTO_INCREMENT | TINYINT(1) |
| MS SQL Server | square brackets | @p1, @p2 | IDENTITY(1,1) | BIT |
Following the code by hand for the User model above, SQLite gets:
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "username" VARCHAR UNIQUE NOT NULL, "email" VARCHAR NOT NULL, "age" INTEGER)
INSERT INTO "users" ("username", "email", "age") VALUES (?, ?, ?)What is finished and what is not
The model layer works: macros, registry, introspection and defaults, covered by tests/test_model.c. The SQL builder and the SQLite backend (src/backends/sqlite/: connection, query, schema, transaction) also have code and their own tests, but none of those tests use ORM_MODEL_DEFINE. I found no test that goes from a macro model to a live SQLite table, even though ORM_SQLiteCreateTable takes a model directly.
Not finished: the generated User_save, User_get, User_objects and User_delete are placeholders that return ORM_ERROR or NULL. PostgreSQL, MySQL and SQL Server exist only as the dialect strings in the table above, with no connection code, and the docs/tasks files for those backends are plans. PROJECT_STATUS.md still lists the query builder, SQL generation and SQLite as pending, so trust the source over the status files. tests/test_sql_generation.c calls ORM_CreateModel and FIELD_VARCHAR, which exist nowhere in src/, so I would not expect it to build.
Where the metadata stops being used
A few places in orm-c still bypass the metadata.
ORM_Filtertypes every value as anint, with a comment that the type should be inferred from the model. The model is already inqs->model.ORM_BuildColumnDefinitionwrites a bareVARCHAR. The 50 fromORM_FIELD_STRING(username, 50, ...)is stored in.sizebut never reaches the DDL. SQLite does not mind, but MySQL requires a length.ORM_TYPE_FOREIGN_KEYhas no case inORM_DialectTypeName, so it falls through toTEXT, while the README table says INTEGER. The SQLite binder handles no date, time, datetime or foreign key type and bindsNULLfor them.- There are two SELECT builders.
ORM_BuildSQLinqueryset.cemits unquoted names and writes filter values into the text, whileORM_BuildSelectSQLquotes identifiers and uses placeholders. The first one also does not escape string values.
The macros also check less than they appear to. ORM_FIELD_INT(username, 0) compiles, because offsetof only proves the member exists and .size is sizeof(int) from the macro, not the member's own size. Next time I would derive .size from the member and route every layer through ORM_ModelMeta before adding a second backend.
This approach fits a small C codebase that wants introspection without a code generator. It stops working when you need the compiler to check field declarations against the struct. The repository also commits build/bin and build/obj and has no .gitignore, which is worth cleaning up.
Found this useful? Share it with your team.