Validate PostgreSQL CSV Imports with Staging and Atomic Rollback

Validate PostgreSQL CSV Imports with Staging and Atomic Rollback

Validate PostgreSQL CSV Imports with Staging and Atomic Rollback

When a business database receives a CSV file, a successful import command does not prove that field order, null values, and amounts meet the agreed contract. A more dangerous case is a script that commits one row at a time: when it stops on a bad record, part of the batch is already in the target table. Database imports on a dedicated server should separate file parsing, business validation, and the final write, then use failure cases to prove that the transaction boundary works.

This walkthrough uses Debian 12 with PostgreSQL and psql already installed. Use a separate test database, not a production connection; keep all tables in a dedicated schema and use synthetic CSV data. Rely on the existing authentication and authorization configuration for the database connection rather than putting a password on the command line.

1. Define the File and Field Contract First

This import accepts only three fields: a positive integer business key, a nonempty name, and an optional amount. The business key must contain one to nine digits, with no leading zero. The amount must be a nonnegative decimal number with one to ten integer digits and no more than two fractional digits. Scientific notation, thousands separators, and leading or trailing whitespace are rejected, not silently corrected.

A missing amount means unknown, not zero. In the CSV, an unquoted empty field represents SQL NULL, while "" represents an empty string; the latter is not a valid amount. Names may contain commas and quotation marks, but must follow CSV escaping rules.

The staging table preserves the original values produced by parsing; it does not guess their business meaning. Automatically trimming whitespace, converting empty strings to zero, or rounding amounts can turn upstream errors into apparently normal records that are difficult to trace.

First, create the target table in the separate test database. Run the following commands using the existing connection configuration:

CREATE SCHEMA import_accept;

CREATE TABLE import_accept.customer_credit (
    source_key integer PRIMARY KEY,
    display_name text NOT NULL CHECK (length(display_name) > 0),
    credit numeric(12,2) CHECK (credit >= 0)
);

If the schema already exists, check the state left by the previous exercise before proceeding; do not simply drop and recreate it. Create the target table outside the import transaction so that it remains available for inspection from another connection after a failure.

2. Prepare Input That Distinguishes Nulls from Empty Strings

Create a working directory on the same machine that runs psql, and restrict file permissions. The following example generates the CSV with the Python standard library to avoid missing quote escapes when constructing the file manually.

umask 077
mkdir -p /tmp/csv-accept
python3 - <<'PY'
import csv
from pathlib import Path

path = Path("/tmp/csv-accept/input.csv")
with path.open("w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["source_key", "display_name", "credit"])
    writer.writerow(["101", "alpha, east", "12.30"])
    writer.writerow(["102", "beta", ""])
PY

The second data record ends with an empty field. In this three-column record, that field is not individually quoted, so it imports as NULL. The client reads the file: paths used by \copy and server-side SQL COPY refer to different locations. Do not mistake a client-side path for a path on the database server.

Before loading, use a real CSV parser to check the header and column count:

python3 - <<'PY'
import csv

with open("/tmp/csv-accept/input.csv", encoding="utf-8", newline="") as f:
    reader = csv.reader(f, strict=True)
    if next(reader, None) != ["source_key", "display_name", "credit"]:
        raise SystemExit("Invalid header")
    for row in reader:
        if len(row) != 3:
            raise SystemExit("Invalid column count")
PY

This preflight check does not replace database validation. It checks only the agreed column order and basic structure. Set limits for field lengths, file size, and record count to suit the import task as well, so that oversized input cannot monopolize database resources.

3. Load and Validate Within a Single Transaction

Save the following as import.sql in the working directory. Every staging column uses text, preventing premature numeric conversions during loading and giving the business rules a clearly defined point at which to reject invalid data.

\set ON_ERROR_STOP on
BEGIN;

CREATE TEMP TABLE stage_credit (
    source_key text,
    display_name text,
    credit text
) ON COMMIT DROP;

\copy stage_credit (source_key, display_name, credit) FROM '/tmp/csv-accept/input.csv' WITH (FORMAT csv, HEADER true, ENCODING 'UTF8', NULL '')

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM stage_credit
        WHERE source_key IS NULL
           OR source_key !~ '^[1-9][0-9]{0,8}$'
           OR display_name IS NULL
           OR display_name = ''
           OR (
               credit IS NOT NULL
               AND credit !~ '^[0-9]{1,10}([.][0-9]{1,2})?$'
           )
    ) THEN
        RAISE EXCEPTION 'Invalid staged record';
    END IF;
