Skip to content

Commit 75160dc

Browse files
authored
Test mixed-case Postgres schemas and tables with unmappable column types (#1839)
ibis sets the search_path to the server's schema without quoting it, so a schema like "Reporting" was read as reporting and every check failed with "Could not read model". The table is now qualified with the schema, as for Redshift. ibis cannot map some Postgres types (regclass), and a single such column made every check on its table fail. Those columns are now read as unknown, so the other columns are checked. bit(8) and bit varying are bit strings, not booleans; only bit and bit(1) map to boolean, as in Entropy Data's asset import, which now reads the Postgres catalog with the same queries as datacontract import postgres.
1 parent 5f35d6d commit 75160dc

7 files changed

Lines changed: 130 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Fixed
1111
- `datacontract test` checks the constraints and quality rules of nested properties (struct fields and array items) on Dremio servers
12+
- `datacontract test` finds tables in Postgres schemas with upper case letters, such as `"Reporting"`
13+
- `datacontract test` checks the other columns of a Postgres table with a column of a type ibis cannot read, such as `regclass`
14+
- `datacontract import postgres` and `import sql` no longer map bit strings of more than one bit (`bit(8)`, `bit varying`) to `boolean`
1215

1316
## [1.2.11] - 2026-11-17
1417

‎datacontract/engines/ibis/ibis_check_execute.py‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,6 +1667,9 @@ def _table_database(con, server: Optional[Server]) -> Optional[str]:
16671667
- **SQL Server** (``mssql`` backend) has no ``schema`` kwarg on
16681668
``do_connect()`` either, so it has the same limitation as Oracle: an
16691669
unqualified lookup falls back to the login's default schema.
1670+
- **Postgres** sets the ``search_path`` to the schema without quoting it,
1671+
so a mixed-case schema such as ``Reporting`` is read as ``reporting``
1672+
and an unqualified lookup raises ``TableNotFound``.
16701673
- **Redshift** has no dedicated ibis backend and goes through the Postgres
16711674
backend (``con.name == "postgres"``). When no schema is passed, ibis's
16721675
Postgres introspection resolves the active schema with ``SELECT
@@ -1685,9 +1688,8 @@ def _table_database(con, server: Optional[Server]) -> Optional[str]:
16851688
# so a table outside `main` has to be qualified at lookup.
16861689
if get_server_type(server) == "duckdb":
16871690
return server.schema_
1688-
# Redshift rides the Postgres backend, so detect it by the contract's server
1689-
# type rather than con.name.
1690-
if get_server_type(server) == "redshift":
1691+
# Redshift rides the Postgres backend, so this covers both.
1692+
if getattr(con, "name", None) == "postgres":
16911693
return server.schema_
16921694
return None
16931695

@@ -1721,10 +1723,14 @@ def _resolve_table(con, model: str, database: Optional[str] = None):
17211723
# duckdb reads `DESCRIBE "tables"` as `SHOW TABLES` however it is quoted, unless the name is qualified
17221724
if getattr(con, "name", None) == "duckdb" and not database and model.lower() in _DUCKDB_SHOW_NAMES:
17231725
database = "main"
1726+
from ibis.common.exceptions import TableNotFound
1727+
17241728
kwargs = {"database": database} if database else {}
17251729
try:
17261730
return con.table(model, **kwargs)
1727-
except Exception:
1731+
except Exception as e:
1732+
if getattr(con, "name", None) == "postgres" and not isinstance(e, TableNotFound):
1733+
return _postgres_table_unmappable_as_unknown(con, model, database)
17281734
try:
17291735
available = con.list_tables(**kwargs)
17301736
except Exception:
@@ -1735,6 +1741,47 @@ def _resolve_table(con, model: str, database: Optional[str] = None):
17351741
return con.table(match, **kwargs)
17361742

17371743

1744+
def _postgres_table_unmappable_as_unknown(con, name: str, database: Optional[str]):
1745+
"""Reflect a postgres table, typing any column whose type ibis cannot map
1746+
(e.g. `regclass`) as `Unknown`, so the other columns can still be checked.
1747+
"""
1748+
import ibis.expr.datatypes as dt
1749+
import ibis.expr.operations as ops
1750+
import ibis.expr.schema as sch
1751+
from ibis.common.exceptions import TableNotFound
1752+
1753+
# The query ibis's get_schema() runs, including its reading of enums
1754+
query = """
1755+
SELECT a.attname,
1756+
CASE WHEN t.typtype = 'e' THEN 'enum' ELSE pg_catalog.format_type(a.atttypid, a.atttypmod) END,
1757+
NOT a.attnotnull
1758+
FROM pg_catalog.pg_attribute a
1759+
JOIN pg_catalog.pg_class c ON a.attrelid = c.oid
1760+
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
1761+
JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
1762+
WHERE a.attnum > 0 AND NOT a.attisdropped AND n.nspname = %(schema)s AND c.relname = %(name)s
1763+
ORDER BY a.attnum
1764+
"""
1765+
with con.con.cursor() as cursor:
1766+
rows = cursor.execute(query, {"schema": database or con.current_database, "name": name}).fetchall()
1767+
if not rows:
1768+
raise TableNotFound(name)
1769+
fields, unknown_columns = {}, []
1770+
for column, type_name, nullable in rows:
1771+
try:
1772+
fields[column] = con.compiler.type_mapper.from_string(type_name, nullable=nullable)
1773+
except Exception:
1774+
fields[column] = dt.unknown
1775+
unknown_columns.append(f"{column} ({type_name})")
1776+
logger.warning(
1777+
f"Model '{name}': column(s) {', '.join(unknown_columns)} have a type ibis cannot represent. "
1778+
f"Type checks for these columns will fail."
1779+
)
1780+
return ops.DatabaseTable(
1781+
name, schema=sch.Schema(fields), source=con, namespace=ops.Namespace(database=database)
1782+
).to_expr()
1783+
1784+
17381785
def _pyspark_table_unconvertible_as_unknown(con, name: str):
17391786
"""Reflect a pyspark table, typing any column whose Spark type Ibis cannot
17401787
convert (e.g. Databricks `VariantType`) as `Unknown`.

‎datacontract/imports/postgres_importer.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,13 @@
4545

4646
# to_regclass() yields NULL instead of raising for objects the user cannot see,
4747
# so a missing comment never fails the whole import.
48+
# Entropy Data's Postgres asset import runs the same queries (PostgresCatalog.kt);
49+
# keep the two in sync so both give the same types, descriptions and keys.
4850
_TABLES_QUERY = """
4951
SELECT table_name,
5052
lower(replace(table_type, 'BASE ', '')) AS table_type,
5153
obj_description(
52-
to_regclass(quote_ident(table_schema) || '.' || quote_ident(table_name))
54+
to_regclass(quote_ident(table_schema) || '.' || quote_ident(table_name)), 'pg_class'
5355
) AS remarks
5456
FROM information_schema.tables
5557
WHERE table_schema = %s

‎datacontract/imports/sql_importer.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,8 @@ def map_type_from_sql(sql_type: str) -> tuple[str | None, str | None]:
461461
return ("number", None)
462462
elif sql_type_normed.startswith("bool"):
463463
return ("boolean", None)
464-
elif sql_type_normed.startswith("bit"):
464+
elif sql_type_normed in ("bit", "bit(1)"):
465+
# A string of more bits (bit(8), bit varying) is not a boolean
465466
return ("boolean", None)
466467
elif sql_type_normed.startswith("binary"):
467468
return ("string", "binary")

‎tests/test_ibis_oracle_schema.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,19 @@ def test_table_database_none_for_oracle_without_schema():
4545

4646

4747
def test_table_database_none_for_non_oracle_backend():
48-
# Postgres/snowflake pin the schema at connect time, so no qualifier is added.
49-
server = Server(type="postgres", schema="public")
50-
con = _FakeBackend("postgres", {})
48+
# Snowflake pins the schema at connect time, so no qualifier is added.
49+
server = Server(type="snowflake", schema="public")
50+
con = _FakeBackend("snowflake", {})
5151
assert _table_database(con, server) is None
5252

5353

54+
def test_table_database_uses_server_schema_for_postgres():
55+
# ibis sets the search_path without quotes, so a mixed-case schema is not found unqualified.
56+
server = Server(type="postgres", schema="Reporting")
57+
con = _FakeBackend("postgres", {})
58+
assert _table_database(con, server) == "Reporting"
59+
60+
5461
def test_table_database_uses_server_schema_for_redshift():
5562
# Redshift rides the Postgres ibis backend (con.name == "postgres"). Without
5663
# an explicit schema, ibis introspects via `SELECT current_schema` (no

‎tests/test_import_sql_postgres.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,12 @@ def test_map_type_from_sql_uuid():
206206
from datacontract.imports.sql_importer import map_type_from_sql
207207

208208
assert map_type_from_sql("uuid") == ("string", "uuid")
209+
210+
211+
def test_map_type_from_sql_bit_strings_are_not_booleans():
212+
from datacontract.imports.sql_importer import map_type_from_sql
213+
214+
assert map_type_from_sql("bit") == ("boolean", None)
215+
assert map_type_from_sql("bit(1)") == ("boolean", None)
216+
assert map_type_from_sql("bit(8)") == (None, None)
217+
assert map_type_from_sql("bit varying(16)") == (None, None)

‎tests/test_test_postgres.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,55 @@ def test_catalog_views_are_checked_like_tables(postgres_container, monkeypatch):
262262
run = DataContract(data_contract_str=contract).test()
263263

264264
assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"]
265+
266+
267+
def test_mixed_case_schema_and_a_column_type_ibis_cannot_map(postgres_container, monkeypatch):
268+
"""A schema created with quotes, such as "Reporting", is found, and a column ibis
269+
cannot type (regclass) does not stop the other columns from being checked."""
270+
monkeypatch.setenv("DATACONTRACT_POSTGRES_USERNAME", postgres.username)
271+
monkeypatch.setenv("DATACONTRACT_POSTGRES_PASSWORD", postgres.password)
272+
import psycopg2
273+
274+
with psycopg2.connect(
275+
database=postgres.dbname,
276+
user=postgres.username,
277+
password=postgres.password,
278+
host=postgres.get_container_host_ip(),
279+
port=postgres.get_exposed_port(5432),
280+
) as connection:
281+
connection.cursor().execute(
282+
'CREATE SCHEMA "Reporting";'
283+
'CREATE TABLE "Reporting"."MonthlyRevenue" ("Month" date NOT NULL, "RevenueEUR" numeric(14,2), source regclass);'
284+
"""INSERT INTO "Reporting"."MonthlyRevenue" VALUES ('2026-10-01', 1200.50, 'pg_class');"""
285+
)
286+
contract = f"""apiVersion: v3.1.0
287+
kind: DataContract
288+
id: postgres-mixed-case
289+
name: Postgres mixed case
290+
version: 1.0.0
291+
status: active
292+
servers:
293+
- server: production
294+
type: postgres
295+
host: localhost
296+
port: {postgres.get_exposed_port(5432)}
297+
database: {postgres.dbname}
298+
schema: Reporting
299+
schema:
300+
- name: MonthlyRevenue
301+
quality:
302+
- metric: rowCount
303+
mustBe: 1
304+
properties:
305+
- name: Month
306+
logicalType: date
307+
physicalType: date
308+
required: true
309+
- name: RevenueEUR
310+
logicalType: number
311+
physicalType: numeric(14,2)
312+
"""
313+
314+
run = DataContract(data_contract_str=contract).test()
315+
316+
assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"]

0 commit comments

Comments
 (0)