From cdf4bc9beae20c1922b10ac540474a5c6a446473 Mon Sep 17 00:00:00 2001 From: YangKeao Date: Tue, 23 Aug 2022 23:08:20 -0400 Subject: [PATCH] expression: implement comparison between json opaque (#37316) close pingcap/tidb#37315 --- types/json/binary_functions.go | 7 +++- types/json/binary_functions_test.go | 54 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/types/json/binary_functions.go b/types/json/binary_functions.go index c929ea02b6..32b414cafb 100644 --- a/types/json/binary_functions.go +++ b/types/json/binary_functions.go @@ -803,10 +803,15 @@ func CompareBinary(left, right BinaryJSON) int { } } case TypeCodeOpaque: - cmp = bytes.Compare(left.GetString(), right.GetString()) + cmp = bytes.Compare(left.GetOpaque().Buf, right.GetOpaque().Buf) } } else { cmp = precedence1 - precedence2 + if cmp > 0 { + cmp = 1 + } else if cmp < 0 { + cmp = -1 + } } return cmp } diff --git a/types/json/binary_functions_test.go b/types/json/binary_functions_test.go index f8319c2d4f..34f1101549 100644 --- a/types/json/binary_functions_test.go +++ b/types/json/binary_functions_test.go @@ -49,3 +49,57 @@ func BenchmarkMergeBinary(b *testing.B) { _ = MergeBinary([]BinaryJSON{valueA, valueB}) } } + +func TestBinaryCompare(t *testing.T) { + tests := []struct { + left BinaryJSON + right BinaryJSON + result int + }{ + { + CreateBinary("a"), + CreateBinary("b"), + -1, + }, + { + CreateBinary(Opaque{ + TypeCode: 0, + Buf: []byte{0, 1, 2, 3}, + }), + CreateBinary(Opaque{ + TypeCode: 0, + Buf: []byte{0, 1, 2}, + }), + 1, + }, + { + CreateBinary(Opaque{ + TypeCode: 0, + Buf: []byte{0, 1, 2, 3}, + }), + CreateBinary(Opaque{ + TypeCode: 0, + Buf: []byte{0, 2, 1}, + }), + -1, + }, + { + CreateBinary("test"), + CreateBinary(Opaque{ + TypeCode: 0, + Buf: []byte{0, 2, 1}, + }), + -1, + }, + } + + compareMsg := map[int]string{ + 1: "greater than", + 0: "equal with", + -1: "smaller than", + } + + for _, test := range tests { + require.Equal(t, test.result, CompareBinary(test.left, test.right), "%s should be %s %s", test.left.String(), compareMsg[test.result], test.right.String()) + } +}