-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
298 lines (261 loc) · 6.7 KB
/
store.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
package ceous
import (
"bytes"
"fmt"
sq "github.com/elgris/sqrl"
"github.com/pkg/errors"
)
var (
ErrNonNewDocument = errors.New("ceous: cannot insert a non new document")
ErrNotWritable = errors.New("ceous: record is not writable")
ErrNewDocument = errors.New("ceous: cannot updated a new document")
ErrNoRowUpdate = errors.New("ceous: update affected no rows")
ErrNotFound = errors.New("ceous: entity not found")
)
type (
// BaseStore is the generic implementation of the Store.
//
// TODO(jota): To document it...
BaseStore struct {
schema Schema
_runner DBRunner
runner DBRunner
disableCache bool
}
)
// NewStore returns a new base implementation of a Store. That does not aims to
// be used by itself, but to be used as composition on real stores.
//
// TODO(jota): Improve documentation.
func NewStore(schema Schema, options ...CeousOption) *BaseStore {
store := &BaseStore{
schema: schema,
}
for _, option := range options {
option(store)
}
if !store.disableCache {
store.runner = store._runner
} else {
store.runner = sq.NewStmtCacher(store._runner)
}
return store
}
// Insert will insert a record.
//
// `fields` define what fields are going to be used on the insert.
func (store *BaseStore) Insert(record Record, fields ...SchemaField) error {
if record.IsPersisted() {
return ErrNonNewDocument
}
if len(fields) == 0 {
fields = store.schema.Columns()
}
var (
autoIncPks = make([]string, 0, 1)
columnNames = make([]string, 0, len(fields))
columnValues = make([]interface{}, 0, len(fields))
fieldName string
fieldValue interface{}
err error
)
for _, col := range fields {
fieldName = col.String()
if col.IsAutoInc() {
autoIncPks = append(autoIncPks, fieldName)
continue
}
fieldValue, err = record.Value(fieldName)
if err != nil {
return err
}
columnNames = append(columnNames, fieldName)
columnValues = append(columnValues, fieldValue)
}
// TODO(jota): To add support for virtual columns.
// cols = append(cols, virtualCols...)
// values = append(values, virtualColValues...)
var colBuf bytes.Buffer
var valBuf bytes.Buffer
for i, col := range columnNames {
if i != 0 {
colBuf.WriteRune(',')
valBuf.WriteRune(',')
}
colBuf.WriteString(col)
valBuf.WriteString(fmt.Sprintf("$%d", i+1))
}
var query bytes.Buffer
query.WriteString("INSERT INTO ")
query.WriteString(store.schema.Table())
query.WriteString(" (")
query.Write(colBuf.Bytes())
query.WriteString(") VALUES (")
query.Write(valBuf.Bytes())
query.WriteString(")")
if len(autoIncPks) > 0 {
pkRefs := make([]interface{}, len(autoIncPks))
query.WriteString(" RETURNING ")
for i, pkField := range autoIncPks {
if i > 0 {
query.WriteString(",")
}
query.WriteString(pkField)
pkFieldRef, err := record.ColumnAddress(pkField)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("could not find PK %s", pkField))
}
pkRefs[i] = pkFieldRef
}
rows, err := store.runner.Query(query.String(), columnValues...)
if err != nil {
return errors.Wrap(err, "query error")
}
defer rows.Close()
if rows.Next() {
err = rows.Scan(pkRefs...)
if err != nil {
return errors.Wrap(err, "scan error")
}
}
} else {
_, err = store.runner.Exec(query.String(), columnValues...)
if err != nil {
return errors.Wrap(err, " error")
}
}
record.setWritable(true)
record.setPersisted()
return nil
}
func (store *BaseStore) Update(record Record, fields ...SchemaField) (int64, error) {
if !record.IsWritable() {
return 0, ErrNotWritable
}
if !record.IsPersisted() {
return 0, ErrNewDocument
}
// TODO(jota): To take in consideration the primary key.
/*
if record.GetID().IsEmpty() {
return 0, ErrEmptyID
}
*/
if len(fields) == 0 {
fields = store.schema.Columns()
}
var (
pkNames = make([]string, 0, 1)
pkValues = make([]interface{}, 0, 1)
fieldName string
fieldValue interface{}
err error
)
for _, col := range store.schema.Columns() {
if !col.IsPK() {
continue
}
fieldName = col.String()
fieldValue, err = record.Value(fieldName)
if err != nil {
return 0, err
}
pkNames = append(pkNames, fieldName)
pkValues = append(pkValues, fieldValue)
}
var (
columnNames = make([]string, 0, len(fields))
columnValues = make([]interface{}, 0, len(fields))
)
// remove the ID from there
for _, col := range fields {
fieldName = col.String()
fieldValue, err = record.Value(fieldName)
if err != nil {
return 0, err
}
columnNames = append(columnNames, fieldName)
columnValues = append(columnValues, fieldValue)
}
/*
// TODO(jota): Add support for virtual columns.
virtualCols, virtualColValues := virtualColumns(record, columnNames)
columnNames = append(columnNames, virtualCols...)
values = append(values, virtualColValues...)
*/
var query bytes.Buffer
query.WriteString("UPDATE ")
query.WriteString(store.schema.Table())
query.WriteString(" SET ")
for i, col := range columnNames {
if i > 0 {
query.WriteRune(',')
}
query.WriteString(col)
query.WriteRune('=')
query.WriteString(fmt.Sprintf("$%d", i+1))
}
query.WriteString(" WHERE ")
for i, field := range pkNames {
if i > 0 {
query.WriteString(" AND ")
}
query.WriteString(field)
query.WriteRune('=')
query.WriteString(fmt.Sprintf("$%d", len(columnNames)+1+i)) // TODO(jota): Use a placeholder configuration to ensure multi database support.
}
result, err := store.runner.Exec(query.String(), append(columnValues, pkValues...)...)
if err != nil {
return 0, err
}
cnt, err := result.RowsAffected()
if err != nil {
return 0, err
}
if cnt == 0 {
return 0, ErrNoRowUpdate
}
return cnt, nil
}
func (store *BaseStore) Delete(record Record) error {
if !record.IsWritable() {
return ErrNotWritable
}
if !record.IsPersisted() {
return ErrNewDocument
}
var (
pkNames = make([]string, 0, 1)
pkValues = make([]interface{}, 0, 1)
fieldName string
fieldValue interface{}
err error
)
for _, col := range store.schema.Columns() {
if !col.IsPK() {
continue
}
fieldName = col.String()
fieldValue, err = record.Value(fieldName)
if err != nil {
return err
}
pkNames = append(pkNames, fieldName)
pkValues = append(pkValues, fieldValue)
}
var query bytes.Buffer
query.WriteString("DELETE FROM ")
query.WriteString(store.schema.Table())
query.WriteString(" WHERE ")
for i, field := range pkNames {
if i > 0 {
query.WriteString(" AND ")
}
query.WriteString(field)
query.WriteRune('=')
query.WriteString(fmt.Sprintf("$%d", 1+i)) // TODO(jota): Use a placeholder configuration to ensure multi database support.
}
fmt.Println(query.String())
_, err = store.runner.Exec(query.String(), pkValues...)
return err
}