Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `datacontract import postgres` and `import sql` no longer map bit strings of more than one bit (`bit(8)`, `bit varying`) to `boolean`
- `datacontract lint` accepts the ids and references the current ODCS v3.1.0 schema allows, such as ids with `:` and shorthand references with `-` (#1859)
- `datacontract lint` accepts quality rules that combine several operators, such as `mustBeGreaterThan` with `mustBeLessThan`, and `test`, `breaking`, `dbt sync` and `export sodacl` apply every one of them; `export excel` warns about the ones it cannot hold (#1859)
- `datacontract test` runs MySQL checks on the server instead of copying the whole table into DuckDB (#1602)

## [1.2.11] - 2026-11-17

Expand Down
5 changes: 3 additions & 2 deletions datacontract/engines/checks/create_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,7 @@ def _quality_rule_checks(
check_key, check_type, model, field, quality, e.reason, "error", e.name, e.dimension, e.warnings
)
rule = instance.quality
refusal = refusal_reason(query, dialect)
refusal = refusal_reason(query, dialect, server_type=get_server_type(server))
if refusal is not None:
return _unexecuted_check(
check_key,
Expand Down Expand Up @@ -1094,7 +1094,8 @@ def not_executed(reason: str) -> List[CheckSpec]:
return not_executed(str(e))
# The query is read as the dialect of the server it runs against, so
# dialect-specific syntax is not mistaken for something that is not a query.
refusal = refusal_reason(query, dialect_for_server_type(get_server_type(server)))
server_type = get_server_type(server)
refusal = refusal_reason(query, dialect_for_server_type(server_type), server_type=server_type)
if refusal is not None:
return not_executed(refusal)
return [
Expand Down
26 changes: 24 additions & 2 deletions datacontract/engines/checks/sql_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"api": "duckdb",
"iceberg": "duckdb",
"duckdb": "duckdb",
# copied into duckdb
# queried through duckdb
"mysql": "duckdb",
# spark session backends
"dataframe": "spark",
Expand Down Expand Up @@ -82,12 +82,17 @@ def sqlglot_dialect_by_name(dialect: Optional[str]):
return dialect


def refusal_reason(query: str, dialect: Optional[str] = None) -> Optional[str]:
def refusal_reason(query: str, dialect: Optional[str] = None, *, server_type: Optional[str] = None) -> Optional[str]:
"""Why `query` is refused, or None when it is a single read-only statement.

Fails closed: a query that does not parse is refused rather than passed
through, and so is one that holds a second statement -- a trailing
`; DROP TABLE orders` must never reach the data source.

On MySQL the database stays attached so a view can push the check down, and
``server_type="mysql"`` also refuses ``mysql_query`` and the attached
catalog. A rule is DuckDB SQL over the contracted tables; those two would
send the rule's own SQL, or read a table the contract does not name.
"""
try:
statements = sqlglot.parse(query, dialect=sqlglot_dialect_by_name(dialect))
Expand All @@ -106,10 +111,27 @@ def refusal_reason(query: str, dialect: Optional[str] = None) -> Optional[str]:
# A trailing semicolon parses as an extra empty statement.
statements = [statement for statement in statements if statement is not None]
if len(statements) == 1 and isinstance(statements[0], _READ_ONLY):
if (server_type or "").lower() == "mysql":
reason = _mysql_attachment_reason(statements[0])
if reason is not None:
return reason
return None
return "A quality rule query must be a single read-only query, so it was not executed."


def _mysql_attachment_reason(statement) -> Optional[str]:
for node in statement.walk():
name = getattr(node, "name", None)
if isinstance(node, exp.Func) and isinstance(name, str) and name.lower() in {"mysql_query", "mysql_execute"}:
return _MYSQL_ONLY_CONTRACTED_TABLES
if isinstance(node, exp.Table) and any(part.lower() == "mysqldb" for part in (node.catalog, node.db) if part):
return _MYSQL_ONLY_CONTRACTED_TABLES
return None


_MYSQL_ONLY_CONTRACTED_TABLES = "A quality rule can only read the contracted MySQL tables, so it was not executed."


def _unreadable(error: sqlglot.errors.SqlglotError, dialect: Optional[str]) -> str:
# `str(error)` of a ParseError carries terminal escape codes around the offending token.
if isinstance(error, sqlglot.errors.ParseError) and error.errors:
Expand Down
25 changes: 13 additions & 12 deletions datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,8 +626,9 @@ def _connect_mysql_via_duckdb(
ibis's native MySQL backend requires ``mysqlclient`` (a C extension with no
macOS/Linux wheels, needing system MySQL client libraries to build). Routing
through DuckDB keeps the install pure-pip: DuckDB ATTACHes the MySQL database
and we expose each contract model as a view in the default catalog so the
rest of the engine works unchanged.
read-only and each contract model is a view in the default catalog, so the
rest of the engine works unchanged. DuckDB pushes the filters and aggregates
it can, so the table is not copied first.
"""
import duckdb

Expand All @@ -645,6 +646,8 @@ def _connect_mysql_via_duckdb(

con = duckdb.connect()
_load_extension(con, "mysql", "mysql")
# The extension leaves this off, so a MAX would still read every value.
con.execute("SET mysql_aggregate_pushdown_enabled = true")

run.log_info(f"Attaching MySQL {host}:{port} via the duckdb mysql extension")
_attach_mysql(con, host, port, user, password, database, config.get_connect_timeout())
Expand All @@ -654,23 +657,21 @@ def _connect_mysql_via_duckdb(
if schema_name != "all" and schema_obj.name != schema_name:
continue
model = schema_obj.physicalName or schema_obj.name
_materialize_attached_table(con, "mysqldb", database, model)
_expose_attached_table(con, "mysqldb", database, model)

# the checks read the local copies; contract SQL must not reach MySQL with these credentials
con.execute("DETACH mysqldb")
# The attachment stays so the views can run. It is read-only, and a quality
# rule cannot call mysql_query or name this catalog.
if untrusted_contract:
restrict_to_paths(con, [])

return ibis.duckdb.from_connection(con)


def _materialize_attached_table(con, catalog: str, database: str | None, model: str):
"""Copy an attached-catalog table into a local DuckDB table named ``model``.
def _expose_attached_table(con, catalog: str, database: str | None, model: str):
"""Point a local view named ``model`` at an attached MySQL table.

Materializing (rather than a view over the attached catalog) ensures all
checks run against local DuckDB data. Pushing complex check queries through
the DuckDB MySQL scanner can trigger DuckDB binder errors (e.g. on the
grouped duplicate-count query), so we read the rows once and check locally.
A check runs against the view, and DuckDB sends the filters and aggregates
it can to MySQL instead of copying the table first.
"""
# both come from the contract
safe_model = model.replace('"', '""')
Expand All @@ -682,7 +683,7 @@ def _materialize_attached_table(con, catalog: str, database: str | None, model:
last_error = None
for src in candidates:
try:
con.execute(f'CREATE OR REPLACE TABLE "{safe_model}" AS SELECT * FROM {src}')
con.execute(f'CREATE OR REPLACE VIEW "{safe_model}" AS SELECT * FROM {src}')
return
except Exception as e: # noqa: BLE001 - try the next naming candidate
last_error = e
Expand Down
9 changes: 7 additions & 2 deletions datacontract/engines/ibis/connections/duckdb_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,15 +711,20 @@ def _attach_mysql(
database: str | None,
connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,
) -> None:
"""ATTACH MySQL as ``mysqldb``; the password goes in a secret, as DuckDB echoes the ATTACH string in its errors."""
"""ATTACH MySQL as ``mysqldb``, read-only.

The password goes in a secret, as DuckDB echoes the ATTACH string in its errors.
Read-only so a check cannot change the server. The catalog stays attached:
views over it push filters and aggregates to MySQL.
"""
_wait_for_mysql_greeting(host, port, connect_timeout)
parts = [f"host={host}", f"port={port}", f"user={user}"]
if database:
parts.append(f"database={database}")
conn_str = " ".join(parts).replace("'", "''")
con.execute("CREATE TEMPORARY SECRET mysqldb_password (TYPE mysql, PASSWORD ?)", [password])
try:
con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql, SECRET mysqldb_password)")
con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql, SECRET mysqldb_password, READ_ONLY)")
finally:
con.execute("DROP TEMPORARY SECRET mysqldb_password")

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/quality-rules/sql.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ There is no `dialect` field on a quality rule. The dialect is **derived from the

The ODCS synonyms resolve to the spelling above before the dialect is looked up, so `postgresql` is read as `postgres`. A server declared as `type: custom` with `customType: mssql` is read as `tsql`, like `sqlserver`.

Files, Kafka topics, API responses and Iceberg tables are read through DuckDB, and MySQL tables are copied into DuckDB before the checks run, so a rule on those server types is written in DuckDB SQL — including its functions, such as `read_parquet` or `list_contains`. MySQL-only syntax, such as backtick-quoted names or `DATE_SUB`, does not work there.
Files, Kafka topics, API responses, Iceberg tables and MySQL are queried through DuckDB, so a rule on those server types is written in DuckDB SQL, including its functions, such as `read_parquet` or `list_contains`. MySQL-only syntax, such as backtick-quoted names or `DATE_SUB`, does not work there. On MySQL the table is not copied into DuckDB first. DuckDB runs the query and sends the filters and aggregates it can to the server.

## Notes

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/testing/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ schema:
mustBe: 0
```

The tables are copied into DuckDB before the checks run, so write the query in [DuckDB SQL](../quality-rules/sql.md#sql-dialect), not MySQL.
Write the query in [DuckDB SQL](../quality-rules/sql.md#sql-dialect), not MySQL. The table is not copied into DuckDB first. DuckDB runs the query and sends the filters and aggregates it can to MySQL.

Run `datacontract test datacontract.yaml` again: every violation is listed as an error, and the command exits with code `1` — ready for [CI/CD and scheduled runs](../scheduling/index.md) so you catch drift before your consumers do.

Expand Down
112 changes: 112 additions & 0 deletions tests/test_test_mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,115 @@ def test_catalog_views_are_checked_like_tables(start_mysql_container, monkeypatc
run = DataContract(data_contract_str=contract).test()

assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"]


def test_a_check_does_not_copy_the_mysql_table(start_mysql_container, monkeypatch):
"""A MAX and a filtered count run on MySQL. The server is not asked for every row."""
monkeypatch.setenv("DATACONTRACT_MYSQL_USERNAME", mysql_container.username)
monkeypatch.setenv("DATACONTRACT_MYSQL_PASSWORD", mysql_container.password)
_seed_bulk_orders()
_reset_general_log()
_run_bulk_contract()

data_sql = [
sql for sql in _general_log() if "bulk_orders" in sql.lower() and sql.lower().lstrip().startswith("select")
]
assert data_sql
assert all(_is_pushed_aggregate(sql) for sql in data_sql), data_sql


def _run_bulk_contract():
port = mysql_container.get_exposed_port(3306)
contract = f"""apiVersion: v3.1.0
kind: DataContract
id: mysql-bulk
name: Bulk orders
version: 1.0.0
status: active
servers:
- server: mysql
type: mysql
host: localhost
port: {port}
database: {mysql_container.dbname}
schema:
- name: bulk_orders
properties:
- name: n
logicalType: integer
- name: label
logicalType: string
quality:
- type: sql
description: highest n
query: SELECT MAX(n) FROM bulk_orders
mustBe: 99
- type: sql
description: no negative n
query: SELECT COUNT(*) FROM bulk_orders WHERE n < 0
mustBe: 0
"""
run = DataContract(data_contract_str=contract).test()
assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"]
return run


def _seed_bulk_orders():
connection = mysql.connector.connect(
database=mysql_container.dbname,
user=mysql_container.username,
password=mysql_container.password,
host=mysql_container.get_container_host_ip(),
port=int(mysql_container.get_exposed_port(3306)),
)
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS bulk_orders")
cursor.execute("CREATE TABLE bulk_orders (n INT NOT NULL, label VARCHAR(16) NOT NULL, PRIMARY KEY (n))")
cursor.executemany(
"INSERT INTO bulk_orders (n, label) VALUES (%s, %s)",
[(i, f"row-{i}") for i in range(100)],
)
connection.commit()
cursor.close()
connection.close()


def _reset_general_log():
connection = _root_connection()
cursor = connection.cursor()
cursor.execute("SET GLOBAL log_output = 'TABLE'")
cursor.execute("SET GLOBAL general_log = 'ON'")
cursor.execute("TRUNCATE TABLE mysql.general_log")
connection.commit()
cursor.close()
connection.close()


def _general_log() -> list[str]:
connection = _root_connection()
cursor = connection.cursor()
cursor.execute(
"SELECT argument FROM mysql.general_log WHERE command_type IN ('Query', 'Execute') AND argument IS NOT NULL"
)
statements = []
for (argument,) in cursor.fetchall():
if isinstance(argument, (bytes, bytearray)):
argument = argument.decode()
statements.append(argument)
cursor.close()
connection.close()
return statements


def _root_connection():
return mysql.connector.connect(
user="root",
password=mysql_container.root_password,
host=mysql_container.get_container_host_ip(),
port=int(mysql_container.get_exposed_port(3306)),
)


def _is_pushed_aggregate(sql: str) -> bool:
compact = " ".join(sql.lower().split())
return any(token in compact for token in ("max(", "min(", "count(", "sum(", "avg("))
36 changes: 29 additions & 7 deletions tests/test_untrusted_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from datacontract.data_contract import DataContract
from datacontract.engines.checks.create_checks import prepare_query
from datacontract.engines.checks.sql_guard import dialect_for_server_type, refusal_reason
from datacontract.engines.ibis.connections.connect import _materialize_attached_table
from datacontract.engines.ibis.connections.connect import _expose_attached_table
from datacontract.engines.ibis.connections.duckdb_connection import restrict_to_paths
from datacontract.model.run import ResultEnum

Expand Down Expand Up @@ -136,8 +136,8 @@ def test_the_server_dialect_still_refuses_what_is_not_a_query():


def test_server_types_run_in_duckdb_are_read_as_duckdb():
"""local/s3/gcs/azure/iceberg are read through duckdb and mysql tables are copied
into it, so a rule on them is duckdb SQL."""
"""local/s3/gcs/azure/iceberg and mysql are queried through duckdb, so a rule
on them is duckdb SQL."""
for server_type in ("local", "s3", "gcs", "azure", "iceberg", "mysql"):
assert dialect_for_server_type(server_type) == "duckdb"

Expand All @@ -160,16 +160,38 @@ def test_a_backslash_in_a_name_cannot_hide_a_second_statement_on_mysql():


def test_a_quote_in_a_table_name_cannot_start_a_second_statement_on_mysql():
"""The table name comes from the contract and runs while MySQL is still attached."""
"""The table name comes from the contract and is quoted into the view definition."""
model = 'orders" AS SELECT 1; CREATE TABLE pwned AS SELECT 1; --'
con = duckdb.connect()
con.execute("ATTACH ':memory:' AS mysqldb")
con.execute('CREATE TABLE mysqldb."orders"" AS SELECT 1; CREATE TABLE pwned AS SELECT 1; --" AS SELECT 1 AS id')

_materialize_attached_table(con, "mysqldb", None, model)
_expose_attached_table(con, "mysqldb", None, model)

tables = [name for (name,) in con.execute("SELECT table_name FROM duckdb_tables()").fetchall()]
views = [
name
for (name,) in con.execute(
"SELECT view_name FROM duckdb_views() WHERE schema_name = 'main' AND NOT internal"
).fetchall()
]
assert "pwned" not in tables
assert views == [model]


def test_a_mysql_rule_cannot_use_the_attached_server():
"""The attachment stays up so checks can be pushed down. A rule must not use it
to send its own SQL or to read a table the contract does not name."""
for query in (
"SELECT * FROM mysql_query('mysqldb', 'SELECT * FROM mysql.user')",
"SELECT mysql_execute('mysqldb', 'SELECT 1')",
"SELECT COUNT(*) FROM mysqldb.secrets",
"SELECT COUNT(*) FROM mysqldb.test.secrets",
):
assert refusal_reason(query, "duckdb", server_type="mysql") is not None
assert refusal_reason(query, "duckdb") is None

tables = con.execute("SELECT table_name FROM duckdb_tables() WHERE database_name = 'memory'").fetchall()
assert tables == [(model,)]
assert refusal_reason("SELECT MAX(n) FROM orders", "duckdb", server_type="mysql") is None


def test_the_documented_dialect_mapping_matches_the_code():
Expand Down
Loading