generating-orm-code
Execute use when you need to work with ORM code generation. This skill provides ORM model and code generation with comprehensive guidance and automation. Trigger with phrases like "generate ORM models", "create entity classes", or "scaffold database models".
- License 许可
- MIT
- 最近更新
- 2026-03-20
- Stars
- ★ 4
- Forks
- 0
01 前言 Front Matter
- name
- generating-orm-code
- author
- Jeremy Longshore <jeremy@intentsolutions.io>
- license
- MIT
- version
- 1.0.0
- description
- Execute use when you need to work with ORM code generation. This skill provides ORM model and code generation with comprehensive guidance and automation. Trigger with phrases like "generate ORM models", "create entity classes", or "scaffold database models".
- allowed-tools
- Read, Write, Edit, Grep, Glob, Bash(psql:*), Bash(mysql:*), Bash(mongosh:*)
- compatible-with
- claude-code, codex, openclaw
02 资源文件 5
- 资产文件assets/README.md235 B
- 参考文档references/README.md62 B
- 脚本scripts/generate_model.py3.6 KB
- 脚本scripts/generate_schema.py3.6 KB
- 脚本scripts/README.md459 B
03 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
psqlormysqlCLI for queryinginformation_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
-
Introspect the database schema by querying
information_schema.COLUMNS,information_schema.TABLE_CONSTRAINTS, andinformation_schema.KEY_COLUMN_USAGEto extract all tables, columns, data types, nullable flags, defaults, primary keys, foreign keys, and unique constraints. -
For PostgreSQL, additionally query
pg_catalog.pg_typefor custom enum types andpg_catalog.pg_indexfor index definitions. For MySQL, queryinformation_schema.STATISTICSfor index details. -
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->Stringwith@default(uuid())oruuid.uuid4- Custom enums -> Generate enum type definitions
-
Generate model classes with proper decorators/attributes:
- For Prisma: Generate
schema.prismawithmodelblocks,@id,@unique,@relation, and@defaultdirectives. - For TypeORM: Generate entity classes with
@Entity(),@Column(),@PrimaryGeneratedColumn(),@ManyToOne(),@OneToMany()decorators. - For SQLAlchemy: Generate model classes extending
BasewithColumn(),ForeignKey(),relationship(), and__tablename__. - For Drizzle: Generate table definitions with
pgTable(),serial(),varchar(),timestamp(), andrelations().
- For Prisma: Generate
-
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.
-
Create migration files that capture the current schema state. For Prisma:
npx prisma migrate dev --name init. For TypeORM: generate migration withtypeorm migration:generate. For Alembic:alembic revision --autogenerate. -
Generate repository/service layer with common CRUD operations:
findById,findAllwith pagination,create,update,delete, and relationship-aware queries (findWithRelations). -
Add validation decorators or constraints matching database CHECK constraints and NOT NULL columns. Use
class-validatorfor TypeORM, Pydantic validators for SQLAlchemy, or Zod schemas for Prisma. -
Generate TypeScript/Python type definitions or interfaces for API layer consumption, ensuring the ORM models and API types stay synchronized.
-
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
| Error | Cause | Solution |
|---|---|---|
| Circular relationship dependency | Two entities reference each other, causing import cycles | Use lazy loading (() => RelatedEntity) in TypeORM; use ForwardRef in SQLAlchemy; split into separate files with deferred imports |
| Unknown column type mapping | Database uses custom types, extensions, or domain types not in the standard mapping | Add custom type mapping in generator config; use @Column({ type: 'text' }) as fallback; register custom transformers |
| Migration conflicts with existing data | Generated migration adds NOT NULL columns without defaults | Add default values to new columns; create a two-phase migration (add nullable, backfill, set NOT NULL) |
| Junction table not detected as many-to-many | Junction table has extra columns beyond the two foreign keys | Model as an explicit entity with two ManyToOne relationships instead of an implicit ManyToMany |
| Schema drift between ORM models and database | Manual database changes not reflected in ORM code | Run 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/
04 同仓库更多 Skills
azure-apim-architecture
Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.
apiops-deployment
Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep/Terraform), CI/CD pipelines (GitHub Actions/Azure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.
apim-policy-authoring
Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request/response processing logic.
api-security-review
Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.
jira-cli
Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.
calculator
Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.