Drop RowsAffected check from Delete methods
Deletes are idempotent — zero affected rows is not an error. Signed-off-by: Émile Ré <emile@probo.com>
This commit is contained in:
@@ -113,6 +113,8 @@ This ensures the compiler catches renamed or removed enum values instead of sile
|
||||
|
||||
Use `conn.Query` + `pgx.Collect*` only for `SELECT` and `INSERT … RETURNING` statements that return rows. For `UPDATE` and `DELETE`, use `conn.Exec` — there is no need for `RETURNING` since the caller already owns all the field values.
|
||||
|
||||
**Delete must not check `RowsAffected()`.** A DELETE that affects zero rows is not an error — the resource may have already been deleted (idempotent deletes). Only `Update` checks `RowsAffected() == 0` to return `ErrResourceNotFound`.
|
||||
|
||||
```go
|
||||
// Single row (SELECT / INSERT … RETURNING)
|
||||
rows, err := conn.Query(ctx, q, args)
|
||||
@@ -127,7 +129,7 @@ rows, err := conn.Query(ctx, q, args)
|
||||
assets, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Asset])
|
||||
*a = assets
|
||||
|
||||
// Update / Delete — no RETURNING
|
||||
// Update — no RETURNING, check RowsAffected
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -135,6 +137,12 @@ if err != nil {
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
// Delete — no RETURNING, do NOT check RowsAffected
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
## Sentinel errors
|
||||
|
||||
@@ -429,15 +429,11 @@ func (t CommonThirdParty) Delete(
|
||||
|
||||
args := pgx.StrictNamedArgs{"id": id}
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot delete common third party: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -172,15 +172,11 @@ func (d CommonThirdPartyDomain) Delete(
|
||||
|
||||
args := pgx.StrictNamedArgs{"id": d.ID}
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot delete common third party domain: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -274,15 +274,11 @@ func (p CommonTrackerPattern) Delete(
|
||||
|
||||
args := pgx.StrictNamedArgs{"id": id}
|
||||
|
||||
result, err := conn.Exec(ctx, q, args)
|
||||
_, err := conn.Exec(ctx, q, args)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot delete common tracker pattern: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrResourceNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user