Articles Architecture

GDPR data export implementation: stop missing tables

A GDPR data export implementation is a list: every table that holds a user’s data, and for each one either a section in the export file or a written reason why it is left out. The list goes stale the day a new feature adds a table with a user_id. The reliable way to export all user data under the right of access is a test that reads the database catalog and fails when a table references the user and the export has no decision for it.

This describes an engineering practice and is not legal advice. The schema and code are a small example that ran on PostgreSQL 16.

What do the right of access and data portability require?

Article 15 of the GDPR gives a person the right to obtain confirmation that their personal data is processed, access to that data, and information such as the purposes and the recipients. Article 15(3) obliges the controller to provide a copy, in a commonly used electronic form when the request was made electronically. Article 12(3) sets the time limit: without undue delay and in any event within one month of receipt, extendable by two further months for complex or numerous requests. Under Article 12(5) the answer is free of charge unless a request is manifestly unfounded or excessive.

Article 20, data portability, is narrower and stricter about format. It covers data the person “has provided” to the controller, processed by automated means on the basis of consent or a contract, and requires a “structured, commonly used and machine-readable format”. The EDPB Guidelines 01/2022 on the right of access state the practical difference: access also includes inferred and derived data created by the service, while portability only includes data the person provided. One export that contains everything, in a structured format, serves both.

Why does a data export become incomplete?

Three ordinary things happen in sequence. The export is written once, as a class that reads a fixed set of tables. Each later feature adds its own table with a user_id, and the pull request is about the feature, so nobody opens the export. Nothing fails: the endpoint still returns a valid file, it is only shorter than it claims.

The usual safety net does not catch it either. A typical export has an integration test that seeds one user and asserts each section of the file. That test proves that the sections it knows about are correct. It cannot notice a table that was created after it was written, or a table that reaches the user only through a parent table. What is missing is a check that compares the export with the schema.

How do you find every table that holds user data?

Start from the foreign keys. This query walks them recursively, so it also finds tables that belong to a user through a parent:

WITH RECURSIVE fk AS (
    SELECT tc.table_name   AS child,
           kcu.column_name AS child_column,
           ccu.table_name  AS parent,
           rc.delete_rule
    FROM information_schema.table_constraints tc
    JOIN information_schema.key_column_usage kcu
      USING (constraint_schema, constraint_name, table_name)
    JOIN information_schema.referential_constraints rc
      USING (constraint_schema, constraint_name)
    JOIN information_schema.constraint_column_usage ccu
      USING (constraint_schema, constraint_name)
    WHERE tc.constraint_type = 'FOREIGN KEY'
      AND tc.table_schema = 'public'
),
reachable AS (
    SELECT * FROM fk WHERE parent = 'app_user'
    UNION
    SELECT fk.* FROM fk JOIN reachable r ON fk.parent = r.child
)
SELECT child AS table_name, child_column, parent AS refers_to, delete_rule
FROM reachable
ORDER BY table_name, child_column

The example schema has ten tables: app_user, a course catalog table with no user data, the six tables below and two more that come up in a moment. On PostgreSQL 16 the query returns:

table_name        child_column   refers_to   delete_rule
ai_usage_event    user_id        app_user    CASCADE
course_progress   user_id        app_user    CASCADE
note              user_id        app_user    CASCADE
note_attachment   note_id        note        CASCADE
payment           user_id        app_user    SET NULL
session_token     user_id        app_user    CASCADE

Run it as the role that owns the tables, because constraint_column_usage only lists tables owned by the current role.

One limit matters in practice. The joins match constraints by schema and name, and PostgreSQL only requires a constraint name to be unique within its table. Generated names such as note_user_id_fkey are unique in practice. Hand-written names are not: if two tables both declare a constraint called fk_owner, the query pairs each with the other’s parent and reports wrong rows. Give foreign keys unique names, or read pg_constraint, which identifies a constraint by its table as well.

The same schema has two more tables that the query cannot see, because they have no foreign key: an audit_log with an actor_id and a newsletter_signup keyed by email. A second query lists columns that look like a user reference and are not part of any foreign key:

