Skip to content

PipelineViewDataSink

laktory.models.datasinks.PipelineViewDataSink ¤

Bases: BaseDataSink

Data sink writing to a Declarative Pipeline (formerly Delta Live Tables) view. This view is virtual and does not materialize data.

Examples:

```python tag:skip-run from laktory import models

df = spark.createDataFrame([{"x": 1}, {"x": 2}, {"x": 3}])

sink = models.PipelineViewDataSink( pipeline_view_name="my_view", ) sink.write(df) ``` References


PARAMETER DESCRIPTION
as_stream

If True output DataFrame is written as Streaming DataFrame. If None, write mode is derived fromDataFrame.

TYPE: bool | None | VariableType DEFAULT: None

checkpoint_path_

Path to which the checkpoint file for which a streaming dataframe should be written.

TYPE: str | Path | VariableType DEFAULT: None

custom_writer

Custom writer that fully replaces Laktory's built-in write logic. Laktory manages the streaming query lifecycle (foreachBatch, trigger, checkpoint, start/await). Can be set as a plain string (func_name only) or a full CustomWriter object with func_name, func_args, and func_kwargs. Mutually exclusive with mode and merge_cdc_options.

TYPE: CustomWriter | None | VariableType DEFAULT: None

databricks_data_profiling_config

Databricks Data Quality Monitor data profiling configuration

TYPE: Literal[None] | VariableType DEFAULT: None

is_quarantine

Sink used to store quarantined results from a pipeline node expectations.

TYPE: bool | VariableType DEFAULT: False

merge_cdc_options

Merge options to handle input DataFrames that are Change Data Capture (CDC). Only used when MERGE mode is selected.

TYPE: DataSinkMergeCDCOptions | VariableType DEFAULT: None

metadata

Table and columns metadata.

TYPE: Literal[None] | VariableType DEFAULT: None

mode

Write mode.

Spark¤

  • OVERWRITE: Overwrite existing data.
  • APPEND: Append contents of this DataFrame to existing data.
  • ERROR: Throw an exception if data already exists.
  • IGNORE: Silently ignore this operation if data already exists.

Spark Streaming¤

  • APPEND: Only the new rows in the streaming DataFrame/Dataset will be written to the sink.
  • COMPLETE: All the rows in the streaming DataFrame/Dataset will be written to the sink every time there are some updates.
  • UPDATE: Only the rows that were updated in the streaming DataFrame/Dataset will be written to the sink every time there are some updates.

Polars Delta¤

  • OVERWRITE: Overwrite existing data.
  • APPEND: Append contents of this DataFrame to existing data.
  • ERROR: Throw an exception if data already exists.
  • IGNORE: Silently ignore this operation if data already exists.

Laktory¤

  • MERGE: Append, update and optionally delete records. Only supported for DELTA format. Requires cdc specification.

TYPE: Literal['OVERWRITE', 'ERROR', 'ERRORIFEXISTS', 'COMPLETE', 'IGNORE', 'MERGE', 'UPDATE', 'APPEND'] | None | VariableType DEFAULT: None

pipeline_view_name

Pipeline View name

TYPE: str | None | VariableType

reset_mode

Strategy used to reset this sink's data on a full refresh or a reset run.

  • DROP: Drop the table (or delete the file/data) entirely, then recreate it on next write.
  • TRUNCATE: Remove all rows but keep the table/schema/location intact. Only supported by tables (not views) and DELTA file sinks, not with declarative orchestrators.

Ignored by shared sinks (shared), which only delete the rows of their writer. To reset only part of a table, declare the rows owned by the sink with shared.where. Can be overridden for a single run (reset_mode run parameter).

TYPE: Literal['DROP', 'TRUNCATE'] | VariableType DEFAULT: 'DROP'

schema_definition

Explicit table schema used when creating the table. If not set, schema is inferred from the transformer output DataFrame.

TYPE: DataFrameSchema | VariableType DEFAULT: None

shared

Options for a sink written by multiple writers: each writer owns its rows, identified by a writer column or a SQL predicate, and a full refresh of a writer only deletes its own rows. Required on every sink of a target written by several nodes or pipelines. true for the default options. See DataSinkSharedOptions.

TYPE: DataSinkSharedOptions | None | VariableType DEFAULT: None

type

Sink Type

TYPE: Literal['PIPELINE_VIEW'] | VariableType DEFAULT: 'PIPELINE_VIEW'

writer_kwargs

Keyword arguments passed directly to dataframe backend writer. Passed to .options() method when using PySpark.

TYPE: dict[str | VariableType, Any | VariableType] | VariableType DEFAULT: {}

