drizzle

package
v1.0.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 10, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

Drizzle Writer

Generates TypeScript/JavaScript files with Drizzle ORM schema definitions from database schema information.

Overview

The Drizzle Writer converts RelSpec's internal database model representation into TypeScript source code with Drizzle ORM schema definitions, including tables, columns, relationships, and constraints.

Features

  • Generates Drizzle-compatible TypeScript schema
  • Supports PostgreSQL and MySQL schemas
  • Creates table definitions with proper column types
  • Generates relationship definitions
  • Handles constraints and indexes
  • Outputs formatted TypeScript code

Usage

Basic Example
package main

import (
    "git.warky.dev/wdevs/relspecgo/pkg/models"
    "git.warky.dev/wdevs/relspecgo/pkg/writers"
    "git.warky.dev/wdevs/relspecgo/pkg/writers/drizzle"
)

func main() {
    options := &writers.WriterOptions{
        OutputPath: "schema.ts",
        Metadata: map[string]interface{}{
            "database_type": "postgresql", // or "mysql"
        },
    }

    writer := drizzle.NewWriter(options)
    err := writer.WriteDatabase(db)
    if err != nil {
        panic(err)
    }
}
CLI Examples
# Generate Drizzle schema from PostgreSQL database
relspec --input pgsql \
  --conn "postgres://localhost/mydb" \
  --output drizzle \
  --out-file schema.ts

# Convert GORM models to Drizzle
relspec --input gorm --in-file models.go --output drizzle --out-file schema.ts

# Convert JSON schema to Drizzle
relspec --input json --in-file schema.json --output drizzle --out-file db/schema.ts

Generated Code Example

import { pgTable, serial, varchar, text, timestamp, integer } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  username: varchar('username', { length: 50 }).notNull().unique(),
  email: varchar('email', { length: 100 }).notNull(),
  bio: text('bio'),
  createdAt: timestamp('created_at').notNull().defaultNow(),
});

export const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  title: varchar('title', { length: 200 }).notNull(),
  content: text('content'),
});

export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  user: one(users, {
    fields: [posts.userId],
    references: [users.id],
  }),
}));

Supported Column Types

PostgreSQL
  • serial, bigserial - Auto-increment integers
  • integer, bigint, smallint - Integer types
  • varchar, text - String types
  • boolean - Boolean
  • timestamp, date, time - Date/time types
  • json, jsonb - JSON types
  • uuid - UUID type
MySQL
  • int, bigint, smallint - Integer types
  • varchar, text - String types
  • boolean - Boolean
  • datetime, timestamp - Date/time types
  • json - JSON type

Notes

  • Table names and column names are preserved as-is
  • Relationships are generated as separate relation definitions
  • Constraint actions (CASCADE, etc.) are included in references
  • Schema names other than 'public' are supported
  • Output is formatted TypeScript code

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColumnData

type ColumnData struct {
	Name           string // Column name in database
	FieldName      string // Field name in TypeScript (camelCase)
	DrizzleChain   string // Complete Drizzle column chain (e.g., "integer('id').primaryKey()")
	TypeScriptType string // TypeScript type for interface (e.g., "string", "number | null")
	IsForeignKey   bool   // Whether this is a foreign key
	ReferencesLine string // The .references() line if FK
	Comment        string // Column comment
}

ColumnData represents a column in a table

func NewColumnData

func NewColumnData(col *models.Column, table *models.Table, tm *TypeMapper, isEnum bool) *ColumnData

NewColumnData creates ColumnData from a models.Column

type EnumData

type EnumData struct {
	Name       string   // Enum name (PascalCase)
	VarName    string   // Variable name for the enum (camelCase)
	Values     []string // Enum values
	ValuesStr  string   // Comma-separated quoted values for pgEnum()
	TypeUnion  string   // TypeScript union type (e.g., "'admin' | 'user' | 'guest'")
	SchemaName string   // Schema name
}

EnumData represents an enum in the schema

func NewEnumData

func NewEnumData(enum *models.Enum, tm *TypeMapper) *EnumData

NewEnumData creates EnumData from a models.Enum

type IndexData

type IndexData struct {
	Name       string   // Index name
	Columns    []string // Column names
	IsUnique   bool     // Whether it's a unique index
	Definition string   // Complete index definition line
}

IndexData represents an index definition

func NewIndexData

func NewIndexData(index *models.Index, tableVar string, tm *TypeMapper) *IndexData

