Skip to content

--postgres: foreign keys are dropped, and the schema is disconnected from the code #1854

Closed

Description

@qt1bo

Summary

Two problems when importing a live DB into a code graph via --postgres (graphify 0.9.14):

  1. Bug — FK relationships are lost. The help says --postgres maps "tables, views,
    functions + FK relationships", but the graph gets 0 FK edges. My DB declares
    207 FOREIGN KEY constraints; graph.json contains 0 table → table edges.
  2. Feature gap — the schema is an island. Imported tables form a star (one DB hub
    → tables via contains) with 0 edges to the code that maps them (ORM entities,
    repositories). The schema can't take part in any code↔DB traversal.

Environment

Component Version
graphify 0.9.14
PostgreSQL server 17.2
Doctrine ORM 2.20.9
Doctrine DBAL 3.10.4
DoctrineBundle 2.13.3
Symfony 5.4.45
Backend claude-cli (claude-opus-4-8)

Repro & evidence

graphify extract . --postgres "postgresql://<user>:<pass>@localhost:5432/<db>"
# log: PostgreSQL: 152 nodes, 163 edges

Live DB vs. graph.json:

DB (real) graph.json
tables + views 148 + 3 148 + 3 ✅
FOREIGN KEY constraints 207 0 ❌
table → table edges 207 expected 0
DB→code edges — 0

FK count verified with:

SELECT constraint_type, count(*) FROM information_schema.table_constraints
WHERE table_schema='public' GROUP BY constraint_type;
--  FOREIGN KEY | 207

The only DB edges written are 151 contains (hub → object). Note the log's 163 edges
matches neither the 151 written nor the 207 real FKs.

