← Back to notebook inventory
Project 01 · Implementation example

Shared functions

common_functions.py

This shared Python module builds reusable Spark expressions and lazy DataFrame transformations. It defines deterministic SHA-256 key helpers, unknown-member keys and explicit monetary type conventions.

Additional helpers detect duplicate or missing keys, build quality signals and normalize source strings. The casting helper uses Spark SQL try_cast expressions and retains the names of failed conversions in _conversion_errors.

The Silver pipeline imports its normalization and casting functions directly. The SQL tab shows the original cast templates with their Python substitutions identified.

Source and execution context

This is an importable Python module rather than a notebook or dataset declaration source. It does not create a Spark session or trigger DataFrame actions at import time.

The supplied Python source is reproduced unchanged. The original key-contract version string is retained for compatibility. Python syntax has been checked; no Spark or Lakeflow execution was performed for this portfolio update.

"""Side-effect-free expressions and helpers for the Invoice Project.

This is a Python module, not a Databricks notebook or a table declaration source.
It does not initialize Spark or execute DataFrame actions. Returned expressions
and transformations can be used inside Lakeflow dataset definitions.

Key contract v1: SHA-256 of a named JSON structure including key_namespace.
Compatible with Batch 14 dimensions and Batch 15 fact preparation. Key column
order is part of the contract. Unknown members explicitly use UNKNOWN_SK or
UNKNOWN_DATE_SK; do not hash NULL as a substitute.
The existing KEY_CONTRACT_VERSION value is preserved for compatibility.

Deployment: make this module importable as common_functions, for example by
placing it beside 02_invoice_silver_pipeline.py in the pipeline source folder.
"""

from functools import reduce
from pyspark.sql import functions as F

KEY_CONTRACT_VERSION = "factures_keys_v1"
UNKNOWN_SK = "0" * 64
UNKNOWN_DATE_SK = 0
MONEY_TYPE = "decimal(19,4)"
AGGREGATE_MONEY_TYPE = "decimal(29,4)"
KEY_NAMESPACES = {
    "dim_account": "account_v1",
    "dim_institution": "institution_v1",
    "fact_statements": "statement_v1",
    "fact_bank_transactions": "bank_transaction_v1",
}


def qi(value):
    """Escape one Spark SQL identifier segment, including accents and backticks."""
    if not isinstance(value, str) or not value:
        raise ValueError("A nonempty identifier is required.")
    return "`" + value.replace("`", "``") + "`"


quote_identifier = qi


def qualified(*parts):
    """Build a qualified name by escaping each segment separately."""
    if not parts:
        raise ValueError("At least one identifier segment is required.")
    return ".".join(qi(part) for part in parts)


def sql_string(value):
    """Build a Spark SQL string literal with escaped quotes and backslashes."""
    if value is None:
        raise ValueError("Use NULL explicitly for a missing SQL value.")
    return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'"


def _column(value):
    # Pass through classic Spark or Spark Connect Columns without a class check.
    # A string here denotes a literal column name, not a SQL expression.
    return F.col(qi(value)) if isinstance(value, str) else value


def _column_names(columns):
    result = [columns] if isinstance(columns, str) else list(columns)
    if not result or any(not isinstance(c, str) or not c for c in result):
        raise ValueError("A nonempty list of column names is required.")
    if len(set(result)) != len(result):
        raise ValueError("Key or check columns must be distinct.")
    return result


def clean_text(column):
    """Trim surrounding spaces and map empty strings to NULL; preserve case and punctuation.

    For descriptive attributes only. Natural identifiers remain exact, and their
    anomalies must be checked before generating keys.
    """
    value = F.trim(_column(column).cast("string"))
    return F.when(value != "", value).otherwise(F.lit(None).cast("string"))


