-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigration.go
46 lines (39 loc) · 1.16 KB
/
migration.go
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
36
37
38
39
40
41
42
43
44
45
46
package repoimpl
import (
"fmt"
"os"
"strings"
)
func createDbQuery(nameOfModel string, fields []*field) (string, string) {
crt := strings.Builder{}
crt.Write([]byte(fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%ss\" (\n", nameOfModel)))
for i, v := range fields {
if i != len(fields)-1 {
crt.Write([]byte(fmt.Sprintf("\t\"%s\" %s,\n", v.DBTag, goTypeToDBType(v.Type))))
} else {
crt.Write([]byte(fmt.Sprintf("\t\"%s\" %s\n", v.DBTag, goTypeToDBType(v.Type))))
}
}
crt.Write([]byte(");"))
drp := fmt.Sprintf("DROP TABLE IF EXISTS \"%ss\";", nameOfModel)
return crt.String(), drp
}
func migrationFiles(nameOfModel, create, drop string) error {
file, err := os.Create(fmt.Sprintf("%s/%s/01_create_%s.up.sql", migrationPath, postgresPath, nameOfModel))
if err != nil {
return clear("migration", err)
}
_, err = file.Write([]byte(create))
if err != nil {
return clear("migration", err)
}
file, err = os.Create(fmt.Sprintf("%s/%s/01_create_%s.down.sql", migrationPath, postgresPath, nameOfModel))
if err != nil {
return clear("migration", err)
}
_, err = file.Write([]byte(drop))
if err != nil {
return clear("migration", err)
}
return nil
}