Awesome Go

dbmate

CategoryDatabase
SubcategoryDatabase Schema Migration
Stars7,575

A lightweight, framework-agnostic database migration tool

About dbmate

This large README is shown as a plain-text preview. Read the full README at the source

# Dbmate

[![Release](https://img.shields.io/github/release/amacneil/dbmate.svg)](https://github.com/amacneil/dbmate/releases)
[![Go Report](https://goreportcard.com/badge/github.com/amacneil/dbmate)](https://goreportcard.com/report/github.com/amacneil/dbmate)
[![Reference](https://img.shields.io/badge/go.dev-reference-blue?logo=go&logoColor=white)](https://pkg.go.dev/github.com/amacneil/dbmate/v2/pkg/dbmate)

Dbmate is a database migration tool that will keep your database schema in sync across multiple developers and your production servers.

It is a standalone command line tool that can be used with Go, Node.js, Python, Ruby, PHP, Rust, C++, or any other language or framework you are using to write database-backed applications. This is especially helpful if you are writing multiple services in different languages, and want to maintain some sanity with consistent development tools.

For a comparison between dbmate and other popular database schema migration tools, please see [Alternatives](#alternatives).

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Commands](#commands)
  - [Command Line Options](#command-line-options)
- [Usage](#usage)
  - [Environment Variables](#environment-variables)
  - [Connecting to the Database](#connecting-to-the-database)
    - [PostgreSQL](#postgresql)
    - [MySQL](#mysql)
    - [MariaDB](#mariadb)
    - [SQLite](#sqlite)
    - [ClickHouse](#clickhouse)
    - [BigQuery](#bigquery)
    - [Spanner](#spanner)
  - [Creating Migrations](#creating-migrations)
  - [Running Migrations](#running-migrations)
  - [Rolling Back Migrations](#rolling-back-migrations)
  - [Checking Migration Status](#checking-migration-status)
  - [Migration Options](#migration-options)
  - [Waiting For The Database](#waiting-for-the-database)
  - [Exporting Schema File](#exporting-schema-file)
- [Library](#library)
  - [Use dbmate as a library](#use-dbmate-as-a-library)
  - [Embedding migrations](#embedding-migrations)
- [Concepts](#concepts)
  - [Migration files](#migration-files)
  - [Schema file](#schema-file)
  - [Schema migrations table](#schema-migrations-table)
- [Alternatives](#alternatives)
- [Contributing](#contributing)

## Features

- Supports MySQL, MariaDB, PostgreSQL, SQLite, and ClickHouse
- Uses plain SQL for writing schema migrations
- Migrations are timestamp-versioned, to avoid version number conflicts with multiple developers
- Migrations are run atomically inside a transaction
- Supports creating and dropping databases (handy in development/test)
- Supports saving a `schema.sql` file to easily diff schema changes in git
- Database connection URL is defined using an environment variable (`DATABASE_URL` by default), or specified on the command line
- Built-in support for reading environment variables from your `.env` file
- Easy to distribute, single self-contained binary
- Doesn't try to upsell you on a SaaS service

## Installation

**NPM**

Install using [NPM](https://www.npmjs.com/):

```sh
npm install --save-dev dbmate
npx dbmate --help
```

**macOS**

Install using [Homebrew](https://brew.sh/):

```sh
brew install dbmate
dbmate --help
```

**Linux**

Install the binary directly:

```sh
sudo curl -fsSL -o /usr/local/bin/dbmate https://github.com/amacneil/dbmate/releases/latest/download/dbmate-linux-amd64
sudo chmod +x /usr/local/bin/dbmate
/usr/local/bin/dbmate --help
```

**Windows**

Install using [Scoop](https://scoop.sh)

```pwsh
scoop install dbmate
dbmate --help
```

**Docker**

Docker images are published to GitHub Container Registry ([`ghcr.io/amacneil/dbmate`](https://ghcr.io/amacneil/dbmate)).

Remember to set `--network=host` or see [this comment](https://github.com/amacneil/dbmate/issues/128#issuecomment-615924611) for more tips on using dbmate with docker networking:

```sh
docker run --rm -it --network=host ghcr.io/amacneil/dbmate --help
```

If you wish to create or apply migrations, you will need to use Docker's [bind mount](https://docs.docker.com/storage/bind-mounts/) feature to make your local working directory (`pwd`) available inside the dbmate container:

```sh
docker run --rm -it --network=host -v "$(pwd)/db:/db" ghcr.io/amacneil/dbmate new create_users_table
```

## Commands

```sh
dbmate --help         # print usage help
dbmate new            # generate a new migration file
dbmate up             # create the database (if it does not already exist) and run any pending migrations
dbmate create         # create the database
dbmate drop           # drop the database
dbmate migrate        # run any pending migrations
dbmate rollback       # roll back the most recent migration
dbmate down           # alias for rollback
dbmate status         # show the status of all migrations (supports --exit-code, --quiet and --strict)
dbmate dump           # write the database schema.sql file
dbmate dump -- [...]  # optionally pass additional arguments directly to mysqldump or pg_dump
dbmate load           # load schema.sql file to the database
dbmate wait           # wait for the database server to become available
```

### Command Line Options

The following options are available with all commands. You must use command line arguments in the order `dbmate [global options] command [command options]`. Most options can also be configured via environment variables (and loaded from your `.env` file, which is helpful to share configuration between team members).

- `--url, -u "protocol://host:port/dbname"` - specify the database url directly. _(env: `DATABASE_URL`)_
- `--driver "driver_name"` - specify the driver to use (if empty, the driver is derived from database URL scheme). _(env: `DBMATE_DRIVER`)_
- `--env, -e "DATABASE_URL"` - specify an environment variable to read the database connection URL from.
- `--env-file ".env"` - specify an alternate environment variables file(s) to load.
- `--migrations-dir, -d "./db/migrations"` - where to keep the migration files. _(env: `DBMATE_MIGRATIONS_DIR`)_
- `--migrations-table "schema_migrations"` - database table to record migrations in. _(env: `DBMATE_MIGRATIONS_TABLE`)_
- `--schema-file, -s "./db/schema.sql"` - a path to keep the schema.sql file. _(env: `DBMATE_SCHEMA_FILE`)_
- `--no-dump-schema` - don't auto-update the schema.sql file on migrate/rollback _(env: `DBMATE_NO_DUMP_SCHEMA`)_
- `--strict` - fail if migrations would be applied out of order, or (on `rollback`) if the most recently applied migration file is missing, or (on `status`) if any applied migration file is missing _(env: `DBMATE_STRICT`)_
- `--wait` - wait for the db to become available before executing the subsequent command _(env: `DBMATE_WAIT`)_
- `--wait-timeout 60s` - timeout for --wait flag _(env: `DBMATE_WAIT_TIMEOUT`)_
- `--wait-interval 1s` - time to wait between connection attempts for --wait flag _(env: `DBMATE_WAIT_INTERVAL`)_
- `--migration-lock` - hold a database lock while migrating so that concurrent dbmate instances wait for each other (PostgreSQL only) _(env: `DBMATE_MIGRATION_LOCK`)_
- `--migration-lock-timeout 5m` - maximum time to wait for the migration lock, 0 to wait indefinitely _(env: `DBMATE_MIGRATION_LOCK_TIMEOUT`)_
- `--migration-application-name` - record the migration version in application_name during execution (PostgreSQL only) _(env: `DBMATE_MIGRATION_APPLICATION_NAME`)_

## Usage

### Environment Variables

Most dbmate settings can be configured with environment variables in addition to command line flags. This is useful for twelve-factor style deployments and for sharing local configuration via a `.env` file.

#### Which settings use which environment variables

| Setting | Environment variable | Notes |
| --- | --- | --- |
| Database URL | `DATABASE_URL` (default) | Overridden by `--url` / `-u`. Use `--env` / `-e` to read the URL from a different variable (for example `TEST_DATABASE_URL`). |
| Driver | `DBMATE_DRIVER` | Used when `--driver` is not set. |
| Migrations directory | `DBMATE_MIGRATIONS_DIR` | Corresponds to `--migrations-dir` / `-d`. |
| Migrations table | `DBMATE_MIGRATIONS_TABLE` | Corresponds to `--migrations-table`. |
| Schema file | `DBMATE_SCHEMA_FILE` | Corresponds to `--schema-file` / `-s`. |
| Disable schema dump | `DBMATE_NO_DUMP_SCHEMA` | Corresponds to `--no-dump-schema`. |
| Wait for database | `DBMATE_WAIT` | Corresponds to `--wait`. |
| Wait timeout | `DBMATE_WAIT_TIMEOUT` | Corresponds to `--wait-timeout`. |
| Wait interval | `DBMATE_WAIT_INTERVAL` | Corresponds to `--wait-interval`. |
| Migration lock | `DBMATE_MIGRATION_LOCK` | Corresponds to `--migration-lock`. |
| Migration lock timeout | `DBMATE_MIGRATION_LOCK_TIMEOUT` | Corresponds to `--migration-lock-timeout`. |
| Migration application name | `DBMATE_MIGRATION_APPLICATION_NAME` | Corresponds to `--migration-application-name`. |
| Strict migrations | `DBMATE_STRICT` | Corresponds to `--strict` on `up` / `migrate` / `rollback` / `status`. |
| Verbose SQL output | `DBMATE_VERBOSE` | Corresponds to `--verbose` / `-v` on `up` / `migrate` / `rollback`. |

`--env` and `--env-file` are CLI-only options (they are not themselves read from environment variables).

#### Loading `.env` files

By default, dbmate loads environment variables from a `.env` file in the current working directory (if present). Missing files are ignored; an invalid dotenv file causes dbmate to exit with an error.

To load one or more alternate dotenv files, pass `--env-file` (repeatable). When any `--env-file` is given, only the listed files are loaded - the default `.env` is not included unless you specify it:

```sh
dbmate --env-file .env.development up
dbmate --env-file .env --env-file .env.local up
```

Files are loaded in the order given.

#### Variable precedence

From highest to lowest priority:

1. **Command line flags** (for example `--url`, `--driver`, `--migrations-dir`)
2. **Environment variables already set in the calling process**
3. **Values from dotenv files** (`.env` or files passed with `--env-file`)
4. **Built-in defaults**

Dotenv files never overwrite variables that are already set in the process environment. For the database URL specifically, `--url` / `-u` takes precedence over the environment variable named by `--env` / `-e` (default `DATABASE_URL`).

### Connecting to the Database

Dbmate locates your database using the `DATABASE_URL` environment variable by default. If you are writing a [twelve-factor app](http://12factor.net/), you should be storing all connection strings in environment variables.

To make this easy in development, dbmate looks for a `.env` file in the current directory, and treats any variables listed there as if they were specified in the current environment (existing environment variables take preference, however). See [Environment Variables](#environment-variables) for details on `--env-file` and precedence.

If you do not already have a `.env` file, create one and add your database connection URL:

```sh
$ cat .env
DATABASE_URL="postgres://[email protected]:5432/myapp_development?sslmode=disable"
```

`DATABASE_URL` should be specified in the following format:

```
protocol://username:password@host:port/database_name?options
```

- `protocol` must be one of `mysql`, `postgres`, `postgresql`, `sqlite`, `sqlite3`, `clickhouse`
- `username` and `password` must be URL encoded (you will get an error if you use special characters)
- `host` can be either a hostname or IP address
- `options` are driver-specific (refer to the underlying Go SQL drivers if you wish to use these)

Dbmate can also load the connection URL from a different environment variable. For example, before running your test suite, you may wish to drop and recreate the test database. One easy way to do this is to store your test database connection URL in the `TEST_DATABASE_URL` environment variable:

```sh
$ cat .env
DATABASE_URL="postgres://[email protected]:5432/myapp_dev?sslmode=disable"
TEST_DATABASE_URL="postgres://[email protected]:5432/myapp_test?sslmode=disable"
```

You can then specify this environment variable in your test script (Makefile or similar):

```sh
$ dbmate -e TEST_DATABASE_URL drop
Dropping: myapp_test
$ dbmate -e TEST_DATABASE_URL --no-dump-schema up
Creating: myapp_test
Applying: 20151127184807_create_users_table.sql
Applied: 20151127184807_create_users_table.sql in 123µs
```

Alternatively, you can specify the url directly on the command line:

```sh
$ dbmate -u "postgres://[email protected]:5432/myapp_test?sslmode=disable" up
```

The only advantage of using `dbmate -e TEST_DATABASE_URL` over `dbmate -u $TEST_DATABASE_URL` is that the former takes advantage of dbmate's automatic `.env` file loading.

#### PostgreSQL

When connecting to Postgres, you may need to add the `sslmode=disable` option to your connection string, as dbmate by default requires a TLS connection (some other frameworks/languages allow unencrypted connections by default).

```sh
DATABASE_URL="postgres://username:[email protected]:5432/database_name?sslmode=disable"
```

A `socket` or `host` parameter can be specified to connect through a unix socket (note: specify the directory only):

```sh
DATABASE_URL="postgres://username:password@/database_name?socket=/var/run/postgresql"
```

For passwordless authentication such as PostgreSQL [peer auth](https://www.postgresql.org/docs/current/auth-pg-hba-conf.html), the password can be omitted (note the `@` is still required):

```sh
DATABASE_URL="postgres://username@/database_name?socket=/var/run/postgresql"
```

If the username is also omitted, it defaults to the `PGUSER` environment variable if set, otherwise the OS username (via `lib/pq`, matching `libpq` behavior):

```sh
DATABASE_URL="postgres:///database_name?socket=/var/run/postgresql"
```

A `search_path` parameter can be used to specify the [current schema](https://www.postgresql.org/docs/13/ddl-schemas.html#DDL-SCHEMAS-PATH) while applying migrations, as well as for dbmate's `schema_migrations` table.
If the schema does not exist, it will be created automatically. If multiple comma-separated schemas are passed, the first will be used for the `schema_migrations` table.

```sh
DATABASE_URL="postgres://username:[email protected]:5432/database_name?search_path=myschema"
```

```sh
DATABASE_URL="postgres://username:[email protected]:5432/database_name?search_path=myschema,public"
```

#### MySQL

```sh
DATABASE_URL="mysql://username:[email protected]:3306/database_name"
```

A `socket` parameter can be specified to connect through a unix socket:

```sh
DATABASE_URL="mysql://username:password@/database_name?socket=/var/run/mysqld/mysqld.sock"
```

#### MariaDB

MariaDB is supported using the same `mysql://` connection URLs as MySQL. The Docker image includes `mariadb-client` for schema dumps; `mariadb-dump` is used when available.

#### SQLite

SQLite databases are stored on the filesystem, so you do not need to specify a host. By default, files are relative to the current directory. For example, the following will create a database at `./db/database.sqlite3`:

```sh
DATABASE_URL="sqlite:db/database.sqlite3"
```

To specify an absolute path, add a forward slash to the path. The following will create a database at `/tmp/database.sqlite3`:

```sh
DATABASE_URL="sqlite:/tmp/database.sqlite3"
```

Note that for some common [settings](https://sqlite.org/pragma.html) like `journal_mode` to improve performance, transactions need to be disabled for that migration file, e.g.

```sql
-- migrate:up transaction:false
PRAGMA journal_mode = WAL;
```

Otherwise the migration will fail with "Error: cannot change into wal mode from within a transaction".

#### ClickHouse

Dbmate supports connecting to ClickHouse using native TCP (default) or HTTP/HTTPS.

##### Native (TCP)

By default, the `clickhouse://` scheme uses the native protocol on port `9000`.

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name"
```

##### HTTP / HTTPS

You can use `clickhouse+http://` (default port 8123) or `clickhouse+https://` (default port 8443).

```sh
# HTTP (Defaults to port 8123)
DATABASE_URL="clickhouse+http://username:[email protected]:8123/database_name"

# HTTPS (Defaults to port 8443)
DATABASE_URL="clickhouse+https://username:[email protected]:8443/database_name"
```

##### Using the --driver flag

You can use the ClickHouse driver with a standard http/https/tcp URL by providing the --driver flag

```sh
# Connect via HTTP using generic URL syntax
dbmate --driver clickhouse --url "http://username:[email protected]:8123/database_name" status

dbmate --driver clickhouse --url "https://username:[email protected]:8443/database_name" status

# Better to rely on the standard clickhouse:// scheme, but this is supported
dbmate --driver clickhouse --url "tcp://username:[email protected]:9000/database_name" status
```

To work with ClickHouse cluster, there are connection query parameters that can be supplied:

- `on_cluster` - Indication to use cluster statements and replicated migration table. (default: `false`) If this parameter is not supplied, other cluster related query parameters are ignored (except `replicated`). Mutually exclusive with `replicated`.

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?on_cluster"

DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?on_cluster=true"
```

- `cluster_macro` (Optional) - Macro value to be used for ON CLUSTER statements and for the replicated migration table engine zookeeper path. (default: `{cluster}`)

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?on_cluster&cluster_macro={my_cluster}"
```

- `replica_macro` (Optional) - Macro value to be used for the replica name in the replicated migration table engine. (default: `{replica}`)

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?on_cluster&replica_macro={my_replica}"
```

- `zoo_path` (Optional) - The path to the table migration in ClickHouse/ZooKeeper. With `on_cluster`, defaults to `/clickhouse/tables/<cluster_macro>/{table}`. With `replicated`, if omitted the engine uses the server default path (`ReplicatedReplacingMergeTree(ts)`), which follows `default_replica_path` and server macros such as `{shard}` / `{replica}`.

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?on_cluster&zoo_path=/zk/path/tables"
```

- `replicated` - Use `ReplicatedReplacingMergeTree` for the migrations table without `ON CLUSTER`. (default: `false`) Mutually exclusive with `on_cluster`.

  Requires a database that already uses the [Replicated database engine](https://clickhouse.com/docs/reference/engines/database-engines/replicated) (`CREATE DATABASE ... ENGINE = Replicated(...)`) or the Shared database engine on ClickHouse Cloud. `dbmate create` cannot create that database (it issues a bare `CREATE DATABASE`, which yields Atomic by default); create the database yourself first, then point dbmate at it with `replicated`.

```sh
DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?replicated"

DATABASE_URL="clickhouse://username:[email protected]:9000/database_name?replicated&zoo_path=/clickhouse/tables/{uuid}/{shard}"
```

[See other supported connection options](https://github.com/ClickHouse/clickhouse-go#dsn).

#### BigQuery

Follow the following format for `DATABASE_URL` when connecting to actual BigQuery in GCP:

```
bigquery://projectid/location/dataset
```

`projectid` (mandatory) - Project ID

`dataset` (mandatory) - Dataset name within the Project

`location` (optional) - Where Dataset is created

_NOTE: Follow [this doc](https://cloud.google.com/docs/authentication/provide-credentials-adc) on how to set `GOOGLE_APPLICATION_CREDENTIALS` environment variable for proper Authentication_

Follow the following format if trying to connect to a custom endpoint e.g. [BigQuery Emulator](https://github.com/goccy/bigquery-emulator)

```
bigquery://host:port/projectid/location/dataset?disable_auth=true
```

Frequently Asked Questions

What is dbmate?

dbmate is a Database library for the Go programming language. A lightweight, framework-agnostic database migration tool

How many GitHub stars does dbmate have?

dbmate has 7,575 GitHub stars in the directory's latest synchronization.

How do I install dbmate?

Install dbmate with the Go module system using `go get amacneil/dbmate`. Check the repository for the current installation instructions.

What category does dbmate belong to?

dbmate is listed under Database, specifically Database Schema Migration.

← Back to Database Schema Migration