Commit 624b16cb authored by Vladimir Barsukov's avatar Vladimir Barsukov
Browse files

migrations

parent f1b4a007
package zmigrations
import (
"embed"
"fmt"
"git.barsukov.pro/barsukov/zgo/zdb"
"io/fs"
"log"
)
func Migrations(db *zdb.Pool, files embed.FS, loc string, reCreateSchema ...string) error {
var err error
var f []fs.DirEntry
if len(reCreateSchema) > 0 && len(reCreateSchema[0]) > 0 {
_ = db.WExec(fmt.Sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", reCreateSchema[0]))
_ = db.WExec(fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s;", reCreateSchema[0]))
}
if err = db.WExec("CREATE TABLE IF NOT EXISTS z_migrations(name text PRIMARY KEY, created_at timestamptz DEFAULT NOW());"); err != nil {
return err
}
if f, err = files.ReadDir(loc); err != nil {
return err
}
for _, m := range f {
var s string
if err = db.Get(&s, "SELECT name FROM z_migrations WHERE name = $1", m.Name()); err != nil {
if zdb.IsEmpty(err) {
var b []byte
if b, err = files.ReadFile(loc + m.Name()); err != nil {
return err
}
if err = db.WExec(string(b)); err != nil {
return fmt.Errorf("MIGRATION: %s - %v", m.Name(), err)
}
if err = db.WExec("INSERT INTO z_migrations(name) VALUES ($1)", m.Name()); err != nil {
return err
}
log.Printf("MIGRATION: %s", m.Name())
} else {
return err
}
}
}
return nil
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment