system/core/generator/EXAMPLES.md

Code Generator — Примеры использования

Примеры использования Code Generator с YAML конфигурациями.


Быстрый старт

1. Простая генерация

# Генерация всего (backend + database + frontend)
python cli.py generate \
  --config tests/fixtures/blog.yaml \
  --output ./generated/

# Только backend
python cli.py generate \
  --config tests/fixtures/blog.yaml \
  --target backend \
  --output ./backend/

# Только одна entity
python cli.py generate \
  --config tests/fixtures/blog.yaml \
  --entity Post \
  --output ./post-service/

2. Валидация конфига

# Проверить конфиг перед генерацией
python cli.py validate --config config.yaml

# Строгий режим (прервать при первой ошибке)
python cli.py validate --config config.yaml --strict

3. Просмотр обработанного YAML

# Показать результат после extends и DELTA
python cli.py show --config config.yaml

Примеры конфигураций

Пример 1: Простой блог

tests/fixtures/blog.yaml — полный пример с User, Post, Comment.

Что генерируется:
- Backend: FastAPI с CRUD endpoints
- Database: PostgreSQL DDL с indexes и FK
- Frontend: React компоненты (Grid, Form) + hooks

Запуск:

python cli.py generate \
  --config tests/fixtures/blog.yaml \
  --output ./blog-app/

cd blog-app/backend
pip install -r requirements.txt
uvicorn main:app --reload

# API доступен: http://localhost:8000
# Docs: http://localhost:8000/docs

Пример 2: DELTA наследование

DELTA операции позволяют переиспользовать конфигурации.

Базовый конфиг (l0_universal.yaml):

entities:
  - name: Entity
    fields:
      - name: id
        type: uuid
        primary_key: true
      - name: created_at
        type: timestamp
      - name: updated_at
        type: timestamp

Расширенный конфиг (l1_platform.yaml):

extends: l0_universal.yaml

# += добавить новую entity
+= entities:
  - name: Contact
    fields:
      - name: email
        type: email
        unique: true

# -= удалить поле
-= entities:
  - name: Entity
    fields:
      - name: updated_at

# = заменить значение
= api:
  title: Platform API v2

DELTA операции:
- += — добавить (append к списку, merge к dict)
- -= — удалить (remove из списка, delete ключи из dict)
- = — заменить (полная замена значения)


Пример 3: CRM система

crm.yaml:

api:
  title: CRM API
  version: 1.0.0

database:
  name: crm_db

entities:
  - name: Company
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: name, type: string, required: true }
      - { name: website, type: url }
      - { name: created_at, type: timestamp }

  - name: Contact
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: company_id, type: uuid, required: true }
      - { name: email, type: email, required: true }
      - { name: phone, type: phone }
      - { name: full_name, type: string, required: true }
      - { name: created_at, type: timestamp }

  - name: Deal
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: company_id, type: uuid, required: true }
      - { name: contact_id, type: uuid }
      - { name: title, type: string, required: true }
      - { name: amount, type: decimal, required: true }
      - { name: stage, type: string, required: true }
      - { name: closed_at, type: timestamp }
      - { name: created_at, type: timestamp }

relations:
  - type: one_to_many
    from: Contact
    to: Company
  - type: one_to_many
    from: Deal
    to: Company

Генерация:

python cli.py generate --config crm.yaml --output ./crm/

Пример 4: E-commerce каталог

catalog.yaml:

api:
  title: Product Catalog
  version: 1.0.0

entities:
  - name: Category
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: parent_id, type: uuid }
      - { name: name, type: string, required: true }
      - { name: slug, type: string, unique: true }
      - { name: created_at, type: timestamp }

  - name: Product
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: category_id, type: uuid, required: true }
      - { name: sku, type: string, unique: true, required: true }
      - { name: title, type: string, required: true }
      - { name: description, type: text }
      - { name: price, type: decimal, required: true }
      - { name: stock, type: integer, default: 0 }
      - { name: attributes, type: json }
      - { name: published, type: boolean, default: false }
      - { name: created_at, type: timestamp }
    indexes:
      - fields: [sku]
      - fields: [category_id]
      - fields: [published, created_at]

  - name: Review
    fields:
      - { name: id, type: uuid, primary_key: true }
      - { name: product_id, type: uuid, required: true }
      - { name: rating, type: integer, required: true }
      - { name: comment, type: text }
      - { name: created_at, type: timestamp }

