dbml

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 4 Imported by: 0

README

DBML - Database Markup Language for Go

CI Status codecov Go Report Card CodeQL Go Reference License Go Version Release

A Go package for building and generating DBML (Database Markup Language) programmatically.

Schema as Code

Define database schemas with Go's type safety and generate DBML for visualisation tools like dbdiagram.io:

project := dbml.NewProject("ecommerce").
    WithDatabaseType("PostgreSQL")

project.AddTable(
    dbml.NewTable("orders").
        AddColumn(dbml.NewColumn("id", "bigint").WithPrimaryKey()).
        AddColumn(dbml.NewColumn("user_id", "bigint").
            WithRef(dbml.ManyToOne, "public", "users", "id")),
)

fmt.Println(project.Generate())

Schemas become testable, version-controlled, and composable.

Installation

go get github.com/zoobz-io/dbml

Requires Go 1.24 or higher.

Quick Start

package main

import (
    "fmt"
    "github.com/zoobz-io/dbml"
)

func main() {
    project := dbml.NewProject("my_database").
        WithDatabaseType("PostgreSQL")

    users := dbml.NewTable("users").
        AddColumn(
            dbml.NewColumn("id", "bigint").
                WithPrimaryKey().
                WithIncrement(),
        ).
        AddColumn(
            dbml.NewColumn("email", "varchar(255)").
                WithUnique(),
        ).
        AddColumn(
            dbml.NewColumn("created_at", "timestamp").
                WithDefault("now()"),
        )

    project.AddTable(users)

    if err := project.Validate(); err != nil {
        panic(err)
    }

    fmt.Println(project.Generate())
}

Examples

Tables with Relationships
users := dbml.NewTable("users").
    AddColumn(dbml.NewColumn("id", "bigint").WithPrimaryKey())

posts := dbml.NewTable("posts").
    AddColumn(dbml.NewColumn("id", "bigint").WithPrimaryKey()).
    AddColumn(
        dbml.NewColumn("user_id", "bigint").
            WithRef(dbml.ManyToOne, "public", "users", "id"),
    )

project.AddTable(users).AddTable(posts)
Standalone Relationships
ref := dbml.NewRef(dbml.ManyToOne).
    From("public", "posts", "user_id").
    To("public", "users", "id").
    WithOnDelete(dbml.Cascade).
    WithOnUpdate(dbml.Restrict)

project.AddRef(ref)
Indexes
// Simple index
table.AddIndex(dbml.NewIndex("email"))

// Composite index
table.AddIndex(
    dbml.NewIndex("user_id", "created_at").
        WithName("idx_user_created").
        WithUnique(),
)

// Expression-based index
table.AddIndex(
    dbml.NewExpressionIndex("date(created_at)").
        WithType("btree"),
)
Enums
status := dbml.NewEnum("order_status",
    "pending", "processing", "shipped", "delivered").
    WithNote("Order status values")

project.AddEnum(status)
Table Groups
group := dbml.NewTableGroup("User Management").
    AddTable("public", "users").
    AddTable("public", "roles").
    AddTable("public", "permissions")

project.AddTableGroup(group)

Capabilities

Feature Description
Type-safe schemas Catch errors at compile time, not when generating output
Fluent builder API Chainable methods make schema construction readable
Built-in validation Validate schemas before generation to catch structural issues
Serialisation Export schemas to JSON or YAML for storage and interchange
Minimal dependencies Only requires gopkg.in/yaml.v3

Why dbml?

  • Schema as code — Version control, test, and compose database schemas like any other Go code
  • Visualisation ready — Generate DBML for tools like dbdiagram.io directly from your definitions
  • Single source of truth — Define once, generate documentation and diagrams from the same source

API Reference

Core Types
  • Project - Top-level container for database schema
  • Table - Database table definition
  • Column - Table column with type and constraints
  • Index - Single, composite, or expression-based indexes
  • Ref - Relationships between tables
  • Enum - Enumeration types
  • TableGroup - Logical grouping of tables
