Defining Models
Models are the core declaration in Kirak. Every model is a JSON document that defines a database table, its field types, validation constraints, security rules, indexes, and runtime behavior.
Model Anatomy
Section titled “Model Anatomy”Every model JSON document separates data structure from security policy:
flowchart TD Model["models/<name>.json"] --> Top["Top-Level Settings<br/>(table, soft_delete, id_type, max_limit, slug)"] Model --> Schema["schema Block<br/>(Field types, constraints, defaults, search)"] Model --> Access["access Block<br/>(Role permissions, row-level security RLS)"] Model --> Extras["Indexes & Caching<br/>(indexes, rate_limit, cache)"]
subgraph AutoFields["Auto-Managed by Runtime (Never declare in schema)"] F1["id (Integer or UUID Primary Key)"] F2["created_at (UTC Timestamp on INSERT)"] F3["updated_at (UTC Timestamp on UPDATE)"] F4["deleted_at (Managed on Soft-Delete)"] endFile Layout Options
Section titled “File Layout Options”You can organize your models in one of two formats:
1. Directory Layout (Recommended)
Section titled “1. Directory Layout (Recommended)”Pass models_path="./models/". Each file in the directory defines one model, named by its filename:
models/├── posts.json # Defines the "posts" model├── products.json # Defines the "products" model└── orders.json # Defines the "orders" modelmodels/posts.json:
{ "$schema": "../.kirak/model.schema.json", "table": "posts", "soft_delete": true, "schema": { "title": { "type": "string", "required": true, "max_length": 200, "searchable": true }, "content": { "type": "text" }, "user_id": { "type": "integer", "required": true } }, "access": { "fetch": [{ "role": "*" }], "create": [{ "role": "user", "condition": "user_id = {user_id}" }], "update": [{ "role": "user", "condition": "user_id = {user_id}" }] }}2. Single-File Layout
Section titled “2. Single-File Layout”Pass models_path="./models.json". One JSON file maps model names to their configurations:
{ "posts": { "table": "posts", "schema": { ... }, "access": { ... } }, "orders": { "table": "orders", "schema": { ... }, "access": { ... } }}Reserved Fields
Section titled “Reserved Fields”Kirak automatically creates, populates, and indexes these four columns. Do not include them in your schema block:
| Field | Type | Managed When |
|---|---|---|
id |
INTEGER (or CHAR(36) if id_type is "uuid" or "uuid7") |
Primary key: auto-increment, or a UUID Kirak generates on INSERT |
created_at |
TIMESTAMP |
Set to current UTC timestamp on INSERT |
updated_at |
TIMESTAMP |
Updated to current UTC timestamp on INSERT and UPDATE |
deleted_at |
TIMESTAMP |
Set on delete (soft delete); cleared on restore |
Note: The names
orandor_groupsare also reserved by the filter query engine and cannot be used as field names.
Field Types
Section titled “Field Types”Kirak provides database-agnostic data types that map to native types on MySQL, PostgreSQL, and SQLite:
| Type | PostgreSQL | MySQL | SQLite | Description & Validation |
|---|---|---|---|---|
string |
VARCHAR(255) |
VARCHAR(255) |
VARCHAR(255) |
Short text. Length controlled by max_length |
text |
TEXT |
TEXT |
TEXT |
Unbounded text for long descriptions or bodies |
integer |
INTEGER |
INT |
INTEGER |
Whole numbers, 64-bit; a filter value outside that range returns 400 VALIDATION_ERROR |
float |
FLOAT |
FLOAT |
REAL |
Floating-point numbers |
decimal |
NUMERIC |
DECIMAL |
DECIMAL |
Fixed-point numbers. Controlled by precision and scale |
boolean |
BOOLEAN |
TINYINT(1) |
BOOLEAN |
True or false values |
timestamp |
TIMESTAMP |
TIMESTAMP |
TIMESTAMP |
UTC timestamp |
datetime |
TIMESTAMP |
DATETIME |
TIMESTAMP |
Date and time |
date |
DATE |
DATE |
DATE |
Calendar date (YYYY-MM-DD) |
uuid |
CHAR(36) |
CHAR(36) |
CHAR(36) |
Validated 36-character lowercase UUID |
json |
JSONB |
TEXT |
TEXT |
Any JSON value: an object, an array, a string, a number, true / false. Stored as JSON text and returned as the value written: the string '{"a": 1}' comes back as that string, not as an object. An equality filter matches the JSON value as given, so ?settings=5 from a query string matches the string "5", not the number. |
email |
VARCHAR(255) |
VARCHAR(255) |
VARCHAR(255) |
Validated email address syntax. Reserved domains are refused: .test, .local, .localhost, .invalid, .onion, .arpa. Use example.com addresses in tests |
file |
VARCHAR(500) |
VARCHAR(500) |
VARCHAR(500) |
Path or URL to an uploaded file asset |
image |
VARCHAR(500) |
VARCHAR(500) |
VARCHAR(500) |
Path or URL to an image asset |
multiselect |
TEXT |
TEXT |
TEXT |
Stored as JSON array of selected strings |
Field Properties
Section titled “Field Properties”| Property | Type | Description |
|---|---|---|
type |
string | Required. One of the field types listed above. |
required |
bool | Rejects create/update if field is omitted or null. (Default: false). |
unique |
bool | Generates a unique database constraint. Checked on every write. |
searchable |
bool | Enables full-text search across this column via GET /{model}/search. Only valid for string, text, and email. |
sortable |
bool | Allows sorting by this field via order_by. (Default: true). |
default |
any | Value used when a create leaves the field out, and the column’s database default. It must be a value of the field’s type; a json field takes any JSON value, such as {} or []. |
enum |
array | Strict list of allowed values. Non-matching values return 400 VALIDATION_ERROR. |
max_length |
int | Maximum string length constraint. |
min_length |
int | Minimum string length constraint. |
pattern |
string | Regular expression constraint applied on create and update (e.g. ^[A-Z]{3}-\d{4}$). |
min_value |
number | Minimum allowed numerical value. |
max_value |
number | Maximum allowed numerical value. |
precision |
int | Total number of digits for decimal fields. |
scale |
int | Decimal places for decimal fields. |
foreign_key |
bool | Indicates field references another model. |
relationship |
object | Defines join metadata for GraphQL: {"model": "users", "foreign_key": "id"}. |
renamed_from |
string or array | The old column this field takes over, so a migration renames that column and keeps its data instead of dropping it and adding an empty one. See Renaming a Field. |
Renaming a Field
Section titled “Renaming a Field”Fields are matched by name, so renaming one in the model file reads as two changes: the old
column dropped, a new empty one added. The data does not follow the name, and kirak db makemigrations writes the drop as commented-out SQL while a hosted deploy refuses it.
renamed_from names the old column the field takes over:
{ "posts": { "table": "posts", "schema": { "heading": {"type": "string", "max_length": 100, "renamed_from": "title"} }, "indexes": [{"columns": ["heading"]}] }}A migration then applies ALTER TABLE "posts" RENAME COLUMN "title" TO "heading", and the
column keeps its rows. It is not a drop, so a hosted deploy needs no --allow-data-loss.
Rename the column in the model’s indexes and in any access condition that names it: those
are not rewritten for you, and kirak validate reports an indexes entry naming a column the
model no longer has. The indexes themselves keep working: an index on the column is repointed to
the new name, and the field’s UNIQUE moves with it. An index created before the rename keeps
the name it was given, so it can read as idx_posts_title on a column now called heading,
until something rebuilds the table and the name is generated again. That is cosmetic.
The key names an old column, not a state, so the same model file suits a database at any version:
| The database has | What a migration does |
|---|---|
| the old name only | renames the column, with its data |
| the new name already | nothing: it is already renamed |
| neither name | nothing: a new column, added as usual |
| both names | refuses: either column could hold the data |
So leave the key in place. Deleting it too early means a database that has not been renamed yet
drops the old column and adds an empty new one. For a field renamed more than once, list the
names newest first ("renamed_from": ["heading", "title"]); the first name the database still
has is the one renamed. The key is not stored in migrations/models_snapshot.json or in a
hosted database’s model set, which record the columns the database has.
Renaming a model is different: keep its table key on the old table name and the table and
its data stay where they are.
Model Settings
Section titled “Model Settings”1. table
Section titled “1. table”The physical SQL table name (must be a valid SQL identifier):
{ "table": "blog_posts" }2. soft_delete
Section titled “2. soft_delete”When true, the delete operation updates deleted_at rather than dropping the row. All fetch, search, and count operations automatically exclude soft-deleted records (WHERE deleted_at IS NULL):
{ "soft_delete": true }3. id_type
Section titled “3. id_type”Replaces the auto-increment integer ID with a UUID primary key that Kirak generates. A client cannot choose the id: an id sent on create is ignored.
| Value | Id |
|---|---|
"integer" (default) |
Auto-increment integer, made by the database |
"uuid" |
Random UUIDv4 |
"uuid7" |
Time-ordered UUIDv7 (RFC 9562): it starts with the creation time in milliseconds, so ids sort by creation time and new rows go to the end of the primary key index, which keeps inserts into large tables fast |
{ "id_type": "uuid7" }Both UUID kinds are stored as CHAR(36), so a model can switch between "uuid" and "uuid7" without a migration: existing rows keep their ids and new rows get the new kind. A UUIDv7 reveals when the row was created; use "uuid" where that must stay private. Changing between "integer" and a UUID kind is a table change that a deploy refuses.
4. slug
Section titled “4. slug”Overrides the URL path segment used by the CRUD router:
{ "table": "blog_posts", "slug": "articles"}Mounted endpoints: GET /articles/fetch, POST /articles/create, etc.
5. indexes
Section titled “5. indexes”Declares single-column or composite database indexes created during migrations:
{ "indexes": [ { "columns": ["user_id"] }, { "columns": ["status", "created_at"] }, { "columns": ["sku"], "unique": true } ]}Every model needs at least one entry (kirak validate: index_missing). The primary key and
unique fields are indexed automatically and do not count – a model whose only lookups are by id
still needs an index for any other column used in a WHERE clause, access condition, or ORDER BY. A query on an unindexed column scans the whole table; on the Workers/D1 free tier that scan is
billed per row read.
Relationships & Foreign Keys
Section titled “Relationships & Foreign Keys”To enable relational joins in GraphQL without writing custom resolvers, declare relationships on the foreign-key column:
erDiagram USERS ||--o{ POSTS : "has many" POSTS ||--o{ COMMENTS : "has many"
USERS { int id PK string email } POSTS { int id PK int user_id FK string title } COMMENTS { int id PK int post_id FK text body }In models/posts.json:
{ "schema": { "user_id": { "type": "integer", "required": true, "foreign_key": true, "relationship": { "model": "users", "foreign_key": "id" } } }}foreign_key and relationship describe the link for GraphQL and the API docs only: Kirak creates no database FOREIGN KEY constraint and no index for the column. Nothing stops a row from pointing at a parent that does not exist, and deleting a parent leaves its children in place. Check the parent in a before_create hook if it must exist, delete children in an after_delete or after_destroy hook, and add an index in the model’s indexes when you filter or join on the column.
Kirak’s GraphQL engine automatically resolves nested selections like:
query { posts { title user_id { email first_name } }}