file_fdw: Reading Server Files as Tables
Last updated: 2026-11-04
file_fdw: Reading Server Files as Tables
file_fdw is also a foreign data wrapper, but what it reads is not another database — it reads files from the server's filesystem. You declare a CSV or any other COPY-readable file as a foreign table and query it directly, row by row, without importing it first. Paths are resolved relative to the data directory and the file must be readable by the server process; the program option goes further, running a command and reading its standard output.
| Kind | extension |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE EXTENSION IF NOT EXISTS file_fdw;
CREATE SERVER file_server FOREIGN DATA WRAPPER file_fdw;
CREATE FOREIGN TABLE t_csv (
id int,
name text
) SERVER file_server
OPTIONS (filename 'data/orders.csv', format 'csv', header 'true');
SELECT * FROM t_csv;
Returns:CREATE EXTENSION, CREATE SERVER and CREATE FOREIGN TABLE return no result set on success. A SELECT against the foreign table parses the file row by row using COPY rules and returns the declared columns; exactly one of filename and program must be given.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT id, name, score FROM t_csv_scores_fdw ORDER BY id
id | name | score
----+-------+-------
1 | row-1 | 1.50
2 | row-2 | 3.00
3 | row-3 | 4.50
(3 rows)
Note: the example first writes a CSV with COPY and then reads it back through file_fdw, so the script is self-contained; on a real server, writing the file with COPY TO requires superuser or the pg_write_server_files role.
📌 Key Points
- In browser PGlite it must be loaded on demand: import { file_fdw } from '@electric-sql/pglite/contrib/file_fdw', then new PGlite({ extensions: { file_fdw } }).
- Size: file_fdw is about 5 KB, among the smallest contrib extensions (pg_trgm ~15 KB, btree_gist ~22 KB and uuid-ossp ~17 KB are in the same league; pgcrypto at ~1.1 MB is much larger).
- Relative paths resolve against the server's data directory (PGDATA) and absolute paths follow the operating system; the file must be readable by the server process, and non-superusers additionally need the pg_read_server_files role.
- Exactly one of filename and program may be given. The program option hands the command to a shell, so any argument must come from a trusted source — otherwise it is an arbitrary command execution hole.
- file_fdw is read-only: you cannot INSERT, UPDATE or DELETE through a foreign table. Use COPY ... TO or pg_write_file to write files.
- Every foreign-table option value must be spelled out: write header as 'true' rather than the bare HEADER keyword COPY accepts.