Relationship Types
const (
    OneToMany  RelType = "<"   // One-to-many
    ManyToOne  RelType = ">"   // Many-to-one
    OneToOne   RelType = "-"   // One-to-one
    ManyToMany RelType = "<>"  // Many-to-many
)
Referential Actions
const (
    Cascade    RefAction = "cascade"
    Restrict   RefAction = "restrict"
    SetNull    RefAction = "set null"
    SetDefault RefAction = "set default"
    NoAction   RefAction = "no action"
)
Project Methods
  • NewProject(name string) *Project
  • WithDatabaseType(dbType string) *Project
  • WithNote(note string) *Project
  • AddTable(table *Table) *Project
  • AddEnum(enum *Enum) *Project
  • AddRef(ref *Ref) *Project
  • AddTableGroup(group *TableGroup) *Project
  • Validate() error
  • Generate() string
Table Methods
  • NewTable(name string) *Table
  • WithSchema(schema string) *Table
  • WithAlias(alias string) *Table
  • WithNote(note string) *Table
  • WithHeaderColor(color string) *Table
  • AddColumn(column *Column) *Table
  • AddIndex(index *Index) *Table
Column Methods
  • NewColumn(name, colType string) *Column
  • WithPrimaryKey() *Column
  • WithNull() *Column
  • WithUnique() *Column
  • WithIncrement() *Column
  • WithDefault(value string) *Column
  • WithCheck(constraint string) *Column
  • WithNote(note string) *Column
  • WithRef(relType RelType, schema, table, column string) *Column
Index Methods
  • NewIndex(columns ...string) *Index
  • NewExpressionIndex(expressions ...string) *Index
  • WithType(indexType string) *Index
  • WithName(name string) *Index
  • WithUnique() *Index
  • WithPrimaryKey() *Index
  • WithNote(note string) *Index
Ref Methods
  • NewRef(relType RelType) *Ref
  • WithName(name string) *Ref
  • From(schema, table string, columns ...string) *Ref
  • To(schema, table string, columns ...string) *Ref
  • WithOnDelete(action RefAction) *Ref
  • WithOnUpdate(action RefAction) *Ref
  • WithColor(color string) *Ref

Contributing

Contributions are welcome. See CONTRIBUTING.md for development setup and guidelines.

License

MIT

Documentation

Overview

Package dbml provides types and utilities for building and generating Database Markup Language (DBML) schemas programmatically.

DBML is a domain-specific language for defining database structures, commonly used with tools like dbdiagram.io for visualization.

Basic Usage

Create a project, add tables with columns, and generate DBML output:

project := dbml.NewProject("mydb").
	WithDatabaseType("PostgreSQL")

users := dbml.NewTable("users").
	AddColumn(dbml.NewColumn("id", "bigint").WithPrimaryKey()).
	AddColumn(dbml.NewColumn("email", "varchar(255)").WithUnique())

project.AddTable(users)
fmt.Println(project.Generate())

Relationships

Define relationships between tables using inline refs or standalone refs:

// Inline ref on a column
dbml.NewColumn("user_id", "bigint").
	WithRef(dbml.ManyToOne, "public", "users", "id")

// Standalone ref with actions
dbml.NewRef(dbml.ManyToOne).
	From("public", "posts", "user_id").
	To("public", "users", "id").
	WithOnDelete(dbml.Cascade)

Package dbml provides a fluent API for building DBML schemas programmatically.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Column

type Column struct {
	Settings  *ColumnSettings
	Note      *string
	InlineRef *InlineRef
	Name      string
	Type      string
}

Column represents a table column.

func NewColumn

func NewColumn(name, colType string) *Column

NewColumn creates a new column.

func (*Column) Generate

func (c *Column) Generate() string

Generate generates the DBML syntax for a Column.

func (*Column) Validate

func (c *Column) Validate() error

Validate validates a Column.

func (*Column) WithCheck

func (c *Column) WithCheck(constraint string) *Column

WithCheck adds a check constraint to the column.

func (*Column) WithDefault

func (c *Column) WithDefault(value string) *Column

WithDefault sets a default value for the column.

func (*Column) WithIncrement

func (c *Column) WithIncrement() *Column

WithIncrement marks the column as auto-incrementing.

func (*Column) WithNote

func (c *Column) WithNote(note string) *Column

WithNote adds a note to the column.

func (*Column) WithNull

func (c *Column) WithNull() *Column

WithNull marks the column as nullable.

func (*Column) WithPrimaryKey

func (c *Column) WithPrimaryKey() *Column

WithPrimaryKey marks the column as a primary key.

func (*Column) WithRef

func (c *Column) WithRef(relType RelType, schema, table, column string) *Column

WithRef adds an inline relationship to the column.

func (*Column) WithUnique

