Используйте при генерации кода ORM.

Звёзды2 926
Авторjeremylongshore
Установок26

Установка

SKILL.md

ORM Code Generator

Overview

Generate type-safe ORM model classes, migration files, and repository patterns from existing database schemas or domain specifications. Supports Prisma, TypeORM, Sequelize, SQLAlchemy, Django ORM, and Drizzle ORM.

Prerequisites

  • Database connection string or credentials for schema introspection
  • psql or mysql CLI for querying information_schema
  • Target ORM framework already installed in the project (prisma, typeorm, sqlalchemy, etc.)
  • Node.js/Python/Go runtime matching the target ORM
  • Existing project structure to place generated models in the correct directory

Instructions

  1. Introspect the database schema by querying information_schema.COLUMNS, information_schema.TABLE_CONSTRAINTS, and information_schema.KEY_COLUMN_USAGE to extract all tables, columns, data types, nullable flags, defaults, primary keys, foreign keys, and unique constraints.

  2. For PostgreSQL, additionally query pg_catalog.pg_type for custom enum types and pg_catalog.pg_index for index definitions. For MySQL, query information_schema.STATISTICS for index details.

  3. Map database column types to ORM field types:

    • varchar/text -> String / @Column('text')
    • integer/bigint -> Int / @Column('int')
    • boolean -> Boolean / @Column('boolean')
    • timestamp/datetime -> DateTime / @Column('timestamp')
    • jsonb/json -> Json / @Column('jsonb')
    • uuid -> String with @default(uuid()) or uuid.uuid4
    • Custom enums -> Generate enum type definitions
  4. Generate model classes with proper decorators/attributes:

    • For Prisma: Generate schema.prisma with model blocks, @id, @unique, @relation, and @default directives.
    • For TypeORM: Generate entity classes with @Entity(), @Column(), @PrimaryGeneratedColumn(), @ManyToOne(), @OneToMany() decorators.
    • For SQLAlchemy: Generate model classes extending Base with Column(), ForeignKey(), relationship(), and __tablename__.
    • For Drizzle: Generate table definitions with pgTable(), serial(), varchar(), timestamp(), and relations().
  5. Generate relationship mappings from foreign key constraints. Detect one-to-one (unique FK), one-to-many, and many-to-many (junction table with two FKs) patterns automatically. Add both sides of each relationship with proper cascade options.

  6. Create migration files that capture the current schema state. For Prisma: npx prisma migrate dev --name init. For TypeORM: generate migration with typeorm migration:generate. For Alembic: alembic revision --autogenerate.

  7. Generate repository/service layer with common CRUD operations: findById, findAll with pagination, create, update, delete, and relationship-aware queries (findWithRelations).

  8. Add validation decorators or constraints matching database CHECK constraints and NOT NULL columns. Use class-validator for TypeORM, Pydantic validators for SQLAlchemy, or Zod schemas for Prisma.

  9. Generate TypeScript/Python type definitions or interfaces for API layer consumption, ensuring the ORM models and API types stay synchronized.

  10. Validate generated models by running a test migration against a temporary database or by comparing the generated schema against the live database schema with a diff tool.

Output

  • Model/entity files with full type annotations, decorators, and relationship mappings
  • Migration files capturing the initial schema state
  • Enum type definitions for database enum columns
  • Repository/service classes with typed CRUD operations
  • Validation schemas (Zod, class-validator, Pydantic) matching database constraints
  • Type definition files for API layer consumption

Error Handling

ErrorCauseSolution
Circular relationship dependencyTwo entities reference each other, causing import cyclesUse lazy loading (() => RelatedEntity) in TypeORM; use ForwardRef in SQLAlchemy; split into separate files with deferred imports
Unknown column type mappingDatabase uses custom types, extensions, or domain types not in the standard mappingAdd custom type mapping in generator config; use @Column({ type: 'text' }) as fallback; register custom transformers
Migration conflicts with existing dataGenerated migration adds NOT NULL columns without defaultsAdd default values to new columns; create a two-phase migration (add nullable, backfill, set NOT NULL)
Junction table not detected as many-to-manyJunction table has extra columns beyond the two foreign keysModel as an explicit entity with two ManyToOne relationships instead of an implicit ManyToMany
Schema drift between ORM models and databaseManual database changes not reflected in ORM codeRun introspection again; use prisma db pull or sqlacodegen to regenerate; diff against existing models

Examples

Prisma schema from PostgreSQL e-commerce database: Introspect 15 tables including users, orders, products, and categories. Generate schema.prisma with proper @relation directives, enum types for order status, and @default(autoincrement()) for serial columns. Output includes Zod validation schemas for each model.

TypeORM entities from MySQL SaaS application: Generate entity classes for a multi-tenant application with tenant isolation. Each entity includes a tenantId column with a custom @TenantAware decorator. Repository layer includes tenant-scoped query methods.

SQLAlchemy models from legacy database with naming conventions: Introspect a database with inconsistent naming (mix of camelCase and snake_case). Generate models with __tablename__ preserving original names while using Pythonic property names. Alembic migration captures the full schema.

Resources

  • Prisma introspection: https://www.prisma.io/docs/orm/prisma-schema/introspection
  • TypeORM entity documentation: https://typeorm.io/entities
  • SQLAlchemy ORM tutorial: https://docs.sqlalchemy.org/en/20/orm/
  • Drizzle ORM schema: https://orm.drizzle.team/docs/sql-schema-declaration
  • Django inspectdb command: https://docs.djangoproject.com/en/5.0/howto/legacy-databases/

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: generating-orm-code](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-generating-orm-code)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
A11y Architectaffaan-m · Архитектор доступности, специализирующийся на соответствии WCAG 2.2 для веба и нативных…
225 587 ★
Add Language Rulesaffaan-m · Каркас команды workflow для add-language-rules в everything-claude-code.
225 587 ★
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Code Exploreraffaan-m · Глубоко анализирует существующие функции кодовой базы, прослеживая пути выполнения…
225 587 ★
Code Revieweraffaan-m · Эксперт по ревью кода. Проактивно проверяет код на качество, безопасность и…
225 587 ★
Code Simplifieraffaan-m · Упрощение и очистка кода без изменения поведения.
225 587 ★
Comment Analyzeraffaan-m · Анализ комментариев в коде на точность, полноту и риск устаревания.
225 587 ★

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8