From 5f9e5cc6a4a8182b56ea5df71d476156517216db Mon Sep 17 00:00:00 2001 From: ClasWen Date: Tue, 21 May 2024 20:48:38 +0800 Subject: [PATCH] migrate at db init --- repo/db.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/repo/db.go b/repo/db.go index 306b3a0..abfb6de 100644 --- a/repo/db.go +++ b/repo/db.go @@ -8,6 +8,8 @@ import ( "github.com/jackc/pgx/v5/stdlib" + _ "github.com/lib/pq" + "github.com/nbtca/saturday/util" "github.com/qustavo/sqlhooks/v2" "github.com/sirupsen/logrus" @@ -15,7 +17,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/golang-migrate/migrate/v4" - _ "github.com/golang-migrate/migrate/v4/database/postgres" + "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" ) @@ -43,12 +45,22 @@ func (h *Hooks) After(ctx context.Context, query string, args ...interface{}) (c func InitDB() { var err error - sql.Register("mysqlWithHooks", sqlhooks.Wrap(&stdlib.Driver{},&Hooks{})) + sql.Register("mysqlWithHooks", sqlhooks.Wrap(&stdlib.Driver{}, &Hooks{})) db, err = sqlx.Connect("mysqlWithHooks", os.Getenv("DB_URL")) + if err != nil { + util.Logger.Fatal(err) + } + + driver, err := postgres.WithInstance(db.DB, &postgres.Config{}) + if err != nil { + util.Logger.Fatal(err) + } + m, err := migrate.NewWithDatabaseInstance( - "file:///migrations", + "file://migrations", "postgres", driver) m.Up() // or m.Step(2) if you want to explicitly set the number of migrations to run + m.Close() if err != nil { util.Logger.Fatal(err)