All we need is an easy explanation of the problem, so here it is.
I am trying to pass a file path to
COPY ... TO PROGRAM 'lp';.
If I store the file path in a table and query that with
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.
You could use dynamic SQL in a
DO statement using
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.
%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 🙂