How to Fix Postgres Error 22P04 Bad Copy File Format

Published
Length
3 min read

Luis Felipe Dias

All posts

The postgres error 22P04 bad copy file format happens when bulk input breaks parser rules. You fix it by matching delimiters, quotes, and line endings between the file and table. PostgreSQL tracks this failure under state code 22P04 and the ERRCODE_BAD_COPY_FILE_FORMAT macro. The database engine stops the whole import when one row breaks the file layout. Data teams see this issue during batch loads, migrations, and manual table imports. What causes postgres error 22P04 bad copy file format T

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

The postgres error 22P04 bad copy file format happens when bulk input breaks parser rules. You fix it by matching delimiters, quotes, and line endings between the file and table.

PostgreSQL tracks this failure under state code 22P04 and the ERRCODE_BAD_COPY_FILE_FORMAT macro. The database engine stops the whole import when one row breaks the file layout. Data teams see this issue during batch loads, migrations, and manual table imports.

What causes postgres error 22P04 bad copy file format

The copy parser expects a strict structure on every single line of your input file. If a row has too many or too few columns, the engine raises 22P04 right away. A single stray delimiter in a text field can split one column into two columns.

Unescaped quote marks inside text fields also break the copy parser during a load. When a field contains a quote mark, the parser thinks the column ended early. Everything after that quote mark looks corrupt to the database engine.

Mixed line endings between Windows and Linux systems trigger this error code quite often. If a file mixes carriage returns and newlines, the parser reads them as broken data. Corrupt binary headers or truncated files from a dropped network transfer also trigger 22P04.

Sometimes the error happens because the source export and target import use different format settings. One team might export data as comma separated text while the import expects tab characters. Without matching rules on both sides, the database rejects the file before writing any rows.

How to diagnose and fix 22P04 in production

Start by checking the exact line number reported in the database error log message. PostgreSQL tells you which row failed so you do not have to scan the file. Open a small slice of the file around that line in a plain text viewer.

Count the delimiters on the failing line and compare them to your target table columns. Look for unescaped quotes, raw newline characters inside text fields, or trailing delimiter characters. Check that the file encoding and line endings stay the same from start to finish.

End-to-End Encryption + Format-Preserving Encryption: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Do not grant superuser rights or broad write roles just to push a file through. In PostgreSQL, you can set up group roles to manage privileges for many users. Grant users membership in a scoped group role that only touches the target staging table.

Remember that the special role name PUBLIC grants privileges to every role on the system. In PostgreSQL 15 and later, default settings stop every user from creating public schema objects. On older or upgraded databases, an admin must revoke CREATE on the public schema from PUBLIC.

How to prevent bad copy files in data workflows

Clean and validate your source files before you open a database session for the import. Run a fast pre-check script that counts columns and strips stray carriage return characters. Make sure the export tool writes clean quotes around fields that hold delimiter characters.

When teams export data with COPY TO, they only need the SELECT privilege on tables. You can grant SELECT on specific columns of a table or view for safer exports. Scoping column rights keeps sensitive fields like emails or phone numbers out of export files.

If an import includes fields like card numbers or national IDs, keep staging tables locked down. Data masking rewrites matched fields in query results so raw values stay protected during checks. Test a ten-row sample file in a staging schema before running the full production load.

Run guardrails and masking on the Postgres connection

Role grants and firewall rules are needed setup. Setup alone cannot check single SQL statements or mask sensitive rows in a response. By design, hoop.dev sits inline in the Postgres protocol beside Postgres, RDS, or Aurora as a sidecar for your Postgres. On every production query from an engineer or AI agent, hoop.dev decides whether to pass, mask, block, or hold it for approval.

First, hoop.dev guardrails refuse disallowed drops or deletes before they run, and risky statements can pause for human review. Next, hoop.dev data masking rewrites sensitive fields in returned rows in memory. Furthermore, hoop.dev holds SOC 2 Type II and logs every statement and verdict per resource. Check out the project on GitHub.

Frequently asked questions

Does postgres error 22P04 save any rows before the bad line?

No, the copy operation runs inside a single transaction and rolls back on error. When the parser hits a bad line, PostgreSQL cancels the whole load and writes nothing.

Can wrong table permissions cause error code 22P04?

No, permission problems raise a different access error before the file parser ever starts reading. Error 22P04 strictly means the input data stream broke the expected copy file format rules.

How do I fix 22P04 when moving data between two Postgres databases?

Make sure both the export step and the import step use the exact same format. Keep the delimiter, quote rule, and null string identical on both the source and target.

The query runs. The emails stay hidden.