generate_seeds: true  # Генерировать seeds.sql
use_alembic: true     # Генерировать Alembic миграции

Типы полей

Тип Python TypeScript SQL
string str string VARCHAR(255)
text str string TEXT
int, integer int number INTEGER
float float number REAL
decimal Decimal number NUMERIC(10,2)
bool, boolean bool boolean BOOLEAN
date date Date DATE
datetime, timestamp datetime Date TIMESTAMP
uuid UUID string UUID
email str string VARCHAR(255)
url str string VARCHAR(512)
phone str string VARCHAR(20)
json Dict[str, Any] Record<string, any> JSONB
array List[Any] any[] JSONB

Constraints и модификаторы

fields:
  # Primary key
  - name: id
    type: uuid
    primary_key: true

  # Required (NOT NULL)
  - name: email
    type: email
    required: true

  # Unique
  - name: username
    type: string
    unique: true

  # Default value
  - name: is_active
    type: boolean
    default: true

  # Max length (для string)
  - name: title
    type: string
    max_length: 100

Indexes

entities:
  - name: Product
    indexes:
      # Простой индекс
      - fields: [sku]

      # Уникальный индекс
      - fields: [slug]
        unique: true

      # Композитный индекс
      - fields: [category_id, created_at]

      # Именованный индекс
      - name: idx_product_published
        fields: [published, created_at]

Relations

relations:
  # One-to-Many
  - type: one_to_many
    from: Post
    to: User
    from_field: author_id
    to_field: id

  # Many-to-Many (через промежуточную таблицу)
  - type: many_to_many
    from: Product
    to: Tag
    through: ProductTag

  # Cascade delete
  - type: one_to_many
    from: Comment
    to: Post
    on_delete: CASCADE

Структура сгенерированного кода

Backend (FastAPI)

backend/
├── models/
│   ├── __init__.py
│   ├── user.py
│   ├── post.py
│   └── comment.py
├── schemas/
│   ├── __init__.py
│   ├── user.py         # UserCreate, UserUpdate, UserInDB
│   ├── post.py
│   └── comment.py
├── routers/
│   ├── __init__.py
│   ├── user.py         # CRUD endpoints
│   ├── post.py
│   └── comment.py
├── main.py             # FastAPI app
├── database.py         # DB connection
└── requirements.txt

Database (PostgreSQL)

database/
├── schema.sql          # CREATE TABLE, indexes, FK
├── seeds.sql           # Тестовые данные
├── alembic.ini         # Alembic config
└── migrations/
    └── env.py          # Alembic environment

Frontend (React)

frontend/
├── components/
   ├── UserGrid.tsx
   ├── UserForm.tsx
   ├── PostGrid.tsx
   └── PostForm.tsx
├── hooks/
   ├── useUser.ts      # React hook с CRUD
   └── usePost.ts
├── api/
   ├── UserApi.ts      # API client (axios)
   └── PostApi.ts
├── types/
   ├── User.ts         # TypeScript types
   └── Post.ts
└── package.json

Следующие шаги

После генерации:

Backend

cd backend/
pip install -r requirements.txt

# Настроить DATABASE_URL
export DATABASE_URL="postgresql://user:pass@localhost/db"

# Создать таблицы
python -c "from database import init_db; init_db()"

# Запустить
uvicorn main:app --reload

Frontend

cd frontend/
npm install

# Настроить API URL
echo "REACT_APP_API_URL=http://localhost:8000" > .env

# Запустить
npm run dev

Database

cd database/
psql -U postgres -d mydb -f schema.sql
psql -U postgres -d mydb -f seeds.sql  # Опционально

Документация: CLAUDE.md