Re: COPY TO (query) allows no function arguments

From: Joe Conway <mail(at)joeconway(dot)com>
To: Färber, Franz-Josef (StMUK) <Franz-Josef(dot)Faerber(at)stmuk(dot)bayern(dot)de>, "pgsql-bugs(at)lists(dot)postgresql(dot)org" <pgsql-bugs(at)lists(dot)postgresql(dot)org>
Subject: Re: COPY TO (query) allows no function arguments
Date: 2021-03-10 15:17:07
Message-ID: eda708fe-a55c-0df5-8c64-cae6c9eeb54e@joeconway.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On 3/10/21 9:48 AM, Färber, Franz-Josef (StMUK) wrote:
> it is as simple as the subject says:
>
> The COPY TO (query) statement does not allow the passing of function arguments –
> is this by intent or a bug?

This is not a bug -- next time if you are uncertain please try the general list
first.

In any case, you cannot use the passed in argument text as part of a simple SQL
command -- you have to build the command from text and then execute it. For example:

8<------------------------
CREATE TABLE b(id int);
INSERT INTO b VALUES(1),(2),(42);

CREATE OR REPLACE FUNCTION a(myparam text)
RETURNS void LANGUAGE plpgsql AS $func$
BEGIN
EXECUTE $$COPY (SELECT * FROM $$ || myparam || $$) TO '/tmp/a.txt'$$;
END;
$func$;

SELECT a('b');
SELECT pg_read_file('/tmp/a.txt');
pg_read_file
--------------
1 +
2 +
42 +

(1 row)
8<------------------------

HTH,

Joe

--
Crunchy Data - http://crunchydata.com
PostgreSQL Support for Secure Enterprises
Consulting, Training, & Open Source Development

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message David G. Johnston 2021-03-10 15:45:07 Re: COPY TO (query) allows no function arguments
Previous Message Tom Lane 2021-03-10 15:16:00 Re: pg_upgrade from PostgreSQL 12.4 to PostgreSQL 13.2 on Windows 10 failes because of missing function pg_catalog.ascii_to_mic