dlt-utils-lib 0.1__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.
- dlt_utils/__init__.py +0 -0
- dlt_utils/dlt_transformation.py +23 -0
- dlt_utils/dlt_transformations.py +90 -0
- dlt_utils/dlt_utils.py +44 -0
- dlt_utils/main_cdc_utils.py +85 -0
- dlt_utils/main_dlt_utils.py +59 -0
- dlt_utils_lib-0.1.0.dist-info/METADATA +6 -0
- dlt_utils_lib-0.1.0.dist-info/RECORD +11 -0
- dlt_utils_lib-0.1.0.dist-info/WHEEL +5 -0
- dlt_utils_lib-0.1.0.dist-info/tmpz2kz6zic +5 -0
- dlt_utils_lib-0.1.0.dist-info/top_level.txt +1 -0
dlt_utils/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
def apply_partitions(df: DataFrame, partitions: dict):
|
|
2
|
+
# apply partitioning to the dataframe
|
|
3
|
+
if partitions:
|
|
4
|
+
for col_name, expression in partitions.items():
|
|
5
|
+
if expression.replace(" ", "") != '':
|
|
6
|
+
df = df.withColumn(col_name, expr(expression))
|
|
7
|
+
return df
|
|
8
|
+
|
|
9
|
+
def update_cdc_timestamp(df: DataFrame) -> DataFrame:
|
|
10
|
+
# if cdc_timestamp is null or time difference is greater than threshold, set it to the max timestamp in the row
|
|
11
|
+
time_diff_threshold = 5 # 5 days
|
|
12
|
+
timestamp_cols = [col.name for col in df.schema.fields if isinstance(col.dataType, (TimestampType, DateType)) and col.name != 'cdc_timestamp']
|
|
13
|
+
if timestamp_cols:
|
|
14
|
+
max_timestamp_per_row = greatest(*[col(col_name) for col_name in timestamp_cols])
|
|
15
|
+
df = df.withColumn(
|
|
16
|
+
'cdc_timestamp',
|
|
17
|
+
when(
|
|
18
|
+
col('cdc_timestamp').isNull() |
|
|
19
|
+
(spark_abs(datediff(max_timestamp_per_row, col('cdc_timestamp'))) > time_diff_threshold),
|
|
20
|
+
max_timestamp_per_row
|
|
21
|
+
).otherwise(col('cdc_timestamp'))
|
|
22
|
+
)
|
|
23
|
+
return df
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from pyspark.sql import DataFrame
|
|
2
|
+
from pyspark.sql.types import TimestampType, DateType
|
|
3
|
+
from pyspark.sql.functions import col, expr, greatest, when, datediff, lag, min as spark_min, expr, count, coalesce
|
|
4
|
+
from pyspark.sql.window import Window
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def apply_partitions(df: DataFrame, partitions: dict):
|
|
8
|
+
# apply partitioning to the dataframe
|
|
9
|
+
if partitions:
|
|
10
|
+
for col_name, expression in partitions.items():
|
|
11
|
+
if expression.replace(" ", "") != '':
|
|
12
|
+
df = df.withColumn(col_name, expr(expression))
|
|
13
|
+
return df
|
|
14
|
+
|
|
15
|
+
def update_cdc_timestamp(df: DataFrame, time_diff_threshold: int) -> DataFrame:
|
|
16
|
+
# if cdc_timestamp is null or time difference is greater than threshold, set it to the max timestamp in the row
|
|
17
|
+
timestamp_cols = [col.name for col in df.schema.fields if isinstance(col.dataType, (TimestampType, DateType)) and col.name != 'cdc_timestamp']
|
|
18
|
+
|
|
19
|
+
if timestamp_cols:
|
|
20
|
+
max_timestamp_per_row = None
|
|
21
|
+
|
|
22
|
+
if len(timestamp_cols) > 1:
|
|
23
|
+
max_timestamp_per_row = greatest(*[col(col_name) for col_name in timestamp_cols])
|
|
24
|
+
# temp fix for market table if possible need take last_update_date becouse of market table contnin close time
|
|
25
|
+
if 'last_update_date' in timestamp_cols:
|
|
26
|
+
max_timestamp_per_row = when(
|
|
27
|
+
col('last_update_date').isNotNull(),
|
|
28
|
+
col('last_update_date')
|
|
29
|
+
).otherwise(max_timestamp_per_row)
|
|
30
|
+
# temp fix for artemis table if possible need take last_update_date becouse of market table contnin close time
|
|
31
|
+
if 'version' in timestamp_cols:
|
|
32
|
+
max_timestamp_per_row = when(
|
|
33
|
+
col('version').isNotNull(),
|
|
34
|
+
col('version')
|
|
35
|
+
).otherwise(max_timestamp_per_row)
|
|
36
|
+
else:
|
|
37
|
+
max_timestamp_per_row = col(timestamp_cols[0])
|
|
38
|
+
|
|
39
|
+
df = df.withColumn(
|
|
40
|
+
'cdc_timestamp',
|
|
41
|
+
when(
|
|
42
|
+
(col('cdc_timestamp').isNull()) |
|
|
43
|
+
(datediff(col('cdc_timestamp'), max_timestamp_per_row) > time_diff_threshold),
|
|
44
|
+
max_timestamp_per_row
|
|
45
|
+
).otherwise(col('cdc_timestamp'))
|
|
46
|
+
)
|
|
47
|
+
return df
|
|
48
|
+
|
|
49
|
+
def compare_cdc_timestamp_and_commit_timestamp(df, uniq_columns):
|
|
50
|
+
|
|
51
|
+
if 'commit_timestamp' in df.columns:
|
|
52
|
+
df = df.withColumn('commit_timestamp', coalesce(col('commit_timestamp').cast('timestamp'), col('cdc_timestamp').cast('timestamp')))
|
|
53
|
+
else:
|
|
54
|
+
df = df.withColumn('commit_timestamp', col('cdc_timestamp').cast('timestamp'))
|
|
55
|
+
|
|
56
|
+
columns = uniq_columns + ['cdc_timestamp']
|
|
57
|
+
df = df.withWatermark('cdc_timestamp', '5 minutes')
|
|
58
|
+
|
|
59
|
+
grouped_df = df.groupBy(columns).agg(
|
|
60
|
+
count("*").alias("record_count"),
|
|
61
|
+
)
|
|
62
|
+
df_with_conditions = df.join(grouped_df, on=columns, how="left")
|
|
63
|
+
|
|
64
|
+
df_adjusted = df_with_conditions.withColumn(
|
|
65
|
+
"cdc_timestamp",
|
|
66
|
+
when((col("record_count") > 1) & (col("commit_timestamp").isNotNull()), col("commit_timestamp"))
|
|
67
|
+
.otherwise(col("cdc_timestamp"))
|
|
68
|
+
)
|
|
69
|
+
df_adjusted = df_adjusted.drop("record_count")
|
|
70
|
+
return df_adjusted
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def adjust_sequence_operation(df: DataFrame, uniq_columns: list) -> DataFrame:
|
|
75
|
+
window_spec = Window.partitionBy(uniq_columns).orderBy("cdc_timestamp")
|
|
76
|
+
|
|
77
|
+
df_with_lag = df.withColumn("prev_op", lag("Op").over(window_spec)) \
|
|
78
|
+
.withColumn("prev_cdc_timestamp", lag("cdc_timestamp").over(window_spec))
|
|
79
|
+
|
|
80
|
+
window_spec_all = Window.partitionBy(uniq_columns)
|
|
81
|
+
df_with_max_u_timestamp = df_with_lag.withColumn(
|
|
82
|
+
"min_u_cdc_timestamp", spark_min(when(col("Op") == "U", col("cdc_timestamp"))).over(window_spec_all)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
df_adjusted = df_with_max_u_timestamp.withColumn(
|
|
86
|
+
"cdc_timestamp",
|
|
87
|
+
when((col("Op") == "I") & (col("min_u_cdc_timestamp").isNotNull()), col("min_u_cdc_timestamp") -expr("interval 1 milliseconds")).otherwise(col("cdc_timestamp"))
|
|
88
|
+
)
|
|
89
|
+
df_final = df_adjusted.drop("prev_op", "prev_cdc_timestamp", "min_u_cdc_timestamp")
|
|
90
|
+
return df_final
|
dlt_utils/dlt_utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from pyspark.sql.functions import col, expr
|
|
2
|
+
import dlt
|
|
3
|
+
|
|
4
|
+
def create_bronze_table_definition(table_name, files_path, file_format, schema_exclude_columns):
|
|
5
|
+
@dlt.table(
|
|
6
|
+
name=f"bronze_{table_name}",
|
|
7
|
+
comment="This is the bronze table.",
|
|
8
|
+
temporary=False
|
|
9
|
+
)
|
|
10
|
+
def transform_cdc_to_bronze():
|
|
11
|
+
df = spark.read.format(file_format).load(files_path)
|
|
12
|
+
fields = [field for field in df.schema.fields if field.name not in schema_exclude_columns]
|
|
13
|
+
schema_string = ', '.join([f"{field.name} {field.dataType.simpleString()}" for field in fields])
|
|
14
|
+
return spark \
|
|
15
|
+
.readStream \
|
|
16
|
+
.format('cloudFiles') \
|
|
17
|
+
.option("cloudFiles.format", file_format) \
|
|
18
|
+
.option("cloudFiles.schemaHints", schema_string) \
|
|
19
|
+
.load(files_path) \
|
|
20
|
+
.withColumn('cdc_timestamp', col('cdc_timestamp').cast('timestamp'))
|
|
21
|
+
|
|
22
|
+
return transform_cdc_to_bronze
|
|
23
|
+
|
|
24
|
+
def silver_streaming_process(table_name, keys, partition_col, exclude_columns):
|
|
25
|
+
dlt.create_streaming_table(
|
|
26
|
+
name=table_name,
|
|
27
|
+
table_properties={
|
|
28
|
+
"delta.autoOptimize.optimizeWrite": "true",
|
|
29
|
+
"delta.autoOptimize.autoCompact": "true"
|
|
30
|
+
},
|
|
31
|
+
comment="This is the silver table with source in",
|
|
32
|
+
partition_cols=partition_col if partition_col else None
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
dlt.apply_changes(
|
|
36
|
+
target=table_name,
|
|
37
|
+
source=f"bronze_{table_name}",
|
|
38
|
+
keys=keys,
|
|
39
|
+
sequence_by=col("cdc_timestamp"),
|
|
40
|
+
apply_as_deletes=expr("Op = 'D'"),
|
|
41
|
+
apply_as_truncates=expr("Op = 'T'"),
|
|
42
|
+
except_column_list=["Op", "_rescued_data"] + exclude_columns,
|
|
43
|
+
stored_as_scd_type=1
|
|
44
|
+
)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from pyspark.sql.functions import col, expr, coalesce, lit
|
|
2
|
+
from .dlt_transformations import update_cdc_timestamp, apply_partitions
|
|
3
|
+
|
|
4
|
+
# Base code pipeline: streaming process
|
|
5
|
+
def base_cdc_replication_process(dlt, spark, table_name: str, files_path: str, bucket_name: str, cdc_data_list_maps: list, bronze_directory: str,time_diff_history_cdc_timestamp: int = 30):
|
|
6
|
+
|
|
7
|
+
# parse list with tables for replication
|
|
8
|
+
for table in cdc_data_list_maps:
|
|
9
|
+
source_table_name = table['source_table_name']
|
|
10
|
+
source_schema = table['source_schema']
|
|
11
|
+
file_format = table['format']
|
|
12
|
+
keys = table['keys']
|
|
13
|
+
exclude_columns = table['exclude_columns']
|
|
14
|
+
partition_col = table['partition_col']
|
|
15
|
+
|
|
16
|
+
s3_files_path = f"{source_schema}/{source_table_name}/"
|
|
17
|
+
bronze_table_path = f"{bucket_name}/{bronze_directory}/{s3_files_path}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Execute pipeline
|
|
21
|
+
create_bronze_table_definition(spark=spark,
|
|
22
|
+
dlt=dlt,
|
|
23
|
+
table_name=source_table_name,
|
|
24
|
+
files_path=bronze_table_path,
|
|
25
|
+
file_format=file_format,
|
|
26
|
+
partitions=partition_col,
|
|
27
|
+
schema_exclude_columns=exclude_columns,
|
|
28
|
+
keys=keys,
|
|
29
|
+
time_diff_history_cdc_timestamp=time_diff_history_cdc_timestamp
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
silver_streaming_process(dlt=dlt,
|
|
33
|
+
table_name=source_table_name,
|
|
34
|
+
keys=keys,
|
|
35
|
+
partitions=partition_col,
|
|
36
|
+
exclude_columns=exclude_columns)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# Define the transformation function dynamically
|
|
40
|
+
def create_bronze_table_definition(spark, dlt, table_name: str, files_path: str, file_format: str, partitions: dict, schema_exclude_columns: list, keys: list, time_diff_history_cdc_timestamp: int):
|
|
41
|
+
@dlt.table(
|
|
42
|
+
name=f"bronze_{table_name}",
|
|
43
|
+
comment="This is the bronze table.",
|
|
44
|
+
temporary=False
|
|
45
|
+
)
|
|
46
|
+
def transform_cdc_to_bronze():
|
|
47
|
+
df = spark.read.format(file_format).load(files_path)
|
|
48
|
+
fields = [field for field in df.schema.fields if field.name not in schema_exclude_columns]
|
|
49
|
+
schema_string = ', '.join([f"{field.name} {field.dataType.simpleString()}" for field in fields])
|
|
50
|
+
return spark \
|
|
51
|
+
.readStream \
|
|
52
|
+
.format('cloudFiles') \
|
|
53
|
+
.option("cloudFiles.format", file_format) \
|
|
54
|
+
.option("cloudFiles.schemaHints", schema_string) \
|
|
55
|
+
.load(files_path) \
|
|
56
|
+
.withColumn('cdc_timestamp', col('cdc_timestamp').cast('timestamp')) \
|
|
57
|
+
.withColumn('ar_h_change_seq', col('ar_h_change_seq').cast('string')) \
|
|
58
|
+
.transform(lambda df: update_cdc_timestamp(df, time_diff_history_cdc_timestamp)) \
|
|
59
|
+
.transform(lambda df: apply_partitions(df, partitions))
|
|
60
|
+
|
|
61
|
+
return transform_cdc_to_bronze
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# Create silver streaming data
|
|
65
|
+
def silver_streaming_process(dlt, table_name: str, keys: list, partitions: dict, exclude_columns: list):
|
|
66
|
+
dlt.create_streaming_table(
|
|
67
|
+
name=table_name,
|
|
68
|
+
table_properties={
|
|
69
|
+
"delta.autoOptimize.optimizeWrite": "true",
|
|
70
|
+
"delta.autoOptimize.autoCompact": "true"
|
|
71
|
+
},
|
|
72
|
+
comment = "This is the silver table with source in",
|
|
73
|
+
partition_cols=partitions if partitions else None
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
dlt.apply_changes(
|
|
77
|
+
target=table_name,
|
|
78
|
+
source=f"bronze_{table_name}",
|
|
79
|
+
keys=keys,
|
|
80
|
+
sequence_by=col("ar_h_change_seq"),
|
|
81
|
+
apply_as_deletes=expr("Op = 'D'"),
|
|
82
|
+
apply_as_truncates=expr("Op = 'T'"),
|
|
83
|
+
except_column_list=["Op", "_rescued_data"] + exclude_columns,
|
|
84
|
+
stored_as_scd_type=1
|
|
85
|
+
)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import dlt
|
|
2
|
+
from pyspark.sql.functions import col, expr, greatest, when, datediff, abs as spark_abs
|
|
3
|
+
from dlt_transformations import update_cdc_timestamp, apply_partitions
|
|
4
|
+
from pyspark.sql.types import TimestampType, DateType
|
|
5
|
+
from pyspark.sql import DataFrame
|
|
6
|
+
from pyspark.sql import SparkSession
|
|
7
|
+
|
|
8
|
+
# Assuming SparkSession is already created in your Databricks notebook
|
|
9
|
+
spark = SparkSession.builder.appName("DLT Pipeline").getOrCreate()
|
|
10
|
+
spark.conf.set("pipelines.tableManagedByMultiplePipelinesCheck.enabled", "false")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# Define the transformation function dynamically
|
|
14
|
+
def create_bronze_table_definition(table_name: str, files_path: str, file_format: str, partitions: dict, schema_exclude_columns: list):
|
|
15
|
+
@dlt.table(
|
|
16
|
+
name=f"bronze_{table_name}",
|
|
17
|
+
comment="This is the bronze table.",
|
|
18
|
+
temporary=False
|
|
19
|
+
)
|
|
20
|
+
def transform_cdc_to_bronze():
|
|
21
|
+
df = spark.read.format(file_format).load(files_path)
|
|
22
|
+
fields = [field for field in df.schema.fields if field.name not in schema_exclude_columns]
|
|
23
|
+
schema_string = ', '.join([f"{field.name} {field.dataType.simpleString()}" for field in fields])
|
|
24
|
+
return spark \
|
|
25
|
+
.readStream \
|
|
26
|
+
.format('cloudFiles') \
|
|
27
|
+
.option("cloudFiles.format", file_format) \
|
|
28
|
+
.option("cloudFiles.schemaHints", schema_string) \
|
|
29
|
+
.load(files_path) \
|
|
30
|
+
.withColumn('cdc_timestamp', col('cdc_timestamp').cast('timestamp')) \
|
|
31
|
+
.transform(update_cdc_timestamp) \
|
|
32
|
+
.transform(lambda df: apply_partitions(df, partitions))
|
|
33
|
+
|
|
34
|
+
return transform_cdc_to_bronze
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Create silver streaming data
|
|
39
|
+
def silver_streaming_process(table_name: str, keys: list, partitions: dict, exclude_columns: list):
|
|
40
|
+
dlt.create_streaming_table(
|
|
41
|
+
name=table_name,
|
|
42
|
+
table_properties={
|
|
43
|
+
"delta.autoOptimize.optimizeWrite": "true",
|
|
44
|
+
"delta.autoOptimize.autoCompact": "true"
|
|
45
|
+
},
|
|
46
|
+
comment = "This is the silver table with source in",
|
|
47
|
+
partition_cols=partitions if partitions else None
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
dlt.apply_changes(
|
|
51
|
+
target=table_name,
|
|
52
|
+
source=f"bronze_{table_name}",
|
|
53
|
+
keys=keys,
|
|
54
|
+
sequence_by=col("cdc_timestamp"),
|
|
55
|
+
apply_as_deletes=expr("Op = 'D'"),
|
|
56
|
+
apply_as_truncates=expr("Op = 'T'"),
|
|
57
|
+
except_column_list=["Op", "_rescued_data"] + exclude_columns,
|
|
58
|
+
stored_as_scd_type=1
|
|
59
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
dlt_utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
dlt_utils/dlt_transformation.py,sha256=PPvNi4pVtP5fM69Zpzm1VvagA0e93B7augVzEB_WeGU,1109
|
|
3
|
+
dlt_utils/dlt_transformations.py,sha256=R1bCH3JtidIK0embVqbH-gBdkkpiYG6F2WVdUJxkT5A,4258
|
|
4
|
+
dlt_utils/dlt_utils.py,sha256=KzZjLgWtACns3kQJI9O-1F030xCvgJPDcT3T6Il0NZg,1691
|
|
5
|
+
dlt_utils/main_cdc_utils.py,sha256=PI9oFiYOP0dczRqX5iguP8FZqdR7k6VGeS9KjmLEeWI,3907
|
|
6
|
+
dlt_utils/main_dlt_utils.py,sha256=goPB2SsoHx6IeX7BYSn_eGZmyxA4emN-tT6Px-LK1Ao,2408
|
|
7
|
+
dlt_utils_lib-0.1.0.dist-info/METADATA,sha256=14Gb20-s7sH2rsjyamzWSfFYyY9lPB2utVXAd_-H8Rk,108
|
|
8
|
+
dlt_utils_lib-0.1.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
|
|
9
|
+
dlt_utils_lib-0.1.0.dist-info/tmpz2kz6zic,sha256=ovntz9H59jTF7MwMFD9bqx2-k_fa759JGnM8ENGfr7s,105
|
|
10
|
+
dlt_utils_lib-0.1.0.dist-info/top_level.txt,sha256=KQIiBkukfDFtKV6NmbNK651_k5Oj0jLk5dpU0ZO1xuQ,10
|
|
11
|
+
dlt_utils_lib-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dlt_utils
|