Skip to main content
skill CX Codex

zenstack-schema-modeling — Claude Code skill for ZenStack schemas

The zenstack-schema-modeling Claude Code skill helps write and revise ZModel schemas for ZenStack V3. It activates for work on models, fields, relations, enums, and typed JSON fields.

MIT 470 installs ★ 3 updated 2026-10-28

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add zenstackhq/skills --skill zenstack-schema-modeling -a claude-code
Open on GitHub

What zenstack-schema-modeling does

The skill guides agents through ZModel schema design, from model and field declarations to attributes and relations. It covers one-to-one, one-to-many, many-to-many, and self-relations, along with enums, custom types, and mixins.

Its scope also includes polymorphism with @@delegate, computed fields, and typed JSON fields. The default schema path is zenstack/schema.zmodel. After editing, zen check validates the schema; zen generate validates it while generating the database client. Both commands require the ZenStack CLI.

What it helps with

  • define models and field types in ZModel
  • connect models with foreign-key relations
  • add enums and reusable field mixins
  • represent polymorphic models with @@delegate
  • validate a schema and regenerate the database client

Example prompts for the agent

  • Add User and Post models to zenstack/schema.zmodel with a one-to-many relation.
  • Define a typed JSON field and a mixin for shared model fields.
  • Validate the edited schema, then regenerate the database client.

How to install zenstack-schema-modeling

1Skills CLI (Vercel)

npx skills add zenstackhq/skills --skill zenstack-schema-modeling -a claude-code

2Manually: put the files in place

~/.claude/skills/zenstack-schema-modeling/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/zenstack-schema-modeling/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about zenstack-schema-modeling

How do I install zenstack-schema-modeling in Claude Code?

Run npx skills add zenstackhq/skills --skill zenstack-schema-modeling -a claude-code. The skill file is at ~/.claude/skills/zenstack-schema-modeling/SKILL.md.

What does zenstack-schema-modeling do?

It guides ZModel schema work for ZenStack V3, including models, fields, relations, enums, mixins, and polymorphism.

What does zenstack-schema-modeling require?

Schema checks and client generation use the ZenStack CLI commands zen check and zen generate.

Source text

SKILL.md · MIT
---
name: zenstack-schema-modeling
description: Author ZModel (.zmodel) data schemas for ZenStack V3. Use when defining models, fields, field/model attributes, relations (1-1, 1-many, many-many, self), enums, custom types & mixins, polymorphic models (@@delegate), strongly-typed JSON fields, or computed fields.
---

# ZenStack — Schema Modeling (ZModel)

ZModel is ZenStack's schema language — a superset of Prisma's schema. The schema lives at
`zenstack/schema.zmodel` by default. For access policies/validation use `zenstack-access-control`;
for queries use `zenstack-querying`.

After editing the schema:

```bash
zen check      # only validate the schema for syntax/semantic errors (use --schema <file> for a non-default path)
zen generate   # regenerate the database client — also validates the schema as it compiles
```

Run `zen check` when you just want to confirm the schema is valid; run `zen generate` when you want
to regenerate the client (the normal step after a schema change).

Strings accept both single and double quotes. **Every valid Prisma schema is valid ZModel**, so
existing Prisma knowledge transfers directly — the sections below cover both the basics and the
additions ZModel layers on top.

## Datasource

Exactly one `datasource` block per schema. The ORM runtime doesn't use `url` (the driver carries
the connection); the migration engine does.

```zmodel
datasource db {
    provider = 'postgresql'        // 'postgresql' | 'mysql' | 'sqlite'
    url      = env('DATABASE_URL') // or 'file:./dev.db' for SQLite
}
```

> ZModel has **no `generator` block**. Code generation is driven by `zen generate`; optional behavior
> is configured with `plugin` blocks (e.g. `plugin policy`, `plugin prisma`).

## Models & fields

```zmodel
model User {
    id        Int      @id @default(autoincrement())
    email     String   @unique
    name      String?              // optional
    role      Role     @default(USER)
    tags      String[]             // list
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
}
```

**Scalar types**: `String`, `Boolean`, `Int`, `BigInt`, `Float`, `Decimal`, `DateTime`, `Json`,
`Bytes`, `Unsupported("...")`.

**Modifiers**: `?` optional, `[]` list. A field cannot be both optional *and* a list.

### Field attributes (`@`)

`@id`, `@unique`, `@default(...)`, `@updatedAt`, `@map('col')`, `@relation(...)`, `@db.*` (native
type, e.g. `@db.VarChar(64)`), `@json` (typed-JSON field), `@computed` (virtual field).

### Model attributes (`@@`)

`@@id([a, b])` (composite PK), `@@unique([a, b])`, `@@index([a, b])`, `@@map('table')`,
`@@delegate(field)` (polymorphism), plus `@@allow` / `@@deny` / `@@validate` (see
`zenstack-access-control`).

```zmodel
model City {
    country String
    name    String
    @@id([country, name])     // composite primary key
    @@map('cities')
}
```

A model needs an identifier: a `@id` field, an `@@id([...])`, or — failing those — a `@unique`
field / `@@unique([...])`.

### Default value functions

`autoincrement()`, `now()`, `cuid()`, `uuid()` / `uuid(4)`, `ulid()`, `nanoid()`,
`dbgenerated("...")`, plus literals and enum values.

Since v3.1.0, string ID generators accept a `format` with `%s`:

```zmodel
id String @id @default(uuid(4, "user_%s"))   // -> "user_<uuid>"
```

## Enums

```zmodel
enum Role {
    USER
    ADMIN
}
```

Enum value names are global and must not collide.

## Relations

The **owner** side holds the foreign key (`@relation(fields: [...], references: [...])`).

**One-to-one** — FK is `@unique`; the non-owner side is optional:

```zmodel
model User {
    id      Int      @id
    profile Profile?
}
model Profile {
    id     Int  @id
    user   User @relation(fields: [userId], references: [id])
    userId Int  @unique
}
```

**One-to-many** — list on the non-owner side:

```zmodel
model User {
    id    Int    @id
    posts Post[]
}
model Post {
    id       Int  @id
    author   User @relation(fields: [authorId], references: [id])
    authorId Int
}
```

**Many-to-many (implicit)** — list on both sides; the migration engine creates the join table:

```zmodel
model User { id Int @id  posts Post[] }
model Post { id Int @id  editors User[] }
```

**Many-to-many (explicit)** — model the join table yourself when it needs extra fields:

```zmodel
model UserPost {
    user   User @relation(fields: [userId], references: [id])
    userId Int
    post   Post @relation(fields: [postId], references: [id])
    postId Int
    @@id([userId, postId])
}
```

**Named relations** disambiguate multiple relations between the same two models (give both ends the
same name): `@relation('UserPosts', ...)`.

**Self-relations** use a named relation, e.g. a one-to-many manager/reports tree:

```zmodel
model Employee {
    id           Int        @id
    managerId    Int?
    manager      Employee?  @relation('Mgmt', fields: [managerId], references: [id])
    subordinates Employee[] @relation('Mgmt')
}
```

**Referential actions** on the owner side: `onDelete` / `onUpdate` with `Cascade`, `Restrict`,
`NoAction`, `SetNull`, `SetDefault`.

```zmodel
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
```

## Custom types & mixins

A `type` declaration is **not** backed by a table. Use it for typed JSON (below) or as a **mixin**
of reusable fields, applied with `with`:

```zmodel
type BaseFields {
    id        String   @id @default(cuid())
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
}

model User with BaseFields {
    email String @unique
}
model Post with BaseFields {
    title String
}
```

Mixin fields are inlined into the model. Multiple mixins are allowed if names don't conflict. This is
ZModel's mechanism for sharing fields across models (use it instead of an abstract base model).

A type may even carry relation fields (v3.6.0+), but then it can only be used as a mixin, not as a
JSON field:

```zmodel
type AuditMixin {
    createdBy   User   @relation('CreatedBy', fields: [createdById], references: [id])
    createdById String
}
model Post with AuditMixin { title String }
```

## Polymorphism — `@@delegate`

Multi-table inheritance: a base model with a discriminator field and `@@delegate`, concrete models
using `extends`. Concrete and base rows share the same id; you create concrete models, never the
base directly.

```zmodel
model Content {
    id        Int      @id @default(autoincrement())
    createdAt DateTime @default(now())
    owner     User     @relation(fields: [ownerId], references: [id])
    ownerId   Int
    type      String   // discriminator
    @@delegate(type)
}

model Post extends Content {
    content String
}
model Image extends Content {
    data Bytes
}
```

Customize the stored discriminator value with `@@delegateMap` (v3.7.1+), which also works with enum
discriminators:

```zmodel
model Video extends Content {
    url String
    @@delegateMap("video")
}
```

## Strongly-typed JSON

Define a `type`, use it as a field type, and mark the field `@json`. The column is plain JSON in the
database, but ZenStack validates writes and returns a typed value.

```zmodel
type Address {
    street  String
    city    String
    zip     Int
}
model User {
    id      Int     @id
    address Address @json
}
```

## Computed fields

Declare a virtual field with `@computed`; implement it with a Kysely expression in the client
config. It can be selected, filtered, sorted, and referenced in policies.

```zmodel
model User {
    id        Int @id
    postCount Int @computed
}
```

