Skip to content

Commit

Permalink
fix(contrib/drivers/pgsql): #3671 fix invalid pgsql insert json type (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Ghw2066 authored Sep 9, 2024
1 parent 26d2a98 commit 467a5c1
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 6 deletions.
15 changes: 9 additions & 6 deletions contrib/drivers/pgsql/pgsql_convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,15 @@ func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fie
)

if fieldValueKind == reflect.Slice {
fieldValue = gstr.ReplaceByMap(gconv.String(fieldValue),
map[string]string{
"[": "{",
"]": "}",
},
)
// For pgsql, json or jsonb require '[]'
if !gstr.Contains(fieldType, "json") {
fieldValue = gstr.ReplaceByMap(gconv.String(fieldValue),
map[string]string{
"[": "{",
"]": "}",
},
)
}
}
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue)
}
Expand Down
39 changes: 39 additions & 0 deletions contrib/drivers/pgsql/pgsql_z_unit_issue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,42 @@ func Test_Issue3632(t *testing.T) {
t.AssertNil(err)
})
}

// https://github.com/gogf/gf/issues/3671
func Test_Issue3671(t *testing.T) {
type SubMember struct {
Seven string
Eight int64
}
type Member struct {
One []int64 `json:"one" orm:"one"`
Two [][]string `json:"two" orm:"two"`
Three []string `json:"three" orm:"three"`
Four []int64 `json:"four" orm:"four"`
Five []SubMember `json:"five" orm:"five"`
}
var (
sqlText = gtest.DataContent("issues", "issue3671.sql")
table = fmt.Sprintf(`%s_%d`, TablePrefix+"issue3632", gtime.TimestampNano())
)
if _, err := db.Exec(ctx, fmt.Sprintf(sqlText, table)); err != nil {
gtest.Fatal(err)
}
defer dropTable(table)

gtest.C(t, func(t *gtest.T) {
var (
dao = db.Model(table)
member = Member{
One: []int64{1, 2, 3},
Two: [][]string{{"a", "b"}, {"c", "d"}},
Three: []string{"x", "y", "z"},
Four: []int64{1, 2, 3},
Five: []SubMember{{Seven: "1", Eight: 2}, {Seven: "3", Eight: 4}},
}
)

_, err := dao.Ctx(ctx).Data(&member).Insert()
t.AssertNil(err)
})
}
8 changes: 8 additions & 0 deletions contrib/drivers/pgsql/testdata/issues/issue3671.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE "public"."%s"
(
"one" int8[] NOT NULL,
"two" text[][] NOT NULL,
"three" jsonb,
"four" json,
"five" jsonb
);

0 comments on commit 467a5c1

Please sign in to comment.