Home
Sql To Typebox

SQL DDL to TypeBox TypeScript Schema Generator

Convert SQL CREATE TABLE statements into @sinclair/typebox runtime validation schemas using Type.Object, Type.String, Type.Number, and Type.Optional.

Presets:
Dialect:
Null Strategy:
Date Mode:
Casing:
SQL DDL Input3 tables detected
import { Type, Static } from '@sinclair/typebox';

UserRole {
  SUPERADMIN = 'SUPERADMIN',
  ORG_ADMIN = 'ORG_ADMIN',
  MEMBER = 'MEMBER',
  BILLING = 'BILLING',
  GUEST = 'GUEST',
}
UserRoleSchema = Type.Enum(UserRole);
UserRoleType = Static<typeof UserRoleSchema>;

SubscriptionStatus {
  TRIALING = 'TRIALING',
  ACTIVE = 'ACTIVE',
  PAST_DUE = 'PAST_DUE',
  CANCELED = 'CANCELED',
}
SubscriptionStatusSchema = Type.Enum(SubscriptionStatus);
SubscriptionStatusType = Static<typeof SubscriptionStatusSchema>;

/**
 * TypeBox Schema for SQL table "organizations"
 * Primary Key: [id]
 */
OrganizationSchema = Type.Object({
  id: Type.String({ format: 'uuid' }),
  slug: Type.String({ maxLength: 64 }),
  name: Type.String({ maxLength: 255 }),
  billingEmail: Type.String({ format: 'email', maxLength: 255 }),
  status: SubscriptionStatusSchema,
  settings: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
  isActive: Type.Boolean({ default: true }),
  createdAt: Type.String({ format: 'date-time' }),
  updatedAt: Type.String({ format: 'date-time' }),
}, { additionalProperties: false });
Organization = Static<typeof OrganizationSchema>;

/**
 * TypeBox Schema for SQL table "users"
 * Primary Key: [id]
 */
UserSchema = Type.Object({
  id: Type.String({ format: 'uuid' }),
  organizationId: Type.String({ format: 'uuid' }),
  email: Type.String({ format: 'email', maxLength: 255 }),
  fullName: Type.Optional(Type.String({ maxLength: 120 })),
  avatarUrl: Type.Optional(Type.String({ format: 'uri', maxLength: 500 })),
  role: UserRoleSchema,
  phoneNumber: Type.Optional(Type.String({ maxLength: 32 })),
  isVerified: Type.Boolean({ default: false }),
  lastLoginAt: Type.Optional(Type.String({ format: 'date-time' })),
  createdAt: Type.String({ format: 'date-time' }),
}, { additionalProperties: false });
User = Static<typeof UserSchema>;

/**
 * TypeBox Schema for SQL table "audit_logs"
 * Primary Key: [id]
 */
AuditLogSchema = Type.Object({
  id: Type.Integer({ minimum: 0 }),
  organizationId: Type.String({ format: 'uuid' }),
  actorId: Type.Optional(Type.String({ format: 'uuid' })),
  eventName: Type.String({ maxLength: 100 }),
  ipAddress: Type.Optional(Type.String({ format: 'ipv4' })),
  userAgent: Type.Optional(Type.String({ maxLength: 500 })),
  payload: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
  createdAt: Type.String({ format: 'date-time' }),
}, { additionalProperties: false });
AuditLog = Static<typeof AuditLogSchema>;
Tables Detected
3
Columns Processed
27
TypeBox Schemas
14

Zero-Knowledge Local Execution

All data processing, parsing, and compilation execute strictly inside your local browser memory. Zero external server uploads.

Sub-Millisecond AST Engine

All data payloads remain strictly local with zero external server communication.

Production Ready Export

Clean, optimized output formats ready for immediate deployment.

Technical Reference & Architecture Guide

SQL DDL to TypeBox TypeScript Schema Generator — Reference Guide

Convert SQL CREATE TABLE statements into @sinclair/typebox runtime validation schemas using Type.Object, Type.String, Type.Number, and Type.Optional.

Key Parameters & Controls

SQL DialectEnum ('postgres' | 'mysql' | 'sqlite' | 'generic')

Specifies the SQL dialect to correctly map vendor-specific types such as UUID, JSONB, ENUM, SERIAL, and DATETIME.

Default: 'postgres'
Nullability ModeEnum ('optional' | 'union-null' | 'optional-null')

Determines how SQL columns without a NOT NULL constraint are represented in TypeBox (Type.Optional, Type.Union with Type.Null, or both).

Default: 'optional'
Generate Static TypesBoolean

Generates accompanying TypeScript type aliases using TypeBox's Static<typeof Schema> utility alongside runtime schemas.

Default: true
Output FormatEnum ('standard' | 'fastify' | 'elysia')

Formats the generated code for standalone TypeBox validation, Fastify route schemas, or Elysia.js models.

Default: 'standard'

Pro Tips & Best Practices

Fastify and Elysia.js Direct Integration

Because TypeBox compiles down to JSON Schema, you can directly pass the generated Type.Object schemas into Fastify route definitions or Elysia.js model guards for zero-overhead validation and automatic TypeScript inference.

For PostgreSQL JSON/JSONB or MySQL

For PostgreSQL JSON/JSONB or MySQL JSON columns, use Type.Unknown() or nested Type.Record(Type.String(), Type.Any()) to maintain strict schema typing while allowing structured arbitrary payloads.

Numeric Range and BigInt Safeguards

When mapping BIGINT or INT8 columns, note that JavaScript numbers exceed safe integers past 2^53 - 1. Consider generating Type.BigInt() or Type.String({ pattern: '^[0-9]+$' }) to prevent runtime precision loss in API payloads.

Common Gotchas & Troubleshooting

Columns without NOT NULL generate unexpected Type.Optional fields

In SQL DDL, columns default to nullable unless explicitly declared with NOT NULL. If a property should always exist in the payload even if null, switch the Nullability Mode to 'union-null' or add NOT NULL to your SQL definition.

Custom database extensions or composite types fail to parse

Specialized types such as PostGIS GEOMETRY, HSTORE, or custom ENUM types not defined in the DDL will be mapped to Type.Unknown(). Replace them with standard SQL primitive types (e.g., TEXT, JSONB, BYTEA) before conversion.

Frequently Asked Questions

What is @sinclair/typebox and why convert SQL DDL to it?▼

TypeBox is an ultra-fast JSON Schema type builder for TypeScript that provides both runtime validation and compile-time static type inference. Converting SQL DDL to TypeBox schemas ensures database schema consistency across API routes, request validation, and application layers.

How does TypeBox Static<typeof Schema> provide TypeScript types?▼

TypeBox schemas are plain JavaScript objects representing JSON Schema structures. Using TypeScript's type-level programming, the Static<typeof Schema> utility extracts the equivalent compile-time TypeScript type without requiring code generation tools or duplicative interface files.

How are auto-incrementing primary keys (SERIAL, AUTO_INCREMENT) handled?▼

The generator maps auto-incrementing integer columns to Type.Integer({ minimum: 1 }). For insert schemas (where the database assigns the ID automatically), you can mark the ID field as optional using Type.Optional().

Does this tool transmit SQL schemas or database structures to external servers?▼

No. The entire SQL parsing and TypeBox schema generation pipeline operates 100% client-side in your web browser. No SQL text, schema metadata, or queries are ever uploaded to any backend server.

Related Tools & Utilities

All Tools →