NewIndexData creates IndexData from a models.Index

type TableData

type TableData struct {
	Name              string        // Table variable name (camelCase, e.g., users)
	TableName         string        // Actual database table name (e.g., users)
	TypeName          string        // TypeScript type name (PascalCase, e.g., Users)
	Columns           []*ColumnData // Column definitions
	Indexes           []*IndexData  // Index definitions
	Comment           string        // Table comment
	SchemaName        string        // Schema name
	NeedsSQLTag       bool          // Whether we need to import 'sql' from drizzle-orm
	IndexColumnFields []string      // Column field names used in indexes (for destructuring)
}

TableData represents a table in the template

func NewTableData

func NewTableData(table *models.Table, tm *TypeMapper) *TableData

NewTableData creates TableData from a models.Table

func (*TableData) AddColumn

func (td *TableData) AddColumn(col *ColumnData)

AddColumn adds a column to the table data

func (*TableData) AddIndex

func (td *TableData) AddIndex(idx *IndexData)

AddIndex adds an index to the table data

type TemplateData

type TemplateData struct {
	Imports []string
	Enums   []*EnumData
	Tables  []*TableData
}

TemplateData represents the data passed to the template for code generation

func NewTemplateData

func NewTemplateData() *TemplateData

NewTemplateData creates a new TemplateData

func (*TemplateData) AddEnum

func (td *TemplateData) AddEnum(enum *EnumData)

AddEnum adds an enum to the template data

func (*TemplateData) AddImport

func (td *TemplateData) AddImport(importLine string)

AddImport adds an import to the template data (deduplicates automatically)

func (*TemplateData) AddTable

func (td *TemplateData) AddTable(table *TableData)

AddTable adds a table to the template data

func (*TemplateData) FinalizeImports

func (td *TemplateData) FinalizeImports()

FinalizeImports sorts imports

type Templates

type Templates struct {
	// contains filtered or unexported fields
}

Templates holds the parsed templates

func NewTemplates

func NewTemplates() (*Templates, error)

NewTemplates creates and parses the templates

func (*Templates) GenerateCode

func (t *Templates) GenerateCode(data *TemplateData) (string, error)

GenerateCode executes the template with the given data

type TypeMapper

type TypeMapper struct{}

TypeMapper handles SQL to Drizzle type conversions

func NewTypeMapper

func NewTypeMapper() *TypeMapper

NewTypeMapper creates a new TypeMapper instance

func (*TypeMapper) BuildColumnChain

func (tm *TypeMapper) BuildColumnChain(col *models.Column, table *models.Table, isEnum bool) string

BuildColumnChain builds the complete column definition chain for Drizzle Example: integer('id').primaryKey().notNull()

func (*TypeMapper) BuildReferencesChain

func (tm *TypeMapper) BuildReferencesChain(fk *models.Constraint, referencedTable string) string

BuildReferencesChain builds the .references() chain for foreign key columns

func (*TypeMapper) DrizzleTypeToTypeScript

func (tm *TypeMapper) DrizzleTypeToTypeScript(drizzleType string, isEnum bool, enumName string) string

DrizzleTypeToTypeScript converts Drizzle column types to TypeScript types

func (*TypeMapper) SQLTypeToDrizzle

func (tm *TypeMapper) SQLTypeToDrizzle(sqlType string) string

SQLTypeToDrizzle converts SQL types to Drizzle column type functions Returns the Drizzle column constructor (e.g., "integer", "varchar", "text")

func (*TypeMapper) ToCamelCase

func (tm *TypeMapper) ToCamelCase(s string) string

ToCamelCase converts snake_case or PascalCase to camelCase

func (*TypeMapper) ToPascalCase

func (tm *TypeMapper) ToPascalCase(s string) string

ToPascalCase converts snake_case to PascalCase

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer implements the writers.Writer interface for Drizzle ORM

func NewWriter

func NewWriter(options *writers.WriterOptions) *Writer

NewWriter creates a new Drizzle writer with the given options

func (*Writer) WriteDatabase

func (w *Writer) WriteDatabase(db *models.Database) error

WriteDatabase writes a complete database as Drizzle schema

func (*Writer) WriteSchema

func (w *Writer) WriteSchema(schema *models.Schema) error

WriteSchema writes a schema as Drizzle schema

func (*Writer) WriteTable

func (w *Writer) WriteTable(table *models.Table) error

WriteTable writes a single table as a Drizzle schema

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL