Skip to content

Commit

Permalink
feat: support sqlite contains path queries (#274)
Browse files Browse the repository at this point in the history
  • Loading branch information
jiazheng2 authored Oct 18, 2024
1 parent 3071fc4 commit e2e91b3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
16 changes: 14 additions & 2 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 10 additions & 8 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

0 comments on commit e2e91b3

Please sign in to comment.