Expected / request

  1. Emit FK edges from pg_constraint / information_schema.referential_constraints as
    table → table edges.
  2. Provide a way to link tables to code. For ORM stacks the table name is in the source
    (e.g. Doctrine #[ORM\Table(name: 'x')]), so entity → table edges could be matched
    deterministically — or just document the DB node ID scheme so users can inject bridges.

Minor note

DB nodes carry file_type: "code" and no kind/_origin; the only way to tell a table
from a code symbol is the postgresql_ id prefix, e.g.:

{"label": "\"public\".\"order_line\"", "file_type": "code",
 "source_file": "postgresql:/localhost/appdb", "source_location": "L1",
 "id": "postgresql_localhost_appdb_public_order_line"}

A file_type: "db" or metadata.kind: "table" would let tooling filter them (they
currently interleave with code in graphify query results).

Activity

  1. sekmur commented on Jul 13, 2026

    @sekmur
    Contributor

    Can confirm the FK drop on a completely different stack (Rails 8 / PostgreSQL 14 /
    graphifyy 0.9.14, Windows), and I think I've found the root cause. It's not that FK
    extraction is missing — pg_introspect.py queries pg_constraint and emits
    ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY statements correctly. The edges are
    lost one step later, in the parse.

    Root cause. introspect_postgres() reconstructs one synthetic DDL document in the
    order tables → views → functions → FKs and hands the whole thing to
    extract_sql() in a single tree-sitter parse. For a C-language function
    (information_schema.routines.external_language = 'C'), the reconstructed stub looks
    like:

    CREATE FUNCTION "public"."levenshtein"() RETURNS void AS $gfx$ levenshtein $gfx$ LANGUAGE c;

    tree-sitter-sql can't parse that form, and tree-sitter's error recovery consumes
    following statements into the ERROR subtree. Since the FK ALTER TABLE statements
    are emitted last, they're what gets swallowed. Any database with a common extension
    installed (uuid-ossp, pgcrypto, pg_trgm, fuzzystrmatch, unaccent, PostGIS, …)
    has C-language routines in public, so this reproduces almost everywhere.
    plpgsql bodies (e.g. trigger functions) parse fine — it's specifically the
    LANGUAGE c stubs.

    (The current ordering is understandable — tables → views → functions → FKs-last is pg_dump's canonical restore-safe order, where constraints run last so they never precede their tables. That's the right order for DDL meant to be executed. But this document is only ever parsed, and for an error-recovering parser that order puts the highest-value statements directly downstream of the least-parseable ones.)

    Standalone repro (no database needed):

    from pathlib import PurePosixPath
    from graphify.extractors.sql import extract_sql
    
    N = 6
    tables = "".join(f'CREATE TABLE "public"."t{i}" (id INT);\n' for i in range(N + 1))
    fks = "".join(
        f'ALTER TABLE "public"."t{i}" ADD CONSTRAINT "fk{i}" '
        f'FOREIGN KEY ("ref_id") REFERENCES "public"."t{i+1}"("id");\n'
        for i in range(N)
    )
    c_fn = ('CREATE FUNCTION "public"."somefunc"() RETURNS void'
            " AS $gfx$ somefunc $gfx$ LANGUAGE c;\n")
    pl_fn = ('CREATE FUNCTION "public"."trigfunc"() RETURNS void'
             " AS $gfx$ BEGIN SELECT 1; END; $gfx$ LANGUAGE plpgsql;\n")
    
    for label, ddl in [
        ("no functions        ", tables + fks),
        ("1 C stub before FKs ", tables + c_fn + fks),
        ("1 plpgsql before FKs", tables + pl_fn + fks),
        ("C+plpgsql before FKs", tables + c_fn + pl_fn + fks),
        ("same stubs AFTER FKs", tables + fks + c_fn + pl_fn),
    ]:
        r = extract_sql(PurePosixPath("postgresql://host/db"), content=ddl)
        refs = [e for e in r["edges"] if e.get("relation") == "references"]
        print(f"{label}: {len(refs)}/{N} references edges")

    Output on 0.9.14 (tree-sitter-sql installed):

    no functions        : 6/6 references edges
    1 C stub before FKs : 0/6 references edges
    1 plpgsql before FKs: 6/6 references edges
    C+plpgsql before FKs: 3/6 references edges   <- every other FK statement eaten
    same stubs AFTER FKs: 6/6 references edges
    

    On my real DB (35 tables, 41 FKs, 41 extension routines from fuzzystrmatch/pg_trgm):
    stock 0.9.14 yields 1/41 references edges; the reorder below yields 41/41.
    The severity varies with the statement mix — which would also explain your log's
    163 edges not matching the 151 written: partial error recovery mangles the
    statement stream nondeterministically relative to input order.

    Mitigation (verified): in
    graphify/pg_introspect.py,
    move the FK block (L131–139) above the function block (L116–129) — a pure block move,
    no logic change. The DDL assembly order becomes:

    # before (v8) — assembly order in introspect_postgres():
    #   tables -> views -> functions -> FKs
    #                      ^^^^^^^^^    ^^^
    #                      unparseable  swallowed by the parser's
    #                      LANGUAGE c   error recovery
    #                      stubs
    
    # after — swap the two trailing blocks:
    #   tables -> views -> FKs -> functions
    #                      ^^^    ^^^^^^^^^
    #                      parsed clean     ERROR recovery now only
    #                      before any       eats trailing stubs, which
    #                      ERROR state      contribute no edges anyway

    i.e. move this loop:

        # FK edges — one ALTER TABLE per constraint (handles composite FKs correctly)
        for constraint_name, t_schema, t_name, cols, r_schema, r_name, r_cols in fks:
            ...
            ddl.append(
                f"ALTER TABLE {_quote_ident(t_schema)}.{_quote_ident(t_name)} "
                ...
            )

    to just before the # Functions & Procedures loop. FK statements only reference
    tables, which are emitted first, so the reorder is safe. Result on my DB: 41/41
    references edges vs 1/41 stock.

    Robust fix suggestions:

    1. Parse each reconstructed statement (or each section) in its own extract_sql
      call, so one unparseable statement can't cascade into its neighbors.
    2. Skip body reconstruction for LANGUAGE c / LANGUAGE internal routines and emit a
      parseable no-op stub (the body is just the C symbol name — there's nothing to
      extract from it anyway).
    3. Surface a warning when the parse tree contains ERROR nodes covering more than some
      fraction of the input — this failure was completely silent, which is what let it
      masquerade as "FK extraction not implemented."
  2. safishamsi commented on Jul 14, 2026

    @safishamsi
    Member

    The dropped-FK half was already fixed in 0.9.12 (#1746, reading FKs from pg_constraint) - the numbers in this report match pre-0.9.12 output, so please verify your installed version (a uv tool / pipx install may need a forced reinstall to actually upgrade). The 'schema disconnected from code' half is a genuine feature (entity->table bridging), now tracked at #1903. Closing this one; reopen if FK edges are still missing on a confirmed 0.9.16.

  3. sekmur commented on Jul 15, 2026

    @sekmur
    Contributor

    Confirmed on a fresh (forced) uv tool install graphifyy[postgres]@0.9.16 the failure
    is unchanged, so asking for a reopen per the note above.

    The repro in my comment above never connects to a database it feeds synthetic DDL
    directly into extract_sql(). #1746 fixed FK reading (privilege filtering in
    information_schema.referential_constraints); this bug is in the parse of the
    reconstructed DDL, downstream of a correct read.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions