-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
json.go
2481 lines (2225 loc) · 74 KB
/
json.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package json
import (
"bytes"
"encoding/json"
"fmt"
"math/big"
"reflect"
"sort"
"strconv"
"strings"
"unicode/utf8"
"unsafe"
"github.com/cockroachdb/apd/v2"
"github.com/cockroachdb/cockroach/pkg/geo"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/inverted"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
uniq "github.com/cockroachdb/cockroach/pkg/util/unique"
"github.com/cockroachdb/errors"
)
// Type represents a JSON type.
type Type int
// This enum defines the ordering of types. It should not be reordered.
const (
_ Type = iota
NullJSONType
StringJSONType
NumberJSONType
FalseJSONType
TrueJSONType
ArrayJSONType
ObjectJSONType
)
const (
wordSize = unsafe.Sizeof(big.Word(0))
decimalSize = unsafe.Sizeof(apd.Decimal{})
stringHeaderSize = unsafe.Sizeof(reflect.StringHeader{})
sliceHeaderSize = unsafe.Sizeof(reflect.SliceHeader{})
keyValuePairSize = unsafe.Sizeof(jsonKeyValuePair{})
jsonInterfaceSize = unsafe.Sizeof((JSON)(nil))
)
const (
msgModifyAfterBuild = "modify after Build()"
)
// JSON represents a JSON value.
type JSON interface {
fmt.Stringer
Compare(JSON) (int, error)
// Type returns the JSON type.
Type() Type
// Format writes out the JSON document to the specified buffer.
Format(buf *bytes.Buffer)
// Size returns the size of the JSON document in bytes.
Size() uintptr
// encodeInvertedIndexKeys takes in a key prefix and returns a slice of
// inverted index keys, one per path through the receiver.
encodeInvertedIndexKeys(b []byte) ([][]byte, error)
// encodeContainingInvertedIndexSpans takes in a key prefix and returns the
// spans that must be scanned in the inverted index to evaluate a contains (@>)
// predicate with the given JSON (i.e., find the objects in the index that
// contain the given JSON).
//
// The spans are returned in an inverted.SpanExpression, which represents the
// set operations that must be applied on the spans read during execution. See
// comments in the SpanExpression definition for details.
//
// If isRoot is true, this function is being called at the root level of the
// JSON hierarchy. If isObjectValue is true, the given JSON is the value of a
// JSON object key. Note that isRoot and isObjectValue cannot both be true at
// the same time.
encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (invertedExpr inverted.Expression, err error)
// encodeContainedInvertedIndexSpans takes in a key prefix and returns the
// spans that must be scanned in the inverted index to evaluate a contained
// by (<@) predicate with the given JSON (i.e., find the objects in the index
// that are contained by the given JSON).
//
// The spans are returned in an inverted.SpanExpression, which represents the
// set operations that must be applied on the spans read during execution. See
// comments in the SpanExpression definition for details.
//
// If isRoot is true, this function is being called at the root level of the
// JSON hierarchy.
encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (invertedExpr inverted.Expression, err error)
// numInvertedIndexEntries returns the number of entries that will be
// produced if this JSON gets included in an inverted index.
numInvertedIndexEntries() (int, error)
// allPaths returns a slice of new JSON documents, each a path to a leaf
// through the receiver. Note that leaves include the empty object and array
// in addition to scalars.
allPaths() ([]JSON, error)
// FetchValKey implements the `->` operator for strings, returning nil if the
// key is not found.
FetchValKey(key string) (JSON, error)
// FetchValIdx implements the `->` operator for ints, returning nil if the
// key is not found.
FetchValIdx(idx int) (JSON, error)
// FetchValKeyOrIdx is used for path access, if obj is an object, it tries to
// access the given field. If it's an array, it interprets the key as an int
// and tries to access the given index.
FetchValKeyOrIdx(key string) (JSON, error)
// RemoveString implements the `-` operator for strings, returning JSON after removal,
// whether removal is valid and error message.
RemoveString(s string) (JSON, bool, error)
// RemoveIndex implements the `-` operator for ints, returning JSON after removal,
// whether removal is valid and error message.
RemoveIndex(idx int) (JSON, bool, error)
// RemovePath and doRemovePath implement the `#-` operator for strings, returning JSON after removal,
// whether removal is valid and error message.
RemovePath(path []string) (JSON, bool, error)
doRemovePath(path []string) (JSON, bool, error)
// Concat implements the `||` operator.
Concat(other JSON) (JSON, error)
// AsText returns the JSON document as a string, with quotes around strings removed, and null as nil.
AsText() (*string, error)
// AsDecimal returns the JSON document as a apd.Decimal if it is a numeric
// type, and a boolean inidicating if this JSON document is a numeric type.
AsDecimal() (*apd.Decimal, bool)
// Exists implements the `?` operator: does the string exist as a top-level
// key within the JSON value?
//
// If the object is a JSON array, returns true when the key is a top-level
// element of the array.
Exists(string) (bool, error)
// StripNulls returns the JSON document with all object fields that have null values omitted
// and whether it needs to strip nulls. Stripping nulls is needed only if it contains some
// object fields having null values.
StripNulls() (JSON, bool, error)
// ObjectIter returns an *ObjectKeyIterator, nil if json is not an object.
ObjectIter() (*ObjectIterator, error)
// isScalar returns whether the JSON document is null, true, false, a string,
// or a number.
isScalar() bool
// preprocessForContains converts a JSON document to an internal interface
// which is used to efficiently implement the @> operator.
preprocessForContains() (containsable, error)
// encode appends the encoding of the JSON document to appendTo, returning
// the result alongside the JEntry for the document. Note that some values
// (true/false/null) are encoded with 0 bytes and are purely defined by their
// JEntry.
encode(appendTo []byte) (jEntry jEntry, b []byte, err error)
// MaybeDecode returns an equivalent JSON which is not a jsonEncoded.
MaybeDecode() JSON
// toGoRepr returns the Go-style representation of this JSON value
// (map[string]interface{} for objects, etc.).
toGoRepr() (interface{}, error)
// tryDecode returns an equivalent JSON which is not a jsonEncoded, returning
// an error if the encoded data was corrupt.
tryDecode() (JSON, error)
// Len returns the number of outermost elements in the JSON document if it is an object or an array.
// Otherwise, Len returns 0.
Len() int
// HasContainerLeaf returns whether this document contains in it somewhere
// either the empty array or the empty object.
HasContainerLeaf() (bool, error)
}
type jsonTrue struct{}
// TrueJSONValue is JSON `true`
var TrueJSONValue = jsonTrue{}
type jsonFalse struct{}
// FalseJSONValue is JSON `false`
var FalseJSONValue = jsonFalse{}
type jsonNull struct{}
// NullJSONValue is JSON `null`
var NullJSONValue = jsonNull{}
type jsonNumber apd.Decimal
type jsonString string
type jsonArray []JSON
type jsonKeyValuePair struct {
k jsonString
v JSON
}
// ArrayBuilder builds JSON Array by a JSON sequence.
type ArrayBuilder struct {
jsons []JSON
}
// NewArrayBuilder returns an ArrayBuilder. The builder will reserve spaces
// based on hint about number of adds to reduce times of growing capacity.
func NewArrayBuilder(numAddsHint int) *ArrayBuilder {
return &ArrayBuilder{
jsons: make([]JSON, 0, numAddsHint),
}
}
// Add appends JSON to the sequence.
func (b *ArrayBuilder) Add(j JSON) {
b.jsons = append(b.jsons, j)
}
// Build returns the constructed JSON array. A caller may not modify the array,
// and the ArrayBuilder reserves the right to re-use the array returned (though
// the data will not be modified). This is important in the case of a window
// function, which might want to incrementally update an aggregation.
func (b *ArrayBuilder) Build() JSON {
return jsonArray(b.jsons)
}
// ArrayBuilderWithCounter builds JSON Array by a JSON sequence with a size counter.
type ArrayBuilderWithCounter struct {
ab *ArrayBuilder
size uintptr
}
// NewArrayBuilderWithCounter returns an ArrayBuilderWithCounter.
func NewArrayBuilderWithCounter() *ArrayBuilderWithCounter {
return &ArrayBuilderWithCounter{
ab: NewArrayBuilder(0),
size: sliceHeaderSize,
}
}
// Add appends JSON to the sequence and updates the size counter.
func (b *ArrayBuilderWithCounter) Add(j JSON) {
oldCap := cap(b.ab.jsons)
b.ab.Add(j)
b.size += j.Size() + (uintptr)(cap(b.ab.jsons)-oldCap)*jsonInterfaceSize
}
// Build returns a JSON array built from a JSON sequence. After that, it should
// not be modified any longer.
func (b *ArrayBuilderWithCounter) Build() JSON {
return b.ab.Build()
}
// Size returns the size in bytes of the JSON Array the builder is going to build.
func (b *ArrayBuilderWithCounter) Size() uintptr {
return b.size
}
// ObjectBuilderWithCounter builds a JSON object a key/value pair at a time, keeping the memory usage of the object.
type ObjectBuilderWithCounter struct {
ob *ObjectBuilder
size uintptr
}
// NewObjectBuilderWithCounter creates and instantiates ObjectBuilder with memory counter.
func NewObjectBuilderWithCounter() *ObjectBuilderWithCounter {
ob := NewObjectBuilder(0)
return &ObjectBuilderWithCounter{
ob: ob,
// initial memory allocation
size: unsafe.Sizeof(ob) + jsonInterfaceSize,
}
}
// Add appends key value pair to the sequence and updates
// amount of memory allocated for the overall keys and values.
func (b *ObjectBuilderWithCounter) Add(k string, v JSON) {
b.ob.Add(k, v)
// Size of added JSON + overhead of storing key/value pair + the size of the key.
b.size += v.Size() + keyValuePairSize + uintptr(len(k))
}
// Build returns a JSON object built from a key value pair sequence. After that,
// it should not be modified any longer.
func (b *ObjectBuilderWithCounter) Build() JSON {
return b.ob.Build()
}
// Size returns the size in bytes of the JSON object the builder is going to build.
func (b *ObjectBuilderWithCounter) Size() uintptr {
return b.size
}
// ObjectBuilder builds JSON Object by a key value pair sequence.
type ObjectBuilder struct {
pairs []jsonKeyValuePair
}
// NewObjectBuilder returns an ObjectBuilder. The builder will reserve spaces
// based on hint about number of adds to reduce times of growing capacity.
func NewObjectBuilder(numAddsHint int) *ObjectBuilder {
return &ObjectBuilder{
pairs: make([]jsonKeyValuePair, 0, numAddsHint),
}
}
// Add appends key value pair to the sequence.
func (b *ObjectBuilder) Add(k string, v JSON) {
if b.pairs == nil {
panic(errors.AssertionFailedf(msgModifyAfterBuild))
}
b.pairs = append(b.pairs, jsonKeyValuePair{k: jsonString(k), v: v})
}
// Build returns a JSON object built from a key value pair sequence. After that,
// it should not be modified any longer.
func (b *ObjectBuilder) Build() JSON {
if b.pairs == nil {
panic(errors.AssertionFailedf(msgModifyAfterBuild))
}
orders := make([]int, len(b.pairs))
for i := range orders {
orders[i] = i
}
sorter := pairSorter{
pairs: b.pairs,
orders: orders,
hasNonUnique: false,
}
b.pairs = nil
sort.Sort(&sorter)
sorter.unique()
return jsonObject(sorter.pairs)
}
// pairSorter sorts and uniqueifies JSON pairs. In order to keep
// the last one for pairs with the same key while sort.Sort is
// not stable, pairSorter uses []int orders to maintain order and
// bool hasNonUnique to skip unnecessary uniqueifying.
type pairSorter struct {
pairs []jsonKeyValuePair
orders []int
hasNonUnique bool
}
func (s *pairSorter) Len() int {
return len(s.pairs)
}
func (s *pairSorter) Less(i, j int) bool {
cmp := strings.Compare(string(s.pairs[i].k), string(s.pairs[j].k))
if cmp != 0 {
return cmp == -1
}
s.hasNonUnique = true
// The element with greater order has lower rank when their keys
// are same, since unique algorithm will prefer first element.
return s.orders[i] > s.orders[j]
}
func (s *pairSorter) Swap(i, j int) {
s.pairs[i], s.orders[i], s.pairs[j], s.orders[j] = s.pairs[j], s.orders[j], s.pairs[i], s.orders[i]
}
func (s *pairSorter) unique() {
// If there are any duplicate keys, then in sorted order it will have
// two pairs with rank i and i + 1 whose keys are same.
// For sorting based on comparisons, if two unique elements (pair.k, order)
// have rank i and i + 1, they have to compare once to figure out their
// relative order in the final position i and i + 1. So if there are any
// equal elements, then the sort must have compared them at some point.
if !s.hasNonUnique {
return
}
top := 0
for i := 1; i < len(s.pairs); i++ {
if s.pairs[top].k != s.pairs[i].k {
top++
if top != i {
s.pairs[top] = s.pairs[i]
}
}
}
s.pairs = s.pairs[:top+1]
}
// jsonObject represents a JSON object as a sorted-by-key list of key-value
// pairs, which are unique by key.
type jsonObject []jsonKeyValuePair
var emptyJSONObject = jsonObject(nil)
var emptyJSONArray = jsonArray(nil)
func (jsonNull) Type() Type { return NullJSONType }
func (jsonFalse) Type() Type { return FalseJSONType }
func (jsonTrue) Type() Type { return TrueJSONType }
func (jsonNumber) Type() Type { return NumberJSONType }
func (jsonString) Type() Type { return StringJSONType }
func (jsonArray) Type() Type { return ArrayJSONType }
func (jsonObject) Type() Type { return ObjectJSONType }
func (j jsonNull) MaybeDecode() JSON { return j }
func (j jsonFalse) MaybeDecode() JSON { return j }
func (j jsonTrue) MaybeDecode() JSON { return j }
func (j jsonNumber) MaybeDecode() JSON { return j }
func (j jsonString) MaybeDecode() JSON { return j }
func (j jsonArray) MaybeDecode() JSON { return j }
func (j jsonObject) MaybeDecode() JSON { return j }
func (j jsonNull) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonFalse) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonTrue) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonString) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonArray) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonObject) AsDecimal() (*apd.Decimal, bool) { return nil, false }
func (j jsonNumber) AsDecimal() (*apd.Decimal, bool) {
d := apd.Decimal(j)
return &d, true
}
func (j jsonNull) tryDecode() (JSON, error) { return j, nil }
func (j jsonFalse) tryDecode() (JSON, error) { return j, nil }
func (j jsonTrue) tryDecode() (JSON, error) { return j, nil }
func (j jsonNumber) tryDecode() (JSON, error) { return j, nil }
func (j jsonString) tryDecode() (JSON, error) { return j, nil }
func (j jsonArray) tryDecode() (JSON, error) { return j, nil }
func (j jsonObject) tryDecode() (JSON, error) { return j, nil }
func cmpJSONTypes(a Type, b Type) int {
if b > a {
return -1
}
if b < a {
return 1
}
return 0
}
func (j jsonNull) Compare(other JSON) (int, error) { return cmpJSONTypes(j.Type(), other.Type()), nil }
func (j jsonFalse) Compare(other JSON) (int, error) { return cmpJSONTypes(j.Type(), other.Type()), nil }
func (j jsonTrue) Compare(other JSON) (int, error) { return cmpJSONTypes(j.Type(), other.Type()), nil }
func decodeIfNeeded(j JSON) (JSON, error) {
if enc, ok := j.(*jsonEncoded); ok {
var err error
j, err = enc.decode()
if err != nil {
return nil, err
}
}
return j, nil
}
func (j jsonNumber) Compare(other JSON) (int, error) {
cmp := cmpJSONTypes(j.Type(), other.Type())
if cmp != 0 {
return cmp, nil
}
var err error
if other, err = decodeIfNeeded(other); err != nil {
return 0, err
}
dec := apd.Decimal(j)
o := apd.Decimal(other.(jsonNumber))
return dec.Cmp(&o), nil
}
func (j jsonString) Compare(other JSON) (int, error) {
cmp := cmpJSONTypes(j.Type(), other.Type())
if cmp != 0 {
return cmp, nil
}
// TODO(justin): we should optimize this, we don't have to decode the whole thing.
var err error
if other, err = decodeIfNeeded(other); err != nil {
return 0, err
}
o := other.(jsonString)
if o > j {
return -1, nil
}
if o < j {
return 1, nil
}
return 0, nil
}
func (j jsonArray) Compare(other JSON) (int, error) {
cmp := cmpJSONTypes(j.Type(), other.Type())
if cmp != 0 {
return cmp, nil
}
lenJ := j.Len()
lenO := other.Len()
if lenJ < lenO {
return -1, nil
}
if lenJ > lenO {
return 1, nil
}
// TODO(justin): we should optimize this, we don't have to decode the whole thing.
var err error
if other, err = decodeIfNeeded(other); err != nil {
return 0, err
}
o := other.(jsonArray)
for i := 0; i < lenJ; i++ {
cmp, err := j[i].Compare(o[i])
if err != nil {
return 0, err
}
if cmp != 0 {
return cmp, nil
}
}
return 0, nil
}
func (j jsonObject) Compare(other JSON) (int, error) {
cmp := cmpJSONTypes(j.Type(), other.Type())
if cmp != 0 {
return cmp, nil
}
lenJ := j.Len()
lenO := other.Len()
if lenJ < lenO {
return -1, nil
}
if lenJ > lenO {
return 1, nil
}
// TODO(justin): we should optimize this, we don't have to decode the whole thing.
var err error
if other, err = decodeIfNeeded(other); err != nil {
return 0, err
}
o := other.(jsonObject)
for i := 0; i < lenJ; i++ {
cmpKey, err := j[i].k.Compare(o[i].k)
if err != nil {
return 0, err
}
if cmpKey != 0 {
return cmpKey, nil
}
cmpVal, err := j[i].v.Compare(o[i].v)
if err != nil {
return 0, err
}
if cmpVal != 0 {
return cmpVal, nil
}
}
return 0, nil
}
var errTrailingCharacters = pgerror.WithCandidateCode(errors.New("trailing characters after JSON document"), pgcode.InvalidTextRepresentation)
func (jsonNull) Format(buf *bytes.Buffer) { buf.WriteString("null") }
func (jsonFalse) Format(buf *bytes.Buffer) { buf.WriteString("false") }
func (jsonTrue) Format(buf *bytes.Buffer) { buf.WriteString("true") }
func (j jsonNumber) Format(buf *bytes.Buffer) {
dec := apd.Decimal(j)
// Make sure non-finite values are encoded as valid strings by
// quoting them. Unfortunately, since this is JSON, there's no
// defined way to express the three special numeric values (+inf,
// -inf, nan) except as a string. This means that the decoding
// side can't tell whether the field should be a float or a
// string. Testing for exact types is thus tricky. As of this
// comment, our current tests for this behavior happen it the SQL
// package, not here in the JSON package.
nonfinite := dec.Form != apd.Finite
if nonfinite {
buf.WriteByte('"')
}
buf.WriteString(dec.String())
if nonfinite {
buf.WriteByte('"')
}
}
func (j jsonString) Format(buf *bytes.Buffer) {
encodeJSONString(buf, string(j))
}
func asString(j JSON) string {
var buf bytes.Buffer
j.Format(&buf)
return buf.String()
}
func (j jsonNull) String() string { return asString(j) }
func (j jsonTrue) String() string { return asString(j) }
func (j jsonFalse) String() string { return asString(j) }
func (j jsonString) String() string { return asString(j) }
func (j jsonNumber) String() string { return asString(j) }
func (j jsonArray) String() string { return asString(j) }
func (j jsonObject) String() string { return asString(j) }
const hexAlphabet = "0123456789abcdef"
// encodeJSONString writes a string literal to buf as a JSON string.
// Cribbed from https://github.com/golang/go/blob/7badae85f20f1bce4cc344f9202447618d45d414/src/encoding/json/encode.go.
func encodeJSONString(buf *bytes.Buffer, s string) {
buf.WriteByte('"')
start := 0
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
if safeSet[b] {
i++
continue
}
if start < i {
buf.WriteString(s[start:i])
}
switch b {
case '\\', '"':
buf.WriteByte('\\')
buf.WriteByte(b)
case '\n':
buf.WriteByte('\\')
buf.WriteByte('n')
case '\r':
buf.WriteByte('\\')
buf.WriteByte('r')
case '\t':
buf.WriteByte('\\')
buf.WriteByte('t')
default:
// This encodes bytes < 0x20 except for \t, \n and \r.
// If escapeHTML is set, it also escapes <, >, and &
// because they can lead to security holes when
// user-controlled strings are rendered into JSON
// and served to some browsers.
buf.WriteString(`\u00`)
buf.WriteByte(hexAlphabet[b>>4])
buf.WriteByte(hexAlphabet[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
if start < i {
buf.WriteString(s[start:i])
}
buf.WriteString(`\ufffd`)
i += size
start = i
continue
}
i += size
}
if start < len(s) {
buf.WriteString(s[start:])
}
buf.WriteByte('"')
}
func (j jsonArray) Format(buf *bytes.Buffer) {
buf.WriteByte('[')
for i := range j {
if i != 0 {
buf.WriteString(", ")
}
j[i].Format(buf)
}
buf.WriteByte(']')
}
func (j jsonObject) Format(buf *bytes.Buffer) {
buf.WriteByte('{')
for i := range j {
if i != 0 {
buf.WriteString(", ")
}
encodeJSONString(buf, string(j[i].k))
buf.WriteString(": ")
j[i].v.Format(buf)
}
buf.WriteByte('}')
}
func (jsonNull) Size() uintptr { return 0 }
func (jsonFalse) Size() uintptr { return 0 }
func (jsonTrue) Size() uintptr { return 0 }
func (j jsonNumber) Size() uintptr {
intVal := j.Coeff
return decimalSize + uintptr(cap(intVal.Bits()))*wordSize
}
func (j jsonString) Size() uintptr {
return stringHeaderSize + uintptr(len(j))
}
func (j jsonArray) Size() uintptr {
valSize := sliceHeaderSize + uintptr(cap(j))*jsonInterfaceSize
for _, elem := range j {
valSize += elem.Size()
}
return valSize
}
func (j jsonObject) Size() uintptr {
valSize := sliceHeaderSize + uintptr(cap(j))*keyValuePairSize
// jsonKeyValuePair consists of jsonString(i.e. string header) k and JSON interface v.
// Since elem.k.Size() has already taken stringHeaderSize into account, we should
// reduce len(j) * stringHeaderSize to avoid counting the size of string headers twice
valSize -= uintptr(len(j)) * stringHeaderSize
for _, elem := range j {
valSize += elem.k.Size()
valSize += elem.v.Size()
}
return valSize
}
// ParseJSON takes a string of JSON and returns a JSON value.
func ParseJSON(s string) (JSON, error) {
// This goes in two phases - first it parses the string into raw interface{}s
// using the Go encoding/json package, then it transforms that into a JSON.
// This could be faster if we wrote a parser to go directly into the JSON.
var result interface{}
decoder := json.NewDecoder(strings.NewReader(s))
// We want arbitrary size/precision decimals, so we call UseNumber() to tell
// the decoder to decode numbers into strings instead of float64s (which we
// later parse using apd).
decoder.UseNumber()
err := decoder.Decode(&result)
if err != nil {
err = errors.Handled(err)
err = errors.Wrap(err, "unable to decode JSON")
err = pgerror.WithCandidateCode(err, pgcode.InvalidTextRepresentation)
return nil, err
}
if decoder.More() {
return nil, errTrailingCharacters
}
return MakeJSON(result)
}
// EncodeInvertedIndexKeys takes in a key prefix and returns a slice of inverted index keys,
// one per unique path through the receiver.
func EncodeInvertedIndexKeys(b []byte, json JSON) ([][]byte, error) {
return json.encodeInvertedIndexKeys(encoding.EncodeJSONAscending(b))
}
// EncodeContainingInvertedIndexSpans takes in a key prefix and returns the
// spans that must be scanned in the inverted index to evaluate a contains (@>)
// predicate with the given JSON (i.e., find the objects in the index that
// contain the given JSON).
//
// The spans are returned in an inverted.SpanExpression, which represents the
// set operations that must be applied on the spans read during execution. See
// comments in the SpanExpression definition for details.
//
// The input inKey is prefixed to the keys in all returned spans.
func EncodeContainingInvertedIndexSpans(
b []byte, json JSON,
) (invertedExpr inverted.Expression, err error) {
return json.encodeContainingInvertedIndexSpans(
encoding.EncodeJSONAscending(b), true /* isRoot */, false, /* isObjectValue */
)
}
// EncodeContainedInvertedIndexSpans takes in a key prefix and returns the
// spans that must be scanned in the inverted index to evaluate a contained by
// (<@) predicate with the given JSON (i.e., find the objects in the index that
// could be contained by the given JSON).
//
// The spans are returned in an inverted.SpanExpression, which represents the
// set operations that must be applied on the spans read during execution. See
// comments in the SpanExpression definition for details.
//
// The input inKey is prefixed to the keys in all returned spans.
func EncodeContainedInvertedIndexSpans(
b []byte, json JSON,
) (invertedExpr inverted.Expression, err error) {
invertedExpr, err = json.encodeContainedInvertedIndexSpans(
encoding.EncodeJSONAscending(b), true /* isRoot */, false, /* isObjectValue */
)
if err != nil {
return nil, err
}
// The produced inverted expression will never be tight. This is because the
// span expression produced will match all objects that contain at least one
// of the keys, which does not guarantee they only contain the keys.
// In other words, there may be false positives included that will need to
// pass through an additional filter.
// For example, the spans produced for '{"a": "b"}' will include both
// '{"a": "b"}' and '{"a": "b", "c", "d"}', but the second row should be
// filtered out since '{"a": "b", "c", "d"}' <@ '{"a": "b"}' is false.
invertedExpr.SetNotTight()
return invertedExpr, nil
}
func (j jsonNull) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
b = encoding.AddJSONPathTerminator(b)
return [][]byte{encoding.EncodeNullAscending(b)}, nil
}
func (j jsonNull) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
func (j jsonNull) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
invertedExpr, err := encodeContainedInvertedIndexSpansFromLeaf(j, b, isRoot)
return invertedExpr, err
}
func (jsonTrue) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
b = encoding.AddJSONPathTerminator(b)
return [][]byte{encoding.EncodeTrueAscending(b)}, nil
}
func (j jsonTrue) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
func (j jsonTrue) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
invertedExpr, err := encodeContainedInvertedIndexSpansFromLeaf(j, b, isRoot)
return invertedExpr, err
}
func (jsonFalse) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
b = encoding.AddJSONPathTerminator(b)
return [][]byte{encoding.EncodeFalseAscending(b)}, nil
}
func (j jsonFalse) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
func (j jsonFalse) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
invertedExpr, err := encodeContainedInvertedIndexSpansFromLeaf(j, b, isRoot)
return invertedExpr, err
}
func (j jsonString) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
b = encoding.AddJSONPathTerminator(b)
return [][]byte{encoding.EncodeStringAscending(b, string(j))}, nil
}
func (j jsonString) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
func (j jsonString) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
invertedExpr, err := encodeContainedInvertedIndexSpansFromLeaf(j, b, isRoot)
return invertedExpr, err
}
func (j jsonNumber) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
b = encoding.AddJSONPathTerminator(b)
var dec = apd.Decimal(j)
return [][]byte{encoding.EncodeDecimalAscending(b, &dec)}, nil
}
func (j jsonNumber) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
func (j jsonNumber) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (inverted.Expression, error) {
invertedExpr, err := encodeContainedInvertedIndexSpansFromLeaf(j, b, isRoot)
return invertedExpr, err
}
func (j jsonArray) encodeInvertedIndexKeys(b []byte) ([][]byte, error) {
// Checking for an empty array.
if len(j) == 0 {
return [][]byte{encoding.EncodeJSONEmptyArray(b)}, nil
}
prefix := encoding.EncodeArrayAscending(b)
var outKeys [][]byte
for i := range j {
children, err := j[i].encodeInvertedIndexKeys(prefix[:len(prefix):len(prefix)])
if err != nil {
return nil, err
}
outKeys = append(outKeys, children...)
}
// Deduplicate the entries, since arrays can have duplicates - we don't want
// to emit duplicate keys from this method, as it's more expensive to
// deduplicate keys via KV (which will actually write the keys) than to do
// it now (just an in-memory sort and distinct).
outKeys = uniq.UniquifyByteSlices(outKeys)
return outKeys, nil
}
func (j jsonArray) encodeContainingInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (invertedExpr inverted.Expression, err error) {
// Checking for an empty array.
if len(j) == 0 {
return encodeContainingInvertedIndexSpansFromLeaf(j, b, isRoot, isObjectValue)
}
prefix := encoding.EncodeArrayAscending(b)
for i := range j {
child, err := j[i].encodeContainingInvertedIndexSpans(
prefix[:len(prefix):len(prefix)], false /* isRoot */, false, /* isObjectValue */
)
if err != nil {
return nil, err
}
if invertedExpr == nil {
invertedExpr = child
} else {
invertedExpr = inverted.And(invertedExpr, child)
}
}
// If this array is not at the root and has more than one element,
// we cannot produce tight spans. This is because we cannot rely on the keys
// alone to determine whether the top level JSON is contained in another JSON.
// For example, '[[1], [2]]' and '[[1, 2]]' have exactly the same keys, but
// '[[1, 2]]' @> '[[1], [2]]' is true, while '[[1], [2]]' @> '[[1, 2]]' is
// false. We will return an expression with Tight=false for the second case,
// which will signal the need to filter out false positives.
//
// Note that in addition to checking that the original array had length > 1,
// we also check that the spanExpr is an intersection. The inverted.And
// function performs some deduplication, so it's possible that the original
// array had duplicates that were removed, causing the intersection to be
// removed.
if spanExpr, ok := invertedExpr.(*inverted.SpanExpression); ok &&
!isRoot && j.Len() > 1 && spanExpr.Operator == inverted.SetIntersection {
invertedExpr.SetNotTight()
}
return invertedExpr, nil
}
func (j jsonArray) encodeContainedInvertedIndexSpans(
b []byte, isRoot, isObjectValue bool,
) (invertedExpr inverted.Expression, err error) {
if !isObjectValue || len(j) == 0 {
// The empty array should always be added to the spans, since it is contained
// by everything. Empty array values are already accounted for when getting
// the spans for a non-empty object value, so they should be excluded.