К основному содержанию
скилл CX Codex

zenstack-schema-modeling — скилл для Claude Code: схемы ZenStack

Скилл zenstack-schema-modeling для Claude Code помогает создавать и менять схемы данных ZModel для ZenStack V3. Запускается при работе с моделями, полями, связями, перечислениями и типизированными JSON-полями.

MIT 470 установок ★ 3 обновлён 2026-10-28

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add zenstackhq/skills --skill zenstack-schema-modeling -a claude-code
Открыть на GitHub

Что делает zenstack-schema-modeling

Скилл описывает правила для схем ZModel и помогает задавать модели, поля, атрибуты и связи между моделями. Он охватывает отношения «один к одному», «один ко многим», «многие ко многим» и связи модели с самой собой, а также перечисления, собственные типы и примеси.

Среди тем — полиморфные модели через @@delegate, вычисляемые поля и типизированные JSON-поля. Схема по умолчанию находится в zenstack/schema.zmodel; после правок zen check проверяет её, а zen generate проверяет схему и создаёт клиент базы данных. Для этих команд нужен установленный ZenStack CLI.

Какие задачи решает

  • описать модели и типы полей в ZModel
  • задать связи и внешние ключи между моделями
  • добавить перечисления и повторно используемые примеси
  • смоделировать полиморфные модели через @@delegate
  • проверить схему и пересоздать клиент базы данных

Примеры запросов агенту

  • Опиши модели пользователей и публикаций в zenstack/schema.zmodel и свяжи их отношением «один ко многим».
  • Добавь в схему типизированное JSON-поле и примесь с общими полями.
  • Проверь схему после изменений и пересоздай клиент базы данных.

Как установить zenstack-schema-modeling

1Через Skills CLI (Vercel)

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

2Вручную: положить файлы

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

Папка скилла целиком; для одного проекта — .claude/skills/zenstack-schema-modeling/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о zenstack-schema-modeling

Как установить zenstack-schema-modeling в Claude Code?

Выполни npx skills add zenstackhq/skills --skill zenstack-schema-modeling -a claude-code. Файл скилла находится по пути ~/.claude/skills/zenstack-schema-modeling/SKILL.md.

Что делает zenstack-schema-modeling?

Скилл помогает описывать схемы данных ZModel для ZenStack V3: модели, поля, связи, перечисления, примеси и полиморфизм.

Что нужно для работы zenstack-schema-modeling?

Для проверки схемы и генерации клиента нужен ZenStack CLI: команды zen check и zen generate.

Исходный текст

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

Похожие скиллы

Все скиллы по теме «Данные и базы» →
data-schema-knowledge-modeling lyndonkl Скилл data-schema-knowledge-modeling для Claude Code моделирует сущности, связи и ограничения для баз данных, графов знаний и онтологий. Формализует структуру данных перед разработкой. CX Codex +1 159установок convex-schema-validator waynesutton Скилл convex-schema-validator для Claude Code, Codex, Cursor и других платформ: создаёт convex/schema.ts с типами, индексами и валидаторами. Запускается при создании таблиц, добавлении полей, ошибках валидации или проектировании связей. CX Codex +1 3 100установок schema-consistency-checker patricio0312rev Скилл schema-consistency-checker проверяет схему базы на единый стиль имён, типы id, NULL в критичных полях и внешние ключи без индекса, а потом отдаёт список нарушений с рекомендациями. CX Codex +1 265установок database-schema-designer borghei Скилл database-schema-designer для Claude Code превращает требования к продукту в нормализованную реляционную схему: таблицы, ORM-модели, RLS, индексы и миграции. Запускается на шести платформах, среди которых Codex, Cursor и Gemini CLI. CX Codex +1 183установок design-database-schema davila7 Команда design-database-schema проектирует структуру базы данных с учётом связей, ограничений и запросов. Она пригодится при создании схемы или пересмотре существующей. CX Codex +1 1 021установок schema-designer rohitg00 Плагин schema-designer для Claude Code генерирует диаграммы сущностей и связей (ERD) и помогает проектировать схемы баз данных. Запускается прямо в редакторе, чтобы визуализировать структуру данных и связи между таблицами. ★ 2 858звёзд репо

Из того же набора9

zenstack-access-control Скилл zenstack-access-control для Claude Code помогает задавать правила доступа в схеме ZenStack V3. Подключается при работе с @@allow, @@deny, auth() и проверками после обновления. CX Codex +1 556установок zenstack-db-migration Скилл zenstack-db-migration для Claude Code управляет миграциями схемы базы данных в ZenStack V3. Вызывается при создании и применении миграций, синхронизации схемы или работе с существующей базой. CX Codex +1 551установок zenstack-crud-server Скилл zenstack-crud-server для Claude Code превращает модели ZenStack V3 в REST- или RPC CRUD API. Подключается при создании серверных маршрутов, настройке доступа к данным или вызове API из клиента. CX Codex +1 548установок zenstack-plugin-dev Скилл zenstack-plugin-dev для Claude Code помогает создавать плагины ZenStack V3. Включается при работе с ZModel, генерацией кода через CLI или расширением ORM-клиента. CX Codex +1 521установок zenstack-migrate-from-prisma Скилл zenstack-migrate-from-prisma для Claude Code переносит проект с Prisma на ZenStack V3. Он помогает заменить схему, клиент и команды миграции, сохранив рабочие вызовы ORM. CX Codex +1 520установок zenstack-migrate-from-v2 Скилл zenstack-migrate-from-v2 для Claude Code переводит проект ZenStack с V2 на V3. Помогает обновить схему, политики доступа, серверные адаптеры и клиентские хуки. CX Codex +1 515установок zenstack-project-setup Скилл zenstack-project-setup для Claude Code настраивает проекты ZenStack V3: устанавливает зависимости, создаёт каркас и запускает команды zen. Активируется при установке ZenStack, создании проекта или работе с CLI. CX Codex +1 510установок zenstack-querying Скилл zenstack-querying для Claude Code помогает работать с данными через клиент ZenStack V3. Он включается при создании запросов, изменении записей и настройке выборок со связями. CX Codex +1 494установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой