-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathmemory.go
More file actions
333 lines (296 loc) · 6.76 KB
/
Copy pathmemory.go
File metadata and controls
333 lines (296 loc) · 6.76 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package model
import (
"context"
"fmt"
"reflect"
"strings"
"sync"
)
type memoryModel struct {
mu sync.RWMutex
schemas map[string]*Schema
types map[reflect.Type]*Schema
tables map[string]map[string]map[string]any // table -> key -> fields
}
func newMemoryModel(opts ...Option) Model {
return &memoryModel{
schemas: make(map[string]*Schema),
types: make(map[reflect.Type]*Schema),
tables: make(map[string]map[string]map[string]any),
}
}
func (m *memoryModel) Init(opts ...Option) error {
return nil
}
func (m *memoryModel) Register(v interface{}, opts ...RegisterOption) error {
schema := BuildSchema(v, opts...)
t := ResolveType(v)
m.mu.Lock()
defer m.mu.Unlock()
m.schemas[schema.Table] = schema
m.types[t] = schema
if _, ok := m.tables[schema.Table]; !ok {
m.tables[schema.Table] = make(map[string]map[string]any)
}
return nil
}
func (m *memoryModel) schema(v interface{}) (*Schema, error) {
t := ResolveType(v)
m.mu.RLock()
s, ok := m.types[t]
m.mu.RUnlock()
if !ok {
return nil, ErrNotRegistered
}
return s, nil
}
func (m *memoryModel) Create(ctx context.Context, v interface{}) error {
schema, err := m.schema(v)
if err != nil {
return err
}
fields := StructToMap(schema, v)
key := KeyValue(schema, v)
if key == "" {
return fmt.Errorf("model: key field %q not set", schema.Key)
}
m.mu.Lock()
defer m.mu.Unlock()
tbl := m.tables[schema.Table]
if _, exists := tbl[key]; exists {
return ErrDuplicateKey
}
row := make(map[string]any, len(fields))
for k, v := range fields {
row[k] = v
}
tbl[key] = row
return nil
}
func (m *memoryModel) Read(ctx context.Context, key string, v interface{}) error {
schema, err := m.schema(v)
if err != nil {
return err
}
m.mu.RLock()
defer m.mu.RUnlock()
tbl := m.tables[schema.Table]
row, ok := tbl[key]
if !ok {
return ErrNotFound
}
MapToStruct(schema, row, v)
return nil
}
func (m *memoryModel) Update(ctx context.Context, v interface{}) error {
schema, err := m.schema(v)
if err != nil {
return err
}
fields := StructToMap(schema, v)
key := KeyValue(schema, v)
if key == "" {
return fmt.Errorf("model: key field %q not set", schema.Key)
}
m.mu.Lock()
defer m.mu.Unlock()
tbl := m.tables[schema.Table]
if _, ok := tbl[key]; !ok {
return ErrNotFound
}
row := make(map[string]any, len(fields))
for k, v := range fields {
row[k] = v
}
tbl[key] = row
return nil
}
func (m *memoryModel) Delete(ctx context.Context, key string, v interface{}) error {
schema, err := m.schema(v)
if err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
tbl := m.tables[schema.Table]
if _, ok := tbl[key]; !ok {
return ErrNotFound
}
delete(tbl, key)
return nil
}
func (m *memoryModel) List(ctx context.Context, result interface{}, opts ...QueryOption) error {
// result must be *[]*T
rv := reflect.ValueOf(result)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Slice {
return fmt.Errorf("model: result must be a pointer to a slice")
}
sliceVal := rv.Elem()
elemType := sliceVal.Type().Elem() // *T
structType := elemType
if structType.Kind() == reflect.Pointer {
structType = structType.Elem()
}
m.mu.RLock()
s, ok := m.types[structType]
m.mu.RUnlock()
if !ok {
return ErrNotRegistered
}
q := ApplyQueryOptions(opts...)
m.mu.RLock()
tbl := m.tables[s.Table]
var rows []map[string]any
for _, row := range tbl {
if matchFilters(row, q.Filters) {
cp := make(map[string]any, len(row))
for k, v := range row {
cp[k] = v
}
rows = append(rows, cp)
}
}
m.mu.RUnlock()
if q.OrderBy != "" {
sortRows(rows, q.OrderBy, q.Desc)
}
if q.Offset > 0 && uint(len(rows)) > q.Offset {
rows = rows[q.Offset:]
} else if q.Offset > 0 {
rows = nil
}
if q.Limit > 0 && uint(len(rows)) > q.Limit {
rows = rows[:q.Limit]
}
results := reflect.MakeSlice(sliceVal.Type(), len(rows), len(rows))
for i, row := range rows {
vp := reflect.New(structType)
MapToStruct(s, row, vp.Interface())
if elemType.Kind() == reflect.Pointer {
results.Index(i).Set(vp)
} else {
results.Index(i).Set(vp.Elem())
}
}
sliceVal.Set(results)
return nil
}
func (m *memoryModel) Count(ctx context.Context, v interface{}, opts ...QueryOption) (int64, error) {
schema, err := m.schema(v)
if err != nil {
return 0, err
}
q := ApplyQueryOptions(opts...)
m.mu.RLock()
defer m.mu.RUnlock()
tbl := m.tables[schema.Table]
var count int64
for _, row := range tbl {
if matchFilters(row, q.Filters) {
count++
}
}
return count, nil
}
func (m *memoryModel) Close() error {
return nil
}
func (m *memoryModel) String() string {
return "memory"
}
// matchFilters returns true if the row satisfies all filters.
func matchFilters(row map[string]any, filters []Filter) bool {
for _, f := range filters {
val, ok := row[f.Field]
if !ok {
return false
}
if !compareValues(val, f.Op, f.Value) {
return false
}
}
return true
}
// compareValues compares two values with the given operator.
func compareValues(a any, op string, b any) bool {
switch op {
case "=":
return fmt.Sprint(a) == fmt.Sprint(b)
case "!=":
return fmt.Sprint(a) != fmt.Sprint(b)
case "LIKE":
pattern := fmt.Sprint(b)
val := fmt.Sprint(a)
if strings.HasPrefix(pattern, "%") && strings.HasSuffix(pattern, "%") {
return strings.Contains(val, pattern[1:len(pattern)-1])
}
if strings.HasPrefix(pattern, "%") {
return strings.HasSuffix(val, pattern[1:])
}
if strings.HasSuffix(pattern, "%") {
return strings.HasPrefix(val, pattern[:len(pattern)-1])
}
return val == pattern
case "<", ">", "<=", ">=":
return compareNumeric(a, op, b)
default:
return false
}
}
func compareNumeric(a any, op string, b any) bool {
af, aOk := toFloat64(a)
bf, bOk := toFloat64(b)
if !aOk || !bOk {
as, bs := fmt.Sprint(a), fmt.Sprint(b)
switch op {
case "<":
return as < bs
case ">":
return as > bs
case "<=":
return as <= bs
case ">=":
return as >= bs
}
return false
}
switch op {
case "<":
return af < bf
case ">":
return af > bf
case "<=":
return af <= bf
case ">=":
return af >= bf
}
return false
}
func toFloat64(v any) (float64, bool) {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(rv.Int()), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(rv.Uint()), true
case reflect.Float32, reflect.Float64:
return rv.Float(), true
default:
return 0, false
}
}
func sortRows(rows []map[string]any, field string, desc bool) {
for i := 1; i < len(rows); i++ {
for j := i; j > 0; j-- {
a := fmt.Sprint(rows[j-1][field])
b := fmt.Sprint(rows[j][field])
shouldSwap := a > b
if desc {
shouldSwap = a < b
}
if shouldSwap {
rows[j-1], rows[j] = rows[j], rows[j-1]
}
}
}
}