END
$$;

INSERT INTO import_accept.customer_credit
    (source_key, display_name, credit)
SELECT source_key::integer, display_name, credit::numeric(12,2)
FROM stage_credit;

COMMIT;

When running the script, explicitly disable personal psql startup configuration, enable stop-on-error behavior, and verify the connection target:

psql -X -v ON_ERROR_STOP=1 -d import_lab \
  -f /tmp/csv-accept/import.sql

import_lab is the test database created beforehand. If the script fails, psql exits and closes the connection, rolling back the uncommitted transaction. A wrapper script must not ignore the exit code and continue to report success.

HEADER true only skips the first record; it does not match fields by header name. That makes the header preflight check and explicit column list essential. The amount regex rejects excess decimal places before casting, preventing numeric(12,2) from silently rounding the input.

4. Use Bad Records to Prove the Whole Batch Rolls Back

After the first successful run, query the target table from another connection. It should contain both business keys; the amount for 102 should satisfy IS NULL, not equal zero. The comma in the name should also be preserved.

Next, prepare a batch that should fail: change the business keys to 103 and 104, keep the first amount valid, and change the second to 1.234. Run the same script again. It should return a nonzero exit code, and an independent query should confirm that neither new key exists.

Then change the second amount to a double-quoted empty string and run the import again. It should fail during text validation. A field looking empty in an editor is not proof; inspect the parsed value or explicitly check the distinction between SQL NULL and an empty string.

Finally, create two records with otherwise valid data: one with the new key 103, and another reusing the existing key 101. This run should trigger a primary key violation, and 103 must not remain in the table either.

SELECT source_key, display_name, credit, credit IS NULL AS credit_missing
FROM import_accept.customer_credit
ORDER BY source_key;

SELECT count(*) AS unexpected_rows
FROM import_accept.customer_credit
WHERE source_key IN (103, 104);

For the failure cases, the second query must return zero. Do not infer the result from any assumed internal row-processing order within INSERT; the point is to prove that the transaction did not partially commit.

5. Apply the Acceptance Checks to Real Batches

Before a real import, freeze the input file and record its checksum, byte count, parsed record count, target database, and script version. Do not replace the file between the header preflight check and loading. If needed, use a separate batch directory with restrictive permissions to avoid checking one file and importing another.

The acceptance record must cover at least three paths: a valid batch is written in full, a batch with an invalid amount is rejected in full, and a batch with a duplicate key is rolled back in full. Retain the script exit code, error category, and verification results from an independent connection together. Logs must not include real customer names or complete raw records.

This procedure rejects duplicate keys; it does not automatically overwrite existing data. A failed batch can be corrected and rerun, but rerunning a successful batch will cause a conflict. This is not an idempotent import. If resumability or batch deduplication is required, design persistent batch identifiers and commit records separately.

Clean up the synthetic data and working files only after all exercises are complete. An import is not complete merely because a success message appears. It is complete when the input contract holds, the committed result can be independently verified, and every expected failure leaves no partially written batch.

Frequently asked questions

Does HEADER validate the CSV column names?

The HEADER true option used here only skips the first record. Validate header names and order separately, and explicitly list the destination columns.

Are empty CSV fields always imported as NULL?

With CSV and NULL '', an unquoted empty field becomes SQL NULL, while a quoted empty field remains an empty string. The amount contract accepts the former and rejects the latter.

Can a duplicate key leave earlier rows imported?

Loading, validation, and insertion run inside one explicit transaction. Any failure before commit rolls back the entire batch. Verify the destination using a separate connection.

EPYC 7543P Dedicated Server

From $444/month; total due = monthly rate × number of months. No discounts, setup fees, or contracts.

Choose a dedicated server configuration based on workload and budget

Check memory options, disk layout, and sustained bandwidth, then select the operating system and billing term. Plan images and off-site backups separately.