-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding internal migrations code for smd to use
- Loading branch information
1 parent
a1baa6c
commit 747a44a
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package pgmigrate | ||
|
||
import ( | ||
"database/sql" | ||
|
||
"github.com/golang-migrate/migrate/v4" | ||
"github.com/golang-migrate/migrate/v4/database/postgres" | ||
_ "github.com/golang-migrate/migrate/v4/source/file" | ||
_ "github.com/lib/pq" | ||
) | ||
|
||
func DBConnect(dbDSN string) (*sql.DB, error) { | ||
db, err := sql.Open("postgres", dbDSN) | ||
if err != nil { | ||
return nil, err | ||
} | ||
//ensure the database is accessible | ||
err = db.Ping() | ||
if err != nil { | ||
return db, err | ||
} | ||
return db, nil | ||
} | ||
|
||
func ApplyMigrations(migrations_dir string, db *sql.DB) error { | ||
dbDriver, err := postgres.WithInstance(db, &postgres.Config{}) | ||
if err != nil { | ||
return err | ||
} | ||
m, err := migrate.NewWithDatabaseInstance( | ||
"file://"+migrations_dir, | ||
"postgres", dbDriver) | ||
if err != nil { | ||
return err | ||
} | ||
defer m.Close() | ||
err = m.Up() | ||
if err != nil && err != migrate.ErrNoChange { | ||
return err | ||
} | ||
return nil | ||
} |