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 reCreateSchemeDo(db, reCreateSchema...) 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 { if m.IsDir() { continue } 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 }