func (c *Column) WithUnique() *Column

WithUnique marks the column as unique.

type ColumnSettings

type ColumnSettings struct {
	Default    *string
	Check      *string
	PrimaryKey bool
	Null       bool
	Unique     bool
	Increment  bool
}

ColumnSettings represents all column-level settings.

type Enum

type Enum struct {
	Note   *string
	Schema string
	Name   string
	Values []string
}

Enum represents an enumeration type.

func NewEnum

func NewEnum(name string, values ...string) *Enum

NewEnum creates a new enum.

func (*Enum) Generate

func (e *Enum) Generate() string

Generate generates the DBML syntax for an Enum.

func (*Enum) Validate

func (e *Enum) Validate() error

Validate validates an Enum.

func (*Enum) WithNote

func (e *Enum) WithNote(note string) *Enum

WithNote adds a note to the enum.

func (*Enum) WithSchema

func (e *Enum) WithSchema(schema string) *Enum

WithSchema sets the schema for the enum.

type Index

type Index struct {
	Type       *string
	Name       *string
	Note       *string
	Columns    []IndexColumn
	Unique     bool
	PrimaryKey bool
}

Index represents a table index.

func NewExpressionIndex

func NewExpressionIndex(expressions ...string) *Index

NewExpressionIndex creates a new expression-based index.

func NewIndex

func NewIndex(columns ...string) *Index

NewIndex creates a new index.

func (*Index) Generate

func (i *Index) Generate() string

Generate generates the DBML syntax for an Index.

func (*Index) Validate

func (i *Index) Validate() error

Validate validates an Index.

func (*Index) WithName

func (i *Index) WithName(name string) *Index

WithName sets the index name.

func (*Index) WithNote

func (i *Index) WithNote(note string) *Index

WithNote adds a note to the index.

func (*Index) WithPrimaryKey

func (i *Index) WithPrimaryKey() *Index

WithPrimaryKey marks the index as a primary key.

func (*Index) WithType

func (i *Index) WithType(indexType string) *Index

WithType sets the index type.

func (*Index) WithUnique

func (i *Index) WithUnique() *Index

WithUnique marks the index as unique.

type IndexColumn

type IndexColumn struct {
	Name       *string // for regular columns
	Expression *string // for expression-based indexes like `id*2`
}

IndexColumn represents a column or expression in an index.

type InlineRef

type InlineRef struct {
	Type   RelType
	Schema string
	Table  string
	Column string
}

InlineRef represents an inline relationship definition.

func (*InlineRef) Validate

func (r *InlineRef) Validate() error

Validate validates an InlineRef.

type Project

type Project struct {
	Name         string
	DatabaseType *string // "PostgreSQL", "MySQL", etc.
	Note         *string
	Tables       map[string]*Table
	Enums        map[string]*Enum
	TableGroups  []*TableGroup
	Refs         []*Ref
}

Project represents the top-level DBML project.

func NewProject

func NewProject(name string) *Project

NewProject creates a new DBML project.

func (*Project) AddEnum

func (p *Project) AddEnum(enum *Enum) *Project

AddEnum adds an enum to the project.

func (*Project) AddRef

func (p *Project) AddRef(ref *Ref) *Project

AddRef adds a relationship to the project.

func (*Project) AddTable

func (p *Project) AddTable(table *Table) *Project

AddTable adds a table to the project.

func (*Project) AddTableGroup

func (p *Project) AddTableGroup(group *TableGroup) *Project

AddTableGroup adds a table group to the project.

func (*Project) FromJSON

func (p *Project) FromJSON(data []byte) error

FromJSON populates a Project from JSON bytes.

func (*Project) FromYAML

func (p *Project) FromYAML(data []byte) error

FromYAML populates a Project from YAML bytes.

func (*Project) Generate

func (p *Project) Generate() string

Generate generates the DBML syntax from a Project.

func (*Project) ToJSON

func (p *Project) ToJSON() ([]byte, error)

ToJSON converts a Project to JSON bytes.

func (*Project) ToYAML

func (p *Project) ToYAML() ([]byte, error)

ToYAML converts a Project to YAML bytes.

func (*Project) Validate

func (p *Project) Validate() error

Validate validates a Project.

func (*Project) WithDatabaseType

func (p *Project) WithDatabaseType(dbType string) *Project

WithDatabaseType sets the database type for the project.

func (*Project) WithNote

