Skip to content

BaseDataSink

laktory.models.datasinks.BaseDataSink ¤

Bases: BaseModel, PipelineChild

Base class for data sinks

PARAMETER DESCRIPTION
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_quality_monitor

Databricks Quality Monitor

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['UPDATE', 'ERRORIFEXISTS', 'OVERWRITE', 'COMPLETE', 'APPEND', 'MERGE', 'ERROR', 'IGNORE'] | None | VariableType DEFAULT: None

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

type

Name of the data sink type

TYPE: Literal['FILE', 'HIVE_METASTORE', 'UNITY_CATALOG'] | VariableType

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.

purge

Delete sink data and checkpoints

read

Read dataframe from sink.

write

Write dataframe into sink.

ATTRIBUTE DESCRIPTION
dlt_apply_changes_kwargs

Keyword arguments for dlt.apply_changes function

TYPE: dict[str, str]

dlt_pre_merge_view_name

DLT view applying node transformer prior to applying CDC changes.

dlt_apply_changes_kwargs property ¤

Keyword arguments for dlt.apply_changes function

dlt_pre_merge_view_name property ¤

DLT 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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

purge() ¤

Delete sink data and checkpoints

Source code in laktory/models/datasinks/basedatasink.py
623
624
625
626
627
def purge(self):
    """
    Delete sink data and checkpoints
    """
    raise NotImplementedError()

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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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()

write(df=None, view_definition=None, mode=None) ¤

Write dataframe into sink.

PARAMETER DESCRIPTION
df

Input dataframe.

TYPE: AnyFrame DEFAULT: None

mode

Write mode overwrite of the sink default mode.

TYPE: str DEFAULT: None

view_definition

View definition for table data sinks of VIEW type

TYPE: str DEFAULT: None

Source code in laktory/models/datasinks/basedatasink.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def write(
    self,
    df: AnyFrame = None,
    view_definition: str = None,
    mode: str = None,
) -> None:
    """
    Write dataframe into sink.

    Parameters
    ----------
    df:
        Input dataframe.
    mode:
        Write mode overwrite of the sink default mode.
    view_definition:
        View definition for table data sinks of `VIEW` type
    """

    logger.info("Write initiated.")

    if getattr(self, "table_type", None) == "VIEW":
        if view_definition is None:
            raise ValueError(f"`view_definition` for '{self._id}' is `None`")

        from laktory.models.dataframe.dataframeexpr import DataFrameExpr

        if not isinstance(view_definition, DataFrameExpr):
            view_definition = DataFrameExpr(expr=view_definition)

        if self.dataframe_backend == DataFrameBackends.PYSPARK:
            self._write_spark_view(view_definition)
        elif self.dataframe_backend == DataFrameBackends.POLARS:
            self._write_polars_view(view_definition)
        else:
            raise ValueError(
                f"DataFrame backend '{self.dataframe_backend}' is not supported"
            )
        return

    if not isinstance(df, (nw.DataFrame, nw.LazyFrame)):
        df = nw.from_native(df)
    self._update_backend_from_df(df)

    # Custom Writer
    if self.custom_writer:
        df_native = df.to_native()

        # Special Treatment for Spark Streaming
        if (
            self.dataframe_backend == DataFrameBackends.PYSPARK
            and df_native.isStreaming
        ):
            if self.checkpoint_path is None:
                raise ValueError(
                    f"Checkpoint location not specified for sink '{self._id}'"
                )
            # Build context before the foreachBatch lambda so that _parent
            # references are captured while intact. Inside foreachBatch on
            # Databricks, the lambda closure is serialized via cloudpickle
            # and _parent attributes may not survive the round-trip.
            from laktory.models.laktorycontext import LaktoryContext

            _context = LaktoryContext(
                node=self.parent_pipeline_node,
                pipeline=self.parent_pipeline,
                sink=self,
            )
            query = (
                df_native.writeStream.foreachBatch(
                    lambda batch_df, _: self.custom_writer.execute(
                        batch_df, context=_context
                    )
                )
                .trigger(availableNow=True)
                .options(checkpointLocation=self.checkpoint_path)
                .start()
            )
            query.awaitTermination()

        else:
            self.custom_writer.execute(df)

        logger.info("Write completed.")
        return

    if mode is None:
        mode = self.mode

    self._validate_mode(mode, df)
    self._validate_format()

    if mode and mode.lower() == "merge":
        self.merge_cdc_options.execute(source=df)
        logger.info("Write completed.")
        return

    if self.dataframe_backend == DataFrameBackends.PYSPARK:
        self._write_spark(df=df, mode=mode)
    elif self.dataframe_backend == DataFrameBackends.POLARS:
        self._write_polars(df=df, mode=mode)
    else:
        raise ValueError(
            f"DataFrame backend '{self.dataframe_backend}' is not supported"
        )

    logger.info("Write completed.")