---
name: generating-orm-code
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:*)
version: 1.28.0
author: Jeremy Longshore <jeremy@intentsolutions.io>
license: MIT
tags:
  - database
  - orm-code
compatibility: Designed for Claude Code
title: generating-orm-code
canonical_url: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/generating-orm-code
last_updated: 2026-10-07T06:06:28.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [assets/README.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/generating-orm-code/assets/README.md), [references/README.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/generating-orm-code/references/README.md), [scripts/generate_model.py](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/generating-orm-code/scripts/generate_model.py), [scripts/generate_schema.py](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/generating-orm-code/scripts/generate_schema.py), [scripts/README.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/generating-orm-code/scripts/README.md).
>
> If the user asked to install this Skill, run `npx skilld install jeremylongshore/tons-of-skills-marketplace/generating-orm-code`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/generating-orm-code`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/jeremylongshore/tons-of-skills-marketplace/generating-orm-code) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/generating-orm-code`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/generating-orm-code --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/generating-orm-code --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# 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

| 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/
