dbschema

Crates.iodbschema
lib.rsdbschema
version0.1.4
created_at2025-10-20 08:59:33.891626+00
updated_at2025-10-22 14:49:16.185326+00
descriptionDefine database schema's as HCL files, and generate idempotent SQL migrations
homepagehttps://github.com/TheKnarf/dbschema
repositoryhttps://github.com/TheKnarf/dbschema
max_upload_size
id1891636
size688,380
TheKnarf (TheKnarf)

documentation

README

dbschema

Define database schema's as HCL files, and generate idempotent SQL migrations. Dbschema aims to support all PostgreSQL features (like extensions, functions, triggers, etc).

Designed to complement Prisma (or any tool) when you want to declaratively define features the ORM might not support out of the box (for example: Postgres triggers). Prisma supports custom migrations, so you can generate SQL with this tool and ship it alongside your Prisma migrations.

Docs

Read full docs

Install

cargo install dbschema

Usage

Example: a small HCL file that defines a provider, an enum, a table, a trigger function, and a trigger.

provider "postgres" {
  version = "16"
}

extension "pgcrypto" {}

enum "Status" {
  values = ["ACTIVE", "INACTIVE"]
}

table "users" {
  column "id"           { type = "uuid"      nullable = false default = "gen_random_uuid()" }
  column "email"        { type = "text"      nullable = false }
  column "status"       { type = "Status"    nullable = false }
  column "createdDate"  { type = "timestamp" nullable = false default = "now()" }
  column "updatedDate"  { type = "timestamp" nullable = true }

  primary_key { columns = ["id"] }
  index "users_email_key" { columns = ["email"] unique = true }
}

function "set_updated_at" {
  language = "plpgsql"
  returns  = "trigger"
  body = <<-SQL
  BEGIN
    NEW."updatedDate" := now();
    RETURN NEW;
  END;
  SQL
}

trigger "users_set_updated_at" {
  table = "users"
  timing = "BEFORE"
  events = ["UPDATE"]
  level  = "ROW"
  function = "set_updated_at"
}

If you omit the provider block dbschema will assume a default Postgres provider.

Create a migration (writes SQL to the given directory):

dbschema --input main.hcl create-migration --out-dir migrations --name init

Development

  • Ensure Rust toolchain is installed.
  • Build:
cargo build

Examples

  • Validate all bundled examples: just examples-validate
  • Create migrations for all examples: just examples-create-migration
  • Run tests for a single example against Docker Postgres: just example-test file=examples/table.hcl
  • Run tests for all examples against Docker Postgres: just examples-test

Logging

This project uses env_logger with info output enabled by default. Set the RUST_LOG environment variable to control verbosity:

RUST_LOG=debug dbschema --input examples/table.hcl validate

Use warn or error to reduce output, e.g. RUST_LOG=warn.

Commit count: 0

cargo fmt