SELECT c.table_name, c.column_name
FROM information_schema.columns c
WHERE c.table_schema = 'public'
  AND c.table_name <> 'app_user'
  AND (c.column_name ~ '(user|actor|author|owner)_id$' OR c.column_name LIKE '%email%')
  AND NOT EXISTS (
      SELECT 1
      FROM information_schema.key_column_usage k
      JOIN information_schema.table_constraints t
        USING (constraint_schema, constraint_name, table_name)
      WHERE t.constraint_type = 'FOREIGN KEY'
        AND k.table_schema = c.table_schema
        AND k.table_name = c.table_name
        AND k.column_name = c.column_name
  )
ORDER BY c.table_name, c.column_name
table_name          column_name
audit_log           actor_id
newsletter_signup   email

That query is a heuristic for a manual review, since it depends on naming. No catalog query finds the rest: user data inside JSON columns, application logs, uploaded files, and the copies held by the payment provider, the email provider and analytics. The EDPB guidelines say the controller has to search for personal data throughout all IT systems, so those places need their own line in the list even though no test can discover them.

How do you test that the export covers every table?

Keep the decisions in code, next to the export:

public final class UserDataRegistry {

    public sealed interface Decision permits Exported, Excluded {}
    public record Exported(String section) implements Decision {}
    public record Excluded(String reason) implements Decision {}

    /** Tables the foreign key query finds. The test keeps this map in step with the schema. */
    public static final Map<String, Decision> TABLES = Map.ofEntries(
        Map.entry("course_progress", new Exported("courseProgress")),
        Map.entry("note",            new Exported("notes")),
        Map.entry("note_attachment", new Exported("noteAttachments")),
        Map.entry("payment",         new Exported("payments")),
        Map.entry("ai_usage_event",  new Exported("aiUsageEvents")),
        Map.entry("session_token",   new Excluded("credential: a token hash is a security secret"))
    );

    /** Tables found by review: no foreign key leads to them, so no query can keep this map complete. */
    public static final Map<String, Decision> WITHOUT_FOREIGN_KEY = Map.ofEntries(
        Map.entry("audit_log",         new Exported("auditLog")),
        Map.entry("newsletter_signup", new Exported("newsletterSignup"))
    );

    private UserDataRegistry() {}
}

There are two maps because the test below can only vouch for the first. TABLES is compared with the catalog in both directions. WITHOUT_FOREIGN_KEY holds what the manual review found, and the only thing a test can check there is that the tables still exist. Map.ofEntries is used because Map.of stops at ten pairs, and this list will outgrow that.

The test starts a throwaway PostgreSQL, applies the schema, runs the first query (stored as user-tables.sql) and compares the result with the registry:

class ExportCompletenessTest {

    static EmbeddedPostgres postgres;

    @BeforeAll
    static void migrate() throws IOException, SQLException {
        postgres = EmbeddedPostgres.start();
        try (Connection c = connection(); Statement s = c.createStatement()) {
            s.execute(resource("/schema.sql"));
        }
    }

    @AfterAll
    static void stop() throws IOException {
        postgres.close();
    }

    @Test
    void everyTableReferencingTheUserHasADecision() throws SQLException, IOException {
        Set<String> inDatabase = new TreeSet<>();
        try (Connection c = connection();
             Statement s = c.createStatement();
             ResultSet rs = s.executeQuery(resource("/user-tables.sql"))) {
            while (rs.next()) {
                inDatabase.add(rs.getString("table_name"));
            }
        }

        Set<String> unregistered = new TreeSet<>(inDatabase);
        unregistered.removeAll(UserDataRegistry.TABLES.keySet());
        if (!unregistered.isEmpty()) {
            fail("Tables reference app_user but have no export decision: " + unregistered
                + ". Add each one to UserDataRegistry as Exported(section) or Excluded(reason).");
        }

        Set<String> stale = new TreeSet<>(UserDataRegistry.TABLES.keySet());
        stale.removeAll(inDatabase);
        if (!stale.isEmpty()) {
            fail("UserDataRegistry lists tables that no longer reference app_user: " + stale);
        }
    }

    private static Connection connection() throws SQLException {
        return postgres.getPostgresDatabase().getConnection();
    }

    private static String resource(String name) throws IOException {
        try (var in = ExportCompletenessTest.class.getResourceAsStream(name)) {
            if (in == null) {
                throw new IOException("Test resource not found: " + name);
            }
            return new String(in.readAllBytes(), StandardCharsets.UTF_8);
        }
    }
}

EmbeddedPostgres comes from the io.zonky.test:embedded-postgres library. In a real project, point the test at the database your migration tool has just built. Adding a bookmark table with a user_id foreign key and nothing else makes the build fail with:

[ERROR]   ExportCompletenessTest.everyTableReferencingTheUserHasADecision:55 Tables reference app_user but have no export decision: [bookmark]. Add each one to UserDataRegistry as Exported(section) or Excluded(reason).

The developer who added the table gets the message in their own pull request and has to make the decision there. Two more tests belong in the same class. One checks that every Exported section name is a component of the export record, so the registry cannot promise a section that does not exist. The other checks that every table in WITHOUT_FOREIGN_KEY is still in the schema, so that map does not keep entries for tables that were dropped.

What can you leave out of the export?

Less than is convenient, and each exclusion needs its reason in the registry. Article 15(4) and Article 20(4) say that the copy must not adversely affect the rights and freedoms of others. The EDPB guidelines read this narrowly: the controller has to demonstrate the adverse effect in the concrete situation, and the result is leaving out or redacting those parts, not refusing the request.

Typical entries are credentials (password hashes, session tokens, two-factor secrets), data about other people, and internal fraud signals. Whether a given exclusion holds is a legal question, and the written reason is what a lawyer or a regulator can review. It helps to put a scope note in the export file itself, listing what is included and what is excluded. Access tokens can appear there as metadata without the secret, and uploaded archives as file name, size and checksum instead of the bytes.

What format should the export have, and how do you protect the endpoint?

Article 15 asks for a commonly used electronic form, and Article 20 for a structured, machine-readable one. A JSON document with one named section per table satisfies both readings in practice:

{
  "metadata": { "formatVersion": "1.0", "exportedAt": "2026-12-01T10:00:00Z" },
  "profile": { "email": "ada@example.com" },
  "notes": [ { "body": "Revise streams", "createdAt": "2026-11-20T08:15:00Z" } ],
  "payments": []
}

Keep section names stable and version the format, because people and scripts will read it. Build the export inside one read-only transaction at REPEATABLE READ isolation, so all sections show the same snapshot. Assembling it in memory is fine while one user’s data is small. For large accounts, write the sections to the response with a streaming JSON generator or build the file in a background job.

The file contains everything about a person, so the endpoint deserves more care than a normal read: authenticated, limited to the caller’s own account, rate limited per user, and ideally behind a fresh password check. The EDPB guidelines treat a normal login as sufficient authentication in an online service, so the extra check is a defence against a stolen session, not a legal requirement.

Does account deletion need the same list?

Yes. The right to erasure in Article 17 concerns the same personal data, so the registry that drives the export also tells you what deletion must remove. The delete_rule column of the first query is the deletion plan as the database sees it: CASCADE rows disappear with the user, and SET NULL rows stay without a link to the user. The second kind needs a recorded reason too. A third value needs attention before anything else: NO ACTION, the default when a foreign key declares no rule, and RESTRICT make the delete of the user fail while such rows exist, so the deletion code has to remove or detach them first. Article 17(3)(b) exempts processing that is necessary for compliance with a legal obligation, which is the usual reason to keep purchase records after an account is deleted, with the user reference set to null. Usage data such as LLM usage events is on the CASCADE side and in the export.

Summary

  • Treat the export as a registry: every table that holds user data is either exported as a named section or excluded with a written reason.
  • Find the tables with a recursive foreign key query on information_schema, and review by hand what it cannot see: ids without a foreign key, emails, JSON columns, logs, files, third parties.
  • Add a test that compares the catalog with the registry and fails with the table name.
  • Export structured JSON with stable section names and a format version.
  • Authenticate, rate limit and consider a password check on the export endpoint.
  • Use the same registry for account deletion, and record why anything survives it.