zyvor-cli 0.1.1

CLI for Zyvor — schema-driven ORM code generator
zyvor-cli-0.1.1 is not a library.

Write a .zyvor schema file, get type-safe Rust and tracked PostgreSQL migrations. The CLI is a build-time toolchain — your application depends on zyvor, not on this crate.

⚡ Status: v0.1 — active development. Parsing, validation, modular codegen, migration tracking with diffing, watch mode, and auto database creation are functional and verified end-to-end against PostgreSQL + Axum.


Quick Start

# Install
cargo install zyvor-cli

# Scaffold
zyvor init

# Edit .zyvor/schema.zyvor and .zyvor/.env, then generate + watch
zyvor dev

# In a second terminal — creates the database if it doesn't exist
zyvor migrate --apply

⚠️ Order matters

zyvor dev generates the migration files. Running migrate --apply first gives you:

No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.

Leave dev running in one terminal, work in another.

Project structure after init

my-api/
├── Cargo.toml
├── src/main.rs
└── .zyvor/
    ├── schema.zyvor          ← you edit this
    ├── .env                  ← DATABASE_URL (gitignored)
    ├── config.toml
    ├── .gitignore            ← protects .env
    ├── generated/            ← CLI writes this, never edit by hand
    │   ├── mod.rs            ← flat re-exports
    │   ├── user/
    │   │   ├── mod.rs        ← Entity + Model + fields + relations
    │   │   └── types.rs      ← Create + Update structs
    │   └── post/
    │       ├── mod.rs
    │       └── types.rs
    └── migrations/
        ├── 0001_initial.sql
        ├── 0002_schema_update.sql
        └── snapshot.json

📖 Full quick start


Commands

Command Description
zyvor init Scaffold .zyvor/ — schema template, .env, config, .gitignore
zyvor dev Generate, then watch and regenerate + diff on every save
zyvor migrate --apply Apply pending migrations (creates the database if missing)
zyvor validate [SCHEMA] Lex + parse + validate, nothing written
zyvor generate [SCHEMA] One-shot entity generation
zyvor migrate [SCHEMA] [OUTPUT] Generate migration SQL to a file
zyvor --help / -h Usage
zyvor --version / -V Version

⚠️ Pass schema paths explicitly

validate and generate still default to the legacy filename rust.schema, while dev and migrate --apply use .zyvor/schema.zyvor. Until that's unified, be explicit:

zyvor validate .zyvor/schema.zyvor
zyvor generate .zyvor/schema.zyvor

Similarly, plain zyvor migrate writes to migrations/0001_initial.sql at the project root, not .zyvor/migrations/. For the standard workflow use zyvor dev — it writes to the right place. Plain migrate is for standalone SQL generation with an explicit output path:

zyvor migrate .zyvor/schema.zyvor .zyvor/migrations/0001_initial.sql

Database URL resolution

Highest priority first:

  1. --database <URL> flag
  2. DATABASE_URL environment variable
  3. .zyvor/.env
  4. .zyvor/config.toml → [database] url

Passwords are masked in all console output.

📖 CLI reference


Architecture

schema.zyvor
     ↓
Lexer → Parser → AST → Validator
     ↓
┌──────────────────┬─────────────────┬──────────────────┐
│ Entity Generator │ Migration Gen   │ Snapshot Manager │
└────────┬─────────┴────────┬────────┴────────┬─────────┘
         ↓                  ↓                 ↓
   generated/          migrations/      snapshot.json
   (modular)           (auto-numbered)  (change detection)

Runtime boundary

Responsibility CLI Runtime
Schema parsing & validation ✅ —
Rust code generation ✅ —
Migration SQL generation ✅ —
Migration tracking & diffing ✅ —
Auto database creation ✅ —
Watch-mode regeneration ✅ —
Query building & execution — ✅
Entity CRUD operations — ✅
Relation eager loading — ✅
Transactions — ✅

The CLI generates code for the runtime. It never reimplements it.


