Skip to content

Commit 7592933

Browse files
authored
Merge branch 'main' into geo_scale_checks
2 parents a3b1adf + 293c764 commit 7592933

File tree

5 files changed

+225
-16
lines changed

5 files changed

+225
-16
lines changed

docs/dqx/docs/reference/quality_checks.mdx

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1550,7 +1550,7 @@ You can also define your own custom dataset-level checks (see [Creating custom c
15501550
| `sql_query` | Checks whether the condition column produced by a SQL query is satisfied. The check supports two modes: **Row-level validation** (when `merge_columns` is provided) - query results are joined back to the input DataFrame to mark specific rows; **Dataset-level validation** (when `merge_columns` is None or empty) - the check result applies to all rows (or filtered rows if `row_filter` is used), making it ideal for aggregate validations with custom metrics. The query must return a boolean condition column (True = fail, False = pass). For row-level checks: if merge columns aren't unique, multiple query rows can attach to a single input row, potentially causing false positives. Performance tip: for complex queries, writing a custom dataset-level rule is usually more performant than `sql_query` check. | `query`: query string, must return condition column (and merge columns if provided); `input_placeholder`: name to be used in the sql query as `{{ input_placeholder }}` to refer to the input DataFrame, optional reference DataFrames are referred by the name provided in the dictionary of reference DataFrames (e.g. `{{ ref_df_key }}`, dictionary of DataFrames can be passed when applying checks); `merge_columns`: (optional) list of columns used for merging with the input DataFrame which must exist in the input DataFrame and be present in output of the sql query; when not provided (None or empty list), the check result applies to all rows in the dataset (dataset-level validation); `condition_column`: name of the column indicating a violation (False = pass, True = fail); `msg`: (optional) message to output; `name`: (optional) name of the resulting check (it can be overwritten by `name` specified at the check level); `negate`: if the condition should be negated |
15511551
| `compare_datasets` | Compares two DataFrames at both row and column levels, providing detailed information about differences, including new or missing rows and column-level changes. Only columns present in both the source and reference DataFrames are compared. Use with caution if `check_missing_records` is enabled, as this may increase the number of rows in the output beyond the original input DataFrame. The comparison does not support Map types (any column comparison on map type is skipped automatically). Comparing datasets is valuable for validating data during migrations, detecting drift, performing regression testing, or verifying synchronization between source and target systems. | `columns`: columns to use for row matching with the reference DataFrame (can be a list of string column names or column expressions, but only simple column expressions are allowed such as 'F.col("col1")'), if not having primary keys or wanting to match against all columns you can pass 'df.columns'; `ref_columns`: list of columns in the reference DataFrame or Table to row match against the source DataFrame (can be a list of string column names or column expressions, but only simple column expressions are allowed such as 'F.col("col1")'), if not having primary keys or wanting to match against all columns you can pass 'ref_df.columns'; note that `columns` are matched with `ref_columns` by position, so the order of the provided columns in both lists must be exactly aligned; `exclude_columns`: (optional) list of columns to exclude from the value comparison but not from row matching (can be a list of string column names or column expressions, but only simple column expressions are allowed such as 'F.col("col1")'); the `exclude_columns` field does not alter the list of columns used to determine row matches (columns), it only controls which columns are skipped during the value comparison; `ref_df_name`: (optional) name of the reference DataFrame (dictionary of DataFrames can be passed when applying checks); `ref_table`: (optional) fully qualified reference table name; either `ref_df_name` or `ref_table` must be provided but never both; the number of passed `columns` and `ref_columns` must match and keys are checks in the given order; `check_missing_records`: perform a FULL OUTER JOIN to identify records that are missing from source or reference DataFrames, default is False; use with caution as this may increase the number of rows in the output, as unmatched rows from both sides are included; `null_safe_row_matching`: (optional) treat NULLs as equal when matching rows using `columns` and `ref_columns` (default: True); `null_safe_column_value_matching`: (optional) treat NULLs as equal when comparing column values (default: True) |
15521552
| `is_data_fresh_per_time_window` | Freshness check that validates whether at least X records arrive within every Y-minute time window. | `column`: timestamp column (can be a string column name or a column expression); `window_minutes`: time window in minutes to check for data arrival; `min_records_per_window`: minimum number of records expected per time window; `lookback_windows`: (optional) number of time windows to look back from `curr_timestamp`, it filters records to include only those within the specified number of time windows from `curr_timestamp` (if no lookback is provided, the check is applied to the entire dataset); `curr_timestamp`: (optional) current timestamp column (if not provided, current_timestamp() function is used) |
1553-
| `has_valid_schema` | Schema check that validates whether the DataFrame schema matches an expected schema. In non-strict mode, validates that all expected columns exist with compatible types (allows extra columns). In strict mode, validates exact schema match (same columns, same order, same types) for all columns by default or for all columns specified in `columns`. This check is applied at the dataset level and reports schema violations for all rows in the DataFrame when incompatibilities are detected. | `expected_schema`: expected schema as a DDL string (e.g., "id INT, name STRING") or StructType object; `columns`: (optional) list of columns to validate (if not provided, all columns are considered); `strict`: (optional) whether to perform strict schema validation (default: False) - False: validates that all expected columns exist with compatible types, True: validates exact schema match |
1553+
| `has_valid_schema` | Schema check that validates whether the DataFrame schema matches an expected schema. In non-strict mode, validates that all expected columns exist with compatible types (allows extra columns). In strict mode, validates exact schema match (same columns, same order, same types) for all columns by default or for all columns specified in `columns`. This check is applied at the dataset level and reports schema violations for all rows in the DataFrame when incompatibilities are detected. | `expected_schema`: (optional) expected schema as a DDL string (e.g., "id INT, name STRING") or StructType object; `ref_df_name`: (optional) name of the reference DataFrame to load the schema from (dictionary of DataFrames can be passed when applying checks); `ref_table`: (optional) fully qualified reference table name to load the schema from (e.g. "catalog.schema.table"); exactly one of `expected_schema`, `ref_df_name`, or `ref_table` must be provided; `columns`: (optional) list of columns to validate (if not provided, all columns are considered); `strict`: (optional) whether to perform strict schema validation (default: False) - False: validates that all expected columns exist with compatible types, True: validates exact schema match |
15541554
| `has_no_outliers` | Checks whether the values in the input column contain any outliers. This function implements a median absolute deviation (MAD) algorithm to find outliers. | `column`: column of type numeric to check (can be a string column name or a column expression); |
15551555

15561556
**Compare datasets check**
@@ -1897,6 +1897,38 @@ Complex data types are supported as well.
18971897
- id
18981898
- name
18991899

1900+
# has_valid_schema check using reference table
1901+
- criticality: error
1902+
check:
1903+
function: has_valid_schema
1904+
arguments:
1905+
ref_table: "catalog1.schema1.reference_table"
1906+
1907+
# has_valid_schema check using reference table with strict mode
1908+
- criticality: error
1909+
check:
1910+
function: has_valid_schema
1911+
arguments:
1912+
ref_table: "catalog1.schema1.reference_table"
1913+
strict: true
1914+
1915+
# has_valid_schema check using reference DataFrame
1916+
- criticality: error
1917+
check:
1918+
function: has_valid_schema
1919+
arguments:
1920+
ref_df_name: "my_ref_df"
1921+
1922+
# has_valid_schema check using reference DataFrame with specific columns
1923+
- criticality: warn
1924+
check:
1925+
function: has_valid_schema
1926+
arguments:
1927+
ref_df_name: "my_ref_df"
1928+
columns:
1929+
- id
1930+
- name
1931+
19001932
# apply check to multiple columns
19011933
- criticality: error
19021934
check:
@@ -2320,6 +2352,44 @@ checks = [
23202352
},
23212353
),
23222354

2355+
# has_valid_schema check using reference table
2356+
DQDatasetRule(
2357+
criticality="error",
2358+
check_func=check_funcs.has_valid_schema,
2359+
check_func_kwargs={
2360+
"ref_table": "catalog1.schema1.reference_table",
2361+
},
2362+
),
2363+
2364+
# has_valid_schema check using reference table with strict mode
2365+
DQDatasetRule(
2366+
criticality="error",
2367+
check_func=check_funcs.has_valid_schema,
2368+
check_func_kwargs={
2369+
"ref_table": "catalog1.schema1.reference_table",
2370+
"strict": True,
2371+
},
2372+
),
2373+
2374+
# has_valid_schema check using reference DataFrame
2375+
DQDatasetRule(
2376+
criticality="error",
2377+
check_func=check_funcs.has_valid_schema,
2378+
check_func_kwargs={
2379+
"ref_df_name": "my_ref_df",
2380+
},
2381+
),
2382+
2383+
# has_valid_schema check using reference DataFrame with specific columns
2384+
DQDatasetRule(
2385+
criticality="warn",
2386+
check_func=check_funcs.has_valid_schema,
2387+
check_func_kwargs={
2388+
"ref_df_name": "my_ref_df",
2389+
"columns": ["id", "name"],
2390+
},
2391+
),
2392+
23232393
# apply check to multiple columns
23242394
*DQForEachColRule(
23252395
check_func=check_funcs.is_unique, # 'columns' as first argument
@@ -2353,6 +2423,9 @@ The reference DataFrames are used in selected Dataset-level checks:
23532423
* `compare_datasets`: required for this check if `ref_df_name` argument is specified and not `ref_table`, e.g. `ref_df_name="ref_df_key"`.
23542424
The value of `ref_df_name` must match the key in the `ref_dfs` dictionary.
23552425

2426+
* `has_valid_schema`: required for this check if `ref_df_name` argument is specified and not `ref_table` or `expected_schema`, e.g. `ref_df_name="ref_df_key"`.
2427+
The value of `ref_df_name` must match the key in the `ref_dfs` dictionary. The schema from the reference DataFrame is used to validate the input DataFrame schema.
2428+
23562429
* `sql_query`: the reference DataFrames are registered as temporary views and can be used in the sql query.
23572430

23582431
For example, if you have a reference DataFrame named `ref_df_key`, you can use it in the SQL query as `{{ ref_df_key }}`:

src/databricks/labs/dqx/check_funcs.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1865,7 +1865,9 @@ def apply(df: DataFrame) -> DataFrame:
18651865

18661866
@register_rule("dataset")
18671867
def has_valid_schema(
1868-
expected_schema: str | types.StructType,
1868+
expected_schema: str | types.StructType | None = None,
1869+
ref_df_name: str | None = None,
1870+
ref_table: str | None = None,
18691871
columns: list[str | Column] | None = None,
18701872
strict: bool = False,
18711873
) -> tuple[Column, Callable]:
@@ -1879,6 +1881,8 @@ def has_valid_schema(
18791881
18801882
Args:
18811883
expected_schema: Expected schema as a DDL string (e.g., "id INT, name STRING") or StructType object.
1884+
ref_df_name: Name of the reference DataFrame (used when passing DataFrames directly).
1885+
ref_table: Name of the reference table to load the schema from (e.g. "catalog.schema.table")
18821886
columns: Optional list of columns to validate (default: all columns are considered)
18831887
strict: Whether to perform strict schema validation (default: False).
18841888
- False: Validates that all expected columns exist with compatible types (allows extra columns)
@@ -1890,31 +1894,54 @@ def has_valid_schema(
18901894
- A closure that applies the schema check and adds the necessary condition columns.
18911895
18921896
Raises:
1893-
InvalidParameterError: If the schema string is invalid or cannot be parsed, or if
1894-
the input schema is neither a string nor a StructType.
1897+
InvalidParameterError:
1898+
- If the *expected_schema* string is invalid or cannot be parsed
1899+
- If *expected_schema* is neither a string nor a StructType
1900+
- If more than one of *expected_schema*, *ref_df_name*, or *ref_table* are specified
1901+
- If none of *expected_schema*, *ref_df_name*, or *ref_table* are specified
1902+
1903+
Note:
1904+
Exactly one of *expected_schema*, *ref_df_name*, or *ref_table* must be specified.
18951905
"""
1906+
expected_params = ["expected_schema", "ref_df_name", "ref_table"]
1907+
non_null_params = dict(filter(lambda param: param[0] in expected_params and param[1] is not None, locals().items()))
1908+
1909+
if len(non_null_params) != 1:
1910+
raise InvalidParameterError(
1911+
"Must specify one of 'expected_schema', 'ref_df_name', or 'ref_table' when using 'has_valid_schema'"
1912+
)
18961913

18971914
column_names: list[str] | None = None
18981915
if columns:
18991916
column_names = [get_column_name_or_alias(col) if not isinstance(col, str) else col for col in columns]
19001917

1901-
_expected_schema = _get_schema(expected_schema, column_names)
1918+
expected_schema = _get_schema(expected_schema or types.StructType(), column_names)
1919+
19021920
unique_str = uuid.uuid4().hex # make sure any column added to the dataframe is unique
19031921
condition_col = f"__schema_condition_{unique_str}"
19041922
message_col = f"__schema_message_{unique_str}"
19051923

1906-
def apply(df: DataFrame) -> DataFrame:
1924+
def apply(df: DataFrame, spark: SparkSession, ref_dfs: dict[str, DataFrame]) -> DataFrame:
19071925
"""
19081926
Apply the schema compatibility check logic to the DataFrame.
19091927
19101928
Adds columns indicating whether the DataFrame schema is incompatible with the expected schema.
19111929
19121930
Args:
19131931
df: The input DataFrame to validate for schema compatibility.
1932+
spark: SparkSession used to get the reference table schema
1933+
ref_dfs: A dictionary mapping reference DataFrame names to DataFrame objects.
19141934
19151935
Returns:
19161936
The DataFrame with additional condition and message columns for schema validation.
19171937
"""
1938+
1939+
if ref_df_name or ref_table:
1940+
ref_df = _get_ref_df(ref_df_name, ref_table, ref_dfs, spark)
1941+
_expected_schema = _get_schema(ref_df.schema, column_names)
1942+
else:
1943+
_expected_schema = expected_schema
1944+
19181945
actual_schema = df.select(*columns).schema if columns else df.schema
19191946

19201947
if strict:

0 commit comments

Comments
 (0)