```ts
const db = new ZenStackClient(schema, {
    dialect,
    computedFields: {
        User: {
            postCount: (eb) =>
                eb.selectFrom('Post')
                    .whereRef('Post.authorId', '=', 'id')
                    .select(({ fn }) => fn.countAll<number>().as('count')),
        },
    },
});
```

## ZModel additions over Prisma

- No `generator` block (use `zen generate` + `plugin`s).
- `type` declarations + `with` mixins, `@@delegate` polymorphism, `@json` typed JSON, and
  `@computed` fields are ZenStack additions Prisma lacks.
- Single or double quotes are both fine.

## Reference docs

Full ZenStack documentation for this topic is bundled under [`references/`](references/):

- [modeling-overview.md](references/modeling-overview.md) — data modeling concepts
- [datasource.md](references/datasource.md) — the `datasource` block
- [model.md](references/model.md) — models, fields, ids, defaults
- [attribute.md](references/attribute.md) — field & model attributes
- [relation.md](references/relation.md) — 1-1, 1-many, many-many, self relations
- [enum.md](references/enum.md) — enums
- [custom-type.md](references/custom-type.md) — `type` declarations
- [mixin.md](references/mixin.md) — reusable field mixins (`with`)
- [polymorphism.md](references/polymorphism.md) — `@@delegate` polymorphic models
- [typed-json.md](references/typed-json.md) — strongly-typed JSON fields
- [computed-fields.md](references/computed-fields.md) — `@computed` fields
- [zmodel-attribute-reference.md](references/zmodel-attribute-reference.md) — complete attribute reference
- [zmodel-function-reference.md](references/zmodel-function-reference.md) — attribute-function reference

© zenstackhq · MIT · zenstackhq/skills

Similar skills

All skills for Data and databases →
data-schema-knowledge-modeling lyndonkl The data-schema-knowledge-modeling skill builds rigorous models of entities, relationships, and constraints for databases, knowledge graphs, and ontologies. Use it to formalize your data structure before development. CX Codex +1 159installs convex-schema-validator waynesutton convex-schema-validator is a Claude Code skill that creates convex/schema.ts with types, indexes, and validators. It runs when creating tables, adding fields, modeling relationships, or fixing validation errors. CX Codex +1 3,100installs schema-consistency-checker patricio0312rev schema-consistency-checker reads your tables and columns, flags names that break the agreed style, mismatched ID types, nullable critical fields and foreign keys without an index, then hands back a fix list. CX Codex +1 265installs database-schema-designer borghei database-schema-designer — a Claude Code skill that turns product requirements into a normalized relational schema with tables, ORM models, RLS, indexes and migrations. Works across six platforms, including Codex, Cursor and Gemini CLI. CX Codex +1 183installs design-database-schema davila7 The design-database-schema command plans database structures around requirements, relationships, and query patterns. Use it to draft a schema or rethink an existing one. CX Codex +1 1,021installs schema-designer rohitg00 schema-designer — a Claude Code plugin that generates entity-relationship diagrams (ERD) and designs database schemas. Creates visual representations of tables, columns, and relationships directly in the editor. ★ 2,858repo stars

From the same set9

zenstack-access-control The zenstack-access-control Claude Code skill helps define access policies in a ZenStack V3 schema. It activates for @@allow, @@deny, auth(), and post-update rules. CX Codex +1 556installs zenstack-db-migration The zenstack-db-migration Claude Code skill manages database schema migrations in ZenStack V3. It activates for migration work, schema prototyping, or introspecting an existing database. CX Codex +1 551installs zenstack-crud-server zenstack-crud-server — a skill for Claude Code that turns ZenStack V3 models into REST or RPC CRUD APIs. It covers server routes, per-request access control, OpenAPI specs, and client calls. CX Codex +1 548installs zenstack-plugin-dev The zenstack-plugin-dev Claude Code skill guides development of ZenStack V3 plugins. It applies to ZModel extensions, CLI code generation, and ORM client plugins. CX Codex +1 521installs zenstack-migrate-from-prisma The zenstack-migrate-from-prisma Claude Code skill guides a project migration from Prisma to ZenStack V3. It covers schema, client, generation, and migration updates. CX Codex +1 520installs zenstack-migrate-from-v2 The zenstack-migrate-from-v2 skill for Claude Code guides a ZenStack project upgrade from V2 to V3. It covers schema, access policies, server adapters, and client hooks. CX Codex +1 515installs zenstack-project-setup The zenstack-project-setup Claude Code skill sets up ZenStack V3 projects, scaffolds new ones, and runs zen CLI tasks. It activates for ZenStack installation, project creation, or CLI use. CX Codex +1 510installs zenstack-querying The zenstack-querying Claude Code skill explains how to query and change data with the ZenStack V3 client. It covers ORM operations, relations, and SQL-shaped queries built with Kysely. CX Codex +1 494installs

Project sponsors

Companies that keep this analytics open