| PostgreSQL 8.0.0beta4 Documentation | ||||
|---|---|---|---|---|
| Prev | Fast Backward | Chapter 37. PL/Perl - Perl Procedural Language | Fast Forward | Next |
PL/Perl can now be used to write trigger functions using the $_TD hash reference.
Some useful parts of the $_TD hash reference are:
$_TD->{new}{foo} # NEW value of column foo
$_TD->{old}{bar} # OLD value of column bar
$_TD{name} # Name of the trigger being called
$_TD{event} # INSERT, UPDATE, DELETE or UNKNOWN
$_TD{when} # BEFORE, AFTER or UNKNOWN
$_TD{level} # ROW, STATEMENT or UNKNOWN
$_TD{relid} # Relation ID of the table on which the trigger occurred.
$_TD{relname} # Name of the table on which the trigger occurred.
@{$_TD{argv}} # Array of arguments to the trigger function. May be empty.
$_TD{argc} # Number of arguments to the trigger. Why is this here?
Triggers can return one of the following:
return; -- Executes the statement SKIP; -- Doesn't execute the statement MODIFY; -- Says it modified a NEW row
Here is an example of a trigger function, illustrating some of the above.
CREATE TABLE test (
i int,
v varchar
);
CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$
if (($_TD->{new}{i}>=100) || ($_TD->{new}{i}<=0)) {
return "SKIP"; # Skip INSERT/UPDATE command
} elsif ($_TD->{new}{v} ne "immortal") {
$_TD->{new}{v} .= "(modified by trigger)";
return "MODIFY"; # Modify tuple and proceed INSERT/UPDATE command
} else {
return; # Proceed INSERT/UPDATE command
}
$$ LANGUAGE plperl;
CREATE TRIGGER "test_valid_id_trig" BEFORE INSERT OR UPDATE ON test
FOR EACH ROW EXECUTE PROCEDURE "valid_id"();