Skip to content

Commit

Permalink
fix(pgdialect): handle []*time.Time arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
rfarrjr committed Feb 11, 2025
1 parent 0dc4e3e commit 4c4e12a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions dialect/pgdialect/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ func (d *Dialect) arrayElemAppender(typ reflect.Type) schema.AppenderFunc {
if typ.Implements(driverValuerType) {
return arrayAppendDriverValue
}
if typ == timeType {
return appendTimeElemValue
}

switch typ.Kind() {
case reflect.String:
return appendStringElemValue
Expand All @@ -155,6 +159,14 @@ func (d *Dialect) arrayElemAppender(typ reflect.Type) schema.AppenderFunc {
return schema.Appender(d, typ)
}

func appendTimeElemValue(fmter schema.Formatter, b []byte, v reflect.Value) []byte {
ts := v.Convert(timeType).Interface().(time.Time)

b = append(b, '"')
b = appendTime(b, ts)
return append(b, '"')
}

func appendStringElemValue(fmter schema.Formatter, b []byte, v reflect.Value) []byte {
return appendStringElem(b, v.String())
}
Expand Down
8 changes: 8 additions & 0 deletions internal/dbtest/pg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ func TestPostgresTimeArray(t *testing.T) {
Array1 []time.Time `bun:",array"`
Array2 *[]time.Time `bun:",array"`
Array3 *[]time.Time `bun:",array"`
Array4 []*time.Time `bun:",array"`
}

db := pg(t)
Expand All @@ -482,6 +483,7 @@ func TestPostgresTimeArray(t *testing.T) {
ID: 123,
Array1: []time.Time{time1, time2, time3},
Array2: &[]time.Time{time1, time2, time3},
Array4: []*time.Time{&time1, &time2, &time3},
}
_, err := db.NewInsert().Model(model1).Exec(ctx)
require.NoError(t, err)
Expand Down Expand Up @@ -509,6 +511,12 @@ func TestPostgresTimeArray(t *testing.T) {
Scan(ctx, pgdialect.Array(&times))
require.NoError(t, err)
require.Nil(t, times)

err = db.NewSelect().Model((*Model)(nil)).
Column("array4").
Scan(ctx, pgdialect.Array(&times))
require.NoError(t, err)
require.Equal(t, 3, len(model1.Array4))
}

func TestPostgresOnConflictDoUpdate(t *testing.T) {
Expand Down

0 comments on commit 4c4e12a

Please sign in to comment.