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。