salesforce-data-customcode 6.1.0.dev7__py3-none-any.whl → 7.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,12 +13,19 @@
13
13
  # See the License for the specific language governing permissions and
14
14
  # limitations under the License.
15
15
 
16
+ from datacustomcode.spark.column_hints import install_column_casing_hints
17
+
18
+ # Friendlier errors for wrong-case column references. Idempotent.
19
+ install_column_casing_hints()
20
+
16
21
  __all__ = [
17
22
  "AuthType",
18
23
  "Client",
19
24
  "Credentials",
20
25
  "DefaultSparkEinsteinPredictions",
21
26
  "DefaultSparkLLMGateway",
27
+ "LocalDeltasReader",
28
+ "LocalDeltasWriter",
22
29
  "PrintDataCloudWriter",
23
30
  "QueryAPIDataCloudReader",
24
31
  "SparkEinsteinPredictions",
@@ -55,6 +62,14 @@ def __getattr__(name: str):
55
62
  from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader
56
63
 
57
64
  return QueryAPIDataCloudReader
65
+ elif name == "LocalDeltasReader":
66
+ from datacustomcode.io.reader.local_deltas import LocalDeltasReader
67
+
68
+ return LocalDeltasReader
69
+ elif name == "LocalDeltasWriter":
70
+ from datacustomcode.io.writer.local_deltas import LocalDeltasWriter
71
+
72
+ return LocalDeltasWriter
58
73
  elif name == "SparkLLMGateway":
59
74
  from datacustomcode.llm_gateway import SparkLLMGateway
60
75
 
datacustomcode/client.py CHANGED
@@ -368,7 +368,13 @@ class _BaseClient:
368
368
  instance._spark_named_credential = spark_named_credential
369
369
  # Initialize Readers and Writers from config
370
370
  # and/or provided reader and writer
371
- if reader is None or writer is None:
371
+ reader_forced = (
372
+ config.reader_config is not None and config.reader_config.force
373
+ )
374
+ writer_forced = (
375
+ config.writer_config is not None and config.writer_config.force
376
+ )
377
+ if reader is None or writer is None or reader_forced or writer_forced:
372
378
  # We need a spark because we will initialize readers and writers.
373
379
  # Reuse the process-wide session if one client already built it,
374
380
  # so a Client and a StreamingClient share a single connection.
@@ -396,9 +402,7 @@ class _BaseClient:
396
402
  raise ValueError(
397
403
  "Reader config is required when reader is not provided"
398
404
  )
399
- elif reader is None or (
400
- config.reader_config is not None and config.reader_config.force
401
- ):
405
+ elif reader is None or reader_forced:
402
406
  reader_init = config.reader_config.to_object(spark) # type: ignore
403
407
  else:
404
408
  reader_init = reader
@@ -406,9 +410,7 @@ class _BaseClient:
406
410
  raise ValueError(
407
411
  "Writer config is required when writer is not provided"
408
412
  )
409
- elif writer is None or (
410
- config.writer_config is not None and config.writer_config.force
411
- ):
413
+ elif writer is None or writer_forced:
412
414
  writer_init = config.writer_config.to_object(spark) # type: ignore
413
415
  else:
414
416
  writer_init = writer
@@ -716,6 +718,25 @@ class StreamingClient(_BaseClient):
716
718
  self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DMO)
717
719
  return self._writer.write_dlo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return]
718
720
 
721
+ def write_dmo_deltas(
722
+ self, name: str, dataframe: PySparkDataFrame, **kwargs
723
+ ) -> StreamingQuery:
724
+ """Write a streaming DataFrame of deltas to a DMO in Data Cloud.
725
+
726
+ Starts a streaming query that writes each micro-batch to the
727
+ target DMO and returns the ``StreamingQuery`` handle; the caller
728
+ typically calls ``query.awaitTermination()``.
729
+
730
+ Args:
731
+ name: The name of the DMO to write to.
732
+ dataframe: The streaming PySpark DataFrame to write.
733
+
734
+ Returns:
735
+ The started ``StreamingQuery``.
736
+ """
737
+ self._validate_data_layer_history_does_not_contain(DataCloudObjectType.DLO)
738
+ return self._writer.write_dmo_deltas(name, dataframe, **kwargs) # type: ignore[no-any-return]
739
+
719
740
  def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None:
