-
Notifications
You must be signed in to change notification settings - Fork 22
/
load.go
152 lines (133 loc) · 3.67 KB
/
load.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package fixtures
import (
"database/sql"
"fmt"
"io/ioutil"
"strings"
"gopkg.in/yaml.v2"
)
// NewProcessingError ...
func NewProcessingError(row int, cause error) error {
return fmt.Errorf("Error loading row %d: %s", row, cause.Error())
}
// NewFileError ...
func NewFileError(filename string, cause error) error {
return fmt.Errorf("Error loading file %s: %s", filename, cause.Error())
}
// Load processes a YAML fixture and inserts/updates the database accordingly
func Load(data []byte, db *sql.DB, driver string) error {
// Unmarshal the YAML data into a []Row slice
var rows []Row
if err := yaml.Unmarshal(data, &rows); err != nil {
return err
}
// Begin a transaction
tx, err := db.Begin()
if err != nil {
return err
}
// Iterate over rows define in the fixture
for i, row := range rows {
// Load internat struct variables
row.Init()
// Run a SELECT query to find out if we need to insert or UPDATE
selectQuery := fmt.Sprintf(
`SELECT COUNT(*) FROM "%s" WHERE %s`,
row.Table,
row.GetWhere(driver, 0),
)
var count int
err = tx.QueryRow(selectQuery, row.GetPKValues()...).Scan(&count)
if err != nil {
tx.Rollback() // rollback the transaction
return NewProcessingError(i+1, err)
}
if count == 0 {
// Primary key not found, let's run an INSERT query
insertQuery := fmt.Sprintf(
`INSERT INTO "%s"(%s) VALUES(%s)`,
row.Table,
strings.Join(row.GetInsertColumns(), ", "),
strings.Join(row.GetInsertPlaceholders(driver), ", "),
)
_, err := tx.Exec(insertQuery, row.GetInsertValues()...)
if err != nil {
tx.Rollback() // rollback the transaction
return NewProcessingError(i+1, err)
}
if driver == postgresDriver && row.GetInsertColumns()[0] == "\"id\"" {
err = fixPostgresPKSequence(tx, row.Table, "id")
if err != nil {
tx.Rollback()
return NewProcessingError(i+1, err)
}
}
} else {
// Primary key found, let's run UPDATE query
updateQuery := fmt.Sprintf(
`UPDATE "%s" SET %s WHERE %s`,
row.Table,
strings.Join(row.GetUpdatePlaceholders(driver), ", "),
row.GetWhere(driver, row.GetUpdateColumnsLength()),
)
values := append(row.GetUpdateValues(), row.GetPKValues()...)
_, err := tx.Exec(updateQuery, values...)
if err != nil {
tx.Rollback() // rollback the transaction
return NewProcessingError(i+1, err)
}
if driver == postgresDriver && row.GetUpdateColumns()[0] == "\"id\"" {
err = fixPostgresPKSequence(tx, row.Table, "id")
if err != nil {
tx.Rollback()
return NewProcessingError(i+1, err)
}
}
}
}
// Commit the transaction
if err := tx.Commit(); err != nil {
tx.Rollback() // rollback the transaction
return err
}
return nil
}
// LoadFile ...
func LoadFile(filename string, db *sql.DB, driver string) error {
// Read fixture data from the file
data, err := ioutil.ReadFile(filename)
if err != nil {
return NewFileError(filename, err)
}
// Insert the fixture data
return Load(data, db, driver)
}
// LoadFiles ...
func LoadFiles(filenames []string, db *sql.DB, driver string) error {
for _, filename := range filenames {
if err := LoadFile(filename, db, driver); err != nil {
return err
}
}
return nil
}
// fixPostgresPKSequence
func fixPostgresPKSequence(tx *sql.Tx, table string, column string) error {
// Query for the qualified sequence name
var seqName *string
err := tx.QueryRow(`
SELECT pg_get_serial_sequence($1, $2)
`, table, column).Scan(&seqName)
if err != nil {
return err
}
if seqName == nil {
// No sequence to fix
return nil
}
// Set the sequence
_, err = tx.Exec(fmt.Sprintf(`
SELECT pg_catalog.setval($1, (SELECT MAX("%s") FROM "%s"))
`, column, table), *seqName)
return err
}