Prisma Schema to SQL DDL Migration Generator

Prisma Schema to SQL DDL Migration Generator

Convert Prisma schema definitions into clean, production-ready SQL DDL migration scripts for PostgreSQL, MySQL, and SQLite.

Presets:
Target Dialect:
Prisma Schema Definition(4 models, 2 enums)
-- ============================================================================
-- ToolsAA Prisma to SQL DDL Generator
-- Target Dialect: POSTGRESQL
-- Generated via ToolsAA Prisma-to-SQL Engine
-- 100% Pure Client-Side Browser Compilation
-- ============================================================================

-- ----------------------------------------------------------------------------
-- Drop Existing Tables
-- ----------------------------------------------------------------------------
DROP TABLE IF EXISTS "user_sessions" CASCADE;
DROP TABLE IF EXISTS "memberships" CASCADE;
DROP TABLE IF EXISTS "users" CASCADE;
DROP TABLE IF EXISTS "organizations" CASCADE;

-- ----------------------------------------------------------------------------
-- Custom Enum Types
-- ----------------------------------------------------------------------------
DROP TYPE IF EXISTS "Role";
CREATE TYPE "Role" AS ENUM ('SUPERADMIN', 'ADMIN', 'MEMBER', 'VIEWER');
DROP TYPE IF EXISTS "MemberStatus";
CREATE TYPE "MemberStatus" AS ENUM ('INVITED', 'ACTIVE', 'SUSPENDED');

