dbtpl is a free, open source databases project written in Go and released under MIT. It has 3,895 GitHub stars, 337 forks and 70 open issues, and was last pushed 10 days ago. On this registry it ranks #167 of 203 tracked projects in Databases, with 5 head-to-head comparisons available.

What is dbtpl?

dbtpl is an MIT-licensed command-line tool that inspects a SQL database schema or a custom SQL query and generates idiomatic Go code from the results, built for Go developers who want typed models and query code without hand-writing the repetitive parts.

What it is

dbtpl is a code generator written in Go that connects to a database, reads its metadata through SQL introspection queries, and applies a set of base or customized Go templates against the discovered tables, columns, types, and relationships. It supports PostgreSQL, MySQL, Oracle, Microsoft SQL Server, and SQLite3, and it can emit types for tables, enums, stored procedures, and custom SQL queries depending on what each database exposes. It works in two modes: schema mode, which points at a live database and generates code from the whole schema, and query mode, which parses a single custom query, finds the related tables in the database, and generates code from that query so the result stays type-safe.

The concrete problem it solves is the manual authoring of Go structs, model types, and query plumbing that normally has to be kept in sync with a database schema by hand. Instead of writing the same mapping code every time a column changes, a developer runs dbtpl against the schema and regenerates. Beyond model code, it can also produce schema creation scripts, JSON and YAML definitions of a schema, and Graphviz diagrams, which makes it useful as a schema inspection tool even where code generation is not the immediate goal. The project is explicit that this is not a silver bullet: the generated code is production quality, but dbtpl is not intended to eliminate manual authoring of SQL and Go code entirely.

Key capabilities

  • Generates Go model code for tables, enums, stored procedures, and functions, with the database feature matrix confirming models, primary keys, foreign keys, indexes, stored procs, and functions across all five supported databases.
  • Runs in query mode, parsing a custom SQL query and locating related tables in the database so the generated code is type-safe.
  • Drives generation through Go templates, so the base templates can be customized rather than only accepting fixed output.
  • Emits schema creation scripts, JSON and YAML schema definitions, and Graphviz diagrams for schemas alongside the code it generates.
  • Handles ENUM types on PostgreSQL and MySQL, and custom types on PostgreSQL, per the documented feature support matrix.
  • Installs through multiple channels: release archives (.tar.bz2 and .zip), the Homebrew tap xo/xo, the Arch Linux AUR package, Scoop on Windows, and Go itself.
  • Currently generates Go only; other languages are described as possible but not currently planned.

Who uses it and how

  • Go teams that keep a relational schema as the source of truth and want model types regenerated from it rather than edited by hand.
  • Shops running more than one of the supported engines, since the same tool covers PostgreSQL, MySQL, Oracle, Microsoft SQL Server, and SQLite without a per-database generator.
  • Developers working against legacy or enterprise databases such as Oracle and Microsoft SQL Server, where stored procedures and functions are common and are covered by the feature matrix.
  • Projects that want schema documentation as a byproduct, using the JSON, YAML, and Graphviz output rather than only the generated Go.
  • Teams that need generated output adapted to house style, using the template layer instead of accepting the defaults.

Getting started

Install with brew install xo/xo/dbtpl on macOS or Linux, yay -S dbtpl on Arch Linux, Scoop on Windows, or via Go, or download a platform release archive and put the dbtpl binary on the path.

How it compares

No list of paid products that this project replaces is provided in the facts, and no comparable tools are named in the topic list or README excerpt. On the available evidence, dbtpl stands alone in this registry.

When to use it — and when not to

Schema mode requires a reachable database and the credentials to introspect it, so a self-hoster or build pipeline must supply that connection rather than generating from a static schema file. Teams not writing Go should look elsewhere, since only Go is supported and other languages are not currently planned. The project also carries 70 open issues and describes itself as explicitly not a silver bullet, so it fits teams willing to keep manual SQL and Go authoring alongside generation rather than expecting it to be removed.

project readme (upstream, from github) — read inline

dbtpl

dbtpl is a command-line tool to inspect and generate templated code based on a database schema or a custom database query.

In addition to being able to generate standardized "model" code for a database, dbtpl is also capable of creating schema creation scripts for a database, generating JSON/YAML definitions, and Graphviz diagrams for schemas.

Installing | Building | Using | Releases

Releases Discord Discussion

Supported languages

At the moment, dbtpl only supports Go. Support for other languages is possible, but not currently planned.

How it works

In schema mode, dbtpl connects to your database and generates code using Go templates. dbtpl works by using database metadata and SQL introspection queries to discover the types and relationships contained within a schema, and applying a standard set of base (or customized) Go templates against the discovered relationships.

Currently, dbtpl can generate types for tables, enums, stored procedures, and custom SQL queries for PostgreSQL, MySQL, Oracle, Microsoft SQL Server, and SQLite3 databases.

Note: While the code generated by dbtpl is production quality, it is not the goal, nor the intention for dbtpl to be a "silver bullet," nor to completely eliminate the manual authoring of SQL / Go code.

In query mode, dbtpl parses your query to generate code from Go templates. It finds related tables in your database to ensure type safety.

