migrate
v4.18.1
数据库迁移写在GO中。用作CLI或导入作为库。
从哑光/迁移中分叉
数据库驱动程序运行迁移。添加新数据库?
数据库连接字符串是通过URL指定的。 URL格式取决于驱动程序,但通常具有: dbdriver://username:password@host:port/dbname?param1=true¶m2=false
任何保留的URL字符都需要逃脱。请注意, %字符也需要逃脱
明确地,需要逃脱以下字符: ! , # , $ , % , & ' , ( , ) , * , + , / , : ,, ; , = ? , @ , [ , ]
始终运行DB连接URL(例如用户名,密码等)的URL部分最容易通过URL编码器运行。请参阅下面的示例python摘要:
$ python3 -c ' import urllib.parse; print(urllib.parse.quote(input("String to encode: "), "")) '
String to encode: FAKEpassword!#$%&' () * +,/:;= ? @[]
FAKEpassword%21%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D
$ python2 -c ' import urllib; print urllib.quote(raw_input("String to encode: "), "") '
String to encode: FAKEpassword!#$%&' () * +,/:;= ? @[]
FAKEpassword%21%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D
$源驱动程序从本地或远程来源读取迁移。添加新来源?
CLI文档
$ migrate -source file://path/to/migrations -database postgres://localhost:5432/database up 2$ docker run -v {{ migration dir }}:/migrations --network host migrate/migrate
-path=/migrations/ -database postgres://localhost:5432/database up 2GracefulStop chan bool支持优雅的停止。io.Reader流以低内存开销。去文档
import (
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/github"
)
func main () {
m , err := migrate . New (
"github://mattes:personal-access-token@mattes/migrate_test" ,
"postgres://localhost:5432/database?sslmode=enable" )
m . Steps ( 2 )
}想使用现有数据库客户端吗?
import (
"database/sql"
_ "github.com/lib/pq"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
func main () {
db , err := sql . Open ( "postgres" , "postgres://localhost:5432/database?sslmode=enable" )
driver , err := postgres . WithInstance ( db , & postgres. Config {})
m , err := migrate . NewWithDatabaseInstance (
"file:///migrations" ,
"postgres" , driver )
m . Up () // or m.Steps(2) if you want to explicitly set the number of migrations to run
}开始
(更多教程将来)
每个迁移都有上下迁移。为什么?
1481574547_create_users_table.up.sql
1481574547_create_users_table.down.sql最佳实践:如何写迁移。
查看偏头痛者。注意:偏头痛者没有该项目的隶属关系或支持
| 版本 | 支持? | 进口 | 笔记 |
|---|---|---|---|
| 掌握 | ✅ | import "github.com/golang-migrate/migrate/v4" | 新功能和错误修复首先到达这里 |
| v4 | ✅ | import "github.com/golang-migrate/migrate/v4" | 用于稳定版本 |
| V3 | import "github.com/golang-migrate/migrate" (包装经理)或import "gopkg.in/golang-migrate/migrate.v3" (不建议) | 不要使用- 不再支持 |
是的,请! Makefile是您的朋友,请阅读《开发指南》。
还要看看常见问题解答。
寻找替代方案? https://awesome-go.com/#database。