-
Notifications
You must be signed in to change notification settings - Fork 0
/
pq_model.go
305 lines (270 loc) · 7.43 KB
/
pq_model.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package surf
import (
"bytes"
"database/sql"
"errors"
"fmt"
"strconv"
)
// PqModel is a github.com/lib/pq implementation of a Model
type PqModel struct {
Database *sql.DB `json:"-"`
Config Configuration `json:"-"`
}
// GetConfiguration returns the configuration for the model
func (w *PqModel) GetConfiguration() *Configuration {
return &w.Config
}
// Insert inserts the model into the database
func (w *PqModel) Insert() error {
// Get Insertable Fields
var insertableFields []Field
for _, field := range w.Config.Fields {
if field.Insertable {
insertableFields = append(insertableFields, field)
}
}
// Generate Query
var queryBuffer bytes.Buffer
queryBuffer.WriteString("INSERT INTO ")
queryBuffer.WriteString(w.Config.TableName)
queryBuffer.WriteString("(")
for i, field := range insertableFields {
queryBuffer.WriteString(field.Name)
if (i + 1) < len(insertableFields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(") VALUES(")
for i := range insertableFields {
queryBuffer.WriteString("$")
queryBuffer.WriteString(strconv.Itoa(i + 1))
if (i + 1) < len(insertableFields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(") RETURNING ")
for i, field := range w.Config.Fields {
queryBuffer.WriteString(field.Name)
if (i + 1) < len(w.Config.Fields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(";")
// Get Value Fields
var valueFields []interface{}
for _, value := range insertableFields {
valueFields = append(valueFields, value.Pointer)
}
// Log Query
query := queryBuffer.String()
PrintSqlQuery(query, valueFields...)
// Execute Query
row := w.Database.QueryRow(query, valueFields...)
err := consumeRow(w, row)
if err != nil {
return err
}
// Expand foreign references
return expandForeign(w)
}
// Load loads the model from the database from its unique identifier
// and then loads those values into the struct
func (w *PqModel) Load() error {
// Get Unique Identifier
uniqueIdentifierField, err := getUniqueIdentifier(w)
if err != nil {
return err
}
// Generate Query
var queryBuffer bytes.Buffer
queryBuffer.WriteString("SELECT ")
for i, field := range w.Config.Fields {
queryBuffer.WriteString(field.Name)
if (i + 1) < len(w.Config.Fields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(" FROM ")
queryBuffer.WriteString(w.Config.TableName)
queryBuffer.WriteString(" WHERE ")
queryBuffer.WriteString(uniqueIdentifierField.Name)
queryBuffer.WriteString("=$1;")
// Log Query
query := queryBuffer.String()
PrintSqlQuery(query, uniqueIdentifierField.Pointer)
// Execute Query
row := w.Database.QueryRow(query, uniqueIdentifierField.Pointer)
err = consumeRow(w, row)
if err != nil {
return err
}
// Expand foreign references
return expandForeign(w)
}
// Update updates the model with the current values in the struct
func (w *PqModel) Update() error {
// Get Unique Identifier
uniqueIdentifierField, err := getUniqueIdentifier(w)
if err != nil {
return err
}
// Get updatable fields
var updatableFields []Field
for _, field := range w.Config.Fields {
if field.Updatable {
updatableFields = append(updatableFields, field)
}
}
// Generate Query
var queryBuffer bytes.Buffer
queryBuffer.WriteString("UPDATE ")
queryBuffer.WriteString(w.Config.TableName)
queryBuffer.WriteString(" SET ")
for i, field := range updatableFields {
queryBuffer.WriteString(field.Name)
queryBuffer.WriteString("=$")
queryBuffer.WriteString(strconv.Itoa(i + 1))
if (i + 1) < len(updatableFields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(" WHERE ")
queryBuffer.WriteString(uniqueIdentifierField.Name)
queryBuffer.WriteString("=$")
queryBuffer.WriteString(strconv.Itoa(len(updatableFields) + 1))
queryBuffer.WriteString(" RETURNING ")
for i, field := range w.Config.Fields {
queryBuffer.WriteString(field.Name)
if (i + 1) < len(w.Config.Fields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(";")
// Get Value Fields
var valueFields []interface{}
for _, value := range updatableFields {
valueFields = append(valueFields, value.Pointer)
}
valueFields = append(valueFields, uniqueIdentifierField.Pointer)
// Log Query
query := queryBuffer.String()
PrintSqlQuery(query, valueFields...)
// Execute Query
row := w.Database.QueryRow(query, valueFields...)
err = consumeRow(w, row)
if err != nil {
return err
}
// Expand foreign references
return expandForeign(w)
}
// Delete deletes the model
func (w *PqModel) Delete() error {
// Get Unique Identifier
uniqueIdentifierField, err := getUniqueIdentifier(w)
if err != nil {
return err
}
// Generate Query
var queryBuffer bytes.Buffer
queryBuffer.WriteString("DELETE FROM ")
queryBuffer.WriteString(w.Config.TableName)
queryBuffer.WriteString(" WHERE ")
queryBuffer.WriteString(uniqueIdentifierField.Name)
queryBuffer.WriteString("=$1;")
// Log Query
query := queryBuffer.String()
PrintSqlQuery(query, uniqueIdentifierField.Pointer)
// Execute Query
res, err := w.Database.Exec(queryBuffer.String(), uniqueIdentifierField.Pointer)
if err != nil {
return err
}
numRows, _ := res.RowsAffected()
if numRows != 1 {
return errors.New("Nothing was deleted")
}
return nil
}
// BulkFetch gets an array of models
func (w *PqModel) BulkFetch(fetchConfig BulkFetchConfig, buildModel BuildModel) ([]Model, error) {
// Set up values
values := make([]interface{}, 0)
// Generate query
var queryBuffer bytes.Buffer
queryBuffer.WriteString("SELECT ")
for i, field := range w.Config.Fields {
queryBuffer.WriteString(field.Name)
if (i + 1) < len(w.Config.Fields) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(" FROM ")
queryBuffer.WriteString(buildModel().GetConfiguration().TableName)
if len(fetchConfig.Predicates) > 0 {
// WHERE
queryBuffer.WriteString(" ")
predicatesStr, predicateValues := predicatesToString(1, fetchConfig.Predicates)
values = append(values, predicateValues...)
queryBuffer.WriteString(predicatesStr)
}
if len(fetchConfig.OrderBys) > 0 {
queryBuffer.WriteString(" ORDER BY ")
}
for i, orderBy := range fetchConfig.OrderBys {
// Validate that the orderBy.Field is a field
valid := false
for _, field := range w.Config.Fields {
if field.Name == orderBy.Field {
valid = true
break
}
}
if !valid {
return nil, fmt.Errorf("Could not order table '%v' by the invalid column '%v'",
w.Config.TableName, orderBy.Field)
}
// Write to query
queryBuffer.WriteString(orderBy.toString())
if (i + 1) < len(fetchConfig.OrderBys) {
queryBuffer.WriteString(", ")
}
}
queryBuffer.WriteString(" LIMIT ")
queryBuffer.WriteString(strconv.Itoa(fetchConfig.Limit))
queryBuffer.WriteString(" OFFSET ")
queryBuffer.WriteString(strconv.Itoa(fetchConfig.Offset))
queryBuffer.WriteString(";")
// Log Query
query := queryBuffer.String()
PrintSqlQuery(query, values...)
// Execute Query
rows, err := w.Database.Query(query, values...)
if err != nil {
return nil, err
}
// Stuff into []Model
models := make([]Model, 0)
for rows.Next() {
model := buildModel()
// Consume Rows
fields := model.GetConfiguration().Fields
var s []interface{}
for _, value := range fields {
s = append(s, value.Pointer)
}
err := rows.Scan(s...)
if err != nil {
return nil, err
}
models = append(models, model.(Model))
}
// Expand foreign references
err = expandForeigns(buildModel, models)
if err != nil {
return nil, err
}
// OK
return models, nil
}