Database Feature Support

The following is a matrix of the feature support for each database:

PostgreSQL MySQL Oracle Microsoft SQL Server SQLite
Models :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
Primary Keys :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
Foreign Keys :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
Indexes :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
Stored Procs :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
Functions :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark: :white_check_mark:
ENUM types :white_check_mark: :white_check_mark:
Custom types :white_check_mark:

Installing

dbtpl can be installed via Release, via Homebrew, via AUR, via Scoop or via Go:

Installing via Release

  1. Download a release for your platform
  2. Extract the dbtpl or dbtpl.exe file from the .tar.bz2 or .zip file
  3. Move the extracted executable to somewhere on your $PATH (Linux/macOS) or %PATH% (Windows)

Installing via Homebrew (macOS and Linux)

Install dbtpl from the [xo/xo tap][xo-tap] in the usual way with the [brew command][homebrew]:

# install
$ brew install xo/xo/dbtpl

Installing via AUR (Arch Linux)

Install dbtpl from the [Arch Linux AUR][aur] in the usual way with the [yay command][yay]:

# install
$ yay -S dbtpl

Alternately, build and [install using makepkg][arch-makepkg]:

# clone package repo and make/install package
$ git clone https://aur.archlinux.org/dbtpl.git && cd dbtpl
$ makepkg -si
==> Making package: dbtpl 0.4.4-1 (Sat 11 Nov 2023 02:28:28 PM WIB)
==> Checking runtime dependencies...
==> Checking buildtime dependencies...
==> Retrieving sources...
...

Installing via Scoop (Windows)

Install dbtpl using Scoop:

# Optional: Needed to run a remote script the first time
> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

# install scoop if not already installed
> irm get.scoop.sh | iex

# install dbtpl with scoop
> scoop install dbtpl

Installing via Go

Install dbtpl in the usual Go fashion:

# install latest dbtpl version
$ go install github.com/xo/dbtpl@latest

Quickstart

The following is a quick overview of using dbtpl on the command-line:

# Make an output directory for generated code.
$ mkdir -p models

# Generate code from your Postgres schema. (Default output folder is models)
$ dbtpl schema postgres://user:pass@host/dbname

# Generate code from a Microsoft SQL schema using a custom template directory (see notes below)
$ mkdir -p mssqlmodels
$ dbtpl schema mssql://user:pass@host/dbname -o mssqlmodels --src custom/templates

# Generate code from a custom SQL query for Postgres
$ dbtpl query postgres://user:pass@host/dbname -M -B -2 -T AuthorResult << ENDSQL
SELECT
  a.name::varchar AS name,
  b.type::integer AS my_type
FROM authors a
  INNER JOIN authortypes b ON a.id = b.author_id
WHERE
  a.id = %%authorID int%%
LIMIT %%limit int%%
ENDSQL

# Build generated code - verify it compiles
$ go build ./models/
$ go build ./mssqlmodels/

Command Line Options

The following are dbtpl's command-line commands, arguments, and options:

$ dbtpl --help-long
usage: dbtpl []  [ ...]

Flags:
      --help     Show context-sensitive help (also try --help-long and
                 --help-man).
  -v, --verbose  enable verbose output
      --version  display version and exit

Commands:
  help [...]
    Show help.


  query [] 
    Generate code for a database custom query from a template.

    -s, --schema=            database schema name
    -t, --template=go              template type (createdb, dot, go, json, yaml;
                                   default: go)
    -f, --suffix=             file extension suffix for generated files
                                   (otherwise set by template type)
    -o, --out=models               out path (default: models)
    -a, --append                   enable append mode
    -S, --single=            enable single file output
    -D, --debug                    debug generated code (writes generated code
                                   to disk without post processing)
    -Q, --query=""                 custom database query (uses stdin if not
                                   provided)
    -T, --type=              type name
        --type-comment=""          type comment
    -F, --func=              func name
        --func-comment=""          func comment
    -M, --trim                     enable trimming whitespace
    -B, --strip                    enable stripping type casts
    -1, --one                      enable returning single (only one) result
    -l, --flat                     enable returning unstructured values
    -X, --exec                     enable exec (no introspection performed)
    -I, --interpolate              enable interpolation of embedded params
    -L, --delimiter=%%             delimiter used for embedded params (default:
                                   %%)
    -Z, --fields=           override field names for results
    -U, --allow-nulls              allow result fields with NULL values
    -d, --src=               template source directory
    -2, --go-not-first             disable package comment (ie, not first
                                   generated file)
        --go-int32=int             int32 type (default: int)
        --go-uint32=uint           uint32 type (default: uint)
        --go-pkg=            package name
        --go-tag="" ...            build tags
        --go-import="" ...         package imports
        --go-uuid=            uuid type package
        --go-custom=         package name for custom types
        --go-conflict=Val          name conflict su

readme truncated — read the full docs on github

Frequently asked questions

Is dbtpl free to use?

dbtpl is open source under the MIT licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does dbtpl do?

Command line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server

What is dbtpl written in?

dbtpl is primarily written in Go. Its source is publicly available at https://github.com/xo/dbtpl, and it has 3,895 GitHub stars.