Skip to content

Commit 1d8cc3b

Browse files
Only query projection table once
This reduces the query cost for posgres from 16 to 8
1 parent decc4e0 commit 1d8cc3b

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

driver/sql/postgres/projector_aggregate_storage.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,17 @@ func newAggregateProjectionStorage(
9090
// The reason for using `INSERT SELECT` instead of `INSERT VALUES ON CONFLICT DO NOTHING` is that `ON CONFLICT` will
9191
// increase the `no SERIAL` value.
9292
queryAcquireLock: fmt.Sprintf(
93-
`WITH new_projection AS (
93+
`WITH projection AS (
94+
SELECT no, locked, failed, position, state FROM %[1]s WHERE aggregate_id = $1
95+
), new_projection AS (
9496
INSERT INTO %[1]s (aggregate_id, state) SELECT $1, 'null' WHERE NOT EXISTS (
95-
SELECT * FROM %[1]s WHERE aggregate_id = $1 LIMIT 1
97+
SELECT projection.no FROM projection
9698
) ON CONFLICT DO NOTHING
9799
RETURNING *
98100
)
99101
SELECT pg_try_advisory_lock(%[2]s::regclass::oid::int, no), locked, failed, position, state FROM new_projection
100102
UNION
101-
SELECT pg_try_advisory_lock(%[2]s::regclass::oid::int, no), locked, failed, position, state FROM %[1]s WHERE aggregate_id = $1 AND (position < $2 OR failed)`,
103+
SELECT pg_try_advisory_lock(%[2]s::regclass::oid::int, no), locked, failed, position, state FROM projection WHERE (position < $2 OR failed)`,
102104
projectionTableQuoted,
103105
projectionTableStr,
104106
),

0 commit comments

Comments
 (0)