0

I'm trying to build a function that returns some text. The text includes a BEGIN statement which seems to cause an error:

CREATE OR REPLACE FUNCTION create_trigger() RETURNS TEXT AS $$
BEGIN
    RETURN
    'CREATE OR REPLACE FUNCTION update_view() RETURNS trigger AS $$
       BEGIN -- error is near this begin
        IF TG_OP = ''INSERT''  THEN DO SOMETHING;
        ELSIF TG_OP = ''UPDATE'' THEN DO SOMETHING;
        END IF;
        RETURN NEW;
       END;
    $$ language plpgsql';
END;
$$ language plpgsql

I get a syntax error near the word BEGIN in the return statement and don't understand why, as I'm only trying to return some text. Is this because plpgsql recognizes the word BEGIN even if it is in a string portion of the code?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
kaycee
  • 901
  • 1
  • 9
  • 35

1 Answers1

0

Like user3137702 commented, the problem is with the dollar-quotes. I'd also suggest some other simplifications:

CREATE OR REPLACE FUNCTION create_trigger()
  RETURNS text AS
$func$
SELECT
   $f$CREATE OR REPLACE FUNCTION update_view()
        RETURNS trigger AS
      $func1$
      BEGIN
       CASE TG_OP
         WHEN 'INSERT' THEN -- DO SOMETHING;
         WHEN 'UPDATE' THEN -- DO SOMETHING;
       END CASE;
       RETURN NEW;
      END;
      $func1$ LANGUAGE plpgsql$f$;
$func$  LANGUAGE sql IMMUTABLE;

About quoting and nested dollar-quotes:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228