This repository has been archived by the owner on Oct 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema_commands.go
92 lines (79 loc) · 2.27 KB
/
schema_commands.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package sqlutil
import (
"fmt"
"github.com/gchaincl/dotsql"
)
// LoadSchemaCommands takes a filepath to a sql file with create & drop table commands
// and returns a SchemaCommands
func LoadSchemaCommands(sqlFilePath string) (*SchemaCommands, error) {
f, err := dotsql.LoadFromFile(sqlFilePath)
if err != nil {
return nil, err
}
return &SchemaCommands{
file: f,
}, nil
}
func LoadSchemaString(sql string) (*SchemaCommands, error) {
f, err := dotsql.LoadFromString(sql)
if err != nil {
return nil, err
}
return &SchemaCommands{
file: f,
}, nil
}
// SchemaCommands is an sql file that defines a database schema
type SchemaCommands struct {
file *dotsql.DotSql
}
// DropAll executes the command named "drop-all" from the sql file
// this should be a command in the form:
// DROP TABLE IF EXISTS foo, bar, baz ...
func (s *SchemaCommands) DropAll(db Execable) error {
_, err := s.file.Exec(db, "drop-all")
if err != nil {
fmt.Errorf("error executing 'drop-all': %s", err.Error())
}
return nil
}
// Create tables if they don't already exist
func (s *SchemaCommands) Create(db Execable, tables ...string) ([]string, error) {
created := []string{}
for _, table := range tables {
exists := false
if err := db.QueryRow(fmt.Sprintf("select exists(select 1 from %s limit 1)", table)).Scan(&exists); err == nil || exists {
continue
}
cmd := fmt.Sprintf("create-%s", table)
if _, err := s.file.Exec(db, cmd); err != nil {
return created, fmt.Errorf("error executing '%s': %s", cmd, err.Error())
}
created = append(created, table)
}
return created, nil
}
func (s *SchemaCommands) DropAllCreate(db Execable, tables ...string) error {
if err := s.DropAll(db); err != nil {
return err
}
if _, err := s.Create(db, tables...); err != nil {
return err
}
return nil
}
// // InitializeDatabase drops everything and calls create on all tables
// func (s *SchemaCommands) InitializeDatabase(db Execable,) error {
// // // test query to check for database schema existence
// // var exists bool
// // if err = db.QueryRow("select exists(select * from primers limit 1)").Scan(&exists); err == nil {
// // return nil
// // }
// if err := s.DropAll(db); err != nil {
// return err
// }
// if err := s.CreateAll(db); err != nil {
// return err
// }
// return nil
// }