You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
--postgres: foreign keys are dropped, and the schema is disconnected from the code #1854
Two problems when importing a live DB into a code graph via --postgres (graphify 0.9.14):
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 207FOREIGN KEY constraints; graph.json contains 0table → table edges.
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.
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
Emit FK edges from pg_constraint / information_schema.referential_constraints as table → table edges.
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.:
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:
CREATEFUNCTION "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):
frompathlibimportPurePosixPathfromgraphify.extractors.sqlimportextract_sqlN=6tables="".join(f'CREATE TABLE "public"."t{i}" (id INT);\n'foriinrange(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'foriinrange(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")
forlabel, ddlin [
("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= [eforeinr["edges"] ife.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/41references 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)forconstraint_name, t_schema, t_name, cols, r_schema, r_name, r_colsinfks:
...
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:
Parse each reconstructed statement (or each section) in its own extract_sql
call, so one unparseable statement can't cascade into its neighbors.
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).
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."
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.
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.
Activity
sekmur commentedon Jul 13, 2026
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.pyqueriespg_constraintand emitsALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEYstatements correctly. The edges arelost one step later, in the parse.
Root cause.
introspect_postgres()reconstructs one synthetic DDL document in theorder 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 lookslike:
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 TABLEstatementsare 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 cstubs.(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):
Output on 0.9.14 (
tree-sitter-sqlinstalled):On my real DB (35 tables, 41 FKs, 41 extension routines from fuzzystrmatch/pg_trgm):
stock 0.9.14 yields 1/41
referencesedges; the reorder below yields 41/41.The severity varies with the statement mix — which would also explain your log's
163 edgesnot matching the 151 written: partial error recovery mangles thestatement 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:
i.e. move this loop:
to just before the
# Functions & Proceduresloop. FK statements only referencetables, which are emitted first, so the reorder is safe. Result on my DB: 41/41
referencesedges vs 1/41 stock.Robust fix suggestions:
extract_sqlcall, so one unparseable statement can't cascade into its neighbors.
LANGUAGE c/LANGUAGE internalroutines and emit aparseable no-op stub (the body is just the C symbol name — there's nothing to
extract from it anyway).
fraction of the input — this failure was completely silent, which is what let it
masquerade as "FK extraction not implemented."
safishamsi commentedon Jul 14, 2026
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.
sekmur commentedon Jul 15, 2026
Confirmed on a fresh (forced)
uv tool install graphifyy[postgres]@0.9.16the failureis 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 ininformation_schema.referential_constraints); this bug is in the parse of thereconstructed DDL, downstream of a correct read.
fix(pg_introspect): emit FK DDL before function stubs so unparseable …
fix(pg_introspect): emit FK DDL before function stubs so unparseable …
Fix: recover SQL CREATE POLICY statements as nodes (Graphify-Labs#3401)