...
migrate command will create a
db/migrations
folder with tosql
(up/down) file.Edit up file. for example-
Code Block language sql CREATE TABLE IF NOT EXISTS users( user_id serial PRIMARY KEY, username VARCHAR (50) UNIQUE NOT NULL, password VARCHAR (50) NOT NULL, email VARCHAR (300) UNIQUE NOT NULL );
Edit down file. for example-
DROP TABLE IF EXISTS users;
Now let install
golang-migrate
.$ go get github.com/golang-migrate/migrate
Configure migration with
GORM
.Code Block language go db, err := gorm.Open("postgres", config.ConnectionString) driver, err := postgres.WithInstance(db.DB(), &postgres.Config{}) m, err := migrate.NewWithDatabaseInstance( "file://db/migrations", "postgres", driver) m.Steps(2)
Use command line to run migration
If you prefer a command-line tool over configured code then it’s for you!
Remove
GORM
configuration. (If any)Code Block language go db, err := gorm.Open("postgres", config.ConnectionString) // driver, err := postgres.WithInstance(db.DB(), &postgres.Config{}) // m, err := migrate.NewWithDatabaseInstance( // "file://db/migrations", // "postgres", driver) // m.Steps(2)
Run migration script. i.e:
Code Block language go migrate -source file://{migration file path} -database postgres://{user name}:{password}@{db location}/{db name}?sslmode=disable up
For example:
Code Block migrate -source file://db/migrations -database postgres://postgres:648782@localhost:5432/zachai_auction?sslmode=disable up
use down for dropping
Happy Coding…
Info |
---|
Related articles
...