micrach/db/db.go

89 lines
1.6 KiB
Go
Raw Normal View History

2021-08-26 16:16:50 +03:00
package db
import (
"context"
"log"
2021-11-14 13:14:10 +03:00
"path/filepath"
2021-11-16 14:02:39 +03:00
"strconv"
2021-11-14 13:14:10 +03:00
"strings"
2021-08-26 16:16:50 +03:00
Config "micrach/config"
2021-11-14 13:14:10 +03:00
Files "micrach/files"
2021-08-26 16:16:50 +03:00
"github.com/jackc/pgx/v4/pgxpool"
)
var Pool *pgxpool.Pool
2021-11-16 14:02:39 +03:00
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")
}
2021-11-07 11:42:54 +03:00
func Migrate() {
2021-11-16 14:02:39 +03:00
dbMigrations := getDbMigrations()
sqlMigrations := Files.GetFullFilePathsInFolder("migrations")
for _, m := range sqlMigrations {
2021-11-14 13:14:10 +03:00
filename := filepath.Base(m)
splitted := strings.Split(filename, "-")
2021-11-16 14:02:39 +03:00
id, err := strconv.Atoi(splitted[0])
if err != nil {
log.Panicln(err)
}
2021-11-16 14:03:17 +03:00
// Get name without extension
2021-11-16 14:02:39 +03:00
name := strings.Split(splitted[1], ".")[0]
if _, ok := dbMigrations[id]; !ok {
_, err = Pool.Query(context.TODO(), Files.ReadFileText(m))
if err != nil {
log.Panicln(err)
}
sql := `INSERT INTO migrations (id, name) VALUES ($1, $2)`
_, err = Pool.Query(context.TODO(), sql, id, name)
if err != nil {
log.Panicln(err)
}
}
2021-11-14 13:14:10 +03:00
}
2021-11-16 14:02:39 +03:00
2021-11-07 11:42:54 +03:00
log.Println("database migrations - online")
}
2021-11-16 14:02:39 +03:00
func getDbMigrations() MigrationsMap {
sql := `SELECT id, name FROM migrations`
rows, err := Pool.Query(context.TODO(), sql)
if err != nil {
log.Panicln(err)
}
if rows.Err() != nil {
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
}