zmigration.go 1.24 KB
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

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