-
Notifications
You must be signed in to change notification settings - Fork 34
/
simd.go
317 lines (288 loc) · 8.35 KB
/
simd.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
306
307
308
309
310
311
312
313
314
315
316
317
//Package db A simple library to persist structs in json file and perform queries and CRUD operations
package simdb
import (
"encoding/json"
"errors"
"fmt"
"sync"
)
var ErrRecordNotFound = errors.New("record not found")
var ErrUpdateFailed = errors.New("update failed, no record(s) to update")
//Entity any structure wanted to persist to json db should implement this interface function ID().
//ID and Field will be used while doing update and delete operation.
//ID() return the id value and field name that stores the id
//
//Sample Struct
// type Customer struct {
// CustID string `json:"custid"`
// Name string `json:"name"`
// Address string `json:"address"`
// Contact Contact
// }
// type Contact struct {
// Phone string `json:"phone"`
// Email string `json:"email"`
// }
// func (c Customer) ID() (jsonField string, value interface{}) {
// value=c.CustID
// jsonField="custid"
// return
// }
type Entity interface {
ID() (jsonField string, value interface{})
}
// empty represents an empty result
var empty interface{}
// query describes a query
type query struct {
key, operator string
value interface{}
}
//Driver contains all the state of the db.
type Driver struct {
dir string //directory name to store the db
queries [][]query // nested queries
queryIndex int
queryMap map[string]QueryFunc // contains query functions
jsonContent interface{} // copy of original decoded json data for further processing
errors []error // contains all the errors when processing
originalJSON interface{} // actual json when opening the json file
isOpened bool
entityDealingWith interface{} // keeps the entity the driver is dealing with, field will maintain only the last entity inserted or updated or opened
mutex *sync.Mutex
}
//New creates a new database driver. Accepts the directory name to store the db files.
//If the passed directory not exist then will create one.
// driver, err:=db.New("customer")
func New(dir string) (*Driver, error) {
driver := &Driver{
dir: dir,
queryMap: loadDefaultQueryMap(),
mutex: &sync.Mutex{},
}
err := createDirIfNotExist(dir)
return driver, err
}
//Open will open the json db based on the entity passed.
//Once the file is open you can apply where conditions or get operation.
// driver.Open(Customer{})
//Open returns a pointer to Driver, so you can chain methods like Where(), Get(), etc
func (d *Driver) Open(entity Entity) *Driver {
d.queries = nil
d.entityDealingWith = entity
db, err := d.openDB(entity)
d.originalJSON = db
d.jsonContent = d.originalJSON
d.isOpened = true
if err != nil {
d.addError(err)
}
return d
}
//Errors will return errors encountered while performing any operations
func (d *Driver) Errors() []error {
return d.errors
}
//Insert the entity to the json db. Insert will identify the type of the
//entity and insert the entity to the specific json file based on the type of the entity.
//If the db file not exist then will create a new db file
//
// customer:=Customer {
// CustID:"CUST1",
// Name:"sarouje",
// Address: "address",
// Contact: Contact {
// Phone:"45533355",
// Email:"[email protected]",
// },
// }
// err:=driver.Insert(customer)
func (d *Driver) Insert(entity Entity) (err error) {
d.mutex.Lock()
defer d.mutex.Unlock()
d.entityDealingWith = entity
err = d.readAppend(entity)
return
}
//Where builds a where clause to filter the records.
//
// driver.Open(Customer{}).Where("custid","=","CUST1")
func (d *Driver) Where(key, cond string, val interface{}) *Driver {
q := query{
key: key,
operator: cond,
value: val,
}
if d.queryIndex == 0 && len(d.queries) == 0 {
qq := []query{}
qq = append(qq, q)
d.queries = append(d.queries, qq)
} else {
d.queries[d.queryIndex] = append(d.queries[d.queryIndex], q)
}
return d
}
//Get the result from the json db as an array. If no where condition then return all the data from json db
//
//Get based on a where condition
// driver.Open(Customer{}).Where("name","=","sarouje").Get()
//Get all records
// driver.Open(Customer{}).Get()
func (d *Driver) Get() *Driver {
if !d.isDBOpened() {
return d
}
if len(d.queries) > 0 {
d.processQuery()
} else {
d.jsonContent = d.originalJSON
}
d.queryIndex = 0
return d
}
//First return the first record matching the condtion.
// driver.Open(Customer{}).Where("custid","=","CUST1").First()
func (d *Driver) First() *Driver {
if !d.isDBOpened() {
return d
}
records := d.Get().RawArray()
if len(records) > 0 {
d.jsonContent = records[0]
} else {
d.addError(fmt.Errorf("no records to perform First operation"))
}
return d
}
//Raw will return the data in map type
func (d *Driver) Raw() interface{} {
return d.jsonContent
}
//RawArray will return the data in map array type
func (d *Driver) RawArray() []interface{} {
if aa, ok := d.jsonContent.([]interface{}); ok {
return aa
}
return nil
}
//AsEntity will converts the map to the passed structure pointer.
//should call this function after calling Get() or First(). This function will convert
//the result of Get or First operation to the passed structure type
//'output' variable should be a pointer to a structure or stucture array. Function returns error in case
//of any errors in conversion.
//
//First()
// var custOut Customer
// err:=driver.Open(Customer{}).First().AsEntity(&custOut)
// fmt.Printf("%#v", custOut)
// this function will fill the custOut with the values from the map
//
//Get()
// var customers []Customer
// err:=driver.Open(Customer{}).Get().AsEntity(&customers)
func (d *Driver) AsEntity(output interface{}) (err error) {
if !d.isDBOpened() {
return fmt.Errorf("should call Open() before calling AsEntity()")
}
switch t := d.jsonContent.(type) {
case []interface{}:
if len(t) <= 0 {
return ErrRecordNotFound
}
case interface{}:
if t == nil {
return ErrRecordNotFound
}
}
outByte, err := json.Marshal(d.jsonContent)
if err != nil {
return err
}
err = json.Unmarshal(outByte, output)
return
}
//Update the json data based on the id field/value pair
// customerToUpdate:=driver.Open(Customer{}).Where("custid","=","CUST1").First()
// customerToUpdate.Name="Sony Arouje"
// err:=driver.Update(customerToUpdate)
//Should not change the ID field when updating the record.
func (d *Driver) Update(entity Entity) (err error) {
d.queries = nil
d.entityDealingWith = entity
field, entityID := entity.ID()
couldUpdate := false
// entName, _ := d.getEntityName()
d.mutex.Lock()
defer d.mutex.Unlock()
records := d.Open(entity).Get().RawArray()
if len(records) > 0 {
for indx, item := range records {
if record, ok := item.(map[string]interface{}); ok {
if v, ok := record[field]; ok && fmt.Sprintf("%v", v) == fmt.Sprintf("%v", entityID) {
records[indx] = entity
couldUpdate = true
}
}
}
}
if couldUpdate {
err = d.writeAll(records)
} else {
err = ErrUpdateFailed
}
return
}
// Upsert function will try updating the passed entity. If no records to update then
// do the Insert operation.
//
// customer := Customer{
// CustID: "CU4",
// Name: "Sony Arouje",
// Address: "address",
// Contact: Contact{
// Phone: "45533355",
// Email: "[email protected]",
// },
// }
// driver.Upsert(customer)
func (d *Driver) Upsert(entity Entity) (err error) {
err = d.Update(entity)
if errors.Is(err, ErrUpdateFailed) {
err = d.Insert(entity)
}
return
}
//Delete the record from the json db based on the id field/value pair
// custToDelete:=Customer {
// CustID:"CUST1",
// }
// err:=driver.Delete(custToDelete)
func (d *Driver) Delete(entity Entity) (err error) {
d.queries = nil
d.entityDealingWith = entity
field, entityID := entity.ID()
entName, _ := d.getEntityName()
couldDelete := false
newRecordArray := make([]interface{}, 0, 0)
d.mutex.Lock()
defer d.mutex.Unlock()
records := d.Open(entity).Get().RawArray()
if len(records) > 0 {
for indx, item := range records {
if record, ok := item.(map[string]interface{}); ok {
if v, ok := record[field]; ok && v != entityID {
records[indx] = entity
newRecordArray = append(newRecordArray, record)
} else {
couldDelete = true
}
}
}
}
if couldDelete {
err = d.writeAll(newRecordArray)
} else {
err = fmt.Errorf("failed to delete, unable to find any %s record with %s %s", entName, field, entityID)
}
return
}