Skip to content

Commit

Permalink
RowTo(AddrOf)StructByPos ignores fields with "-" db tag
Browse files Browse the repository at this point in the history
  • Loading branch information
jackc committed Jul 15, 2023
1 parent 038fc44 commit 2f6fcf8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
11 changes: 9 additions & 2 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -496,15 +496,17 @@ func (rs *mapRowScanner) ScanRow(rows Rows) error {
}

// RowToStructByPos returns a T scanned from row. T must be a struct. T must have the same number a public fields as row
// has fields. The row and T fields will by matched by position.
// has fields. The row and T fields will by matched by position. If the "db" struct tag is "-" then the field will be
// ignored.
func RowToStructByPos[T any](row CollectableRow) (T, error) {
var value T
err := row.Scan(&positionalStructRowScanner{ptrToStruct: &value})
return value, err
}

// RowToAddrOfStructByPos returns the address of a T scanned from row. T must be a struct. T must have the same number a
// public fields as row has fields. The row and T fields will by matched by position.
// public fields as row has fields. The row and T fields will by matched by position. If the "db" struct tag is "-" then
// the field will be ignored.
func RowToAddrOfStructByPos[T any](row CollectableRow) (*T, error) {
var value T
err := row.Scan(&positionalStructRowScanner{ptrToStruct: &value})
Expand Down Expand Up @@ -545,6 +547,11 @@ func (rs *positionalStructRowScanner) appendScanTargets(dstElemValue reflect.Val
if sf.Anonymous && sf.Type.Kind() == reflect.Struct {
scanTargets = rs.appendScanTargets(dstElemValue.Field(i), scanTargets)
} else if sf.PkgPath == "" {
dbTag, _ := sf.Tag.Lookup(structTagKey)
if dbTag == "-" {
// Field is ignored, skip it.
continue
}
scanTargets = append(scanTargets, dstElemValue.Field(i).Addr().Interface())
}
}
Expand Down
18 changes: 18 additions & 0 deletions rows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,24 @@ func TestRowToStructByPos(t *testing.T) {
})
}

func TestRowToStructByPosIgnoredField(t *testing.T) {
type person struct {
Name string
Age int32 `db:"-"`
}

defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {
rows, _ := conn.Query(ctx, `select 'Joe' as name from generate_series(0, 9) n`)
slice, err := pgx.CollectRows(rows, pgx.RowToStructByPos[person])
require.NoError(t, err)

assert.Len(t, slice, 10)
for i := range slice {
assert.Equal(t, "Joe", slice[i].Name)
}
})
}

func TestRowToStructByPosEmbeddedStruct(t *testing.T) {
type Name struct {
First string
Expand Down

0 comments on commit 2f6fcf8

Please sign in to comment.