用于将迁移应用到 postgresql 数据库的包
项目描述
用于将迁移应用到 postgresql 数据库的包
不用于生产目的。
从文件迁移数据库的工具。
安装
$ pip install pgrate
用法
pgrate -p directorie/to/migrations -d postgres://username:password@localhost:5432/database
或者
pgrate -p directorie/to/migrations -d postgresql://username:password@localhost:5432/database
注意 迁移名称必须以数字+“_”开头,其中数字是迁移版本并以*.up.sql 示例(001_migration_name.up.slq)结尾
例子
- 进入工作目录并创建默认迁移文件夹
$ cd /path/to/project
$ mkdir migrations
- 创建上下迁移
-- migrations/001_init.up.sql
CREATE TABLE IF NOT EXISTS users(
id serial PRIMARY KEY,
name VARCHAR(255)
);
-- migrations/001_init.down.sql
DROP TABLE IF EXISTS users;
- 应用迁移
$ pgrate -p ./migrations -d postgres://username:password@localhost:5432/database
- 结果
迁移架构
| 当前版本 | is_dirt |
|---|---|
| 1 | 错误的 |
- 上下创建迁移时出错
-- migrations/002_users.up.sql
CREATE TABLE users(
id serial PRIMARY KEY,
name VARCHAR(255)
);
-- migrations/002_users.down.sql
DROP TABLE IF EXISTS users;
- 应用迁移
$ pgrate -p ./migrations -d postgres://username:password@localhost:5432/database
- 结果
控制台日志
asyncpg.exceptions.DuplicateTableError: relation "users" already exists
迁移架构
| 当前版本 | is_dirt |
|---|---|
| 2 | 真的 |
命令
| 命令 | 描述 |
|---|---|
| '-p' '--路径' |
迁移文件夹的路径 |
| '-d' '--db-uri' |
数据库连接 URI |