Skip to content

Commit dd2f4d7

Browse files
committed
internalstorage: add function to patch json fields
Signed-off-by: Iceber Gu <[email protected]>
1 parent 6ccabc0 commit dd2f4d7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

pkg/storage/internalstorage/builder.go renamed to pkg/storage/internalstorage/json_builder.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,38 @@ import (
99
"k8s.io/apimachinery/pkg/runtime/schema"
1010
)
1111

12+
type JSONUpdateExpression struct {
13+
column string
14+
key string
15+
value []byte
16+
}
17+
18+
func JSONUpdate(column string, key string, value []byte) *JSONUpdateExpression {
19+
return &JSONUpdateExpression{column: column, key: key, value: value}
20+
}
21+
22+
func (jsonUpdate *JSONUpdateExpression) Build(builder clause.Builder) {
23+
stmt, ok := builder.(*gorm.Statement)
24+
if !ok {
25+
return
26+
}
27+
28+
var rawSQL string
29+
var values []interface{}
30+
dialector := stmt.Dialector.Name()
31+
switch dialector {
32+
case "mysql", "sqlite3", "sqlite":
33+
rawSQL = fmt.Sprintf("JSON_SET(COALESCE(%s, '{}'), ?, JSON(?))", jsonUpdate.column)
34+
values = []interface{}{fmt.Sprintf(`$."%s"`, jsonUpdate.key), string(jsonUpdate.value)}
35+
case "postgres":
36+
rawSQL = fmt.Sprintf("JSONB_SET(COALESCE(%s, '{}'), ?, ?, true)", jsonUpdate.column)
37+
values = []interface{}{fmt.Sprintf("{%s}", jsonUpdate.key), jsonUpdate.value}
38+
}
39+
if rawSQL != "" {
40+
gorm.Expr(rawSQL, values...).Build(builder)
41+
}
42+
}
43+
1244
type JSONQueryExpression struct {
1345
column string
1446
keys []string

0 commit comments

Comments
 (0)