-
Notifications
You must be signed in to change notification settings - Fork 31
/
loadsave.go
247 lines (214 loc) · 6.69 KB
/
loadsave.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package meddler
import (
"database/sql"
"fmt"
"strings"
)
type dbErr struct {
msg string
err error
}
func (err *dbErr) Error() string {
return fmt.Sprintf("%s: %v", err.msg, err.err)
}
// DriverErr returns the original error as returned by the database driver
// if the error comes from the driver, with the second value set to true.
// Otherwise, it returns err itself with false as second value.
func DriverErr(err error) (error, bool) {
if dbe, ok := err.(*dbErr); ok {
return dbe.err, true
}
return err, false
}
// DB is a generic database interface, matching both *sql.Db and *sql.Tx
type DB interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
// Load loads a record using a query for the primary key field.
// Returns sql.ErrNoRows if not found.
func (d *Database) Load(db DB, table string, dst interface{}, pk int64) error {
columns, err := d.ColumnsQuoted(dst, true)
if err != nil {
return err
}
// make sure we have a primary key field
pkName, _, err := d.PrimaryKey(dst)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Load: no primary key field found")
}
// run the query
q := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %s", columns, d.quoted(table), d.quoted(pkName), d.Placeholder)
rows, err := db.Query(q, pk)
if err != nil {
return &dbErr{msg: "meddler.Load: DB error in Query", err: err}
}
// scan the row
return d.ScanRow(rows, dst)
}
// Load using the Default Database type
func Load(db DB, table string, dst interface{}, pk int64) error {
return Default.Load(db, table, dst, pk)
}
// Insert performs an INSERT query for the given record.
// If the record has a primary key flagged, it must be zero, and it
// will be set to the newly-allocated primary key value from the database
// as returned by LastInsertId.
func (d *Database) Insert(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return fmt.Errorf("meddler.Insert: primary key must be zero")
}
// gather the query parts
namesPart, err := d.ColumnsQuoted(src, false)
if err != nil {
return err
}
valuesPart, err := d.PlaceholdersString(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// run the query
q := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", d.quoted(table), namesPart, valuesPart)
if d.UseReturningToGetID && pkName != "" {
q += " RETURNING " + d.quoted(pkName)
var newPk int64
err := db.QueryRow(q, values...).Scan(&newPk)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in QueryRow", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else if pkName != "" {
result, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
// save the new primary key
newPk, err := result.LastInsertId()
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error getting new primary key value", err: err}
}
if err = d.SetPrimaryKey(src, newPk); err != nil {
return fmt.Errorf("meddler.Insert: Error saving updated pk: %v", err)
}
} else {
// no primary key, so no need to lookup new value
_, err := db.Exec(q, values...)
if err != nil {
return &dbErr{msg: "meddler.Insert: DB error in Exec", err: err}
}
}
return nil
}
// Insert using the Default Database type
func Insert(db DB, table string, src interface{}) error {
return Default.Insert(db, table, src)
}
// Update performs and UPDATE query for the given record.
// The record must have an integer primary key field that is non-zero,
// and it will be used to select the database row that gets updated.
func (d *Database) Update(db DB, table string, src interface{}) error {
// gather the query parts
names, err := d.Columns(src, false)
if err != nil {
return err
}
placeholders, err := d.Placeholders(src, false)
if err != nil {
return err
}
values, err := d.Values(src, false)
if err != nil {
return err
}
// form the column=placeholder pairs
var pairs []string
for i := 0; i < len(names) && i < len(placeholders); i++ {
pair := fmt.Sprintf("%s=%s", d.quoted(names[i]), placeholders[i])
pairs = append(pairs, pair)
}
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName == "" {
return fmt.Errorf("meddler.Update: no primary key field")
}
if pkValue < 1 {
return fmt.Errorf("meddler.Update: primary key must be an integer > 0")
}
ph := d.placeholder(len(placeholders) + 1)
// run the query
q := fmt.Sprintf("UPDATE %s SET %s WHERE %s=%s", d.quoted(table),
strings.Join(pairs, ","),
d.quoted(pkName), ph)
values = append(values, pkValue)
if _, err := db.Exec(q, values...); err != nil {
return &dbErr{msg: "meddler.Update: DB error in Exec", err: err}
}
return nil
}
// Update using the Default Database type
func Update(db DB, table string, src interface{}) error {
return Default.Update(db, table, src)
}
// Save performs an INSERT or an UPDATE, depending on whether or not
// a primary keys exists and is non-zero.
func (d *Database) Save(db DB, table string, src interface{}) error {
pkName, pkValue, err := d.PrimaryKey(src)
if err != nil {
return err
}
if pkName != "" && pkValue != 0 {
return d.Update(db, table, src)
}
return d.Insert(db, table, src)
}
// Save using the Default Database type
func Save(db DB, table string, src interface{}) error {
return Default.Save(db, table, src)
}
// QueryRow performs the given query with the given arguments, scanning a
// single row of results into dst. Returns sql.ErrNoRows if there was no
// result row.
func (d *Database) QueryRow(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the result
return d.ScanRow(rows, dst)
}
// QueryRow using the Default Database type
func QueryRow(db DB, dst interface{}, query string, args ...interface{}) error {
return Default.QueryRow(db, dst, query, args...)
}
// QueryAll performs the given query with the given arguments, scanning
// all results rows into dst.
func (d *Database) QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
// perform the query
rows, err := db.Query(query, args...)
if err != nil {
return err
}
// gather the results
return d.ScanAll(rows, dst)
}
// QueryAll using the Default Database type
func QueryAll(db DB, dst interface{}, query string, args ...interface{}) error {
return Default.QueryAll(db, dst, query, args...)
}