-- ----------------------------------------------------------------------------
-- Table Definitions
-- ----------------------------------------------------------------------------
CREATE TABLE "organizations" (
  "id" UUID NOT NULL DEFAULT 'uuid(',
  "name" VARCHAR(128) NOT NULL,
  "slug" VARCHAR(64) NOT NULL UNIQUE,
  "domain" VARCHAR(128),
  "createdAt" TIMESTAMPTZ NOT NULL DEFAULT 'now(',
  "updatedAt" TIMESTAMPTZ NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "users" (
  "id" UUID NOT NULL DEFAULT 'uuid(',
  "email" VARCHAR(255) NOT NULL UNIQUE,
  "fullName" VARCHAR(128) NOT NULL,
  "avatarUrl" VARCHAR(512),
  "emailVerified" TIMESTAMPTZ,
  "isActive" BOOLEAN NOT NULL DEFAULT true,
  "createdAt" TIMESTAMPTZ NOT NULL DEFAULT 'now(',
  "updatedAt" TIMESTAMPTZ NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "memberships" (
  "id" UUID NOT NULL DEFAULT 'uuid(',
  "organizationId" UUID NOT NULL,
  "userId" UUID NOT NULL,
  "role" "Role" NOT NULL DEFAULT 'MEMBER',
  "status" "MemberStatus" NOT NULL DEFAULT 'ACTIVE',
  "joinedAt" TIMESTAMPTZ NOT NULL DEFAULT 'now(',
  PRIMARY KEY ("id"),
  UNIQUE ("organizationId", "userId")
);

CREATE TABLE "user_sessions" (
  "id" UUID NOT NULL DEFAULT 'uuid(',
  "sessionToken" VARCHAR(255) NOT NULL UNIQUE,
  "userId" UUID NOT NULL,
  "ipAddress" VARCHAR(45),
  "userAgent" VARCHAR(512),
  "expiresAt" TIMESTAMPTZ NOT NULL,
  "createdAt" TIMESTAMPTZ NOT NULL DEFAULT 'now(',
  PRIMARY KEY ("id")
);

-- ----------------------------------------------------------------------------
-- Foreign Key Constraints
-- ----------------------------------------------------------------------------
ALTER TABLE "memberships" ADD CONSTRAINT fk_memberships_organizationId FOREIGN KEY ("organizationId") REFERENCES "organizations"("id") ON DELETE CASCADE;
ALTER TABLE "memberships" ADD CONSTRAINT fk_memberships_userId FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE;
ALTER TABLE "user_sessions" ADD CONSTRAINT fk_user_sessions_userId FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE;

-- ----------------------------------------------------------------------------
-- Secondary Indexes
-- ----------------------------------------------------------------------------
CREATE INDEX "idx_memberships_userId" ON "memberships" ("userId");
CREATE INDEX "idx_user_sessions_userId_expiresAt" ON "user_sessions" ("userId", "expiresAt");
4
Models Parsed
27
Attributes & Columns
100%
Executable SQL Ready

Instant Schema Compilation

Parses Prisma models, relations, composite keys, and native database types directly in browser memory without server latency.

100% Client-Side Privacy

Your database schemas, proprietary table designs, and business models never leave your browser. Zero cloud transmission.

Multi-Dialect SQL Target

Tailored DDL generation for PostgreSQL, MySQL, SQLite, and Microsoft SQL Server with dialect-specific types and constraints.

Technical Reference & Architecture Guide

Prisma To Sql — Reference Guide

Developer utility for prisma-to-sql.

Key Parameters & Controls

dialectSqlDialect (postgresql | mysql | sqlite | sqlserver)

Target SQL dialect controlling data type mapping, identifier quoting characters, and enum generation strategies.

Default: postgresql
dropTableIfExistsboolean

Prepends DROP TABLE IF EXISTS statements (and DROP TYPE in PostgreSQL) to create idempotent, re-runnable migration scripts.

Default: true
includeForeignKeysboolean

Generates FOREIGN KEY constraints derived from Prisma @relation fields, mapping onDelete and onUpdate referential actions.

Default: true
separateAlterFkboolean

Appends foreign key constraints as trailing ALTER TABLE statements instead of inline, avoiding circular dependency creation deadlocks.

Default: true
includeIndexesboolean

Generates explicit CREATE INDEX and CREATE UNIQUE INDEX statements for Prisma @@index and multi-field @@unique attributes.

Default: true
quoteIdentifiersboolean

Wraps table, column, and constraint identifiers in dialect-specific quotation marks to avoid reserved keyword collisions.

Default: true

Pro Tips & Best Practices

Decouple Foreign Keys via ALTER

Enable separateAlterFk when generating DDL for models with mutual or cyclic relationships. Emitting constraints after all CREATE TABLE statements prevents dependency order failures during migration execution.

Handle Client-Side ID Generators

Prisma functions like @default(cuid()) or @default(nanoid()) execute exclusively in the client-side JavaScript runtime. Map these columns to VARCHAR(30) or migrate to @default(uuid()) for native database generation.

Enforce Native Types with @db

Prisma String and DateTime fields map to default column types like TEXT or TIMESTAMP. Add precise attributes such as @db.VarChar(255), @db.Timestamptz, or @db.Decimal(12, 2) to generate exact, storage-optimized DDL.

Automate PostgreSQL UpdatedAt

While MySQL handles @updatedAt via ON UPDATE CURRENT_TIMESTAMP, PostgreSQL requires a custom procedural trigger. Combine the generated DDL with a plpgsql BEFORE UPDATE trigger function to update timestamps on change.

Common Gotchas & Troubleshooting

Foreign key table creation fails with relation does not exist

This occurs when inline foreign key definitions reference a table created later in the migration script. Set separateAlterFk to true to decouple table creation from constraint definitions.

PostgreSQL migration fails with type already exists on rerun

Enable dropTableIfExists to prepend DROP TYPE IF EXISTS alongside DROP TABLE statements, or wrap enum creation in DO $$ BEGIN ... EXCEPTION WHEN duplicate_object THEN null; END $$ blocks.

SQLite rejects ALTER TABLE ADD CONSTRAINT FOREIGN KEY syntax

SQLite does not support altering existing tables to add foreign keys. When targeting SQLite, declare constraints inline during initial table definition or recreate tables using temporary staging tables.

Frequently Asked Questions

Can the generated SQL DDL be executed directly in production CI/CD migrations?▼

Yes. The generated output consists of standard, self-contained SQL DDL statements compatible with any migration engine, including Flyway, Liquibase, golang-migrate, and native psql or mysql CLI utilities.

What SQL structures represent Prisma implicit many-to-many relationships?▼

When two models define mutual relation lists without an explicit join model, the compiler synthesizes the Prisma-standard _ModelAToModelB pivot table containing dual primary foreign keys and cascade actions.

Are database schema definitions or credentials transmitted to any remote server?▼

No. The AST parser, relational graph resolver, and SQL emitters execute entirely within local browser memory using client-side JavaScript. Zero schema contents or credentials leave your workstation.

Which SQL constructs represent Prisma composite primary keys and unique constraints?▼

Model-level @@id attributes are transformed into composite PRIMARY KEY (col1, col2) clauses, while @@unique directives compile into CREATE UNIQUE INDEX statements or table-level UNIQUE constraints according to the selected dialect.

Related Tools & Utilities

All Tools →