func (p *Project) WithNote(note string) *Project

WithNote adds a note to the project.

type Ref

type Ref struct {
	Name     *string
	Left     *RefEndpoint
	Right    *RefEndpoint
	OnDelete *RefAction
	OnUpdate *RefAction
	Color    *string
	Type     RelType
}

Ref represents a relationship between tables.

func NewRef

func NewRef(relType RelType) *Ref

NewRef creates a new relationship.

func (*Ref) From

func (r *Ref) From(schema, table string, columns ...string) *Ref

From sets the left side of the relationship.

func (*Ref) Generate

func (r *Ref) Generate() string

Generate generates the DBML syntax for a Ref.

func (*Ref) To

func (r *Ref) To(schema, table string, columns ...string) *Ref

To sets the right side of the relationship.

func (*Ref) Validate

func (r *Ref) Validate() error

Validate validates a Ref.

func (*Ref) WithColor

func (r *Ref) WithColor(color string) *Ref

WithColor sets the relationship color.

func (*Ref) WithName

func (r *Ref) WithName(name string) *Ref

WithName sets the relationship name.

func (*Ref) WithOnDelete

func (r *Ref) WithOnDelete(action RefAction) *Ref

WithOnDelete sets the ON DELETE action.

func (*Ref) WithOnUpdate

func (r *Ref) WithOnUpdate(action RefAction) *Ref

WithOnUpdate sets the ON UPDATE action.

type RefAction

type RefAction string

RefAction represents referential actions.

const (
	Cascade    RefAction = "cascade"
	Restrict   RefAction = "restrict"
	SetNull    RefAction = "set null"
	SetDefault RefAction = "set default"
	NoAction   RefAction = "no action"
)

Referential action constants.

type RefEndpoint

type RefEndpoint struct {
	Schema  string
	Table   string
	Columns []string // supports composite foreign keys
}

RefEndpoint represents one side of a relationship.

func (*RefEndpoint) Validate

func (e *RefEndpoint) Validate() error

Validate validates a RefEndpoint.

type RelType

type RelType string

RelType represents relationship cardinality.

const (
	OneToMany  RelType = "<"
	ManyToOne  RelType = ">"
	OneToOne   RelType = "-"
	ManyToMany RelType = "<>"
)

Relationship cardinality constants.

type Table

type Table struct {
	Alias    *string
	Note     *string
	Settings map[string]string
	Schema   string
	Name     string
	Columns  []*Column
	Indexes  []*Index
}

Table represents a database table.

func NewTable

func NewTable(name string) *Table

NewTable creates a new table.

func (*Table) AddColumn

func (t *Table) AddColumn(column *Column) *Table

AddColumn adds a column to the table.

func (*Table) AddIndex

func (t *Table) AddIndex(index *Index) *Table

AddIndex adds an index to the table.

func (*Table) Generate

func (t *Table) Generate() string

Generate generates the DBML syntax for a Table.

func (*Table) Validate

func (t *Table) Validate() error

Validate validates a Table.

func (*Table) WithAlias

func (t *Table) WithAlias(alias string) *Table

WithAlias sets an alias for the table.

func (*Table) WithHeaderColor

func (t *Table) WithHeaderColor(color string) *Table

WithHeaderColor sets the header color for the table.

func (*Table) WithNote

func (t *Table) WithNote(note string) *Table

WithNote adds a note to the table.

func (*Table) WithSchema

func (t *Table) WithSchema(schema string) *Table

WithSchema sets the schema for the table.

func (*Table) WithSetting

func (t *Table) WithSetting(key, value string) *Table

WithSetting adds a setting to the table.

type TableGroup

type TableGroup struct {
	Name   string
	Tables []TableRef // references to tables by schema.name
}

TableGroup represents a logical grouping of tables.

func NewTableGroup

func NewTableGroup(name string) *TableGroup

NewTableGroup creates a new table group.

func (*TableGroup) AddTable

func (tg *TableGroup) AddTable(schema, name string) *TableGroup

AddTable adds a table reference to the group.

func (*TableGroup) Generate

func (tg *TableGroup) Generate() string

Generate generates the DBML syntax for a TableGroup.

func (*TableGroup) Validate

func (g *TableGroup) Validate() error

Validate validates a TableGroup.

type TableRef

type TableRef struct {
	Schema string
	Name   string
}

TableRef references a table by schema and name.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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