Skip to content

Commit

Permalink
fix(pgdriver): return PostgreSQL DATE as a string
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Sep 15, 2021
1 parent 65feeca commit 40be0e8
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
3 changes: 2 additions & 1 deletion driver/pgdriver/column.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ func readColumnValue(rd *reader, dataType int32, dataLen int) (interface{}, erro
case pgTimestamptz:
return readTimeCol(rd, dataLen)
case pgDate:
return readTimeCol(rd, dataLen)
// Return a string and let the scanner to convert string to time.Time if necessary.
return readStringCol(rd, dataLen)
case pgText, pgVarchar:
return readStringCol(rd, dataLen)
case pgBytea:
Expand Down
10 changes: 10 additions & 0 deletions internal/dbtest/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ func TestDB(t *testing.T) {
{testScanBytes},
{testPointers},
{testExists},
{testScanTimeIntoString},
}

testEachDB(t, func(t *testing.T, dbName string, db *bun.DB) {
Expand Down Expand Up @@ -886,3 +887,12 @@ func testExists(t *testing.T, db *bun.DB) {
require.NoError(t, err)
require.False(t, exists)
}

func testScanTimeIntoString(t *testing.T, db *bun.DB) {
ctx := context.Background()

var str string
err := db.NewSelect().ColumnExpr("CURRENT_TIMESTAMP").Scan(ctx, &str)
require.NoError(t, err)
require.NotZero(t, str)
}
14 changes: 12 additions & 2 deletions internal/dbtest/pg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ func TestPGScanWithoutResult(t *testing.T) {
require.Equal(t, sql.ErrNoRows, err)
}

func TestIPNet(t *testing.T) {
func TestPGIPNet(t *testing.T) {
type Model struct {
Network net.IPNet `bun:"type:inet"`
}
Expand All @@ -287,7 +287,7 @@ func TestIPNet(t *testing.T) {
require.Equal(t, *ipv4Net, model.Network)
}

func TestBytea(t *testing.T) {
func TestPGBytea(t *testing.T) {
type Model struct {
Bytes []byte
}
Expand All @@ -306,3 +306,13 @@ func TestBytea(t *testing.T) {
require.NoError(t, err)
require.Equal(t, []byte("hello"), model.Bytes)
}

func TestPGDate(t *testing.T) {
db := pg(t)
defer db.Close()

var str string
err := db.NewSelect().ColumnExpr("'2021-09-15'::DATE").Scan(ctx, &str)
require.NoError(t, err)
require.Equal(t, "2021-09-15", str)
}
3 changes: 3 additions & 0 deletions schema/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ func scanString(dest reflect.Value, src interface{}) error {
case []byte:
dest.SetString(string(src))
return nil
case time.Time:
dest.SetString(src.Format(time.RFC3339Nano))
return nil
}
return fmt.Errorf("bun: can't scan %#v into %s", src, dest.Type())
}
Expand Down

0 comments on commit 40be0e8

Please sign in to comment.