zmigration.go 1.06 KB
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
15
	reCreateSchemeDo(db, reCreateSchema...)
Vladimir Barsukov's avatar
Vladimir Barsukov committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

	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

Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
33
				if b, err = files.ReadFile(loc + "/" + m.Name()); err != nil {
Vladimir Barsukov's avatar
Vladimir Barsukov committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
					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
}