Models & Fields
Three Translations
Zyvor’s schema is a thin layer over concepts you already know:
| You write | It means | It becomes |
|---|---|---|
model User { } | A table | CREATE TABLE users + struct UserModel |
name String | A column | "name" TEXT NOT NULL + pub name: String |
@unique | A constraint | UNIQUE |
One file, three outputs: Rust types, SQL migrations, and relation metadata.
Start with One Model
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}
Run zyvor dev:
Rust — .zyvor/generated/user/mod.rs
#![allow(unused)]
fn main() {
pub struct UserModel {
pub id: i32,
pub name: String,
pub email: String,
}
}
SQL — .zyvor/migrations/0001_initial.sql
CREATE TABLE IF NOT EXISTS "users" (
"id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL UNIQUE
);
A typed field to query with:
#![allow(unused)]
fn main() {
User::find()
.where_(User::email.eq("ali@example.com"))
.all(&pool).await?;
}
That’s the whole idea. Everything else is detail.
Names Are Translated
| Schema | Database |
|---|---|
model User | users |
model UserProfile | user_profiles |
userId | user_id |
createdAt | created_at |
Tables use pluralized snake_case. Columns use snake_case.
The same naming module feeds both generators, so Rust and SQL can’t drift apart.
Override the default names with @map and @@map when needed.
Two Kinds of Fields
This is the one thing worth reading twice:
model Post {
userId Int // A real column
user User @relation(fields: [userId], ...) // NOT a column
tags Tag[] @relation(through: "post_tags", ...) // NOT a column
}
- Scalar fields are data.
userId Intbecomes a database column and a Rust field. - Model fields are navigation. They become Rust fields (
Option<Arc<UserModel>>,Vec<Arc<TagModel>>) but create zero SQL columns.
Model-Level Attributes
Model-level attributes are written at the bottom of a model and prefixed with @@.
model PostTag {
id Int @id @default(autoincrement())
postId Int @map("post_id")
tagId Int @map("tag_id")
@@unique([postId, tagId])
@@map("post_tags")
}
Comments
Line comments are supported:
// Line comments work
model User {
id Int @id @default(autoincrement()) // Trailing comments work too
}
Block comments (/* ... */) are not supported yet.
Your Feedback Loop
zyvor validate # Is my schema legal?
zyvor dev # Generate + watch
validate runs the following stages without writing files:
- Lexer
- Parser
- Semantic validator
Use it while learning your schema language.
Rules the Validator Enforces
- Every model needs exactly one
@id. - Field names must be unique within each model.
- Model names must be unique within the schema file.
@relationis only allowed on model-typed fields.fields: [...]andreferences: [...]must have equal lengths.- A referenced field must be a primary key or have
@unique. - Foreign-key and referenced fields must share the same scalar type.
Next: Scalar Types