zyvor-cli 0.1.0

CLI for Zyvor — schema-driven ORM code generator
# Zyvor CLI


**Schema parser, code generator, and migration toolchain for Zyvor ORM.**

Zyvor CLI brings a Prisma-inspired development workflow to Rust: define your schema once, generate type-safe entities and migrations automatically, and apply them directly to your database — all from the command line.

> ⚡ **Status:** V0.1 — Active Development
> Schema parsing, validation, modular entity generation, migration tracking with schema diffing, watch-mode regeneration, auto database creation, and Axum integration are all functional and verified end-to-end.

---

## Quick Start


```bash
# Install CLI

cargo install zyvor-cli

# Initialize project

zyvor init

# Edit schema (.zyvor/schema.zyvor)

# Watch & auto-generate on save

zyvor dev

# Apply migrations (auto-creates database if missing!)

zyvor migrate --apply
```

### Project Structure After Init


```
my-api/
├── Cargo.toml
├── src/main.rs
└── .zyvor/
    ├── schema.zyvor          ← Edit your schema here
    ├── .env                  ← Database URL (protected by .gitignore)
    ├── config.toml           ← Advanced configuration
    ├── generated/            ← Auto-generated modular entities
    │   ├── mod.rs
    │   ├── user/
    │   │   ├── mod.rs        ← Entity + Model + Relations
    │   │   └── types.rs      ← Create + Update structs
    │   └── post/
    │       ├── mod.rs
    │       └── types.rs
    └── migrations/
        ├── 0001_initial.sql
        ├── 0002_schema_update.sql
        └── snapshot.json
```

---

## Architecture


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

### Runtime Boundary


