From e2e91b35f4589ab7f7cef2c40bbd891abccfda48 Mon Sep 17 00:00:00 2001 From: jiazheng2 Date: Fri, 18 Oct 2024 10:27:59 +0800 Subject: [PATCH] feat: support sqlite contains path queries (#274) --- json.go | 16 ++++++++++++++-- json_test.go | 18 ++++++++++-------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/json.go b/json.go index 6167477..e6d021e 100644 --- a/json.go +++ b/json.go @@ -506,9 +506,21 @@ func (json *JSONArrayExpression) Build(builder clause.Builder) { case "sqlite": switch { case json.contains: - builder.WriteString("exists(SELECT 1 FROM json_each(" + stmt.Quote(json.column) + ") WHERE value = ") + builder.WriteString("EXISTS(SELECT 1 FROM json_each(") + builder.WriteQuoted(json.column) + if len(json.keys) > 0 { + builder.WriteByte(',') + builder.AddVar(stmt, jsonQueryJoin(json.keys)) + } + builder.WriteString(") WHERE value = ") builder.AddVar(stmt, json.equalsValue) - builder.WriteString(")") + builder.WriteString(") AND json_array_length(") + builder.WriteQuoted(json.column) + if len(json.keys) > 0 { + builder.WriteByte(',') + builder.AddVar(stmt, jsonQueryJoin(json.keys)) + } + builder.WriteString(") > 0") } case "postgres": switch { diff --git a/json_test.go b/json_test.go index 4e43432..598dc65 100644 --- a/json_test.go +++ b/json_test.go @@ -447,7 +447,7 @@ func TestJSONSet(t *testing.T) { } func TestJSONArrayQuery(t *testing.T) { - if SupportedDriver("mysql") { + if SupportedDriver("sqlite", "mysql") { type Param struct { ID int DisplayName string @@ -514,14 +514,16 @@ func TestJSONArrayQuery(t *testing.T) { } AssertEqual(t, len(retMultiple), 1) - if err := DB.Where(datatypes.JSONArrayQuery("config").In([]string{"c", "a"})).Find(&retMultiple).Error; err != nil { - t.Fatalf("failed to find params with json value, got error %v", err) - } - AssertEqual(t, len(retMultiple), 1) + if SupportedDriver("mysql") { + if err := DB.Where(datatypes.JSONArrayQuery("config").In([]string{"c", "a"})).Find(&retMultiple).Error; err != nil { + t.Fatalf("failed to find params with json value, got error %v", err) + } + AssertEqual(t, len(retMultiple), 1) - if err := DB.Where(datatypes.JSONArrayQuery("config").In([]string{"c", "d"}, "test")).Find(&retMultiple).Error; err != nil { - t.Fatalf("failed to find params with json value and keys, got error %v", err) + if err := DB.Where(datatypes.JSONArrayQuery("config").In([]string{"c", "d"}, "test")).Find(&retMultiple).Error; err != nil { + t.Fatalf("failed to find params with json value and keys, got error %v", err) + } + AssertEqual(t, len(retMultiple), 1) } - AssertEqual(t, len(retMultiple), 1) } }