2
0

implement RowToStructByName and RowToAddrOfStructByName

This commit is contained in:
Pavlo Golub
2022-11-03 16:49:20 +01:00
committed by Jack Christensen
parent 1376a2c0ed
commit 14be51536b
2 changed files with 136 additions and 0 deletions
+36
View File
@@ -508,3 +508,39 @@ func TestRowToAddrOfStructPos(t *testing.T) {
}
})
}
func TestRowToStructByNameEmbeddedStruct(t *testing.T) {
type Name struct {
Last string `db:"last_name"`
First string `db:"first_name"`
}
type person struct {
Ignore bool `db:"-"`
Name
Age int32
}
defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {
rows, _ := conn.Query(ctx, `select 'John' as first_name, 'Smith' as last_name, n as age from generate_series(0, 9) n`)
slice, err := pgx.CollectRows(rows, pgx.RowToStructByName[person])
assert.NoError(t, err)
assert.Len(t, slice, 10)
for i := range slice {
assert.Equal(t, "Smith", slice[i].Name.Last)
assert.Equal(t, "John", slice[i].Name.First)
assert.EqualValues(t, i, slice[i].Age)
}
// check missing fields in a returned row
rows, _ = conn.Query(ctx, `select 'Smith' as last_name, n as age from generate_series(0, 9) n`)
_, err = pgx.CollectRows(rows, pgx.RowToStructByName[person])
assert.ErrorContains(t, err, "cannot find field first_name in returned row")
// check missing field in a destination struct
rows, _ = conn.Query(ctx, `select 'John' as first_name, 'Smith' as last_name, n as age, null as ignore from generate_series(0, 9) n`)
_, err = pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[person])
assert.ErrorContains(t, err, "struct doesn't have corresponding row field ignore")
})
}