dbmate

dbmate

数据库Schema同步工具 支持多种数据库和开发语言

dbmate是一个跨平台的数据库迁移工具,用于同步多个开发者和服务器间的数据库schema。支持MySQL、PostgreSQL、SQLite和ClickHouse等主流数据库,采用纯SQL编写迁移脚本。它提供数据库创建、删除等功能,通过环境变量配置连接,支持.env文件。dbmate适用于Go、Node.js、Python、Ruby等多种语言的数据库应用开发,是一个通用的数据库管理工具。

Dbmate数据库迁移SQL版本控制命令行工具Github开源项目

Dbmate

Release Go Report Reference

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.

Table of Contents

Features

  • Supports MySQL, 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:

$ npm install --save-dev dbmate $ npx dbmate --help

macOS

Install using Homebrew:

$ brew install dbmate

Linux

Install the binary directly:

$ 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

Windows

Install using Scoop

$ scoop install dbmate

Docker

Docker images are published to GitHub Container Registry (ghcr.io/amacneil/dbmate).

Remember to set --network=host or see this comment for more tips on using dbmate with docker networking):

$ 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 feature to make your local working directory (pwd) available inside the dbmate container:

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

Commands

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 and --quiet) dbmate dump # write the database schema.sql file 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)
  • --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 (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)

Usage

Connecting to the Database

Dbmate locates your database using the DATABASE_URL environment variable by default. If you are writing a twelve-factor app, 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).

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

$ cat .env DATABASE_URL="postgres://postgres@127.0.0.1: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 charactors)
  • 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:

$ cat .env DATABASE_URL="postgres://postgres@127.0.0.1:5432/myapp_dev?sslmode=disable" TEST_DATABASE_URL="postgres://postgres@127.0.0.1:5432/myapp_test?sslmode=disable"

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

$ 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:

$ dbmate -u "postgres://postgres@127.0.0.1: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).

DATABASE_URL="postgres://username:password@127.0.0.1:5432/database_name?sslmode=disable"

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

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

A search_path parameter can be used to specify the current schema 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.

DATABASE_URL="postgres://username:password@127.0.0.1:5432/database_name?search_path=myschema"
DATABASE_URL="postgres://username:password@127.0.0.1:5432/database_name?search_path=myschema,public"

MySQL

DATABASE_URL="mysql://username:password@127.0.0.1:3306/database_name"

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

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

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:

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:

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

ClickHouse

DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name"

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

  • on_cluster - Indicataion to use cluster statements and replicated migration table. (default: false) If this parameter is not supplied, other cluster related query parameters are ignored.
DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name?on_cluster" DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name?on_cluster=true"
  • cluster_macro (Optional) - Macro value to be used for ON CLUSTER statements and for the replciated migration table engine zookeeper path. (default: {cluster})
DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name?on_cluster&cluster_macro={my_cluster}"
  • replica_macro (Optional) - Macro value to be used for the replica name in the replciated migration table engine. (default: {replica})
DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name?on_cluster&replica_macro={my_replica}"
  • zoo_path (Optional) - The path to the table migration in ClickHouse/Zoo Keeper. (default: /clickhouse/tables/<cluster_macro>/{table})
DATABASE_URL="clickhouse://username:password@127.0.0.1:9000/database_name?on_cluster&zoo_path=/zk/path/tables"

See other supported connection options.

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 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

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

disable_auth (optional) - Pass true to skip Authentication, use only for testing and connecting to emulator.

Spanner

Spanner support is currently limited to databases using the PostgreSQL Dialect, which must be chosen during database creation. For future Spanner with GoogleSQL support, see this discussion.

Spanner with the Postgres interface requires that the PGAdapter is running. Use the following format for DATABASE_URL, with the host and port set to where the PGAdapter is running:

DATABASE_URL="spanner-postgres://127.0.0.1:5432/database_name?sslmode=disable"

Note that specifying a username and password is not necessary, as authentication is handled by the PGAdapter (they will be ignored by the PGAdapter if specified).

Other options of the postgres driver are supported.

Spanner also doesn't allow DDL to be executed inside explicit transactions. You must therefore specify transaction:false on migrations that include DDL:

-- migrate:up transaction:false CREATE TABLE ... -- migrate:down transaction:false DROP TABLE ...

Schema dumps are not currently supported, as pg_dump uses functions that are not provided by Spanner.

Creating Migrations

To create a new migration, run dbmate new create_users_table. You can name the migration anything you like. This will create a file db/migrations/20151127184807_create_users_table.sql in the current directory:

-- migrate:up -- migrate:down

To write a migration, simply add your SQL to the migrate:up section:

-- migrate:up create table users ( id integer, name varchar(255), email varchar(255) not null ); -- migrate:down

Note: Migration files are named in the format [version]_[description].sql. Only the version (defined as all leading numeric characters in the file name) is recorded in the database, so you can safely rename a migration file without having any effect on its current application state.

Running Migrations

Run dbmate up to run any pending migrations.

$ dbmate up Creating: myapp_development Applying: 20151127184807_create_users_table.sql Applied: 20151127184807_create_users_table.sql in 123µs Writing: ./db/schema.sql

Note: dbmate up will create the database if it does not already exist (assuming the current user has permission to create databases). If you want to run migrations without creating the database, run dbmate migrate.

Pending migrations are always applied in numerical order. However, dbmate does not prevent migrations from being applied out of order if they are committed independently (for example: if a developer has been working on a branch for a long time, and commits a migration which has a lower version number than other already-applied migrations, dbmate will simply apply the pending migration). See #159 for a more detailed explanation.

Rolling Back Migrations

By default, dbmate doesn't know how to roll back a migration. In development, it's often useful to be able to revert your database to a previous state. To accomplish this, implement the migrate:down section:

-- migrate:up create table users ( id integer, name varchar(255), email varchar(255) not null ); -- migrate:down drop table users;

Run dbmate rollback to roll back the most recent migration:

$ dbmate rollback Rolling back: 20151127184807_create_users_table.sql Rolled

编辑推荐精选

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

下拉加载更多