[#6835] fixed json_each/json_array_length normalizations to properly check for array values

This commit is contained in:
Gani Georgiev
2025-05-13 21:26:33 +03:00
parent 0113fecca9
commit e73077e7e7
36 changed files with 78 additions and 68 deletions
+8 -4
View File
@@ -8,9 +8,11 @@ import (
// JSONEach returns JSON_EACH SQLite string expression with
// some normalizations for non-json columns.
func JSONEach(column string) string {
// note: we are not using the new and shorter "if(x,y)" syntax for
// compatability with custom drivers that use older SQLite version
return fmt.Sprintf(
`json_each(CASE WHEN json_valid([[%s]]) THEN [[%s]] ELSE json_array([[%s]]) END)`,
column, column, column,
`json_each(CASE WHEN iif(json_valid([[%s]]), json_type([[%s]])='array', FALSE) THEN [[%s]] ELSE json_array([[%s]]) END)`,
column, column, column, column,
)
}
@@ -21,9 +23,11 @@ func JSONEach(column string) string {
//
// Returns 0 for empty string or NULL column values.
func JSONArrayLength(column string) string {
// note: we are not using the new and shorter "if(x,y)" syntax for
// compatability with custom drivers that use older SQLite version
return fmt.Sprintf(
`json_array_length(CASE WHEN json_valid([[%s]]) THEN [[%s]] ELSE (CASE WHEN [[%s]] = '' OR [[%s]] IS NULL THEN json_array() ELSE json_array([[%s]]) END) END)`,
column, column, column, column, column,
`json_array_length(CASE WHEN iif(json_valid([[%s]]), json_type([[%s]])='array', FALSE) THEN [[%s]] ELSE (CASE WHEN [[%s]] = '' OR [[%s]] IS NULL THEN json_array() ELSE json_array([[%s]]) END) END)`,
column, column, column, column, column, column,
)
}
+2 -2
View File
@@ -9,7 +9,7 @@ import (
func TestJSONEach(t *testing.T) {
result := dbutils.JSONEach("a.b")
expected := "json_each(CASE WHEN json_valid([[a.b]]) THEN [[a.b]] ELSE json_array([[a.b]]) END)"
expected := "json_each(CASE WHEN iif(json_valid([[a.b]]), json_type([[a.b]])='array', FALSE) THEN [[a.b]] ELSE json_array([[a.b]]) END)"
if result != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, result)
@@ -19,7 +19,7 @@ func TestJSONEach(t *testing.T) {
func TestJSONArrayLength(t *testing.T) {
result := dbutils.JSONArrayLength("a.b")
expected := "json_array_length(CASE WHEN json_valid([[a.b]]) THEN [[a.b]] ELSE (CASE WHEN [[a.b]] = '' OR [[a.b]] IS NULL THEN json_array() ELSE json_array([[a.b]]) END) END)"
expected := "json_array_length(CASE WHEN iif(json_valid([[a.b]]), json_type([[a.b]])='array', FALSE) THEN [[a.b]] ELSE (CASE WHEN [[a.b]] = '' OR [[a.b]] IS NULL THEN json_array() ELSE json_array([[a.b]]) END) END)"
if result != expected {
t.Fatalf("Expected\n%v\ngot\n%v", expected, result)