Passing a file path to COPY … TO PROGRAM

All we need is an easy explanation of the problem, so here it is.

I am trying to pass a file path to lp using COPY ... TO PROGRAM 'lp';.

If I store the file path in a table and query that with SELECT within COPY statement, it gets passed as a string (i.e echo /path/to/file.pdf | lp) and lp would print that string instead of printing the file itself which is a pdf file.

Is there a way to do this within PostgreSQL or a trick that would pass-to/take-from query the result and pass it to the shell command as file path?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You could use dynamic SQL in a DO statement using format():

DO
$$BEGIN
   EXECUTE format(
              'COPY ... TO PROGRAM %L',
              (SELECT format('echo %L | lp', path) FROM configuration)
           );
END;$$;

In this example configuration is a one row table with a column path that holds the path name – adapt the query as needed.

The placeholder %L is replaced with the second argument, properly escaped as string literal. That way, you avoid the danger of SQL injection.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply