Skip to content

Commit

Permalink
sql: fix semantics of JSON ? operator on strings
Browse files Browse the repository at this point in the history
Fixes cockroachdb#35001.

Release note (sql change): The semantics of the JSON '?' operator when
applied to JSON strings has been changed to match Postgres. Now, a JSON
string '?'s a string when the two are equal.
  • Loading branch information
Justin Jaffray committed Feb 19, 2019
1 parent 0cc63ad commit 2851a10
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 3 deletions.
22 changes: 22 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/json
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,28 @@ SELECT bar FROM foo WHERE bar ? 'a'
----
{"a": "b"}

query BBBBBBB
VALUES (
'"hello"'::JSONB ? 'hello',
'"hello"'::JSONB ? 'goodbye',
'"hello"'::JSONB ? 'ello',
'"hello"'::JSONB ? 'h',
'true'::JSONB ? 'true',
'1'::JSONB ? '1',
'null'::JSONB ? 'null'
)
----
true false false false false false false

query T
SELECT bar FROM foo WHERE bar ? 'hello'
----
"hello"

query T
SELECT bar FROM foo WHERE bar ? 'goodbye'
----

query T
SELECT bar FROM foo WHERE bar ?| ARRAY['a','b']
----
Expand Down
7 changes: 6 additions & 1 deletion pkg/util/json/encoded.go
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,13 @@ func (j *jsonEncoded) Exists(key string) (bool, error) {
return true, nil
}
}
default:
s, err := j.decode()
if err != nil {
return false, err
}
return s.Exists(key)
}
return false, nil
}

func (j *jsonEncoded) FetchValKeyOrIdx(key string) (JSON, error) {
Expand Down
6 changes: 5 additions & 1 deletion pkg/util/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -1434,7 +1434,11 @@ func (jsonNull) Exists(string) (bool, error) { return false, nil }
func (jsonTrue) Exists(string) (bool, error) { return false, nil }
func (jsonFalse) Exists(string) (bool, error) { return false, nil }
func (jsonNumber) Exists(string) (bool, error) { return false, nil }
func (jsonString) Exists(string) (bool, error) { return false, nil }

func (j jsonString) Exists(s string) (bool, error) {
return string(j) == s, nil
}

func (j jsonArray) Exists(s string) (bool, error) {
for i := 0; i < len(j); i++ {
if elem, ok := j[i].(jsonString); ok && string(elem) == s {
Expand Down
2 changes: 1 addition & 1 deletion pkg/util/json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ func TestJSONExists(t *testing.T) {
{`baz`, false},
},
`["a"]`: {{``, false}, {`0`, false}, {`a`, true}},
`"a"`: {{``, false}, {`0`, false}, {`a`, false}},
`"a"`: {{``, false}, {`0`, false}, {`a`, true}},
`1`: {{``, false}, {`0`, false}, {`a`, false}},
`true`: {{``, false}, {`0`, false}, {`a`, false}},
}
Expand Down

0 comments on commit 2851a10

Please sign in to comment.