-
Notifications
You must be signed in to change notification settings - Fork 29.2k
Expand file tree
/
Copy pathapi.py
More file actions
662 lines (582 loc) · 25.7 KB
/
api.py
File metadata and controls
662 lines (582 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import Callable, Dict, List, Literal, Optional, Union, overload
from pyspark.errors import PySparkTypeError
from pyspark.pipelines.graph_element_registry import get_active_graph_element_registry
from pyspark.pipelines.type_error_utils import validate_optional_list_of_str_arg
from pyspark.pipelines.flow import AutoCdcFlow, Flow, QueryFunction
from pyspark.pipelines.source_code_location import (
get_caller_source_code_location,
)
from pyspark.pipelines.output import (
MaterializedView,
StreamingTable,
TemporaryView,
Sink,
)
from pyspark.sql import Column
from pyspark.sql import functions as F
from pyspark.sql.types import StructType
def append_flow(
*,
target: str,
name: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
) -> Callable[[QueryFunction], None]:
"""
Return a decorator on a query function to define a flow in a pipeline.
:param name: The name of the flow. If unspecified, the query function's name will be used.
:param target: The name of the dataset this flow writes to. Must be specified.
:param spark_conf: A dict whose keys are the conf names and values are the conf values. \
These confs will be set when the flow is executed; they can override confs set for the \
destination, for the pipeline, or on the cluster.
"""
if name is not None and type(name) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "name",
"expected_type": "str",
"arg_type": type(name).__name__,
},
)
source_code_location = get_caller_source_code_location(stacklevel=1)
if spark_conf is None:
spark_conf = {}
def outer(func: QueryFunction) -> None:
query_name = name if name is not None else func.__name__
flow = Flow(
name=query_name,
target=target,
spark_conf=spark_conf,
source_code_location=source_code_location,
func=func,
)
get_active_graph_element_registry().register_flow(flow)
return outer
def _validate_stored_dataset_args(
name: Optional[str],
table_properties: Optional[Dict[str, str]],
partition_cols: Optional[List[str]],
cluster_by: Optional[List[str]],
) -> None:
if name is not None and type(name) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "name",
"expected_type": "str",
"arg_type": type(name).__name__,
},
)
if table_properties is not None and not isinstance(table_properties, dict):
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"expected_type": "dict",
"arg_name": "table_properties",
"arg_type": type(table_properties).__name__,
},
)
validate_optional_list_of_str_arg(arg_name="partition_cols", arg_value=partition_cols)
validate_optional_list_of_str_arg(arg_name="cluster_by", arg_value=cluster_by)
@overload
def table(query_function: QueryFunction) -> None: ...
@overload
def table(
*,
query_function: None = None,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
table_properties: Optional[Dict[str, str]] = None,
partition_cols: Optional[List[str]] = None,
cluster_by: Optional[List[str]] = None,
schema: Optional[Union[StructType, str]] = None,
) -> Callable[[QueryFunction], None]: ...
def table(
query_function: Optional[QueryFunction] = None,
*,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
table_properties: Optional[Dict[str, str]] = None,
partition_cols: Optional[List[str]] = None,
cluster_by: Optional[List[str]] = None,
schema: Optional[Union[StructType, str]] = None,
format: Optional[str] = None,
) -> Union[Callable[[QueryFunction], None], None]:
"""
(Return a) decorator to define a table in the pipeline and mark a function as the table's query
function.
@table can be used with or without parameters. If called without parameters, Python will
implicitly pass the decorated query function as the query_function param. If called with
parameters, @table will return a decorator that is applied on the decorated query function.
:param query_function: The table's query function. This parameter should not be explicitly \
passed by users. This is passed implicitly by Python if the decorator is called without \
parameters.
:param name: The name of the dataset. If unspecified, the query function's name will be used.
:param comment: Description of the dataset.
:param spark_conf: A dict whose keys are the conf names and values are the conf values. \
These confs will be set when the query for the dataset is executed and they can override \
confs set for the pipeline or on the cluster.
:param table_properties: A dict where the keys are the property names and the values are the \
property values. These properties will be set on the table.
:param partition_cols: A list containing the column names of the partition columns.
:param cluster_by: A list containing the column names of the cluster columns.
:param schema: Explicit Spark SQL schema to materialize this table with. Supports either a \
Pyspark StructType or a SQL DDL string, such as "a INT, b STRING".
:param format: The format of the table, e.g. "parquet".
"""
_validate_stored_dataset_args(name, table_properties, partition_cols, cluster_by)
source_code_location = get_caller_source_code_location(stacklevel=1)
def outer(
decorated: QueryFunction,
) -> None:
_validate_decorated(decorated, "table")
resolved_name = name or decorated.__name__
registry = get_active_graph_element_registry()
registry.register_output(
StreamingTable(
comment=comment,
name=resolved_name,
table_properties=table_properties or {},
partition_cols=partition_cols,
cluster_by=cluster_by,
schema=schema,
source_code_location=source_code_location,
format=format,
)
)
registry.register_flow(
Flow(
name=resolved_name,
target=resolved_name,
spark_conf=spark_conf or {},
source_code_location=source_code_location,
func=decorated,
)
)
if query_function is not None:
# Case where the decorator is called without parameters, e.g.:
# @table
# def query_fn():
# return ...
outer(query_function)
return None
else:
# Case where the decorator is called with parameters, e.g.:
# @table(name="tbl")
# def query_fn():
# return ...
return outer
@overload
def materialized_view(query_function: QueryFunction) -> None: ...
@overload
def materialized_view(
*,
query_function: None = None,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
table_properties: Optional[Dict[str, str]] = None,
partition_cols: Optional[List[str]] = None,
cluster_by: Optional[List[str]] = None,
schema: Optional[Union[StructType, str]] = None,
) -> Callable[[QueryFunction], None]: ...
def materialized_view(
query_function: Optional[QueryFunction] = None,
*,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
table_properties: Optional[Dict[str, str]] = None,
partition_cols: Optional[List[str]] = None,
cluster_by: Optional[List[str]] = None,
schema: Optional[Union[StructType, str]] = None,
format: Optional[str] = None,
) -> Union[Callable[[QueryFunction], None], None]:
"""
(Return a) decorator to define a materialized view in the pipeline and mark a function as the
materialized view's query function.
@materialized_view can be used with or without parameters. If called without parameters, Python
will implicitly pass the decorated query function as the query_function param. If called with
parameters, it will return a decorator that is applied on the decorated query function.
:param query_function: The table's query function. This parameter should not be explicitly \
passed by users. This is passed implicitly by Python if the decorator is called without \
parameters.
:param name: The name of the dataset. If unspecified, the query function's name will be used.
:param comment: Description of the dataset.
:param spark_conf: A dict whose keys are the conf names and values are the conf values. \
These confs will be set when the query for the dataset is executed and they can override \
confs set for the pipeline or on the cluster.
:param table_properties: A dict where the keys are the property names and the values are the \
property values. These properties will be set on the table.
:param partition_cols: A list containing the column names of the partition columns.
:param cluster_by: A list containing the column names of the cluster columns.
:param schema: Explicit Spark SQL schema to materialize this table with. Supports either a \
Pyspark StructType or a SQL DDL string, such as "a INT, b STRING".
:param format: The format of the table, e.g. "parquet".
"""
_validate_stored_dataset_args(name, table_properties, partition_cols, cluster_by)
source_code_location = get_caller_source_code_location(stacklevel=1)
def outer(
decorated: QueryFunction,
) -> None:
_validate_decorated(decorated, "materialized_view")
resolved_name = name or decorated.__name__
registry = get_active_graph_element_registry()
registry.register_output(
MaterializedView(
comment=comment,
name=resolved_name,
table_properties=table_properties or {},
partition_cols=partition_cols,
cluster_by=cluster_by,
schema=schema,
source_code_location=source_code_location,
format=format,
)
)
registry.register_flow(
Flow(
name=resolved_name,
target=resolved_name,
spark_conf=spark_conf or {},
source_code_location=source_code_location,
func=decorated,
)
)
if query_function is not None:
# Case where the decorator is called without parameters, e.g.:
# @materialized_view
# def query_fn():
# return ...
outer(query_function)
return None
else:
# Case where the decorator is called with parameters, e.g.:
# @materialized_view(name="tbl")
# def query_fn():
# return ...
return outer
@overload
def temporary_view(
query_function: QueryFunction,
) -> None: ...
@overload
def temporary_view(
*,
query_function: None = None,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
) -> Callable[[QueryFunction], None]: ...
def temporary_view(
query_function: Optional[QueryFunction] = None,
*,
name: Optional[str] = None,
comment: Optional[str] = None,
spark_conf: Optional[Dict[str, str]] = None,
) -> Union[Callable[[QueryFunction], None], None]:
"""
(Return a) decorator to define a view in the pipeline and mark a function as the view's query
function.
@view can be used with or without parameters. If called without parameters, Python will
implicitly pass the decorated query function as the query_function param. If called with
parameters, @view will return a decorator that is applied on the decorated query function.
:param query_function: The view's query function. This parameter should not be explicitly \
passed by users. This is passed implicitly by Python if the decorator is called without \
parameters.
:param name: The name of the dataset. If unspecified, the query function's name will be used.
:param comment: Description of the dataset.
:param spark_conf: A dict whose keys are the conf names and values are the conf values. \
These confs will be set when the query for the dataset is executed and they can override \
confs set for the pipeline or on the cluster.
"""
if name is not None and type(name) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "name",
"expected_type": "str",
"arg_type": type(name).__name__,
},
)
source_code_location = get_caller_source_code_location(stacklevel=1)
def outer(decorated: QueryFunction) -> None:
_validate_decorated(decorated, "temporary_view")
resolved_name = name or decorated.__name__
registry = get_active_graph_element_registry()
registry.register_output(
TemporaryView(
comment=comment,
name=resolved_name,
source_code_location=source_code_location,
)
)
registry.register_flow(
Flow(
target=resolved_name,
func=decorated,
spark_conf=spark_conf or {},
name=resolved_name,
source_code_location=source_code_location,
)
)
if query_function is not None:
# Case where the decorator is called without parameters, e.g.:
# @temporary_view
# def query_fn():
# return ...
outer(query_function)
return None
else:
# Case where the decorator is called with parameters, e.g.:
# @temporary_view(name="tbl")
# def query_fn():
# return ...
return outer
def _validate_decorated(decorated: QueryFunction, decorator_name: str) -> None:
if not callable(decorated):
raise PySparkTypeError(
errorClass="DECORATOR_ARGUMENT_NOT_CALLABLE",
messageParameters={
"decorator_name": decorator_name,
"example_usage": f"@{decorator_name}(name='{decorator_name}_a')",
},
)
def create_streaming_table(
name: str,
*,
comment: Optional[str] = None,
table_properties: Optional[Dict[str, str]] = None,
partition_cols: Optional[List[str]] = None,
cluster_by: Optional[List[str]] = None,
schema: Optional[Union[StructType, str]] = None,
format: Optional[str] = None,
) -> None:
"""
Creates a table that can be targeted by append flows.
Example:
create_streaming_table("target")
:param name: The name of the table.
:param comment: Description of the table.
:param table_properties: A dict where the keys are the property names and the values are the \
property values. These properties will be set on the table.
:param partition_cols: A list containing the column names of the partition columns.
:param cluster_by: A list containing the column names of the cluster columns.
:param schema: Explicit Spark SQL schema to materialize this table with. Supports either a \
Pyspark StructType or a SQL DDL string, such as "a INT, b STRING".
:param format: The format of the table, e.g. "parquet".
"""
if type(name) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "name",
"expected_type": "str",
"arg_type": type(name).__name__,
},
)
if table_properties is not None and not isinstance(table_properties, dict):
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"expected_type": "dict",
"arg_name": "table_properties",
"arg_type": type(table_properties).__name__,
},
)
validate_optional_list_of_str_arg(arg_name="partition_cols", arg_value=partition_cols)
validate_optional_list_of_str_arg(arg_name="cluster_by", arg_value=cluster_by)
source_code_location = get_caller_source_code_location(stacklevel=1)
table = StreamingTable(
name=name,
comment=comment,
source_code_location=source_code_location,
table_properties=table_properties or {},
partition_cols=partition_cols,
cluster_by=cluster_by,
schema=schema,
format=format,
)
get_active_graph_element_registry().register_output(table)
def create_sink(
name: str,
format: str,
options: Optional[Dict[str, str]] = None,
) -> None:
"""
Creates a sink that can be targeted by streaming flows, providing a generic destination
for flows to send data external to the pipeline.
:param name: The name of the sink.
:param format: The format of the sink, e.g. "parquet".
:param options: A dict where the keys are the property names and the values are the
property values. These properties will be set on the sink.
"""
if type(name) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "name",
"expected_type": "str",
"arg_type": type(name).__name__,
},
)
if type(format) is not str:
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "format",
"expected_type": "str",
"arg_type": type(format).__name__,
},
)
if options is not None and not isinstance(options, dict):
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"expected_type": "dict",
"arg_name": "options",
"arg_type": type(options).__name__,
},
)
sink = Sink(
name=name,
format=format,
options=options or {},
source_code_location=get_caller_source_code_location(stacklevel=1),
comment=None,
)
get_active_graph_element_registry().register_output(sink)
def create_auto_cdc_flow(
target: str,
source: str,
keys: Union[List[str], List[Column]],
sequence_by: Union[str, Column],
apply_as_deletes: Optional[Union[str, Column]] = None,
apply_as_truncates: Optional[Union[str, Column]] = None,
column_list: Optional[Union[List[str], List[Column]]] = None,
except_column_list: Optional[Union[List[str], List[Column]]] = None,
stored_as_scd_type: Optional[Literal[1, "1"]] = None,
name: Optional[str] = None,
ignore_null_updates_column_list: Optional[Union[List[str], List[Column]]] = None,
ignore_null_updates_except_column_list: Optional[Union[List[str], List[Column]]] = None,
) -> None:
"""
Create an Auto CDC flow into the target table from the Change Data Capture (CDC) source.
Target table must have already been created using create_streaming_table function. Only one
of column_list and except_column_list can be specified.
Example:
create_auto_cdc_flow(
target = "target",
source = "source",
keys = ["key"],
sequence_by = "sequence_expr",
ignore_null_updates_column_list = ["value"],
column_list = ["key", "value"],
)
Note that for keys, sequence_by, column_list, except_column_list,
ignore_null_updates_column_list, and ignore_null_updates_except_column_list the arguments
have to be column identifiers without qualifiers, e.g. they cannot be
col("sourceTable.keyId").
:param target: The name of the target table that receives the Auto CDC flow.
:param source: The name of the CDC source to stream from.
:param keys: The column or combination of columns that uniquely identify a row in the source \
data. This is used to identify which CDC events apply to specific records in the target \
table. These keys also identify records in the target table, e.g., if there exists a record \
for given keys and the CDC source has an UPSERT operation for the same keys, we will update \
the existing record. At least one key must be provided. This should be a list of column \
identifiers without qualifiers, expressed as either Python strings or Pyspark Columns.
:param sequence_by: An expression that we use to order the source data. This can be expressed \
as either a Python string or Pyspark Expression.
:param apply_as_deletes: Delete condition for the merged operation. This should be a string of \
expression e.g. "operation = 'DELETE'"
:param apply_as_truncates: Truncate condition for the merged operation. This should be a string \
expression e.g. "operation = 'TRUNCATE'"
:param column_list: Columns that will be included in the output table. This should be a list \
of column identifiers without qualifiers, expressed as either Python strings or Pyspark \
Column. Only one of column_list and except_column_list can be specified.
:param except_column_list: Columns that will be excluded in the output table. This should be a \
list of column identifiers without qualifiers, expressed as either Python strings or Pyspark \
Column. Only one of column_list and except_column_list can be specified. When this is \
specified, all columns in the dataframe of the target table except those in this list will \
be in the output table.
:param stored_as_scd_type: The SCD type for the target table. Only 1 (or "1") is supported. \
When not specified the server default applies.
:param name: The name of the flow for this create_auto_cdc_flow command. When unspecified this \
will build a "default flow" with name equal to the target name.
:param ignore_null_updates_column_list: Subset of columns to ignore null values in during \
updates. When a source row has a null for one of these columns, the existing value in the \
target is preserved. Only one of ignore_null_updates_column_list and \
ignore_null_updates_except_column_list can be specified.
:param ignore_null_updates_except_column_list: Columns excluded from null-update ignoring. \
All other columns will have null values ignored during updates. Only one of \
ignore_null_updates_column_list and ignore_null_updates_except_column_list can be specified.
"""
keys = _normalize_column_list(keys)
column_list = _normalize_optional_column_list(column_list)
except_column_list = _normalize_optional_column_list(except_column_list)
ignore_null_updates_column_list = _normalize_optional_column_list(
ignore_null_updates_column_list
)
ignore_null_updates_except_column_list = _normalize_optional_column_list(
ignore_null_updates_except_column_list
)
if isinstance(sequence_by, str):
sequence_by = F.expr(sequence_by)
if isinstance(apply_as_deletes, str):
apply_as_deletes = F.expr(apply_as_deletes)
if isinstance(apply_as_truncates, str):
apply_as_truncates = F.expr(apply_as_truncates)
if stored_as_scd_type is not None and str(stored_as_scd_type) != "1":
raise PySparkTypeError(
errorClass="NOT_EXPECTED_TYPE",
messageParameters={
"arg_name": "stored_as_scd_type",
"expected_type": "Literal[1, '1']",
"arg_type": type(stored_as_scd_type).__name__,
},
)
source_code_location = get_caller_source_code_location(stacklevel=1)
flow = AutoCdcFlow(
name=name,
target=target,
source=source,
keys=keys,
sequence_by=sequence_by,
apply_as_deletes=apply_as_deletes,
apply_as_truncates=apply_as_truncates,
column_list=column_list,
except_column_list=except_column_list,
stored_as_scd_type=stored_as_scd_type,
ignore_null_updates_column_list=ignore_null_updates_column_list,
ignore_null_updates_except_column_list=ignore_null_updates_except_column_list,
source_code_location=source_code_location,
)
get_active_graph_element_registry().register_auto_cdc_flow(flow)
def _normalize_optional_column_list(
column_list: Optional[Union[List[str], List[Column]]],
) -> Optional[List[Column]]:
if column_list is None:
return None
return _normalize_column_list(column_list)
def _normalize_column_list(
column_list: Union[List[str], List[Column]],
) -> List[Column]:
return [F.col(c) if isinstance(c, str) else c for c in column_list]