Schema language

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")

    profile   UserProfile?
    posts     Post[]
}

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

    user      User      @relation(fields: [userId], references: [id], onDelete: Cascade)
    comments  Comment[]
    tags      Tag[]     @relation(through: "post_tags", pivotFrom: "post_id", pivotTo: "tag_id")
}
Category Supported
Scalars Int String Boolean Float DateTime Decimal Json
Modifiers nullable T? · model arrays Post[] (relations)
Field attrs @id @unique @default(...) @map("col") @relation(...)
Model attrs @@map("table") @@unique([a, b]) @@index([a, b])
Relations 1:N, N:1, 1:1, M:M (explicit pivot model required)
Referential actions Cascade Restrict SetNull NoAction
Defaults autoincrement(), now(), literals

⚠️ Scalar arrays (tags String[]) parse but are rejected by CRUD generation. Model arrays (posts Post[]) are relations and fully supported.

⚠️ Relation args are camelCase: pivotFrom / pivotTo, not pivot_from.

Type mapping

Schema Generated Rust SQL
Int i32 INTEGER
Int @default(autoincrement()) i32 SERIAL
String String TEXT
Boolean bool BOOLEAN
Float f64 DOUBLE PRECISION
DateTime zyvor::DateTime TIMESTAMP
Decimal zyvor::Decimal NUMERIC
Json zyvor::JsonValue JSONB

Naming is automatic: UserProfile → user_profiles, createdAt → created_at. @map / @@map override it. The same naming module feeds both generators, so Rust and SQL can't drift apart.

📖 Schema reference


Modular code generation

One folder per model, so a 30-model schema stays navigable:

Component File Contents
Entity marker {model}/mod.rs pub struct User;
Model struct {model}/mod.rs UserModel — Serialize, Deserialize, FromRow
Typed fields {model}/mod.rs User::name, User::id
Relations {model}/mod.rs Relation constants + loader impls
Create input {model}/types.rs UserCreate + InsertData impl
Update input {model}/types.rs UserUpdate + UpdateData impl
Re-exports generated/mod.rs pub use user::{User, UserModel, UserCreate, UserUpdate};

Create structs

Fields with @default(autoincrement()) or @default(now()) are excluded — the database fills them. Primary keys and relation fields are excluded too.

⚠️ Literal defaults are not excluded. @default(0) and @default(false) still require a value in Create, because Zyvor lists every non-excluded column in the INSERT.

Update structs

pub struct UserUpdate {
    pub name: Option<String>,               // non-nullable field
    pub email: Option<String>,
    pub age: Option<i32>,
    pub bio: Option<Option<String>>,        // nullable field — two layers
    pub created_at: Option<zyvor::DateTime>,
}
Value Effect
None column omitted from SET
Some(Some(v)) SET col = v
Some(None) SET col = NULL

⚠️ No Default derive — ..Default::default() won't compile. List every field. Over JSON this is a non-issue: serde fills absent fields with None.

⚠️ An all-None update returns an error, not a no-op. Guard PATCH endpoints.

📖 CRUD guide


Migration system

Initial migration

CREATE TABLE IF NOT EXISTS with columns, primary keys, SERIAL, NOT NULL, unique constraints, defaults, foreign keys with ON DELETE, indexes, composite unique indexes, and mapped identifiers.

Schema diffing

zyvor dev compares against migrations/snapshot.json on every save:

Change Generated SQL
field added ALTER TABLE ... ADD COLUMN
field removed ALTER TABLE ... DROP COLUMN IF EXISTS
model removed DROP TABLE IF EXISTS ... CASCADE
model added noted in diff; full CREATE TABLE in regenerated initial

Auto-numbered sequentially: 0001_initial.sql, 0002_schema_update.sql, …

⚠️ Rename detection is not implemented. Renaming a field generates DROP + ADD, which loses data. Review every generated diff before applying.

Tracking

Every migrate --apply maintains _zyvor_migrations:

CREATE TABLE IF NOT EXISTS _zyvor_migrations (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    checksum TEXT NOT NULL,
    applied_at TIMESTAMP NOT NULL DEFAULT NOW()
);
  • Checksum skip — same name + same hash → skipped
  • Drift detection — same name + different hash → hard error with both hashes
  • Idempotent — re-running with unchanged files does nothing

Auto database creation

📦 Creating database 'my_app'...
✅ Database 'my_app' created!
🚀 Applying migrations to database...

Zyvor connects to the postgres maintenance database, checks pg_database, and creates your target if needed. No manual CREATE DATABASE.

📖 Migrations guide


Using generated code

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

