Skip to content

fastflowtransform.storage

spark_write_to_path

spark_write_to_path(spark, identifier, df, *, storage, default_format=None, default_options=None)

Persist a Spark DataFrame to an explicit filesystem location and register it as a table.

Source code in src/fastflowtransform/storage.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def spark_write_to_path(
    spark: Any,
    identifier: str,
    df: Any,
    *,
    storage: Mapping[str, Any],
    default_format: str | None = None,
    default_options: Mapping[str, Any] | None = None,
) -> None:
    """
    Persist a Spark DataFrame to an explicit filesystem location and register it as a table.
    """
    path = storage.get("path")
    if not path:
        raise ValueError("storage path override requires 'path'")

    fmt = storage.get("format") or default_format
    options = dict(default_options or {})
    extra_opts = storage.get("options") or {}
    if isinstance(extra_opts, Mapping):
        options.update({str(k): v for k, v in extra_opts.items()})

    parts = [_sanitize_key(part) for part in identifier.split(".") if part]
    if not parts:
        raise ValueError(f"Invalid Spark identifier: {identifier}")

    def _quote(part: str) -> str:
        return "`" + part.replace("`", "``") + "`"

    target_sql = ".".join(_quote(p) for p in parts)

    writer = df.write.mode("overwrite")
    if fmt:
        writer = writer.format(fmt)
    if options:
        writer = writer.options(**options)

    path_str = str(path)
    is_local_path = "://" not in path_str

    if is_local_path:
        target_path = Path(path_str)
        target_path.parent.mkdir(parents=True, exist_ok=True)
        tmp_path = target_path.parent / f".ff_tmp_{target_path.name}_{uuid4().hex}"
        if tmp_path.exists():
            shutil.rmtree(tmp_path, ignore_errors=True)

        try:
            writer.save(str(tmp_path))
        except Exception:
            shutil.rmtree(tmp_path, ignore_errors=True)
            raise

        spark.sql(f"DROP TABLE IF EXISTS {target_sql}")
        if target_path.exists():
            shutil.rmtree(target_path, ignore_errors=True)
        try:
            tmp_path.rename(target_path)
        except Exception:
            shutil.rmtree(tmp_path, ignore_errors=True)
            raise
    else:
        writer.save(path_str)
        spark.sql(f"DROP TABLE IF EXISTS {target_sql}")

    using_clause = f"USING {fmt}" if fmt else ""
    escaped_path = path_str.replace("'", "''")
    spark.sql(f"CREATE TABLE {target_sql} {using_clause} LOCATION '{escaped_path}'")