def json_hash(columns):
    """Hash a named JSON structure with SHA-256, explicit NULLs and UTC timestamps."""
    items = list(columns)
    if not items:
        raise ValueError("A nonempty hash structure is required.")
    return F.sha2(F.to_json(F.struct(*items), options={"ignoreNullFields": "false", "timeZone": "UTC"}), 256)


def generate_sk(natural_key_cols, namespace):
    """Generate a deterministic STRING(64) key using the existing project contract.

    Example: generate_sk('account_alias', 'account_v1').
    Use an ordered list of column names for a composite key. Validate natural
    keys before calling. Preserve source values and types without implicit
    concatenation or normalization.
    """
    if not isinstance(namespace, str) or not namespace.strip():
        raise ValueError("A versioned namespace is required.")
    columns = _column_names(natural_key_cols)
    return json_hash([F.lit(namespace).alias("key_namespace")] + [F.col(qi(c)).alias(c) for c in columns])


def business_key(namespace, *columns):
    """Signature compatible with the local functions in Batches 14 and 15."""
    return generate_sk(columns, namespace)


def content_hash(columns):
    """Content fingerprint with explicit column order, independent of the run."""
    names = _column_names(columns)
    return json_hash([F.col(qi(c)).alias(c) for c in names])


row_hash = content_hash


def date_key(column):
    """Convert DATE to YYYYMMDD; map a missing date to 0 without inventing a date."""
    value = _column(column)
    return F.when(value.isNull(), F.lit(UNKNOWN_DATE_SK)).otherwise(F.date_format(value, "yyyyMMdd").cast("int"))


def duplicates(frame, keys):
    """Return a DataFrame plan for duplicate groups; execute no actions here."""
    columns = _column_names(keys)
    return frame.groupBy(*columns).count().where(F.col("count") > 1)


def missing_keys(frame, keys):
    """Return rows with NULL or empty identifiers without modifying the source."""
    columns = _column_names(keys)
    conditions = [clean_text(F.col(qi(c))).isNull() for c in columns]
    return frame.where(reduce(lambda a, b: a | b, conditions))


def flags(*conditions):
    """Build ordered signals from (Boolean Column, explicit code) tuples."""
    for _, label in conditions:
        if not isinstance(label, str) or not label:
            raise ValueError("Each signal must have a nonempty code.")
    if not conditions:
        return F.array().cast("array<string>")
    return F.filter(F.array(*[F.when(condition, F.lit(label)) for condition, label in conditions]), lambda x: x.isNotNull())


def normalize_source_strings(frame):
    """Map NULL, blank and case-insensitive null text to NULL in STRING columns.

    Preserve every other value exactly, including surrounding spaces. This
    preserves the established Silver behavior and differs from clean_text().
    Return a lazy DataFrame transformation; execute no Spark actions.
    """
    return frame.select(*[F.when(F.col(c).isNull() | F.lower(F.trim(F.col(c))).isin('', 'null'), F.lit(None).cast('string')).otherwise(F.col(c)).alias(c) if dtype == 'string' else F.col(c) for c, dtype in frame.dtypes])


def cast_with_validation(frame, target_types):
    """Cast configured columns and retain their names in _conversion_errors on failure.

    Call normalize_source_strings first. Missing optional values are allowed;
    required values are checked by dataset expectations. Preserve other
    columns and return a lazy plan without dropping invalid rows.
    """
    checked = frame.withColumn('_conversion_errors', F.concat_ws(', ', *[F.when(F.col(c).isNotNull() & F.expr(f'try_cast(`{c}` AS {dtype})').isNull(), F.lit(c)) for c, dtype in target_types.items()]))
    return checked.select(*[F.expr(f'try_cast(`{c}` AS {target_types[c]})').alias(c) if c in target_types else F.col(c) for c in checked.columns])
© 2026 Joseph-Eliot Bruno · GroupBI Consulting LLC · All rights reserved.
The supplied Python source is reproduced unchanged. The original key-contract version string is retained for compatibility.
Download Python sourceDownload SQL expression reference

Project architecture

Open full-size
Project architecture