⚠️ sqlx must be 0.8

Zyvor 0.1 depends on sqlx 0.8. A different major-minor puts two sqlx_core versions in your graph and produces confusing errors:

the trait bound `UserModel: FromRow<'r, PgRow>` is not satisfied
there are multiple different versions of crate `sqlx_core` in the dependency graph

Pin to 0.8. Verify with cargo tree -i sqlx.

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

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

// Typed fields — chained where_ calls are AND-ed
let users = User::find()
    .where_(User::name.eq("Ali").and(User::age.gte(18)))
    .order_by(User::id.desc())
    .take(20)
    .all(&db).await?;

// Two-level nested eager loading
let users = User::find()
    .with_nested(User::posts, |q| q.with(Post::comments))
    .all(&db).await?;

📖 Runtime API · Axum integration


Verified end-to-end

zyvor init → schema.zyvor → zyvor dev → generated/ + migrations/
     ↓
zyvor migrate --apply → database created, tables applied
     ↓
Axum API → CRUD + all 4 relation types + nested eager loading
     ↓
✅ verified
Area Status
Lexer, parser, validator ✅
Entity + CRUD code generation ✅
Migration SQL generation ✅
Migration tracking + drift detection ✅
Schema diffing + auto-numbering ✅
Auto database creation ✅
Axum CRUD endpoints ✅
Eager loading (1:N, N:1, 1:1, M:M) ✅
Nested eager loading (2 levels) ✅
Error handling (404 / 409 / 422) ✅
Cascade delete ✅

64 CLI tests passing · 115 runtime tests passing in zyvor · cargo clippy --all-targets --all-features -- -D warnings clean.

Reproduce it: zyvor-axum-demo


Known limitations

Limitation Detail
Scalar arrays String[] parses, rejected by CRUD generation
Literal defaults required in Create @default(0) doesn't make a field optional
Update has no Default list every field; all-None update errors
Primary key must be Int named id runtime update/delete emit WHERE id = $1
Composite foreign keys metadata parses, codegen handles single-column only
Composite @@id unsupported — use surrogate id + @@unique([...])
Pivot tables must be declared as an explicit model
@updatedAt parses, no behaviour generated
@default(cuid()) parses, no SQL default
Identifier quoting migrations quote, executor doesn't — keep names lowercase snake_case
Rename detection missing — a rename becomes DROP + ADD (data loss)
Column type changes not diffed
Rollback / migrate status / migrate reset not implemented
Default schema path validate/generate still default to rust.schema
Error locations no line/column info yet
PostgreSQL only no SQLite / MySQL

📖 Full limitations list


Roadmap

✅ Done

  • Schema language, lexer, parser, AST, validator
  • Modular entity generation (per-model folders)
  • All four relation types
  • CRUD codegen (Create / Update / InsertData / UpdateData)
  • Migration generation + execution
  • Tracking, checksum skip, drift detection
  • Schema diffing + auto-numbering
  • Auto database creation
  • Watch mode with snapshot change detection
  • .env / config.toml configuration
  • Axum integration verified
  • Documentation book

🔜 Next

  • Unify default schema paths (rust.schema → .zyvor/schema.zyvor)
  • Default derive on Update structs
  • Make literal defaults optional in Create
  • migrate status
  • Line/column info in parser and validator errors

🔜 Later

  • Column type changes · rename detection · rollback
  • Composite foreign-key codegen
  • VS Code syntax highlighting for .zyvor
  • MySQL / SQLite

Design principles

  1. CLI is a toolchain, not a runtime — generates code for the zyvor crate
  2. Schema is the source of truth — one definition, everything derived
  3. Generated code is readable Rust — no hidden macros, fully inspectable
  4. Milestone-tracked features — parser ≠ validator ≠ generator ≠ runtime verification
  5. Zero manual database setup — auto-create, auto-migrate, auto-diff
  6. Honest scope — limitations documented, not buried

Related repositories

Repo What
zyvor Runtime crate — query builder, CRUD, relations
zyvor-cli This crate — schema toolchain
zyvor-doc Documentation source (live book)
zyvor-axum-demo Verified Axum + PostgreSQL example

License

Licensed under either of

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


Acknowledgements

Inspired by Prisma, Drizzle, and the frustration of writing repetitive ORM boilerplate in Rust.