Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quick Start

Empty folder to a working database in five commands.

1. Scaffold

cargo init my-api && cd my-api
zyvor init
βœ… Initialized zyvor project

  πŸ“ .zyvor/schema.zyvor   ← Edit your schema here
  πŸ“ .zyvor/generated/     ← Entities will be generated here
  πŸ“ .zyvor/migrations/    ← Migration SQL will be generated here
  πŸ“ .zyvor/.env           ← Database URL (edit this)
  πŸ“ .zyvor/config.toml    ← Advanced config
  πŸ“ .zyvor/.gitignore     ← Protects .env from git

2. Point at your database

Edit .zyvor/.env:

DATABASE_URL=postgres://postgres:yourpassword@localhost/my_app

The database my_app doesn’t exist yet. That’s fine β€” step 5 creates it.

3. Write your schema

Replace .zyvor/schema.zyvor:

model User {
    id        Int      @id @default(autoincrement())
    name      String
    email     String   @unique
    age       Int
    bio       String?  @map("user_bio")
    createdAt DateTime @default(now()) @map("created_at")

    posts Post[]
}

model Post {
    id      Int     @id @default(autoincrement())
    title   String
    content String?
    userId  Int     @map("user_id")

    user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

Two models, one relation, a nullable column, a mapped column name, and a timestamp default. That covers most of what you’ll use daily.

4. Generate

zyvor dev
πŸ‘€ Watching .zyvor/schema.zyvor for changes...
   Press Ctrl+C to stop

βœ… Generated 5 modular files in ".zyvor/generated"
  βœ… Generated: .zyvor/generated/ (modular)
  βœ… Generated: .zyvor/migrations/0001_initial.sql
  πŸ’Ύ Snapshot saved

dev keeps running and regenerates on every save. Leave it open in this terminal and use a second one for the rest.

Order matters: dev produces the migration files. Running migrate --apply first gives you No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.

5. Apply

In a second terminal:

zyvor migrate --apply
πŸš€ Applying migrations to database...
   Database: postgres://postgres:****@localhost/my_app
πŸ“¦ Creating database 'my_app'...
βœ… Database 'my_app' created!
πŸ“‹ Found 1 migration file(s)

πŸ“ Applying: 0001_initial.sql
βœ… 0001_initial.sql applied successfully!

Tables in database:
  πŸ“‹ _zyvor_migrations
  πŸ“‹ posts
  πŸ“‹ users

Database created, tables ready, migration recorded. Run it again and it skips everything β€” re-applying is free.

6. Use it in Rust

Add dependencies (see Installation β€” and pin sqlx to 0.8):

[dependencies]
zyvor = "0.1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "chrono"] }
tokio = { version = "1", features = ["full"] }

src/main.rs:

#[path = "../.zyvor/generated/mod.rs"]
mod generated;

use generated::{Post, PostCreate, User, UserCreate, UserUpdate};
use zyvor::Entity;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL")?).await?;

    // Create
    let user = User::create(&pool, UserCreate {
        name: "Ali Khan".into(),
        email: "ali@example.com".into(),
        age: 28,
        bio: Some("Rust developer".into()),
    }).await?;

    println!("created user {}", user.id);

    // Create a related row
    let post = Post::create(&pool, PostCreate {
        title: "Hello Zyvor".into(),
        content: None,
        user_id: user.id,
    }).await?;

    // Query with a typed field
    let adults = User::find()
        .where_(User::age.gte(18))
        .order_by(User::id.desc())
        .take(20)
        .all(&pool)
        .await?;

    println!("{} adults", adults.len());

    // Eager load the relation
    let with_posts = User::find().with(User::posts).all(&pool).await?;
    println!("{} posts for {}", with_posts[0].posts.len(), with_posts[0].name);

    // Partial update
    User::update(&pool, user.id, UserUpdate {
        bio: Some(Some("Senior Rust dev".into())),
        name: None,
        email: None,
        age: None,
        created_at: None,
    }).await?;

    // Delete β€” cascades to posts
    let affected = User::delete(&pool, user.id).await?;
    println!("deleted {affected} user(s)");

    Ok(())
}

Set the env var and run:

$env:DATABASE_URL = "postgres://postgres:yourpassword@localhost/my_app"
cargo run

Three things that trip up every new user

id and createdAt aren’t in UserCreate

Fields with @default(autoincrement()) or @default(now()) are excluded β€” the database fills them. But literal defaults are not excluded: if your schema has viewCount Int @default(0), you still pass view_count in Create.

Nullable update fields have two Option layers

You writeMeaning
Noneleave the column alone
Some(Some("x"))set it to "x"
Some(None)set it to NULL

And every field must be listed β€” Update structs don’t derive Default, so ..Default::default() won’t compile. Over JSON this is a non-issue: serde fills absent fields with None.

posts is empty unless you ask for it

#![allow(unused)]
fn main() {
User::find().all(&pool).await?;               // posts: []
User::find().with(User::posts).all(&pool)...; // posts: populated
}

Relations never load implicitly. See Eager Loading.

Where to go next