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:
Émile Ré
2026-05-19 11:37:26 +04:00
parent 0c89a4b241
commit 370b593217
7 changed files with 139 additions and 40 deletions

View File

@@ -308,9 +308,24 @@ INSERT INTO tracker_resources (
ON CONFLICT (cookie_banner_id, resource_type, origin, path) DO UPDATE SET
last_detected_at = GREATEST(tracker_resources.last_detected_at, EXCLUDED.last_detected_at),
updated_at = EXCLUDED.updated_at
RETURNING (xmax = 0) AS inserted
RETURNING
id,
organization_id,
cookie_banner_id,
cookie_category_id,
resource_type,
origin,
path,
display_name,
description,
excluded,
last_detected_at,
created_at,
updated_at
`
originalID := tr.ID
args := pgx.StrictNamedArgs{
"id": tr.ID,
"tenant_id": scope.GetTenantID(),
@@ -328,12 +343,20 @@ RETURNING (xmax = 0) AS inserted
"updated_at": tr.UpdatedAt,
}
var inserted bool
if err := tx.QueryRow(ctx, q, args).Scan(&inserted); err != nil {
rows, err := tx.Query(ctx, q, args)
if err != nil {
return false, fmt.Errorf("cannot upsert tracker resource: %w", err)
}
defer rows.Close()
return inserted, nil
row, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[TrackerResource])
if err != nil {
return false, fmt.Errorf("cannot collect upsert result: %w", err)
}
*tr = row
return originalID == tr.ID, nil
}
func (tr *TrackerResource) Update(