<p align="center">
<img src="https://raw.githubusercontent.com/Fakhir-Israr-200219/zyvor/main/logo.png" alt="Zyvor" width="180">
</p>
<h1 align="center">Zyvor CLI</h1>
<p align="center"><strong>Schema parser, code generator, and migration toolchain for Zyvor ORM.</strong></p>
<p align="center">
<a href="https://crates.io/crates/zyvor-cli"><img src="https://img.shields.io/crates/v/zyvor-cli.svg" alt="crates.io"></a>
<a href="https://crates.io/crates/zyvor-cli"><img src="https://img.shields.io/crates/d/zyvor-cli.svg" alt="downloads"></a>
<a href="https://fakhir-israr-200219.github.io/zyvor-doc/"><img src="https://img.shields.io/badge/docs-book-blue" alt="docs"></a>
<a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue" alt="license"></a>
</p>
<p align="center">
๐ <a href="https://fakhir-israr-200219.github.io/zyvor-doc/"><strong>Documentation</strong></a> ยท
๐ฆ <a href="https://github.com/Fakhir-Israr-200219/zyvor">Runtime</a> ยท
๐ <a href="https://github.com/Fakhir-Israr-200219/zyvor-axum-demo">Axum example</a> ยท
๐ฆ <a href="https://crates.io/crates/zyvor-cli">crates.io</a>
</p>
---
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`](https://github.com/Fakhir-Israr-200219/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
```bash
# 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:
```text
No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.
```
Leave `dev` running in one terminal, work in another.
### Project structure after init
```text
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](https://fakhir-israr-200219.github.io/zyvor-doc/getting-started/quick-start.html)
---
## Commands
| `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:
```bash
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:
```bash
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](https://fakhir-israr-200219.github.io/zyvor-doc/cli/init.html)
---
## Architecture
```text
schema.zyvor
โ
Lexer โ Parser โ AST โ Validator
โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ
โ Entity Generator โ Migration Gen โ Snapshot Manager โ
โโโโโโโโโโฌโโโโโโโโโโดโโโโโโโโโฌโโโโโโโโโดโโโโโโโโโฌโโโโโโโโโโ
โ โ โ
generated/ migrations/ snapshot.json
(modular) (auto-numbered) (change detection)
```
### Runtime boundary
| 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
```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")
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")
}
```
| 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
| `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](https://fakhir-israr-200219.github.io/zyvor-doc/schema/models.html)
---
## Modular code generation
One folder per model, so a 30-model schema stays navigable:
| 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
```rust
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>,
}
```
| `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](https://fakhir-israr-200219.github.io/zyvor-doc/api/crud.html)
---
## 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:
| 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`:
```sql
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
```text
๐ฆ 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](https://fakhir-israr-200219.github.io/zyvor-doc/schema/migrations.html)
---
## Using generated code
```toml
[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:
```text
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`.
```rust
#[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](https://fakhir-israr-200219.github.io/zyvor-doc/api/queries.html) ยท
[Axum integration](https://fakhir-israr-200219.github.io/zyvor-doc/guides/axum.html)
---
## Verified end-to-end
```text
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
```
| 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`](https://github.com/Fakhir-Israr-200219/zyvor) ยท
`cargo clippy --all-targets --all-features -- -D warnings` clean.
Reproduce it: [zyvor-axum-demo](https://github.com/Fakhir-Israr-200219/zyvor-axum-demo)
---
## Known limitations
| **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](https://fakhir-israr-200219.github.io/zyvor-doc/reference/limitations.html)**
---
## Roadmap
### โ
Done
- [x] Schema language, lexer, parser, AST, validator
- [x] Modular entity generation (per-model folders)
- [x] All four relation types
- [x] CRUD codegen (`Create` / `Update` / `InsertData` / `UpdateData`)
- [x] Migration generation + execution
- [x] Tracking, checksum skip, drift detection
- [x] Schema diffing + auto-numbering
- [x] Auto database creation
- [x] Watch mode with snapshot change detection
- [x] `.env` / `config.toml` configuration
- [x] Axum integration verified
- [x] [Documentation book](https://fakhir-israr-200219.github.io/zyvor-doc/)
### ๐ 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
| [zyvor](https://github.com/Fakhir-Israr-200219/zyvor) | Runtime crate โ query builder, CRUD, relations |
| [zyvor-cli](https://github.com/Fakhir-Israr-200219/zyvor-cli) | This crate โ schema toolchain |
| [zyvor-doc](https://github.com/Fakhir-Israr-200219/zyvor-doc) | Documentation source ([live book](https://fakhir-israr-200219.github.io/zyvor-doc/)) |
| [zyvor-axum-demo](https://github.com/Fakhir-Israr-200219/zyvor-axum-demo) | Verified Axum + PostgreSQL example |
---
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
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](https://www.prisma.io/), [Drizzle](https://orm.drizzle.team/),
and the frustration of writing repetitive ORM boilerplate in Rust.