-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmigrations_dev.go
More file actions
64 lines (53 loc) · 1.69 KB
/
migrations_dev.go
File metadata and controls
64 lines (53 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//go:build dev
// +build dev
package main
import (
"database/sql"
"fmt"
"github.com/dtg-lucifer/everato/config"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/iofs"
_ "github.com/jackc/pgx/v5/stdlib"
)
// This function migrates the current database connection to the lates state according to the
// queries and migrations in the migration directory
func MigrateDB(cfg *config.Config) error {
// Check if the migrations directory exists or not
// designated location is
// - /internal/db/migrations/*
m_fs, err := MigrationsFS()
if err != nil {
return fmt.Errorf("failed to get migrations filesystem: %w", err)
} else if m_fs == nil {
return fmt.Errorf("migrations filesystem is nil, ensure migrations directory exists")
}
source_driver, err := iofs.New(m_fs, ".")
if err != nil {
return fmt.Errorf("failed to create source driver for migrations: %w", err)
}
url := fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s?sslmode=disable",
cfg.DataBase.User,
cfg.DataBase.Password,
cfg.DataBase.Host,
cfg.DataBase.Port,
cfg.DataBase.Name,
)
db, err := sql.Open("pgx", url)
if err != nil {
return fmt.Errorf("failed to connect to the database: %w", err)
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
return fmt.Errorf("failed to create database driver: %w", err)
}
m, err := migrate.NewWithInstance("iofs", source_driver, "postgres", driver)
if err != nil {
return fmt.Errorf("failed to create migrate instance: %w", err)
}
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
return fmt.Errorf("failed to apply migrations: %w", err)
}
return nil
}