Replace xmax upsert trick with RETURNING full row
Upsert methods now RETURNING all struct columns and scan the result back into the pointer receiver, keeping the caller in sync with the actual DB state (id, created_at, etc. from the existing row on conflict). Insert detection compares the saved original ID with the returned ID instead of relying on the PostgreSQL-internal xmax column. Signed-off-by: Émile Ré <emile@probo.com>
This commit is contained in:
@@ -118,7 +118,7 @@ INSERT INTO common_third_party_domains (
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d CommonThirdPartyDomain) Upsert(
|
||||
func (d *CommonThirdPartyDomain) Upsert(
|
||||
ctx context.Context,
|
||||
conn pg.Tx,
|
||||
) (inserted bool, err error) {
|
||||
@@ -139,9 +139,16 @@ INSERT INTO common_third_party_domains (
|
||||
ON CONFLICT (common_third_party_id, domain) DO UPDATE
|
||||
SET
|
||||
updated_at = EXCLUDED.updated_at
|
||||
RETURNING (xmax = 0) AS inserted
|
||||
RETURNING
|
||||
id,
|
||||
common_third_party_id,
|
||||
domain,
|
||||
created_at,
|
||||
updated_at
|
||||
`
|
||||
|
||||
originalID := d.ID
|
||||
|
||||
args := pgx.StrictNamedArgs{
|
||||
"id": d.ID,
|
||||
"common_third_party_id": d.CommonThirdPartyID,
|
||||
@@ -156,12 +163,14 @@ RETURNING (xmax = 0) AS inserted
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
inserted, err = pgx.CollectExactlyOneRow(rows, pgx.RowTo[bool])
|
||||
row, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[CommonThirdPartyDomain])
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("cannot collect upsert result: %w", err)
|
||||
}
|
||||
|
||||
return inserted, nil
|
||||
*d = row
|
||||
|
||||
return originalID == d.ID, nil
|
||||
}
|
||||
|
||||
func (d CommonThirdPartyDomain) Delete(
|
||||
|
||||
Reference in New Issue
Block a user