720
741
  """Write a PySpark DataFrame to a DLO in Data Cloud automatically picking
721
742
  the WriteMode.
@@ -18,6 +18,8 @@ spark_config:
18
18
  spark.submit.deployMode: client
19
19
  spark.sql.execution.arrow.pyspark.enabled: 'true'
20
20
  spark.driver.extraJavaOptions: -Djava.security.manager=allow
21
+ # Resolve columns case-sensitively so wrong-case refs fail locally too.
22
+ spark.sql.caseSensitive: 'true'
21
23
 
22
24
  einstein_predictions_config:
23
25
  type_config_name: DefaultEinsteinPredictions
datacustomcode/deploy.py CHANGED
@@ -415,13 +415,7 @@ class DataTransformConfig(BaseConfig):
415
415
  def _validate_layers(self) -> "DataTransformConfig":
416
416
  read_is_dlo = isinstance(self.permissions.read, DloPermission)
417
417
  write_is_dlo = isinstance(self.permissions.write, DloPermission)
418
- if self.is_streaming:
419
- if not write_is_dlo:
420
- raise ValueError(
421
- "A streaming transform must write to a DLO "
422
- "(permissions.write must be a 'dlo' entry)."
423
- )
424
- elif read_is_dlo != write_is_dlo:
418
+ if read_is_dlo != write_is_dlo:
425
419
  raise ValueError(
426
420
  "permissions.read and permissions.write must both reference "
427
421
  "DLOs or both reference DMOs (got "
@@ -551,15 +545,13 @@ def create_data_transform(
551
545
  "version": "56.0",
552
546
  }
553
547
 
554
- # outputDataObjects is only set for DMO-backed transforms. The server requires
555
- # the schema of any DMO created/updated by the transform; DLO transforms use
556
- # an existing materialized table and must not include this field.
557
- if isinstance(data_transform_config.permissions.write, DmoPermission):
558
- if not data_transform_config.dataObjects:
548
+ if not data_transform_config.dataObjects:
549
+ if isinstance(data_transform_config.permissions.write, DmoPermission):
559
550
  raise ValueError(
560
551
  "DMO transforms require 'dataObjects' in config.json describing "
561
552
  "the schema of each output DMO."
562
553
  )
554
+ else:
563
555
  definition["outputDataObjects"] = [
564
556
  _data_object_to_output(obj) for obj in data_transform_config.dataObjects
565
557
  ]
@@ -632,12 +624,15 @@ def zip(
632
624
  logger.debug(f"Zipping directory... {directory}")
633
625
 
634
626
  with zipfile.ZipFile(ZIP_FILE_NAME, "w", zipfile.ZIP_DEFLATED) as zipf:
635
- for root, dirs, files in os.walk(directory):
636
- # Skip .DS_Store and local credentials.
627
+ for root, dirs, files in os.walk(directory, followlinks=False):
628
+ # Skip symlinks, .DS_Store and local credentials.
637
629
  for file in files:
630
+ abs_path = os.path.join(root, file)
631
+ arcname = os.path.relpath(abs_path, directory)
632
+ if os.path.islink(abs_path):
633
+ logger.warning(f"Skipping symlink file {arcname}")
634
+ continue
638
635
  if file not in EXCLUDED_FILES:
639
- abs_path = os.path.join(root, file)
640
- arcname = os.path.relpath(abs_path, directory)
641
636
  zipf.write(abs_path, arcname)
642
637
 
643
638
  logger.debug(f"Created zip file: {ZIP_FILE_NAME}")
@@ -0,0 +1,34 @@
1
+ # Copyright (c) 2025, Salesforce, Inc.
2
+ # SPDX-License-Identifier: Apache-2
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Final
19
+
20
+ from datacustomcode.io.writer.base import MERGE_RECORD_TYPE_COLUMN, MergeRecordType
21
+
22
+ COMMIT_VERSION: Final = "_commit_version"
23
+ COMMIT_TIMESTAMP: Final = "_commit_timestamp"
24
+ MERGE_RECORD_TYPE: Final = MERGE_RECORD_TYPE_COLUMN
25
+
26
+ CDF_METADATA_COLUMNS: Final = (COMMIT_VERSION, COMMIT_TIMESTAMP, MERGE_RECORD_TYPE)
27
+
28
+ __all__ = [
29
+ "COMMIT_VERSION",
30
+ "COMMIT_TIMESTAMP",
31
+ "MERGE_RECORD_TYPE",
32
+ "CDF_METADATA_COLUMNS",
33
+ "MergeRecordType",
34
+ ]
@@ -0,0 +1,164 @@
1
+ # Copyright (c) 2025, Salesforce, Inc.
2
+ # SPDX-License-Identifier: Apache-2
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ from pathlib import Path
21
+ import sys
22
+ from typing import (
23
+ TYPE_CHECKING,
24
+ Optional,
25
+ Union,
26
+ )
27
+
28
+ from datacustomcode.config import config
29
+ from datacustomcode.io import cdf
30
+ from datacustomcode.io.reader.base import BaseDataCloudReader
31
+ from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader
32
+
33
+ if TYPE_CHECKING:
34
+ from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession
35
+ from pyspark.sql.types import AtomicType, StructType
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ class LocalDeltasReader(BaseDataCloudReader):
41
+ """Local reader for streaming transforms"""
42
+
43
+ CONFIG_NAME = "LocalDeltasReader"
44
+
45
+ def __init__(
46
+ self,
47
+ spark: SparkSession,
48
+ credentials_profile: str = "default",
49
+ dataspace: Optional[str] = None,
50
+ sf_cli_org: Optional[str] = None,
51
+ default_row_limit: Optional[int] = None,
52
+ fixtures_root: str = "payload/streaming_fixtures",
53
+ ) -> None:
54
+ super().__init__(spark)
55
+ self._fixtures_root = Path(fixtures_root)
56
+ self._credentials_profile = credentials_profile
57
+ self._dataspace = dataspace
58
+ self._sf_cli_org = sf_cli_org
59
+ # Reuse the batch reader for INITIAL_SYNC / REBUILD reads.
60
+ self._batch = QueryAPIDataCloudReader(
61
+ spark=spark,
62
+ credentials_profile=credentials_profile,
63
+ dataspace=dataspace,
64
+ sf_cli_org=sf_cli_org,
65
+ default_row_limit=default_row_limit,
66
+ )
67
+ self._current_layer = "dlo"
68
+
69
+ def read_dlo(
70
+ self,
71
+ name: str,
72
+ schema: Union[AtomicType, StructType, str, None] = None,
73
+ ) -> PySparkDataFrame:
74
+ return self._batch.read_dlo(name, schema)
75
+
76
+ def read_dmo(
77
+ self,
78
+ name: str,
79
+ schema: Union[AtomicType, StructType, str, None] = None,
80
+ ) -> PySparkDataFrame:
81
+ return self._batch.read_dmo(name, schema)
82
+
83
+ def read_dlo_deltas(self) -> PySparkDataFrame:
84
+ self._current_layer = "dlo"
85
+ return self._open_stream(self._streaming_source())
86
+
87
+ def read_dmo_deltas(self) -> PySparkDataFrame:
88
+ self._current_layer = "dmo"
89
+ return self._open_stream(self._streaming_source())
90
+
91
+ def _streaming_source(self) -> str:
92
+ source = config.streaming_source
93
+ if not source:
94
+ raise RuntimeError(
95
+ "No streaming source configured. Set streamingSource.name in "
96
+ "config.json."
97
+ )
98
+ return source
99
+
100
+ def _open_stream(self, name: str) -> PySparkDataFrame:
101
+ drop_dir = self._fixtures_root / name
102
+
103
+ if not (drop_dir / "_schema.json").exists():
104
+ seeded = self._try_seed(name)
105
+ if not seeded:
106
+ print(
107
+ f"\nStreaming source {self._current_layer}='{name}' is "
108
+ f"empty.\n"
109
+ f" Populate the stream source with at least one row in "
110
+ f"Data Cloud, then re-run `datacustomcode run`.\n"
111
+ )
112
+ sys.exit(0)
113
+
114
+ print(
115
+ f"\nWrote sample streaming fixture in: {drop_dir} "
116
+ f"based on the contents of the streaming source {name}.\n"
117
+ f" You may add more JSON files alongside it to simulate "
118
+ f"additional changes.\n"
119
+ )
120
+
121
+ schema = self._build_stream_schema(name)
122
+ return (
123
+ self.spark.readStream.format("json")
124
+ .schema(schema)
125
+ .option("maxFilesPerTrigger", 1) # one file = one batch
126
+ .option("latestFirst", "false") # oldest mtime first
127
+ .load(str(drop_dir))
128
+ )
129
+
130
+ def _build_stream_schema(self, name: str) -> "StructType":
131
+ """Compose (source schema + CDF metadata columns) for readStream."""
132
+ from pyspark.sql.types import (
133
+ LongType,
134
+ StringType,
135
+ StructField,
136
+ StructType,
137
+ TimestampType,
138
+ )
139
+
140
+ source_schema = self._resolve_source_schema(name)
141
+ cdf_fields = [
142
+ StructField(cdf.COMMIT_VERSION, LongType(), True),
143
+ StructField(cdf.COMMIT_TIMESTAMP, TimestampType(), True),
144
+ StructField(cdf.MERGE_RECORD_TYPE, StringType(), True),
145
+ ]
146
+ return StructType(list(source_schema.fields) + cdf_fields)
147
+
148
+ def _resolve_source_schema(self, name: str) -> "StructType":
149
+ from pyspark.sql.types import StructType
150
+
151
+ schema_file = self._fixtures_root / name / "_schema.json"
152
+ return StructType.fromJson(json.loads(schema_file.read_text()))
153
+
154
+ def _try_seed(self, name: str) -> bool:
155
+ """Creates source schema and sample change file."""
156
+ from datacustomcode.io.reader.streaming_seeder import StreamingSourceSeeder
157
+
158
+ seeder = StreamingSourceSeeder(
159
+ spark=self.spark,
160
+ credentials_profile=self._credentials_profile,
161
+ dataspace=self._dataspace,
162
+ sf_cli_org=self._sf_cli_org,
163
+ )
164
+ return seeder.seed_source(name, self._current_layer, str(self._fixtures_root))
@@ -0,0 +1,114 @@
1
+ # Copyright (c) 2025, Salesforce, Inc.
2
+ # SPDX-License-Identifier: Apache-2
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ from datetime import datetime, timezone
19
+ import json
20
+ import math
21
+ from pathlib import Path
22
+ from typing import (
23
+ TYPE_CHECKING,
24
+ Any,
25
+ Optional,
26
+ )
27
+
28
+ from datacustomcode.io import cdf
29
+ from datacustomcode.io.reader.query_api import QueryAPIDataCloudReader
30
+
31
+ if TYPE_CHECKING:
32
+ import pandas as pd
33
+ from pyspark.sql import SparkSession
34
+
35
+ SEED_LIMIT = 10
36
+
37
+
38
+ def _clean_for_json(value: Any) -> Any:
39
+ if isinstance(value, float):
40
+ if math.isnan(value):
41
+ return None
42
+ if value.is_integer():
43
+ return int(value)
44
+ return value
45
+
46
+
47
+ class StreamingSourceSeeder:
48
+ def __init__(
49
+ self,
50
+ spark: SparkSession,
51
+ credentials_profile: str = "default",
52
+ dataspace: Optional[str] = None,
53
+ sf_cli_org: Optional[str] = None,
54
+ ) -> None:
55
+ self.spark = spark
56
+ self.reader = QueryAPIDataCloudReader(
57
+ spark=spark,
58
+ credentials_profile=credentials_profile,
59
+ dataspace=dataspace,
60
+ sf_cli_org=sf_cli_org,
61
+ )
62
+
63
+ def seed_source(self, name: str, layer: str, fixtures_root: str) -> bool:
64
+ """Seed streaming fixtures and source schema.
65
+
66
+ Returns:
67
+ ``True`` when schema + fixtures are written
68
+ ``False`` when the source is empty.
69
+ Query API errors (missing creds, missing
70
+ source) propagate as ``RuntimeError``.
71
+ """
72
+ read_fn = self.reader.read_dlo if layer == "dlo" else self.reader.read_dmo
73
+
74
+ try:
75
+ head_df = read_fn(name).limit(1)
76
+ except Exception as exc:
77
+ raise RuntimeError(f"Failed to read {layer}='{name}': {exc}.") from exc
78
+
79
+ head_pandas = head_df.toPandas()
80
+ if len(head_pandas) == 0:
81
+ return False
82
+
83
+ schema = head_df.schema
84
+ out_dir = Path(fixtures_root) / name
85
+ out_dir.mkdir(parents=True, exist_ok=True)
86
+ schema_file_path = out_dir / "_schema.json"
87
+ schema_file_path.write_text(json.dumps(schema.jsonValue()))
88
+ print(
89
+ f"\nStreaming source schema written to {schema_file_path} "
90
+ f"({len(schema.fields)} fields)"
91
+ )
92
+
93
+ # Mix UPSERT and DELETE in the seed so the customer sees both
94
+ # operation types in the starter fixture. Annotated because
95
+ # pyspark's ``.toPandas()`` return type is ``PandasDataFrameLike``,
96
+ # which mypy doesn't recognize as having ``to_dict``.
97
+ snapshot: pd.DataFrame = read_fn(name).limit(SEED_LIMIT).toPandas()
98
+ seed_rows = []
99
+ for i, record in enumerate(snapshot.to_dict("records")):
100
+ op = cdf.MergeRecordType.DELETE if i % 2 else cdf.MergeRecordType.UPSERT
101
+
102
+ cleaned = {k: _clean_for_json(v) for k, v in record.items()}
103
+ seed_rows.append(
104
+ {
105
+ **cleaned,
106
+ cdf.COMMIT_VERSION: i + 1,
107
+ cdf.COMMIT_TIMESTAMP: datetime.now(timezone.utc).isoformat(),
108
+ cdf.MERGE_RECORD_TYPE: op.value,
109
+ }
110
+ )
111
+ (out_dir / "000_seed.json").write_text(
112
+ "\n".join(json.dumps(r, default=str) for r in seed_rows)
113
+ )
114
+ return True
@@ -87,7 +87,7 @@ class BaseDataCloudWriter(BaseDataAccessLayer):
87
87
  Args:
88
88
  name: Target Data Lake Object name.
89
89
  dataframe: Streaming PySpark DataFrame produced from a
90
- ``read_dlo_deltas`` / ``read_dmo_deltas`` source.
90
+ ``read_dlo_deltas`` source.
91
91
 
92
92
  Returns:
93
93
  The started ``StreamingQuery``; the caller drives its lifecycle
@@ -102,3 +102,35 @@ class BaseDataCloudWriter(BaseDataAccessLayer):
102
102
  "streaming runtime; the local writer does not support streaming "
103
103
  "deltas."
104
104
  )
105
+
106
+ def write_dmo_deltas(
107
+ self, name: str, dataframe: PySparkDataFrame
108
+ ) -> StreamingQuery:
109
+ """Write a streaming DataFrame of deltas to a Data Model Object.
110
+
111
+ Streaming counterpart to :meth:`write_to_dmo`. Starts a streaming query
112
+ that writes each micro-batch to the target DMO via the Data Cloud
113
+ streaming sink and returns the resulting ``StreamingQuery`` handle. The
114
+ runtime owns the trigger and checkpoint location; callers pass only the
115
+ table name. Concrete streaming behavior is provided by the deployed
116
+ Data Cloud runtime; the base implementation raises
117
+ :class:`NotImplementedError`.
118
+
119
+ Args:
120
+ name: Target Data Model Object name.
121
+ dataframe: Streaming PySpark DataFrame produced from a
122
+ ``read_dmo_deltas`` source.
123
+
124
+ Returns:
125
+ The started ``StreamingQuery``; the caller drives its lifecycle
126
+ (typically ``query.awaitTermination()``).
127
+
128
+ Raises:
129
+ NotImplementedError: If the active writer does not support streaming
130
+ deltas (e.g. the local development writers).
131
+ """
132
+ raise NotImplementedError(
133
+ "write_dmo_deltas is only supported when running in the Data Cloud "
134
+ "streaming runtime; the local writer does not support streaming "
135
+ "deltas."
136
+ )
@@ -0,0 +1,133 @@
1
+ # Copyright (c) 2025, Salesforce, Inc.
2
+ # SPDX-License-Identifier: Apache-2
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import tempfile
20
+ from typing import TYPE_CHECKING, Optional
21
+ from urllib.parse import urlparse
22
+
23
+ from datacustomcode.io import cdf
24
+ from datacustomcode.io.writer.base import BaseDataCloudWriter, WriteMode
25
+
26
+ if TYPE_CHECKING:
27
+ from pyspark.sql import DataFrame as PySparkDataFrame, SparkSession
28
+ from pyspark.sql.streaming import StreamingQuery
29
+
30
+ _HEADER_WARNING = (
31
+ " NOTE: The output below is based on example streaming changes "
32
+ "auto-generated by this CLI or generated by the user.\n"
33
+ " Once this code extension is deployed, Data Cloud will persist "
34
+ "only the final state per primary key.\n"
35
+ " This local preview shows every emitted row uncollapsed."
36
+ )
37
+
38
+
39
+ class LocalDeltasWriter(BaseDataCloudWriter):
40
+ """Local writer for streaming transforms."""
41
+
42
+ CONFIG_NAME = "LocalDeltasWriter"
43
+
44
+ def __init__(
45
+ self,
46
+ spark: SparkSession,
47
+ credentials_profile: str = "default",
48
+ dataspace: Optional[str] = None,
49
+ sf_cli_org: Optional[str] = None,
50
+ ) -> None:
51
+ super().__init__(spark)
52
+
53
+ from datacustomcode.io.writer.print import PrintDataCloudWriter
54
+
55
+ self._batch_writer = PrintDataCloudWriter(
56
+ spark=spark,
57
+ credentials_profile=credentials_profile,
58
+ dataspace=dataspace,
59
+ sf_cli_org=sf_cli_org,
60
+ )
61
+
62
+ def write_to_dlo(
63
+ self, name: str, dataframe: PySparkDataFrame, write_mode: WriteMode
64
+ ) -> None:
65
+ return self._batch_writer.write_to_dlo(name, dataframe, write_mode)
66
+
67
+ def write_to_dmo(
68
+ self, name: str, dataframe: PySparkDataFrame, write_mode: WriteMode
69
+ ) -> None:
70
+ return self._batch_writer.write_to_dmo(name, dataframe, write_mode)
71
+
72
+ def auto_write_to_dlo(self, name: str, dataframe: PySparkDataFrame) -> None:
73
+ return self._batch_writer.auto_write_to_dlo(name, dataframe)
74
+
75
+ def auto_write_to_dmo(self, name: str, dataframe: PySparkDataFrame) -> None:
76
+ return self._batch_writer.auto_write_to_dmo(name, dataframe)
77
+
78
+ @staticmethod
79
+ def _batch_source_file(batch_df: "PySparkDataFrame") -> str:
80
+ """Return the fixture file backing this micro-batch, relative to CWD"""
81
+ from pyspark.sql import functions as F
82
+
83
+ file_row = batch_df.select(F.input_file_name().alias("_src")).limit(1).collect()
84
+ if not file_row:
85
+ return "?"
86
+ abs_path = str(urlparse(str(file_row[0]["_src"])).path)
87
+ try:
88
+ return os.path.relpath(abs_path)
89
+ except Exception:
90
+ return abs_path
91
+
92
+ def write_dlo_deltas(
93
+ self, name: str, dataframe: PySparkDataFrame, **kwargs
94
+ ) -> StreamingQuery:
95
+ if not name:
96
+ raise ValueError("DLO name must be provided.")
97
+
98
+ def _preview(batch_df, batch_id):
99
+ from pyspark.sql import functions as F
100
+
101
+ source_file = self._batch_source_file(batch_df)
102
+
103
+ output_batch = batch_df.withColumn(
104
+ "_operation",
105
+ F.when(
106
+ F.col(cdf.MERGE_RECORD_TYPE) == cdf.MergeRecordType.DELETE.value,
107
+ F.lit("DELETE"),
108
+ ).otherwise(F.lit("UPSERT")),
109
+ ).drop(
110
+ cdf.COMMIT_VERSION,
111
+ cdf.COMMIT_TIMESTAMP,
112
+ cdf.MERGE_RECORD_TYPE,
113
+ )
114
+
115
+ row_count = output_batch.count()
116
+ print(
117
+ f"\nTarget={name} batch_id={batch_id} "
118
+ f"file={source_file} rows={row_count}"
119
+ )
120
+ print(_HEADER_WARNING)
121
+ output_batch.show(truncate=False)
122
+
123
+ checkpoint_dir = tempfile.mkdtemp(prefix=f"local-deltas-ckpt-{name}-")
124
+ return (
125
+ dataframe.writeStream.foreachBatch(_preview)
126
+ .option("checkpointLocation", checkpoint_dir)
127
+ # AvailableNow: drain every fixture file then
128
+ # terminate. The user's `query.awaitTermination()`
129
+ # returns without needing a timeout, so
130
+ # `datacustomcode run` exits deterministically.
131
+ .trigger(availableNow=True)
132
+ .start()
133
+ )