Subject: Re: variable filename for psql \copy

From: "Daniel Verite" <[email-masked]>
Date: Mon, 25 Apr 2022 12:24:47 +0200

Jiří Fejfar wrote:

> I have found maybe buggy behaviour (of psql parser?) when using psql \copy
> with psql variable used for filename.

While it's annoying that it doesn't work as you tried it, this behavior is 
documented, so in that sense it's not a bug.
The doc also suggests a workaround in a tip section:

From psql manpage:

  The syntax of this command is similar to that of the SQL COPY
   command. All options other than the data source/destination are as
   specified for COPY. Because of this, special parsing rules apply to
   the \copy meta-command. Unlike most other meta-commands, the entire
   remainder of the line is always taken to be the arguments of \copy,
   and neither variable interpolation nor backquote expansion are
   performed in the arguments.

       Tip
       Another way to obtain the same result as \copy ... to is to use
       the SQL COPY ... TO STDOUT command and terminate it with \g
       filename or \g |program. Unlike \copy, this method allows the
       command to span multiple lines; also, variable interpolation
       and backquote expansion can be used.

Best regards,
-- 
Daniel Vérité
https://postgresql.verite.pro/
Twitter: @DanielVerite