Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On what $BODY$ on postgresql trigger function is used for?

I've found some postgresql trigger tutorial. There is this example function:

CREATE OR REPLACE FUNCTION add_log_trigg_function() RETURNS trigger AS
$BODY$
DECLARE
    account_type varchar;
BEGIN
    IF (TG_TABLE_NAME = 'account_current') THEN
        account_type := 'Current';
        RAISE NOTICE 'TRIGER called on %', TG_TABLE_NAME;

    ELSIF (TG_TABLE_NAME = 'account_savings') THEN
        account_type := 'Savings';
        RAISE NOTICE 'TRIGER called on %', TG_TABLE_NAME;

    END IF;

    RETURN null;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION add_log_trigg_function()
  OWNER TO postgres;

I know that $BODY$ starts body function. But why it should named? Does this name BODY can or is usally used on other places? Besides LANGUAGE, COST and ALTER FUNCTION commands, what other commands usually stay outside $BODY$?

like image 527
rado Avatar asked May 24 '26 09:05

rado


1 Answers

https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING

A dollar-quoted string constant consists of a dollar sign ($), an optional “tag” of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign.

In short - you can put any tag - not just BODY fro trigger or function for \sf as psql usually formats it. sample:

t=# do
$anything$
begin
 raise info '%', 'any tag would work';
end;
$anything$
;
INFO:  any tag would work
DO

also answering any it should be named - it should not.jut $$ is same fine as $BODY$, but "naming" is very helpful when you need to use quoting inside quoting. like in my sample above I use single quote quoting with raise, and I don't need to double single quotes or escape them to use inside body, because I use dollar sign quoting already. probably the clearer sample would be:

t=# do
$anything$
begin
 raise info $$%$$, $someothertag$any tag would work$someothertag$;
end;
$anything$
;
INFO:  any tag would work
DO
like image 171
Vao Tsun Avatar answered May 27 '26 00:05

Vao Tsun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!