CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows

fixes https://github.com/jackc/pgx/issues/1334
pull/1363/head
Jack Christensen 2022-10-22 08:44:06 -05:00
parent 11e5f68ff6
commit 6e40968cfc
2 changed files with 32 additions and 0 deletions

View File

@ -433,6 +433,9 @@ func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) {
var err error
if !rows.Next() {
if err = rows.Err(); err != nil {
return value, err
}
return value, ErrNoRows
}

View File

@ -218,6 +218,35 @@ func TestCollectOneRowIgnoresExtraRows(t *testing.T) {
})
}
// https://github.com/jackc/pgx/issues/1334
func TestCollectOneRowPrefersPostgreSQLErrorOverErrNoRows(t *testing.T) {
defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {
_, err := conn.Exec(ctx, `create temporary table t (name text not null unique)`)
require.NoError(t, err)
var name string
rows, _ := conn.Query(ctx, `insert into t (name) values ('foo') returning name`)
name, err = pgx.CollectOneRow(rows, func(row pgx.CollectableRow) (string, error) {
var n string
err := row.Scan(&n)
return n, err
})
require.NoError(t, err)
require.Equal(t, "foo", name)
rows, _ = conn.Query(ctx, `insert into t (name) values ('foo') returning name`)
name, err = pgx.CollectOneRow(rows, func(row pgx.CollectableRow) (string, error) {
var n string
err := row.Scan(&n)
return n, err
})
require.Error(t, err)
var pgErr *pgconn.PgError
require.ErrorAs(t, err, &pgErr)
require.Equal(t, "23505", pgErr.Code)
})
}
func TestRowTo(t *testing.T) {
defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, t testing.TB, conn *pgx.Conn) {
rows, _ := conn.Query(ctx, `select n from generate_series(0, 99) n`)