Skip to content

Commit b6876cb

Browse files
authored
Merge pull request #278 from constructive-io/devin/1768345548-trigger-function-fixture
test(plpgsql-deparser): add trigger function fixture with FOUND/NEW/OLD/TG_OP examples
2 parents 29fd10b + 365628d commit b6876cb

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
CREATE FUNCTION trigger_with_special_vars() RETURNS trigger
2+
LANGUAGE plpgsql
3+
AS $$
4+
BEGIN
5+
IF TG_OP = 'INSERT' THEN
6+
NEW.created_at := now();
7+
RETURN NEW;
8+
ELSIF TG_OP = 'UPDATE' THEN
9+
IF OLD.id IS DISTINCT FROM NEW.id THEN
10+
RAISE EXCEPTION 'IMMUTABLE_FIELD';
11+
END IF;
12+
NEW.updated_at := now();
13+
RETURN NEW;
14+
ELSIF TG_OP = 'DELETE' THEN
15+
RETURN OLD;
16+
END IF;
17+
IF NOT FOUND THEN
18+
RAISE EXCEPTION 'NOT_FOUND';
19+
END IF;
20+
RETURN NEW;
21+
END;
22+
$$

packages/plpgsql-deparser/__tests__/pretty/__snapshots__/plpgsql-pretty.test.ts.snap

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,27 @@ exports[`lowercase: simple-function.sql 1`] = `
208208
end"
209209
`;
210210
211+
exports[`lowercase: trigger-function.sql 1`] = `
212+
"begin
213+
if TG_OP = 'INSERT' then
214+
NEW.created_at := now();
215+
return NEW;
216+
elsif TG_OP = 'UPDATE' then
217+
if OLD.id IS DISTINCT FROM NEW.id then
218+
raise exception 'IMMUTABLE_FIELD';
219+
end if;
220+
NEW.updated_at := now();
221+
return NEW;
222+
elsif TG_OP = 'DELETE' then
223+
return OLD;
224+
end if;
225+
if NOT FOUND then
226+
raise exception 'NOT_FOUND';
227+
end if;
228+
return NEW;
229+
end"
230+
`;
231+
211232
exports[`uppercase: big-function.sql 1`] = `
212233
"DECLARE
213234
v_orders_scanned int := 0;
@@ -415,3 +436,24 @@ exports[`uppercase: simple-function.sql 1`] = `
415436
RETURN a + b;
416437
END"
417438
`;
439+
440+
exports[`uppercase: trigger-function.sql 1`] = `
441+
"BEGIN
442+
IF TG_OP = 'INSERT' THEN
443+
NEW.created_at := now();
444+
RETURN NEW;
445+
ELSIF TG_OP = 'UPDATE' THEN
446+
IF OLD.id IS DISTINCT FROM NEW.id THEN
447+
RAISE EXCEPTION 'IMMUTABLE_FIELD';
448+
END IF;
449+
NEW.updated_at := now();
450+
RETURN NEW;
451+
ELSIF TG_OP = 'DELETE' THEN
452+
RETURN OLD;
453+
END IF;
454+
IF NOT FOUND THEN
455+
RAISE EXCEPTION 'NOT_FOUND';
456+
END IF;
457+
RETURN NEW;
458+
END"
459+
`;

packages/plpgsql-deparser/__tests__/pretty/plpgsql-pretty.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const prettyTest = new PlpgsqlPrettyTest([
55
'simple-function.sql',
66
'if-else-function.sql',
77
'loop-function.sql',
8+
'trigger-function.sql',
89
]);
910

1011
prettyTest.generateTests();

0 commit comments

Comments
 (0)