micrach/db/db.go

100 lines
2.0 KiB
Go
Raw Permalink Normal View History

2021-08-26 16:16:50 +03:00
package db
import (
"context"
"log"
"path/filepath"
"strconv"
"strings"
2021-08-26 16:16:50 +03:00
Config "micrach/config"
Files "micrach/files"
2021-08-26 16:16:50 +03:00
"github.com/jackc/pgx/v4/pgxpool"
)
var Pool *pgxpool.Pool
type MigrationsMap map[int]string
type Migration struct {
ID int
Name string
}
2021-08-26 16:16:50 +03:00
func Init() {
var err error
2021-09-10 19:16:53 +03:00
Pool, err = pgxpool.Connect(context.TODO(), Config.Db.Url)
2021-08-26 16:16:50 +03:00
if err != nil {
log.Println("database - offline")
log.Panicln(err)
}
log.Println("database - online")
}
func Migrate() {
dbMigrations := getDbMigrations()
sqlMigrations := Files.GetFullFilePathsInFolder("migrations")
for _, m := range sqlMigrations {
filename := filepath.Base(m)
splitted := strings.Split(filename, "-")
id, err := strconv.Atoi(splitted[0])
if err != nil {
log.Panicln(err)
}
// Get name without extension
name := strings.Split(splitted[1], ".")[0]
_, isMigrationInDb := dbMigrations[id]
if !isMigrationInDb {
2022-01-21 02:24:30 +03:00
sql := Files.ReadFileText(m)
runMigration(id, name, sql)
2022-05-18 10:23:35 +03:00
log.Println("migration - " + name + " - online")
}
}
2022-05-18 10:23:35 +03:00
log.Println("migrations - online")
}
2022-01-21 02:24:30 +03:00
func runMigration(mid int, mname, msql string) {
_, err := Pool.Exec(context.TODO(), msql)
if err != nil {
log.Panicln(err)
}
sql := `INSERT INTO migrations (id, name) VALUES ($1, $2)`
_, err = Pool.Query(context.TODO(), sql, mid, mname)
if err != nil {
log.Panicln(err)
}
}
func getDbMigrations() MigrationsMap {
sql := `SELECT id, name FROM migrations`
rows, err := Pool.Query(context.TODO(), sql)
2022-05-18 10:23:35 +03:00
if err != nil && isNotNonExistentMigrationsTable(err) {
log.Panicln(err)
}
2022-05-18 10:23:35 +03:00
if rows.Err() != nil && isNotNonExistentMigrationsTable(rows.Err()) {
log.Panicln(rows.Err())
}
migrationsMap := make(MigrationsMap)
for rows.Next() {
var m Migration
err = rows.Scan(&m.ID, &m.Name)
if err != nil {
log.Panicln(err)
}
migrationsMap[m.ID] = m.Name
}
return migrationsMap
}
2022-05-18 10:23:35 +03:00
func isNotNonExistentMigrationsTable(err error) bool {
return err.Error() != `ERROR: relation "migrations" does not exist (SQLSTATE 42P01)`
}