Skip to content

Commit

Permalink
contrib/drivers/pgsql: support slice type to insert into array for pg…
Browse files Browse the repository at this point in the history
…sql (#3645)
  • Loading branch information
oldme-git authored Jun 18, 2024
1 parent 74d0945 commit 4abb32e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
18 changes: 18 additions & 0 deletions contrib/drivers/pgsql/pgsql_convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package pgsql

import (
"context"
"reflect"
"strings"

"github.com/gogf/gf/v2/database/gdb"
Expand All @@ -16,6 +17,23 @@ import (
"github.com/gogf/gf/v2/util/gconv"
)

// ConvertValueForField converts value to database acceptable value.
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) {
var (
fieldValueKind = reflect.TypeOf(fieldValue).Kind()
)

if fieldValueKind == reflect.Slice {
fieldValue = gstr.ReplaceByMap(gconv.String(fieldValue),
map[string]string{
"[": "{",
"]": "}",
},
)
}
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue)
}

// CheckLocalTypeForField checks and returns corresponding local golang type for given db type.
func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue interface{}) (gdb.LocalType, error) {
var typeName string
Expand Down
32 changes: 31 additions & 1 deletion contrib/drivers/pgsql/pgsql_z_unit_issue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ package pgsql_test

import (
"fmt"
"github.com/gogf/gf/v2/database/gdb"
"testing"

"github.com/gogf/gf/v2/database/gdb"

"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/test/gtest"
Expand Down Expand Up @@ -73,3 +74,32 @@ func Test_Issue3330(t *testing.T) {
}
})
}

// https://github.com/gogf/gf/issues/3632
func Test_Issue3632(t *testing.T) {
type Member struct {
One []int64 `json:"one" orm:"one"`
Two [][]string `json:"two" orm:"two"`
}
var (
sqlText = gtest.DataContent("issues", "issue3632.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"}},
}
)

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

0 comments on commit 4abb32e

Please sign in to comment.