views:

99

answers:

1

I'm using psql to run a simple set of COPY statements contained in a file:

psql -d mydb -f 'wbf_queries.data.sql'

where wbf_queries.data.sql contains lines:

copy <my_query> to '/home/gvkv/mydata' delimiter ',' null '';
...

but I get a permission denied error:

... ERROR: could not open file ... for writing: Permission denied

I'm connecting under my user account (gvkv) which is also a superuser in PostgreSQL. Obviously, psql is running under a different (effective) user but I don't know how to change this. Can it be done within psql or do I need some unix-fu?


UPDATE: As per araqnid's answer, here's the relevant information for anyone else who comes by:

\copy ...

Performs a frontend (client) copy. This is an operation that runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.

More here.

+4  A: 

You can't change the effective user of the server process- only root can change UNIX user IDs at will. (To clarify: if you say copy to '/home/gvkv/mydata', the server postgres process will try to write that file (which runs as postgres/pgdba/whatever), not your client psql (which runs as you)).

You can, however, have the server stream the data to the client and then have the client write it, by using the client-side \copy command instead, i.e.:

\copy <copy-source> to '/home/gvkv/mydata' delimiter ',' null ''

psql will translate this to a "COPY TO STDOUT" command and then write /home/gvkv/mydata itself. This transfers the data across the security domains safely, although of course it's a little more expensive.

araqnid
+1 for establishing the distinction : one thing is the client (psql process, unrelated to the server, its own unix user, perhaps even its own computer), other thing is the server (postgres server process - aka postmaster). You must ask yourself which one is supposed to access the filesystem.
leonbloy