Skip to content

Commit e20524b

Browse files
authored
Trigger for updating latest envelope runs per statement (#1596)
Instead of running the trigger per row like before, new trigger runs per statement, which should be more performant on batch inserts.
1 parent 26b388d commit e20524b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
-- First reinstate previous version of the trigger, as defined in 00006_add_latest_envelopes.up.sql
2+
CREATE TRIGGER gateway_latest_upd
3+
AFTER INSERT ON gateway_envelopes_meta
4+
FOR EACH ROW EXECUTE FUNCTION update_latest_envelope();
5+
6+
7+
DROP TRIGGER IF EXISTS gateway_latest_upd_v2 ON gateway_envelopes_meta;
8+
DROP FUNCTION IF EXISTS update_latest_envelope_v2();
9+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
-- Run without timeout, needed as the insert can take a few seconds
2+
SET statement_timeout = 0;
3+
4+
CREATE OR REPLACE FUNCTION update_latest_envelope_v2()
5+
RETURNS trigger AS $$
6+
BEGIN
7+
INSERT INTO gateway_envelopes_latest as g
8+
SELECT originator_node_id, MAX(originator_sequence_id) AS originator_sequence_id, MAX(gateway_time) AS gateway_time
9+
FROM new
10+
GROUP BY originator_node_id
11+
ON CONFLICT (originator_node_id)
12+
DO UPDATE
13+
SET originator_sequence_id = EXCLUDED.originator_sequence_id,
14+
gateway_time = EXCLUDED.gateway_time
15+
WHERE EXCLUDED.originator_sequence_id > g.originator_sequence_id;
16+
RETURN NULL;
17+
END;
18+
$$ LANGUAGE plpgsql;
19+
20+
-- Create a new trigger that's per statement.
21+
CREATE TRIGGER gateway_latest_upd_v2
22+
AFTER INSERT ON gateway_envelopes_meta
23+
REFERENCING NEW TABLE AS new
24+
FOR EACH STATEMENT EXECUTE FUNCTION update_latest_envelope_v2();
25+
26+
-- Remove old trigger.
27+
DROP TRIGGER IF EXISTS gateway_latest_upd ON gateway_envelopes_meta;

0 commit comments

Comments
 (0)