Skip to content

Commit f366a2b

Browse files
authored
Merge pull request #2593 from AlisinaDevelo/fix/2296-db-tag-case-insensitive
rows: restore case-insensitive db tag matching (#2296)
2 parents 4a49cda + 50178a7 commit f366a2b

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

rows.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -843,7 +843,7 @@ func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize
843843
return i
844844
}
845845
} else {
846-
if desc.Name == field {
846+
if strings.EqualFold(desc.Name, field) {
847847
return i
848848
}
849849
}

rows_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,24 @@ func TestRowToStructByNameDbTags(t *testing.T) {
702702
})
703703
}
704704

705+
// A db tag must match its column case-insensitively. PostgreSQL folds unquoted
706+
// identifiers to lower case, so a column aliased `as Region` comes back as
707+
// "region" and has to match a `db:"Region"` tag. See
708+
// https://github.com/jackc/pgx/issues/2296.
709+
func TestRowToStructByNameDbTagsCaseInsensitive(t *testing.T) {
710+
type record struct {
711+
Region string `db:"Region"`
712+
}
713+
714+
defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {
715+
rows, _ := conn.Query(ctx, `select 'east' as Region`)
716+
slice, err := pgx.CollectRows(rows, pgx.RowToStructByName[record])
717+
require.NoError(t, err)
718+
require.Len(t, slice, 1)
719+
assert.Equal(t, "east", slice[0].Region)
720+
})
721+
}
722+
705723
func TestRowToStructByNameEmbeddedStruct(t *testing.T) {
706724
type Name struct {
707725
Last string `db:"last_name"`

0 commit comments

Comments
 (0)