-
Notifications
You must be signed in to change notification settings - Fork 2
/
document.go
693 lines (637 loc) · 17.9 KB
/
document.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
package myjson
import (
"encoding/json"
"fmt"
"io"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/autom8ter/myjson/errors"
"github.com/autom8ter/myjson/util"
"github.com/huandu/xstrings"
flat2 "github.com/nqd/flat"
"github.com/samber/lo"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
func init() {
for k, v := range modifiers {
gjson.AddModifier(k, v)
}
}
var modifiers = map[string]func(json, arg string) string{
"snakeCase": func(json, arg string) string {
return xstrings.ToSnakeCase(json)
},
"camelCase": func(json, arg string) string {
return xstrings.ToCamelCase(json)
},
"kebabCase": func(json, arg string) string {
return xstrings.ToKebabCase(json)
},
"upper": func(json, arg string) string {
return strings.ToUpper(json)
},
"lower": func(json, arg string) string {
return strings.ToLower(json)
},
"replaceAll": func(json, arg string) string {
args := gjson.Parse(arg)
return strings.ReplaceAll(json, args.Get("old").String(), args.Get("new").String())
},
"trim": func(json, arg string) string {
return strings.ReplaceAll(json, " ", "")
},
"dateTrunc": func(json, arg string) string {
json, _ = strconv.Unquote(json)
t := cast.ToTime(json)
yr, month, day := t.Date()
switch arg {
case "month":
return strconv.Quote(time.Date(yr, month, 1, 0, 0, 0, 0, time.UTC).String())
case "day":
return strconv.Quote(time.Date(yr, month, day, 0, 0, 0, 0, time.UTC).String())
case "year":
return strconv.Quote(time.Date(yr, time.January, 1, 0, 0, 0, 0, time.UTC).String())
default:
return json
}
},
"unix": func(json, arg string) string {
json, _ = strconv.Unquote(json)
t := cast.ToTime(json)
if t.IsZero() {
return json
}
return strconv.Quote(fmt.Sprint(t.Unix()))
},
"unixMilli": func(json, arg string) string {
json, _ = strconv.Unquote(json)
t := cast.ToTime(json)
if t.IsZero() {
return json
}
return strconv.Quote(fmt.Sprint(t.UnixMilli()))
},
"unixNano": func(json, arg string) string {
json, _ = strconv.Unquote(json)
t := cast.ToTime(json)
if t.IsZero() {
return json
}
return strconv.Quote(fmt.Sprint(t.UnixNano()))
},
}
const selfRefPrefix = "$"
// Document is a concurrency safe JSON document
type Document struct {
result gjson.Result
mu sync.RWMutex
}
// UnmarshalJSON satisfies the json Unmarshaler interface
func (d *Document) UnmarshalJSON(bytes []byte) error {
d.mu.Lock()
defer d.mu.Unlock()
doc, err := NewDocumentFromBytes(bytes)
if err != nil {
return err
}
d.result = doc.result
return nil
}
// MarshalJSON satisfies the json Marshaler interface
func (d *Document) MarshalJSON() ([]byte, error) {
d.mu.RLock()
defer d.mu.RUnlock()
return d.Bytes(), nil
}
// NewDocument creates a new json document
func NewDocument() *Document {
parsed := gjson.Parse("{}")
return &Document{
result: parsed,
mu: sync.RWMutex{},
}
}
// NewDocumentFromBytes creates a new document from the given json bytes
func NewDocumentFromBytes(json []byte) (*Document, error) {
if !gjson.ValidBytes(json) {
return nil, errors.New(errors.Validation, "invalid json: %s", string(json))
}
d := &Document{
result: gjson.ParseBytes(json),
mu: sync.RWMutex{},
}
if !d.Valid() {
return nil, errors.New(errors.Validation, "invalid document")
}
return d, nil
}
// NewDocumentFrom creates a new document from the given value - the value must be json compatible
func NewDocumentFrom(value any) (*Document, error) {
var err error
bits, err := json.Marshal(value)
if err != nil {
return nil, errors.New(errors.Validation, "failed to json encode value: %#v", value)
}
return NewDocumentFromBytes(bits)
}
// Valid returns whether the document is valid
func (d *Document) Valid() bool {
d.mu.RLock()
defer d.mu.RUnlock()
return gjson.ValidBytes(d.Bytes()) && !d.result.IsArray()
}
// String returns the document as a json string
func (d *Document) String() string {
d.mu.RLock()
defer d.mu.RUnlock()
return d.result.String()
}
// Bytes returns the document as json bytes
func (d *Document) Bytes() []byte {
d.mu.RLock()
defer d.mu.RUnlock()
return []byte(d.result.Raw)
}
// Value returns the document as a map
func (d *Document) Value() map[string]any {
d.mu.RLock()
defer d.mu.RUnlock()
return cast.ToStringMap(d.result.Value())
}
// Clone allocates a new document with identical values
func (d *Document) Clone() *Document {
d.mu.RLock()
defer d.mu.RUnlock()
raw := d.result.Raw
return &Document{result: gjson.Parse(raw)}
}
// Get gets a field on the document. Get has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) Get(field string) any {
d.mu.RLock()
defer d.mu.RUnlock()
if d.result.Get(field).Exists() {
return d.result.Get(field).Value()
}
return nil
}
// GetString gets a string field value on the document. GetString has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetString(field string) string {
return cast.ToString(d.Get(field))
}
// Exists returns true if the fieldPath has a value in the json document. Exists has GJSON syntax support
// // For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) Exists(field string) bool {
d.mu.RLock()
defer d.mu.RUnlock()
return d.result.Get(field).Exists()
}
// GetBool gets a bool field value on the document. GetBool has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetBool(field string) bool {
return cast.ToBool(d.Get(field))
}
// GetFloat gets a float64 field value on the document. GetFloat has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetFloat(field string) float64 {
return cast.ToFloat64(d.Get(field))
}
// GetInt gets an int field value on the document. GetInt has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetInt(field string) int {
return cast.ToInt(d.Get(field))
}
// GetTime gets a time.Time field value on the document. GetTime has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetTime(field string) time.Time {
return cast.ToTime(d.GetString(field))
}
// GetArray gets an array field on the document. Get has GJSON syntax support
// For information on gjson syntax, check out https://github.com/tidwall/gjson/blob/master/SYNTAX.md
func (d *Document) GetArray(field string) []any {
return cast.ToSlice(d.Get(field))
}
// Set sets a field on the document. Set has SJSON syntax support (dot notation)
// For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (d *Document) Set(field string, val any) error {
return d.SetAll(map[string]any{
field: val,
})
}
var setOpts = &sjson.Options{
Optimistic: true,
ReplaceInPlace: true,
}
func (d *Document) set(field string, val any) error {
var (
result []byte
err error
)
switch val := val.(type) {
case gjson.Result:
result, err = sjson.SetBytesOptions([]byte(d.result.Raw), field, val.Value(), setOpts)
case []byte:
result, err = sjson.SetRawBytesOptions([]byte(d.result.Raw), field, val, setOpts)
default:
result, err = sjson.SetBytesOptions([]byte(d.result.Raw), field, val, setOpts)
}
if err != nil {
return err
}
if d.result.Raw != string(result) {
d.result = gjson.ParseBytes(result)
}
return nil
}
// SetAll sets all fields on the document. SJSON systax is supported
// For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (d *Document) SetAll(values map[string]any) error {
d.mu.Lock()
defer d.mu.Unlock()
var err error
for k, v := range values {
err = d.set(k, v)
if err != nil {
return err
}
}
return nil
}
// Overwrite resets the document with the given values. SJSON systax is supported
// For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (d *Document) Overwrite(values map[string]any) error {
d.mu.Lock()
defer d.mu.Unlock()
nd := NewDocument()
for k, v := range values {
if err := nd.Set(k, v); err != nil {
return err
}
}
d.result = nd.result
return nil
}
// Merge merges the document with the provided document.
func (d *Document) Merge(with *Document) error {
if !with.Valid() {
return errors.New(errors.Validation, "invalid document")
}
withMap := with.Value()
flattened, err := flat2.Flatten(withMap, nil)
if err != nil {
return err
}
return d.SetAll(flattened)
}
// MergeJoin merges the document with the input document with each key from the input document prefixed with the given alias
func (d *Document) MergeJoin(with *Document, alias string) error {
if !with.Valid() {
return errors.New(errors.Validation, "invalid document")
}
withMap := with.Value()
flattened, err := flat2.Flatten(withMap, nil)
if err != nil {
return err
}
for k, v := range flattened {
if err := d.Set(fmt.Sprintf("%s.%s", alias, k), v); err != nil {
return err
}
}
return nil
}
// Del deletes a field from the document. SJSON systax is supported
// For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (d *Document) Del(field string) error {
return d.DelAll(field)
}
// DelAll deletes a field from the document. SJSON systax is supported
// For information on sjson syntax, check out https://github.com/tidwall/sjson#path-syntax
func (d *Document) DelAll(fields ...string) error {
d.mu.Lock()
defer d.mu.Unlock()
for _, field := range fields {
result, err := sjson.Delete(d.result.Raw, field)
if err != nil {
return err
}
d.result = gjson.Parse(result)
}
return nil
}
// Where executes the where clauses against the document and returns true if it passes the clauses.
// If the value of a where clause is prefixed with $. it will compare where.field to the same document's $.{field}.
func (d *Document) Where(wheres []Where) (bool, error) {
d.mu.RLock()
defer d.mu.RUnlock()
for _, w := range wheres {
var (
isSelf = strings.HasPrefix(cast.ToString(w.Value), selfRefPrefix)
selfField = strings.TrimPrefix(cast.ToString(w.Value), selfRefPrefix)
)
switch w.Op {
case WhereOpEq:
if isSelf {
if d.Get(w.Field) != d.Get(selfField) || w.Value == "null" && d.Get(selfField) != nil {
return false, nil
}
} else {
if w.Value != d.Get(w.Field) || w.Value == "null" && d.Get(w.Field) != nil {
return false, nil
}
}
case WhereOpNeq:
if isSelf {
if d.Get(w.Field) == d.Get(selfField) || w.Value == "null" && d.Get(selfField) == nil {
return false, nil
}
} else {
if w.Value == d.Get(w.Field) || w.Value == "null" && d.Get(w.Field) == nil {
return false, nil
}
}
case WhereOpLt:
if isSelf {
if d.GetFloat(w.Field) >= d.GetFloat(selfField) {
return false, nil
}
} else {
if d.GetFloat(w.Field) >= cast.ToFloat64(w.Value) {
return false, nil
}
}
case WhereOpLte:
if isSelf {
if d.GetFloat(w.Field) > d.GetFloat(selfField) {
return false, nil
}
} else {
if d.GetFloat(w.Field) > cast.ToFloat64(w.Value) {
return false, nil
}
}
case WhereOpGt:
if isSelf {
if d.GetFloat(w.Field) <= d.GetFloat(selfField) {
return false, nil
}
} else {
if d.GetFloat(w.Field) <= cast.ToFloat64(w.Value) {
return false, nil
}
}
case WhereOpGte:
if isSelf {
if d.GetFloat(w.Field) < d.GetFloat(selfField) {
return false, nil
}
} else {
if d.GetFloat(w.Field) < cast.ToFloat64(w.Value) {
return false, nil
}
}
case WhereOpIn:
bits, _ := json.Marshal(w.Value)
arr := gjson.ParseBytes(bits).Array()
value := d.Get(w.Field)
match := false
for _, element := range arr {
if element.Value() == value {
match = true
}
}
if !match {
return false, nil
}
case WhereOpContains:
fieldVal := d.Get(w.Field)
switch fieldVal := fieldVal.(type) {
case []bool:
if !lo.Contains(fieldVal, cast.ToBool(w.Value)) {
return false, nil
}
case []float64:
if !lo.Contains(fieldVal, cast.ToFloat64(w.Value)) {
return false, nil
}
case []string:
if !lo.Contains(fieldVal, cast.ToString(w.Value)) {
return false, nil
}
case string:
if !strings.Contains(fieldVal, cast.ToString(w.Value)) {
return false, nil
}
default:
if !strings.Contains(util.JSONString(fieldVal), util.JSONString(w.Value)) {
return false, nil
}
}
case WhereOpContainsAll:
fieldVal := cast.ToStringSlice(d.Get(w.Field))
for _, v := range cast.ToStringSlice(w.Value) {
if !lo.Contains(fieldVal, v) {
return false, nil
}
}
case WhereOpContainsAny:
fieldVal := cast.ToStringSlice(d.Get(w.Field))
for _, v := range cast.ToStringSlice(w.Value) {
if lo.Contains(fieldVal, v) {
return true, nil
}
}
case WhereOpHasPrefix:
fieldVal := d.GetString(w.Field)
if !strings.HasPrefix(fieldVal, cast.ToString(w.Value)) {
return false, nil
}
case WhereOpHasSuffix:
fieldVal := d.GetString(w.Field)
if !strings.HasSuffix(fieldVal, cast.ToString(w.Value)) {
return false, nil
}
case WhereOpRegex:
fieldVal := d.Get(w.Field)
match, _ := regexp.Match(cast.ToString(w.Value), []byte(cast.ToString(fieldVal)))
if !match {
return false, nil
}
default:
return false, errors.New(errors.Validation, "unsupported operator: %s", w.Op)
}
}
return true, nil
}
// Diff calculates a json diff between the document and the input document
func (d *Document) Diff(before *Document) []JSONFieldOp {
if before != nil && before.String() == d.String() {
return []JSONFieldOp{}
}
var ops []JSONFieldOp
if before == nil {
before = NewDocument()
}
var (
beforePaths = before.FieldPaths()
afterPaths = d.FieldPaths()
)
for _, path := range beforePaths {
exists := d.result.Get(path).Exists()
switch {
case !exists:
ops = append(ops, JSONFieldOp{
Path: path,
Op: JSONOpRemove,
Value: nil,
BeforeValue: before.Get(path),
})
case exists && !reflect.DeepEqual(d.Get(path), before.Get(path)):
ops = append(ops, JSONFieldOp{
Path: path,
Op: JSONOpReplace,
Value: d.Get(path),
BeforeValue: before.Get(path),
})
}
}
for _, path := range afterPaths {
exists := before.result.Get(path).Exists()
switch {
case !exists:
ops = append(ops, JSONFieldOp{
Path: path,
Op: JSONOpAdd,
Value: d.Get(path),
BeforeValue: nil,
})
}
}
if ops == nil {
return []JSONFieldOp{}
}
return ops
}
// ApplyOps applies the given JSON field operations to the document
func (d *Document) ApplyOps(ops []JSONFieldOp) error {
for _, op := range ops {
switch op.Op {
case JSONOpRemove:
if err := d.Del(op.Path); err != nil {
return err
}
case JSONOpReplace, JSONOpAdd:
if err := d.Set(op.Path, op.Value); err != nil {
return err
}
default:
return errors.New(errors.Validation, "unsupported op: %s", op.Op)
}
}
return nil
}
// RevertOps reverts the given JSON field operations to the document
func (d *Document) RevertOps(diff []JSONFieldOp) error {
for _, op := range diff {
if op.BeforeValue != nil {
if err := d.Set(op.Path, op.BeforeValue); err != nil {
return err
}
}
}
return nil
}
// FieldPaths returns the paths to fields & nested fields in dot notation format
func (d *Document) FieldPaths() []string {
d.mu.RLock()
defer d.mu.RUnlock()
paths := &[]string{}
d.paths(d.result, paths)
return *paths
}
func (d *Document) paths(result gjson.Result, pathValues *[]string) {
result.ForEach(func(key, value gjson.Result) bool {
if value.IsObject() {
d.paths(value, pathValues)
} else {
*pathValues = append(*pathValues, value.Path(d.result.Raw))
}
return true
})
}
// Scan scans the json document into the value
func (d *Document) Scan(value any) error {
return util.Decode(d.Value(), &value)
}
// Encode encodes the json document to the io writer
func (d *Document) Encode(w io.Writer) error {
_, err := w.Write(d.Bytes())
if err != nil {
return errors.Wrap(err, 0, "failed to encode document")
}
return nil
}
// Documents is an array of documents
type Documents []*Document
// Slice slices the documents into a subarray of documents
func (documents Documents) Slice(start, end int) Documents {
return lo.Slice[*Document](documents, start, end)
}
// Filter applies the filter function against the documents
func (documents Documents) Filter(predicate func(document *Document, i int) bool) Documents {
return lo.Filter[*Document](documents, predicate)
}
// Map applies the mapper function against the documents
func (documents Documents) Map(mapper func(t *Document, i int) *Document) Documents {
return lo.Map[*Document, *Document](documents, mapper)
}
// ForEach applies the function to each document in the documents
func (documents Documents) ForEach(fn func(next *Document, i int)) {
lo.ForEach[*Document](documents, fn)
}
// DocBuilder is a builder for creating a document
type DocBuilder struct {
doc *Document
err error
}
// D creates a new document builder
func D() *DocBuilder {
return &DocBuilder{
doc: NewDocument(),
}
}
// From creates a new document builder from the input document
func (b *DocBuilder) From(d *Document) *DocBuilder {
if b.err != nil {
return b
}
if err := b.doc.Overwrite(d.Value()); err != nil {
b.err = err
}
return b
}
// DocBuilder sets the key value pairs on the document
func (b *DocBuilder) Set(values map[string]any) *DocBuilder {
if b.err != nil {
return b
}
if err := b.doc.SetAll(values); err != nil {
b.err = err
}
return b
}
// Doc returns the document
func (b *DocBuilder) Doc() *Document {
return b.doc
}
// Err returns an error if one exists
func (b *DocBuilder) Err() error {
return b.err
}