Skip to content

Commit

Permalink
feature: support using path for JSON_CONTAINS (#271)
Browse files Browse the repository at this point in the history
* feat: support using path for JSON_CONTAINS

* chore: add function description for contains
  • Loading branch information
jiazheng2 authored Oct 11, 2024
1 parent a602643 commit 610acc2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
14 changes: 11 additions & 3 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,14 @@ func JSONArrayQuery(column string) *JSONArrayExpression {

type JSONArrayExpression struct {
column string
keys []string
equalsValue interface{}
}

func (json *JSONArrayExpression) Contains(value interface{}) *JSONArrayExpression {
// Contains checks if the column[keys] has contains the value given. The keys parameter is only supported for MySQL.
func (json *JSONArrayExpression) Contains(value interface{}, keys ...string) *JSONArrayExpression {
json.equalsValue = value
json.keys = keys
return json
}

Expand All @@ -464,9 +467,14 @@ func (json *JSONArrayExpression) Build(builder clause.Builder) {
if stmt, ok := builder.(*gorm.Statement); ok {
switch stmt.Dialector.Name() {
case "mysql":
builder.WriteString("JSON_CONTAINS (" + stmt.Quote(json.column) + ", JSON_ARRAY(")
builder.WriteString("JSON_CONTAINS(" + stmt.Quote(json.column) + ",JSON_ARRAY(")
builder.AddVar(stmt, json.equalsValue)
builder.WriteString("))")
builder.WriteByte(')')
if len(json.keys) > 0 {
builder.WriteByte(',')
builder.AddVar(stmt, jsonQueryJoin(json.keys))
}
builder.WriteByte(')')
case "sqlite":
builder.WriteString("exists(SELECT 1 FROM json_each(" + stmt.Quote(json.column) + ") WHERE value = ")
builder.AddVar(stmt, json.equalsValue)
Expand Down
11 changes: 11 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,13 +468,20 @@ func TestJSONArrayQuery(t *testing.T) {
DisplayName: "JSONArray-2",
Config: datatypes.JSON("[\"c\", \"a\"]"),
}
cmp3 := Param{
DisplayName: "JSONArray-3",
Config: datatypes.JSON("{\"test\": [\"a\", \"b\"]}"),
}

if err := DB.Create(&cmp1).Error; err != nil {
t.Errorf("Failed to create param %v", err)
}
if err := DB.Create(&cmp2).Error; err != nil {
t.Errorf("Failed to create param %v", err)
}
if err := DB.Create(&cmp3).Error; err != nil {
t.Errorf("Failed to create param %v", err)
}

var retSingle1 Param
if err := DB.Where("id = ?", cmp2.ID).First(&retSingle1).Error; err != nil {
Expand All @@ -496,5 +503,9 @@ func TestJSONArrayQuery(t *testing.T) {
}
AssertEqual(t, len(retMultiple), 1)

if err := DB.Where(datatypes.JSONArrayQuery("config").Contains("a", "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)
}
}

0 comments on commit 610acc2

Please sign in to comment.