writer_methods

DataFrame backend writer methods.

TYPE: list[ReaderWriterMethod | VariableType] | VariableType DEFAULT: []

METHOD DESCRIPTION
create

Initialize the sink if required.

filter_writer_rows

Keep the rows written by the writer of a shared sink - matching its writer

is_streaming

Return True if the write should use Spark Structured Streaming.

purge

Delete sink data and checkpoints

read

Read dataframe from sink.

with_writer_column

Add the writer identifier column to a DataFrame written by a shared sink, as the

ATTRIBUTE DESCRIPTION
ldp_auto_cdc_flow_kwargs

Keyword arguments for dp.create_auto_cdc_flow function

TYPE: dict[str, str]

purge_target

Identifier of the physical data written by the sink. Sinks of different pipeline

TYPE: str | None

sdp_pre_merge_view_name

SPD view applying node transformer prior to applying CDC changes.

ldp_auto_cdc_flow_kwargs property ¤

Keyword arguments for dp.create_auto_cdc_flow function

purge_target property ¤

Identifier of the physical data written by the sink. Sinks of different pipeline nodes sharing a purge_target write to the same data. None if the sink does not materialize data.

sdp_pre_merge_view_name property ¤

SPD view applying node transformer prior to applying CDC changes.

create(df=None) ¤

Initialize the sink if required.

Some sinks (e.g., Unity Catalog or Delta tables) must exist before metadata can be applied or data can be written in append mode.

PARAMETER DESCRIPTION
df

Input DataFrame that may be used during sink initialization.

TYPE: DataFrame DEFAULT: None

RETURNS DESCRIPTION
bool

True if the sink was created, False if it already existed or if creation is not required.

Notes

This method is intended to be overridden by subclasses to implement sink-specific initialization logic.

Source code in laktory/models/datasinks/basedatasink.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def create(self, df: "AnyFrame" = None) -> bool:
    """
    Initialize the sink if required.

    Some sinks (e.g., Unity Catalog or Delta tables) must exist before
    metadata can be applied or data can be written in append mode.

    Parameters
    ----------
    df : DataFrame
        Input DataFrame that may be used during sink initialization.

    Returns
    -------
    bool
        True if the sink was created, False if it already existed or if
        creation is not required.

    Notes
    -----
    This method is intended to be overridden by subclasses to implement
    sink-specific initialization logic.
    """
    return False

filter_writer_rows(df) ¤

Keep the rows written by the writer of a shared sink - matching its writer identifier or shared.where - without the writer column: the output of the writer read back from the shared target. Returns the DataFrame unchanged if the sink is not shared.

PARAMETER DESCRIPTION
df

DataFrame read from the sink

TYPE: AnyFrame

RETURNS DESCRIPTION
AnyFrame

DataFrame with the rows of the writer

Source code in laktory/models/datasinks/basedatasink.py
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def filter_writer_rows(self, df: AnyFrame) -> AnyFrame:
    """
    Keep the rows written by the writer of a shared sink - matching its writer
    identifier or `shared.where` - without the writer column: the output of the writer
    read back from the shared target. Returns the DataFrame unchanged if the sink is not
    shared.

    Parameters
    ----------
    df:
        DataFrame read from the sink

    Returns
    -------
    :
        DataFrame with the rows of the writer
    """
    if self.shared is None:
        return df

    is_nw = isinstance(df, (nw.DataFrame, nw.LazyFrame))
    _df = df if is_nw else nw.from_native(df)
    if self.shared.uses_writer_column:
        self._check_writer_id()
        column = self.shared.column
        if column in _df.columns:
            _df = _df.filter(nw.col(column) == self.shared.writer_id).drop(column)
    else:
        _df = nw.from_native(self._filter_where_native(_df))
    return _df if is_nw else _df.to_native()

is_streaming(df=None) ¤

Return True if the write should use Spark Structured Streaming.

Resolution order: 1. If a Narwhals-wrapped PySpark DataFrame is provided, read its native isStreaming attribute. 2. Fall back to self.as_stream (explicit sink configuration). 3. Fall back to the parent node's source as_stream flag. 4. Default to False (static write).

If both the DataFrame state and the configuration are set and they disagree, a TypeError is raised to surface the misconfiguration early.

PARAMETER DESCRIPTION
df

Optional Narwhals DataFrame or LazyFrame. Must be passed before calling .to_native() so that the Narwhals implementation attribute is still available.

DEFAULT: None