The CLI is a **toolchain**, not a second ORM runtime. Generated code targets the [`zyvor`](https://crates.io/crates/zyvor) runtime crate.

| 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 | — | ✅ |

---

## CLI Commands


| Command | Description |
|---------|-------------|
| `zyvor init` | Scaffold `.zyvor/` with schema template, .env, config, .gitignore |
| `zyvor dev` | Watch mode — auto-regenerate on schema change + diff migrations |
| `zyvor migrate --apply` | Apply all pending migrations (**auto-creates database**) |
| `zyvor validate [SCHEMA]` | Validate schema without generating |
| `zyvor generate [SCHEMA]` | One-shot entity generation |
| `zyvor migrate [SCHEMA] [OUTPUT]` | Generate initial migration SQL file |
| `zyvor --help` | Show usage |
| `zyvor --version` | Show version |

### Configuration Priority


CLI `--database` arg > `DATABASE_URL` env var > `.zyvor/.env` > `.zyvor/config.toml`

---

## Schema Language


```rust
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")
}
```

### Supported Features


| Category | Features |
|----------|----------|
| **Scalar Types** | `Int`, `String`, `Boolean`, `Float`, `DateTime`, `Decimal`, `Json` |
| **Modifiers** | Nullable (`?`), Arrays (`[]`) |
| **Attributes** | `@id`, `@unique`, `@default(...)`, `@map(...)`, `@relation(...)` |
| **Model Attrs** | `@@map(...)`, `@@unique([...])`, `@@index([...])` |
| **Relations** | 1:N, N:1, 1:1, M:M (with explicit pivot tables) |
| **Referential Actions** | `Cascade`, `Restrict`, `SetNull`, `NoAction` |
| **Defaults** | `autoincrement()`, `now()`, literal values |

### Type Mapping


| Schema | Generated Rust | SQL Type |
|--------|---------------|----------|
| `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` |

---

## Modular Code Generation


Generated output is organized into **per-model folders** for scalability:

```
generated/
├── mod.rs                 ← Re-exports all models + types
├── user/
│   ├── mod.rs             ← Entity struct, Model, Field constants, Relations
│   └── types.rs           ← UserCreate, UserUpdate, InsertData, UpdateData
├── post/
│   ├── mod.rs
│   └── types.rs
└── comment/
    ├── mod.rs
    └── types.rs
```

### What Gets Generated


| Component | File | Contents |
|-----------|------|----------|
| Entity marker | `{model}/mod.rs` | `pub struct User;` |
| Model struct | `{model}/mod.rs` | `UserModel` with `Serialize`, `Deserialize`, `FromRow` |
| Field constants | `{model}/mod.rs` | `User::name`, `User::id` (type-safe) |
| Relations | `{model}/mod.rs` | `Relation` constants, loader impls |
| Create input | `{model}/types.rs` | `UserCreate` with `InsertData` impl |
| Update input | `{model}/types.rs` | `UserUpdate` with `UpdateData` impl |
| Top-level re-exports | `mod.rs` | `pub use user::{User, UserModel, UserCreate, UserUpdate};` |

### Nullable Update Semantics


```rust
// None = skip field (don't include in SET clause)
// Some(value) = update to value
// Some(None) = explicitly SET NULL
pub struct UserUpdate {
    pub name: Option<String>,              // non-nullable field
    pub bio: Option<Option<String>>,       // nullable field
}
```

---

## Migration System


### Initial Migration


Generates `CREATE TABLE IF NOT EXISTS` with:
- Scalar columns, primary keys, `SERIAL` auto-increment
- `NOT NULL`, unique constraints, defaults
- Foreign keys with `ON DELETE` actions
- Indexes and composite unique constraints
- Mapped table/column names (`@@map`, `@map`)

### Schema Diffing (Incremental Migrations)


When `zyvor dev` detects schema changes via snapshot comparison:

| Change | Generated SQL |
|--------|--------------|
| New field | `ALTER TABLE ... ADD COLUMN` |
| Removed field | `ALTER TABLE ... DROP COLUMN IF EXISTS` |
| New model | Full `CREATE TABLE` in regenerated initial |
| Dropped model | `DROP TABLE IF EXISTS ... CASCADE` |

Diff migrations are **auto-numbered** sequentially:
```
0001_initial.sql
0002_schema_update.sql   ← First change
0003_schema_update.sql   ← Second change
```

### Migration Tracking


Every `migrate --apply` run manages a `_zyvor_migrations` table:

- **Checksum-based skip:** Already-applied migrations with matching checksum are skipped
- **Drift detection:** Checksum mismatch returns clear error
- **Idempotent:** Running multiple times produces no side effects

### Auto Database Creation


`zyvor migrate --apply` **automatically creates the target database** if it doesn't exist:

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

No manual `CREATE DATABASE` needed.

---

## End-to-End Verification


Full workflow tested against PostgreSQL with Axum:

```
zyvor init → schema.zyvor → zyvor dev → generated/ + migrations/
     ↓
zyvor migrate --apply → PostgreSQL tables created
     ↓
Axum API → CRUD + Relations + Nested Eager Loading
     ↓
✅ ALL 21 TESTS PASSED
```

### Verified Test Coverage


| Area | Tests | Status |
|------|-------|--------|
| Lexer + Parser + Validator | 30+ | ✅ |
| Entity + CRUD code generation | 20+ | ✅ |
| Migration SQL generation | 8 | ✅ |
| Migration tracking + drift detection | 3 | ✅ |
| Schema diffing + auto-numbering | 3 | ✅ |
| Axum CRUD endpoints | 5 | ✅ |
| Eager loading (1:N, N:1, 1:1, M:M) | 4 | ✅ |
| Nested eager loading (2-level) | 1 | ✅ |
| Error handling (404/409/422) | 3 | ✅ |
| Cascade delete | 1 | ✅ |
| Auto database creation | 1 | ✅ |
| **Total** | **64 CLI + 115 runtime** | ✅ All passing |

---

## Consumer Project Setup


Add to your `Cargo.toml`:

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

Use generated entities:

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

mod generated;

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

// Type-safe queries
let users = User::find()
    .where_(User::name.eq("Ali").and(User::age.gte(18)))
    .order_by(User::id.desc())
    .take(20)
    .all(&db).await?;

// Eager loading
let users = User::find()
    .with_nested(User::posts, |q| q.with(Post::comments))
    .all(&db).await?;
```

---

## Roadmap


### ✅ Complete

- [x] Schema language + lexer + parser + validator
- [x] Modular entity generation (per-model folders)
- [x] All relation types (1:N, N:1, 1:1, M:M)
- [x] CRUD code generation (Create/Update/InsertData/UpdateData)
- [x] Migration SQL generation + execution
- [x] Migration tracking + checksum-based skip + drift detection
- [x] Schema diffing (ADD/DROP COLUMN) + auto-numbering
- [x] Auto database creation
- [x] Watch mode with snapshot-based change detection
- [x] `.env` / `config.toml` configuration
- [x] Axum integration verified (21 E2E tests)

### 🔜 Next

- [ ] Column type changes (`ALTER COLUMN TYPE`)
- [ ] Column rename detection
- [ ] Rollback support
- [ ] Migration status reporting command
- [ ] VS Code syntax highlighting for `.zyvor`
- [ ] mdbook documentation

---

## 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, derived everything
3. **Generated code is readable Rust** — no hidden macros, fully inspectable
4. **Features are milestone-tracked** — parser ≠ validator ≠ generator ≠ runtime verification
5. **Zero manual database setup** — auto-create, auto-migrate, auto-diff

---

## License


MIT OR Apache-2.0

---

## Acknowledgements


Inspired by [Prisma](https://www.prisma.io/), [Drizzle](https://orm.drizzle.team/), and the frustration of writing repetitive ORM boilerplate in Rust.
```