diff --git a/sqlit/domains/connections/providers/postgresql/adapter.py b/sqlit/domains/connections/providers/postgresql/adapter.py index b2a542c6..4807db01 100644 --- a/sqlit/domains/connections/providers/postgresql/adapter.py +++ b/sqlit/domains/connections/providers/postgresql/adapter.py @@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any +from sqlit.domains.connections.providers.adapters.base import ForeignKeyInfo from sqlit.domains.connections.providers.postgresql.base import PostgresBaseAdapter from sqlit.domains.connections.providers.registry import get_default_port from sqlit.domains.connections.providers.tls import ( @@ -154,3 +155,75 @@ def get_procedures(self, conn: Any, database: str | None = None) -> list[str]: "ORDER BY routine_name" ) return [row[0] for row in cursor.fetchall()] + + # Foreign keys are read from pg_catalog rather than information_schema. + # information_schema.table_constraints / referential_constraints only list + # constraints on tables the current user owns or holds a non-SELECT + # privilege on, so read-only roles would see no FKs at all. + _FK_CATALOG_SQL = ( + "SELECT c.conname, k.ord, " + " own_ns.nspname, own.relname, own_att.attname, " + " ref_ns.nspname, ref.relname, ref_att.attname " + "FROM pg_catalog.pg_constraint c " + "CROSS JOIN LATERAL unnest(c.conkey, c.confkey) WITH ORDINALITY " + " AS k(own_attnum, ref_attnum, ord) " + "JOIN pg_catalog.pg_class own ON own.oid = c.conrelid " + "JOIN pg_catalog.pg_namespace own_ns ON own_ns.oid = own.relnamespace " + "JOIN pg_catalog.pg_attribute own_att " + " ON own_att.attrelid = c.conrelid AND own_att.attnum = k.own_attnum " + "JOIN pg_catalog.pg_class ref ON ref.oid = c.confrelid " + "JOIN pg_catalog.pg_namespace ref_ns ON ref_ns.oid = ref.relnamespace " + "JOIN pg_catalog.pg_attribute ref_att " + " ON ref_att.attrelid = c.confrelid AND ref_att.attnum = k.ref_attnum " + "WHERE c.contype = 'f' AND c.conparentid = 0 " + ) + + @staticmethod + def _fk_rows_to_info(rows: list[Any]) -> list[ForeignKeyInfo]: + return [ + ForeignKeyInfo( + owner_table=row[3], + column=row[4], + referenced_table=row[6], + referenced_column=row[7], + owner_schema=row[2] or "", + referenced_schema=row[5] or "", + constraint_name=row[0], + ordinal=int(row[1]), + ) + for row in rows + ] + + def get_foreign_keys( + self, + conn: Any, + table: str, + database: str | None = None, + schema: str | None = None, + ) -> list[ForeignKeyInfo]: + """List outgoing FKs of `table` from pg_catalog.""" + cursor = conn.cursor() + cursor.execute( + self._FK_CATALOG_SQL + + "AND own_ns.nspname = %s AND own.relname = %s " + "ORDER BY c.conname, k.ord", + (schema or "public", table), + ) + return self._fk_rows_to_info(cursor.fetchall()) + + def get_referencing_foreign_keys( + self, + conn: Any, + table: str, + database: str | None = None, + schema: str | None = None, + ) -> list[ForeignKeyInfo]: + """List FKs from other tables that reference `table`, from pg_catalog.""" + cursor = conn.cursor() + cursor.execute( + self._FK_CATALOG_SQL + + "AND ref_ns.nspname = %s AND ref.relname = %s " + "ORDER BY own_ns.nspname, own.relname, c.conname, k.ord", + (schema or "public", table), + ) + return self._fk_rows_to_info(cursor.fetchall()) diff --git a/sqlit/domains/connections/providers/postgresql/base.py b/sqlit/domains/connections/providers/postgresql/base.py index 88303225..33667138 100644 --- a/sqlit/domains/connections/providers/postgresql/base.py +++ b/sqlit/domains/connections/providers/postgresql/base.py @@ -128,11 +128,24 @@ def quote_identifier(self, name: str) -> str: return f'"{escaped}"' def quote_literal(self, value: Any) -> str: - """Render text independently of PostgreSQL backslash-string settings.""" + """Render text independently of PostgreSQL backslash-string settings. + + Uses a dollar-quoted string: its body is taken verbatim (no backslash + or quote escaping), and it stays an *untyped* literal, so PostgreSQL + coerces it to the column type (uuid, integer, date, ...). An + expression such as convert_from(...) would be typed text and fail + with "operator does not exist: uuid = text". + """ if not isinstance(value, str): return super().quote_literal(value) - encoded = value.encode("utf-8").hex() - return f"convert_from(decode('{encoded}', 'hex'), 'UTF8')" + n = 0 + while True: + tag = f"$sqlit{n or ''}$" + # The body ends at the first occurrence of the tag, including one + # formed by the value's tail plus the closing tag. + if f"{value}{tag}".find(tag) == len(value): + return f"{tag}{value}{tag}" + n += 1 def format_autocomplete_identifier(self, name: str) -> str: """Quote autocomplete identifiers that PostgreSQL would otherwise fold.""" diff --git a/tests/unit/test_foreign_key_introspection.py b/tests/unit/test_foreign_key_introspection.py index d8a68856..e4c8598d 100644 --- a/tests/unit/test_foreign_key_introspection.py +++ b/tests/unit/test_foreign_key_introspection.py @@ -193,10 +193,18 @@ def test_postgres_string_literal_is_independent_of_backslash_settings(self): value=value, ref_schema="public", ) - literal = f"convert_from(decode('{value.encode('utf-8').hex()}', 'hex'), 'UTF8')" + literal = f"$sqlit${value}$sqlit$" assert q == f'SELECT * FROM "public"."users" WHERE "external_id" = {literal} LIMIT 100' + def test_postgres_string_literal_avoids_tag_collisions(self): + from sqlit.domains.connections.providers.postgresql.adapter import PostgreSQLAdapter + + adapter = PostgreSQLAdapter() + assert adapter.quote_literal("a$sqlit$b") == "$sqlit1$a$sqlit$b$sqlit1$" + assert adapter.quote_literal("ends$sqlit") == "$sqlit1$ends$sqlit$sqlit1$" + assert adapter.quote_literal("") == "$sqlit$$sqlit$" + def test_sql_server_uses_bit_and_binary_literals(self): from sqlit.domains.connections.providers.mssql.adapter import SQLServerAdapter from sqlit.domains.results.ui.mixins.results import build_fk_navigation_query diff --git a/tests/unit/test_postgres_foreign_keys_catalog.py b/tests/unit/test_postgres_foreign_keys_catalog.py new file mode 100644 index 00000000..9721d9b7 --- /dev/null +++ b/tests/unit/test_postgres_foreign_keys_catalog.py @@ -0,0 +1,61 @@ +"""PostgreSQL FK introspection must not depend on information_schema. + +information_schema.table_constraints / referential_constraints hide +constraints on tables where the current role only has SELECT, so read-only +users saw no foreign keys and FK navigation (o / O) silently did nothing. +""" + +from __future__ import annotations + +from typing import Any + +from sqlit.domains.connections.providers.postgresql.adapter import PostgreSQLAdapter + + +class _Cursor: + def __init__(self, rows: list[tuple[Any, ...]]) -> None: + self.rows = rows + self.sql = "" + self.params: tuple[Any, ...] = () + + def execute(self, sql: str, params: tuple[Any, ...] = ()) -> None: + self.sql = sql + self.params = params + + def fetchall(self) -> list[tuple[Any, ...]]: + return self.rows + + +class _Conn: + def __init__(self, cursor: _Cursor) -> None: + self._cursor = cursor + + def cursor(self) -> _Cursor: + return self._cursor + + +def test_referencing_foreign_keys_use_pg_catalog() -> None: + cursor = _Cursor( + [("prices_instrument_id_fkey", 1, "currency", "prices", "instrument_id", "currency", "instruments", "id")] + ) + fks = PostgreSQLAdapter().get_referencing_foreign_keys(_Conn(cursor), "instruments", None, "currency") + + assert "pg_catalog.pg_constraint" in cursor.sql + assert "information_schema" not in cursor.sql + assert cursor.params == ("currency", "instruments") + assert len(fks) == 1 + fk = fks[0] + assert (fk.owner_schema, fk.owner_table, fk.column) == ("currency", "prices", "instrument_id") + assert (fk.referenced_schema, fk.referenced_table, fk.referenced_column) == ("currency", "instruments", "id") + + +def test_outgoing_foreign_keys_use_pg_catalog_and_default_schema() -> None: + cursor = _Cursor( + [("orders_user_id_fkey", 1, "public", "orders", "user_id", "public", "users", "id")] + ) + fks = PostgreSQLAdapter().get_foreign_keys(_Conn(cursor), "orders") + + assert "pg_catalog.pg_constraint" in cursor.sql + assert "information_schema" not in cursor.sql + assert cursor.params == ("public", "orders") + assert [(fk.column, fk.referenced_table, fk.referenced_column) for fk in fks] == [("user_id", "users", "id")]