Sub topic 4
Server-side COPY versus psql \copy
This chapter assumes you can run CREATE TABLE, INSERT and SELECT, and that you can connect with psql. It also assumes you have seen the COPY command and its CSV options from the earlier chapters. The question here is where the file lives and which program reads or writes it. Many "COPY doesn't work" problems come from getting that wrong.
Two commands with one engine
PostgreSQL has two ways to run a copy.
- Server-side
COPYis an SQL statement. The database server process opens the file itself, on the server's filesystem, using the server's operating system account. \copyis apsqlmeta-command, not SQL.psqlopens the file on your machine. It then runs aCOPY ... FROM STDINorCOPY ... TO STDOUTstatement and moves the bytes over your existing connection.
The format options are the same in both: FORMAT csv, HEADER, DELIMITER, NULL and the rest. Only the location of the file and the permissions involved change.
Here is the sample table used throughout this tutorial:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);Server-side COPY
A server-side import names a path that the server can see:
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);Three details matter in practice.
- The path is resolved on the server. If PostgreSQL runs in a Docker container, the path is inside the container. If it runs on another host, the file must be on that host. A file on your laptop is invisible to the server.
- Relative paths are relative to the server's data directory, not to your shell's current directory. Use absolute paths.
- The file is opened by the operating system user that runs PostgreSQL, usually
postgres. That user needs read permission on the file and execute permission on every directory in the path. For export, it needs write permission on the target directory.
If the path is wrong or unreadable, you get an error like this:
ERROR: could not open file "/home/me/products.csv" for reading: Permission deniedor No such file or directory. These errors say nothing about your SQL. They describe the server's view of the filesystem.
Database privileges
The operating system check is only half of it. PostgreSQL also restricts which database roles may use server-side files. A role needs one of these:
- superuser status, or
- membership in the predefined role
pg_read_server_filesto read files withCOPY FROM, or - membership in
pg_write_server_filesto write files withCOPY TO.
A role without them sees:
ERROR: permission denied to COPY from a file
DETAIL: Only roles with privileges of the "pg_read_server_files" role may COPY from a file.
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.The hint names the way out. You also need ordinary table privileges: INSERT on the table to load it, and SELECT to export it. Chapter 8 covers the security reasoning in detail. The short version is that server-side file access lets a role read or write any file the postgres account can reach. Grant it sparingly:
GRANT pg_read_server_files TO loader_role;psql \copy
The client-side form looks nearly identical. The explicit column list says which table columns the file's fields map to, in order:
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)Here products.csv is looked up on the machine where psql runs. A relative path is relative to psql's current working directory. File permissions are those of your own user. The database role needs only the normal table privileges, so \copy works for any role that can INSERT into or SELECT from the table.
Export works the same way, and the file is created on the client:
\copy (SELECT id, name, price FROM products WHERE price > 10 ORDER BY id) TO 'expensive.csv' WITH (FORMAT csv, HEADER true)Because the server never touches a file, \copy is the only option when:
- you use a managed database service where you cannot log into the server host and are not given superuser rights;
- the file is on your workstation and the database is elsewhere;
- your role does not hold the
pg_*_server_filesroles.
Syntax quirks of \copy
\copy is a meta-command, so it follows psql rules rather than SQL rules.
- It must fit on one line. Meta-commands end at the end of the line. You cannot split a
\copyacross lines the way you can an SQL statement. - No trailing semicolon is needed. The rest of the line is passed along.
- No variable interpolation. Unlike most meta-commands,
\copydoes not expand:variablereferences or backquoted commands in its arguments. A script that tries\copy products FROM :'file'will not do what you expect. Put the literal path in, or generate the command text with a shell script. - A query can replace the table name when exporting, as in the example above. The query goes in parentheses.
How data flows: STDIN and STDOUT
Underneath, \copy is a thin wrapper. When you type the \copy ... FROM 'products.csv' command, psql sends the server this SQL:
COPY products (id, name, price, released, notes) FROM STDIN WITH (FORMAT csv, HEADER true);The server then switches the connection into copy mode. psql reads your local file and streams its contents as copy data. A COPY ... TO STDOUT runs in the other direction: the server streams rows to the client, and psql writes them to the file.
The STDIN and STDOUT keywords in COPY always refer to the client connection, never to the server's own standard streams. Any client library can use them. For example, psycopg has cursor.copy() and libpq has PQputCopyData. They work without any file access on the server.
Inline data in scripts
The STDIN form also works directly in a script. After a COPY ... FROM STDIN statement, psql reads the following lines as data until a line containing only \.:
COPY products (id, name, price) FROM STDIN WITH (FORMAT csv);
1,Pencil,0.50
2,Notebook,3.20
\.\copy also accepts stdin, stdout, pstdin and pstdout. With pstdin and pstdout, psql uses its own standard input and output. This allows pipelines such as cat products.csv | psql -c "\copy products FROM pstdin WITH (FORMAT csv, HEADER true)". A related option is PROGRAM. Server-side COPY ... FROM PROGRAM 'cmd' runs a command on the server and needs the pg_execute_server_program role. \copy ... FROM PROGRAM 'cmd' runs the command on the client.
Choosing between them
| Question | Server-side `COPY` | `psql \copy` |
|---|---|---|
| Where is the file? | Server filesystem | Client filesystem |
| Who opens the file? | The `postgres` OS user | Your OS user, through `psql` |
| Extra database privilege? | `pg_read_server_files` or `pg_write_server_files`, or superuser | None beyond table privileges |
| Works on managed cloud databases? | Usually not | Yes |
| Data crosses the network? | No | Yes, over the connection |
| Allows multi-line statement? | Yes, it is SQL | No, one line |
| Usable from application drivers? | Only the file form needs server access | The `STDIN` and `STDOUT` forms work from any driver |
Use server-side COPY when the file already sits on the database host, you control that host, and you want the data to skip the network round trip. Typical cases are batch jobs on the same machine and loads from a mounted volume. Use \copy for nearly everything else: ad hoc imports from your own files, exports to your workstation, and any environment where you lack superuser rights.
On speed, the server parses and stores rows the same way in both cases. \copy adds network transfer. Over a fast local link the difference is small. Over a slow link, the transfer can dominate the load time.
A scripted round trip
You can run \copy non-interactively with psql -c. Comparing counts after an export is a simple check that no rows were lost:
psql "$DATABASE_URL" -c "\copy (SELECT * FROM products ORDER BY id) TO 'products_export.csv' WITH (FORMAT csv, HEADER true)"
psql "$DATABASE_URL" -c "SELECT count(*) FROM products"
wc -l products_export.csvThe file has one more line than the table has rows, because of the header. This holds only if no field contains an embedded newline. A quoted field with a line break adds lines without adding rows, so a mismatch is a prompt to look closer, not proof of data loss.
Common errors
could not open file ... No such file or directorywith a server-sideCOPY. You gave a client path. Either copy the file to the server, or switch to\copy.permission denied to COPY from a file. Your role lacks the privilege. Use\copy, or ask an administrator for the appropriate predefined role.could not open file ... Permission denied. The role is allowed, but thepostgresOS user cannot read the file. Check the file mode and every parent directory.\copycomplains about syntax at the end of the line. You may have split the command across lines or tried to use apsqlvariable.- A Docker setup where the file exists on your host. The server-side path is evaluated in the container. Mount the directory into the container, or use
\copyfrom the host.
Exercises
Exercise
You run COPY products FROM '/home/ana/products.csv' WITH (FORMAT csv, HEADER true); from psql on your laptop, and the database runs on a remote server. You get "could not open file ... No such file or directory", although the file exists on your laptop. Why does this happen, and what single change fixes it without moving the file?
Show answer
Server-side COPY opens the path on the database server's filesystem, so /home/ana/products.csv is looked up on the remote host, where it does not exist. Replace COPY with the psql meta-command on one line, for example: \copy products FROM '/home/ana/products.csv' WITH (FORMAT csv, HEADER true). psql then reads the file on your laptop and streams it to the server over the connection.
Exercise
A role named analyst has INSERT and SELECT on products but no special roles. Which of these succeed for analyst: (a) COPY products TO '/tmp/out.csv' WITH (FORMAT csv), (b) \copy products TO 'out.csv' WITH (FORMAT csv), (c) COPY products TO STDOUT WITH (FORMAT csv)?
Show answer
(b) and (c) succeed. Writing to a server file in (a) needs the pgwriteserver_files role or superuser, so it fails with a permission error. (b) writes the file on the client with the user's own permissions, and (c) streams rows to the client without touching a server file. Both need only SELECT on the table.