4
CREATE or replace FUNCTION test() RETURNS boolean AS $$
$filename = '/home/postgres';
if (-e $filename) { 
exec /home/postgres/test.sh &
return true; }
return false;
$$ LANGUAGE plperlu;

exec /home/postgres/test.sh & its showing syntax error. Could you please help how to call bash script into postgres funtion/procedure

2 Answers 2

5

Presumably, the code needs to be syntactically valid Perl. So you'll need to clean up a few bits.

CREATE or replace FUNCTION test() RETURNS boolean AS $$
  my $filename = '/home/postgres';
  if (-e $filename) { 
    system '/home/postgres/test.sh' and return 1;
  }
  return;
$$ LANGUAGE plperlu;

I've changed a few things:

  • I declare the variable $filename using my
  • I used system instead of exec. exec replaces the current process - effectively never returning to the calling function
  • system expects to be passed a string. So I've added quotes around the command
  • and is usually better in flow control statements than && (and always much better than & which is for bit-flipping, not flow control)
  • Perl doesn't have true and false, so I've replaced true with 1 (which is a true value in Perl). And I've removed the false from the other return statement - the default behaviour of return is to return a false value

I don't have a Postgresql installation to test this on. If it still doesn't work, please tell us what errors you get.

4
  • 4
    I'm not a Perl guru, but there seems to be a missing single quote in the system line. Mar 25, 2019 at 15:17
  • its working fine for me. Thank you so much Dave for your help. Mar 25, 2019 at 15:34
  • 1
    It's bad practice to use return when the sub is expected to return a scalar (because the sub won't always return a scalar). return 0 would make more sense here.
    – ikegami
    Mar 25, 2019 at 18:53
  • It's worth noting that Perl has two logical and operators that differ in precedence. The high precedence form && is great for compactly writing logical expressions, like $foo == 27 && $bar >= 5. The low precedence form is best used for flow control, like assert_we_are_done() and return 1; (or gets used for this much more frequently).
    – daotoad
    Mar 25, 2019 at 22:35
1

pl/sh exists, and can be used as a procedual language.

https://github.com/petere/plsh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.