Source code in laktory/models/datasinks/basedatasink.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def is_streaming(self, df=None) -> bool:
    """
    Return `True` if the write should use Spark Structured Streaming.

    Resolution order:
    1. If a Narwhals-wrapped PySpark DataFrame is provided, read its native
       ``isStreaming`` attribute.
    2. Fall back to ``self.as_stream`` (explicit sink configuration).
    3. Fall back to the parent node's source ``as_stream`` flag.
    4. Default to ``False`` (static write).

    If both the DataFrame state and the configuration are set and they
    disagree, a ``TypeError`` is raised to surface the misconfiguration
    early.

    Parameters
    ----------
    df:
        Optional Narwhals DataFrame or LazyFrame. Must be passed before
        calling ``.to_native()`` so that the Narwhals ``implementation``
        attribute is still available.
    """
    # Check if DataFrame is streaming
    df_is_streaming = None
    if df is not None:
        df = nw.from_native(df)
        dataframe_backend = DataFrameBackends(df.implementation)
        if dataframe_backend == DataFrameBackends.PYSPARK:
            df_is_streaming = df.to_native().isStreaming

    # Check if configured as stream from writer or source
    configured_as_stream = self.as_stream
    if configured_as_stream is None:
        node = self.parent_pipeline_node
        if node is not None and node.sources:
            configured_as_stream = node.has_streaming_source

    # Resolve conflict
    if df_is_streaming is not None and configured_as_stream is not None:
        if df_is_streaming != configured_as_stream:
            if df_is_streaming:
                raise TypeError(
                    "Sink configured as static, but received dataframe is streaming."
                )
            else:
                raise TypeError(
                    "Sink configured as stream, but received dataframe is not streaming."
                )

    is_streaming = df_is_streaming or configured_as_stream or False

    return is_streaming

purge(mode=None) ¤

Delete sink data and checkpoints

View is virtual and does not materialize data, so there is nothing to purge regardless of reset_mode.

Source code in laktory/models/datasinks/pipelineviewdatasink.py
62
63
64
65
66
67
68
69
def purge(self, mode: Literal["DROP", "TRUNCATE"] | None = None):
    """
    Delete sink data and checkpoints

    View is virtual and does not materialize data, so there is nothing to purge
    regardless of `reset_mode`.
    """
    return

read(as_stream=None, reader_kwargs=None, reader_methods=None) ¤

Read dataframe from sink.

PARAMETER DESCRIPTION
as_stream

If True, dataframe read as stream.

DEFAULT: None

reader_kwargs

Keyword arguments passed to the dataframe backend reader.

DEFAULT: None

reader_methods

DataFrame backend reader methods.

DEFAULT: None

RETURNS DESCRIPTION
AnyFrame

DataFrame

Source code in laktory/models/datasinks/basedatasink.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def read(self, as_stream=None, reader_kwargs=None, reader_methods=None):
    """
    Read dataframe from sink.

    Parameters
    ----------
    as_stream:
        If `True`, dataframe read as stream.
    reader_kwargs:
        Keyword arguments passed to the dataframe backend reader.
    reader_methods:
        DataFrame backend reader methods.

    Returns
    -------
    AnyFrame
        DataFrame
    """
    return self.as_source(
        as_stream=as_stream,
        reader_kwargs=reader_kwargs,
        reader_methods=reader_methods,
    ).read()

with_writer_column(df) ¤

Add the writer identifier column to a DataFrame written by a shared sink, as the first column so that its statistics are collected. Returns the DataFrame unchanged if the sink is not shared or identifies its rows with shared.where.

PARAMETER DESCRIPTION
df

DataFrame to be written

TYPE: AnyFrame

RETURNS DESCRIPTION
AnyFrame

DataFrame with writer identifier column

Source code in laktory/models/datasinks/basedatasink.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
def with_writer_column(self, df: AnyFrame) -> AnyFrame:
    """
    Add the writer identifier column to a DataFrame written by a shared sink, as the
    first column so that its statistics are collected. Returns the DataFrame unchanged
    if the sink is not shared or identifies its rows with `shared.where`.

    Parameters
    ----------
    df:
        DataFrame to be written

    Returns
    -------
    :
        DataFrame with writer identifier column
    """
    if self.shared is None or not self.shared.uses_writer_column:
        return df

    self._check_writer_id()
    is_nw = isinstance(df, (nw.DataFrame, nw.LazyFrame))
    _df = df if is_nw else nw.from_native(df)
    column = self.shared.column
    columns = [c for c in _df.columns if c != column]
    _df = _df.with_columns(nw.lit(self.shared.writer_id).alias(column)).select(
        [column] + columns
    )
    return _df if is_nw else _df.to_native()