-
Notifications
You must be signed in to change notification settings - Fork 28k
/
plan.py
2286 lines (1886 loc) · 81.2 KB
/
plan.py
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
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
921
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# 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 pyspark.sql.connect.utils import check_dependencies
check_dependencies(__name__)
from typing import Any, List, Optional, Type, Sequence, Union, cast, TYPE_CHECKING, Mapping, Dict
import functools
import json
import pickle
from threading import Lock
from inspect import signature, isclass
import pyarrow as pa
from pyspark.serializers import CloudPickleSerializer
from pyspark.storagelevel import StorageLevel
from pyspark.sql.types import DataType
import pyspark.sql.connect.proto as proto
from pyspark.sql.connect.conversion import storage_level_to_proto
from pyspark.sql.connect.column import Column
from pyspark.sql.connect.expressions import (
Expression,
SortOrder,
ColumnReference,
LiteralExpression,
)
from pyspark.sql.connect.types import pyspark_types_to_proto_types, UnparsedDataType
from pyspark.errors import (
PySparkTypeError,
PySparkNotImplementedError,
PySparkPicklingError,
IllegalArgumentException,
)
if TYPE_CHECKING:
from pyspark.sql.connect._typing import ColumnOrName
from pyspark.sql.connect.client import SparkConnectClient
from pyspark.sql.connect.udf import UserDefinedFunction
class LogicalPlan:
_lock: Lock = Lock()
_nextPlanId: int = 0
INDENT = 2
def __init__(self, child: Optional["LogicalPlan"]) -> None:
self._child = child
plan_id: Optional[int] = None
with LogicalPlan._lock:
plan_id = LogicalPlan._nextPlanId
LogicalPlan._nextPlanId += 1
assert plan_id is not None
self._plan_id = plan_id
def _create_proto_relation(self) -> proto.Relation:
plan = proto.Relation()
plan.common.plan_id = self._plan_id
return plan
def unresolved_attr(self, colName: str) -> proto.Expression:
"""Creates an unresolved attribute from a column name."""
exp = proto.Expression()
exp.unresolved_attribute.unparsed_identifier = colName
return exp
def to_attr_or_expression(
self, col: "ColumnOrName", session: "SparkConnectClient"
) -> proto.Expression:
"""Returns either an instance of an unresolved attribute or the serialized
expression value of the column."""
if type(col) is str:
return self.unresolved_attr(col)
else:
return cast(Column, col).to_plan(session)
def plan(self, session: "SparkConnectClient") -> proto.Relation:
...
def command(self, session: "SparkConnectClient") -> proto.Command:
...
def _verify(self, session: "SparkConnectClient") -> bool:
"""This method is used to verify that the current logical plan
can be serialized to Proto and back and afterwards is identical."""
plan = proto.Plan()
plan.root.CopyFrom(self.plan(session))
serialized_plan = plan.SerializeToString()
test_plan = proto.Plan()
test_plan.ParseFromString(serialized_plan)
return test_plan == plan
def to_proto(self, session: "SparkConnectClient", debug: bool = False) -> proto.Plan:
"""
Generates connect proto plan based on this LogicalPlan.
Parameters
----------
session : :class:`SparkConnectClient`, optional.
a session that connects remote spark cluster.
debug: bool
if enabled, the proto plan will be printed.
"""
plan = proto.Plan()
plan.root.CopyFrom(self.plan(session))
if debug:
print(plan)
return plan
def _parameters_to_print(self, parameters: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Extracts the parameters that are able to be printed. It looks up the signature
in the constructor of this :class:`LogicalPlan`, and retrieves the variables
from this instance by the same name (or the name with prefix `_`) defined
in the constructor.
Parameters
----------
parameters : map
Parameter mapping from ``inspect.signature(...).parameters``
Returns
-------
dict
A dictionary consisting of a string name and variable found in this
:class:`LogicalPlan`.
Notes
-----
:class:`LogicalPlan` itself is filtered out and considered as a non-printable
parameter.
Examples
--------
The example below returns a dictionary from `self._start`, `self._end`,
`self._num_partitions`.
>>> rg = Range(0, 10, 1)
>>> rg._parameters_to_print(signature(rg.__class__.__init__).parameters)
{'start': 0, 'end': 10, 'step': 1, 'num_partitions': None}
If the child is defined, it is not considered as a printable instance
>>> project = Project(rg, "value")
>>> project._parameters_to_print(signature(project.__class__.__init__).parameters)
{'columns': ['value']}
"""
params = {}
for name, tpe in parameters.items():
# LogicalPlan is not to print, e.g., LogicalPlan
is_logical_plan = isclass(tpe.annotation) and isinstance(tpe.annotation, LogicalPlan)
# Look up the string argument defined as a forward reference e.g., "LogicalPlan"
is_forwardref_logical_plan = getattr(tpe.annotation, "__forward_arg__", "").endswith(
"LogicalPlan"
)
# Wrapped LogicalPlan, e.g., Optional[LogicalPlan]
is_nested_logical_plan = any(
isclass(a) and issubclass(a, LogicalPlan)
for a in getattr(tpe.annotation, "__args__", ())
)
# Wrapped forward reference of LogicalPlan, e.g., Optional["LogicalPlan"].
is_nested_forwardref_logical_plan = any(
getattr(a, "__forward_arg__", "").endswith("LogicalPlan")
for a in getattr(tpe.annotation, "__args__", ())
)
if (
not is_logical_plan
and not is_forwardref_logical_plan
and not is_nested_logical_plan
and not is_nested_forwardref_logical_plan
):
# Searches self.name or self._name
try:
params[name] = getattr(self, name)
except AttributeError:
try:
params[name] = getattr(self, "_" + name)
except AttributeError:
pass # Simpy ignore
return params
def print(self, indent: int = 0) -> str:
"""
Print the simple string representation of the current :class:`LogicalPlan`.
Parameters
----------
indent : int
The number of leading spaces for the output string.
Returns
-------
str
Simple string representation of this :class:`LogicalPlan`.
"""
params = self._parameters_to_print(signature(self.__class__.__init__).parameters)
pretty_params = [f"{name}='{param}'" for name, param in params.items()]
if len(pretty_params) == 0:
pretty_str = ""
else:
pretty_str = " " + ", ".join(pretty_params)
return f"{' ' * indent}<{self.__class__.__name__}{pretty_str}>\n{self._child_print(indent)}"
def _repr_html_(self) -> str:
"""Returns a :class:`LogicalPlan` with HTML code. This is generally called in third-party
systems such as Jupyter.
Returns
-------
str
HTML representation of this :class:`LogicalPlan`.
"""
params = self._parameters_to_print(signature(self.__class__.__init__).parameters)
pretty_params = [
f"\n {name}: " f"{param} <br/>" for name, param in params.items()
]
if len(pretty_params) == 0:
pretty_str = ""
else:
pretty_str = "".join(pretty_params)
return f"""
<ul>
<li>
<b>{self.__class__.__name__}</b><br/>{pretty_str}
{self._child_repr()}
</li>
</ul>
"""
def _child_print(self, indent: int) -> str:
return self._child.print(indent + LogicalPlan.INDENT) if self._child else ""
def _child_repr(self) -> str:
return self._child._repr_html_() if self._child is not None else ""
class DataSource(LogicalPlan):
"""A datasource with a format and optional a schema from which Spark reads data"""
def __init__(
self,
format: Optional[str] = None,
schema: Optional[str] = None,
options: Optional[Mapping[str, str]] = None,
paths: Optional[List[str]] = None,
predicates: Optional[List[str]] = None,
is_streaming: Optional[bool] = None,
) -> None:
super().__init__(None)
assert format is None or isinstance(format, str)
assert schema is None or isinstance(schema, str)
if options is not None:
for k, v in options.items():
assert isinstance(k, str)
assert isinstance(v, str)
if paths is not None:
assert isinstance(paths, list)
assert all(isinstance(path, str) for path in paths)
if predicates is not None:
assert isinstance(predicates, list)
assert all(isinstance(predicate, str) for predicate in predicates)
self._format = format
self._schema = schema
self._options = options
self._paths = paths
self._predicates = predicates
self._is_streaming = is_streaming
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
if self._format is not None:
plan.read.data_source.format = self._format
if self._schema is not None:
plan.read.data_source.schema = self._schema
if self._options is not None and len(self._options) > 0:
for k, v in self._options.items():
plan.read.data_source.options[k] = v
if self._paths is not None and len(self._paths) > 0:
plan.read.data_source.paths.extend(self._paths)
if self._predicates is not None and len(self._predicates) > 0:
plan.read.data_source.predicates.extend(self._predicates)
if self._is_streaming is not None:
plan.read.is_streaming = self._is_streaming
return plan
class Read(LogicalPlan):
def __init__(
self,
table_name: str,
options: Optional[Dict[str, str]] = None,
is_streaming: Optional[bool] = None,
) -> None:
super().__init__(None)
self.table_name = table_name
self.options = options or {}
self._is_streaming = is_streaming
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
plan.read.named_table.unparsed_identifier = self.table_name
if self._is_streaming is not None:
plan.read.is_streaming = self._is_streaming
for k, v in self.options.items():
plan.read.named_table.options[k] = v
return plan
def print(self, indent: int = 0) -> str:
return f"{' ' * indent}<Read table_name={self.table_name}>\n"
class LocalRelation(LogicalPlan):
"""Creates a LocalRelation plan object based on a PyArrow Table."""
def __init__(
self,
table: Optional["pa.Table"],
schema: Optional[str] = None,
) -> None:
super().__init__(None)
if table is None:
assert schema is not None
else:
assert isinstance(table, pa.Table)
assert schema is None or isinstance(schema, str)
self._table = table
self._schema = schema
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
if self._table is not None:
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, self._table.schema) as writer:
for b in self._table.to_batches():
writer.write_batch(b)
plan.local_relation.data = sink.getvalue().to_pybytes()
if self._schema is not None:
plan.local_relation.schema = self._schema
return plan
def serialize(self, session: "SparkConnectClient") -> bytes:
p = self.plan(session)
return bytes(p.local_relation.SerializeToString())
def print(self, indent: int = 0) -> str:
return f"{' ' * indent}<LocalRelation>\n"
def _repr_html_(self) -> str:
return """
<ul>
<li><b>LocalRelation</b></li>
</ul>
"""
class CachedLocalRelation(LogicalPlan):
"""Creates a CachedLocalRelation plan object based on a hash of a LocalRelation."""
def __init__(self, hash: str) -> None:
super().__init__(None)
self._hash = hash
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
clr = plan.cached_local_relation
clr.hash = self._hash
return plan
def print(self, indent: int = 0) -> str:
return f"{' ' * indent}<CachedLocalRelation>\n"
def _repr_html_(self) -> str:
return """
<ul>
<li><b>CachedLocalRelation</b></li>
</ul>
"""
class ShowString(LogicalPlan):
def __init__(
self, child: Optional["LogicalPlan"], num_rows: int, truncate: int, vertical: bool
) -> None:
super().__init__(child)
self.num_rows = num_rows
self.truncate = truncate
self.vertical = vertical
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.show_string.input.CopyFrom(self._child.plan(session))
plan.show_string.num_rows = self.num_rows
plan.show_string.truncate = self.truncate
plan.show_string.vertical = self.vertical
return plan
class HtmlString(LogicalPlan):
def __init__(self, child: Optional["LogicalPlan"], num_rows: int, truncate: int) -> None:
super().__init__(child)
self.num_rows = num_rows
self.truncate = truncate
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.html_string.input.CopyFrom(self._child.plan(session))
plan.html_string.num_rows = self.num_rows
plan.html_string.truncate = self.truncate
return plan
class Project(LogicalPlan):
"""Logical plan object for a projection.
All input arguments are directly serialized into the corresponding protocol buffer
objects. This class only provides very limited error handling and input validation.
To be compatible with PySpark, we validate that the input arguments are all
expressions to be able to serialize them to the server.
"""
def __init__(self, child: Optional["LogicalPlan"], *columns: "ColumnOrName") -> None:
super().__init__(child)
self._columns = list(columns)
self._verify_expressions()
def _verify_expressions(self) -> None:
"""Ensures that all input arguments are instances of Expression or String."""
for c in self._columns:
if not isinstance(c, (Column, str)):
raise PySparkTypeError(
error_class="NOT_LIST_OF_COLUMN_OR_STR",
message_parameters={"arg_name": "columns"},
)
def plan(self, session: "SparkConnectClient") -> proto.Relation:
from pyspark.sql.connect.functions import col
assert self._child is not None
plan = self._create_proto_relation()
plan.project.input.CopyFrom(self._child.plan(session))
proj_exprs = []
for c in self._columns:
if isinstance(c, Column):
proj_exprs.append(c.to_plan(session))
else:
proj_exprs.append(col(c).to_plan(session))
plan.project.expressions.extend(proj_exprs)
return plan
class WithColumns(LogicalPlan):
"""Logical plan object for a withColumns operation."""
def __init__(
self,
child: Optional["LogicalPlan"],
columnNames: Sequence[str],
columns: Sequence[Column],
metadata: Optional[Sequence[str]] = None,
) -> None:
super().__init__(child)
assert isinstance(columnNames, list)
assert len(columnNames) > 0
assert all(isinstance(c, str) for c in columnNames)
assert isinstance(columns, list)
assert len(columns) == len(columnNames)
assert all(isinstance(c, Column) for c in columns)
if metadata is not None:
assert isinstance(metadata, list)
assert len(metadata) == len(columnNames)
for m in metadata:
assert isinstance(m, str)
# validate json string
assert m == "" or json.loads(m) is not None
self._columnNames = columnNames
self._columns = columns
self._metadata = metadata
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.with_columns.input.CopyFrom(self._child.plan(session))
for i in range(0, len(self._columnNames)):
alias = proto.Expression.Alias()
alias.expr.CopyFrom(self._columns[i].to_plan(session))
alias.name.append(self._columnNames[i])
if self._metadata is not None:
alias.metadata = self._metadata[i]
plan.with_columns.aliases.append(alias)
return plan
class WithWatermark(LogicalPlan):
"""Logical plan object for a WithWatermark operation."""
def __init__(self, child: Optional["LogicalPlan"], event_time: str, delay_threshold: str):
super().__init__(child)
self._event_time = event_time
self._delay_threshold = delay_threshold
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.with_watermark.input.CopyFrom(self._child.plan(session))
plan.with_watermark.event_time = self._event_time
plan.with_watermark.delay_threshold = self._delay_threshold
return plan
class CachedRemoteRelation(LogicalPlan):
"""Logical plan object for a DataFrame reference which represents a DataFrame that's been
cached on the server with a given id."""
def __init__(self, relationId: str):
super().__init__(None)
self._relationId = relationId
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
plan.cached_remote_relation.relation_id = self._relationId
return plan
class Hint(LogicalPlan):
"""Logical plan object for a Hint operation."""
def __init__(self, child: Optional["LogicalPlan"], name: str, parameters: List[Any]) -> None:
super().__init__(child)
assert isinstance(name, str)
self._name = name
for param in parameters:
assert isinstance(param, (list, str, float, int, Column))
if isinstance(param, list):
assert all(isinstance(p, (str, float, int)) for p in param)
self._parameters = parameters
def plan(self, session: "SparkConnectClient") -> proto.Relation:
from pyspark.sql.connect.functions import array, lit
assert self._child is not None
plan = self._create_proto_relation()
plan.hint.input.CopyFrom(self._child.plan(session))
plan.hint.name = self._name
for param in self._parameters:
if isinstance(param, list):
plan.hint.parameters.append(array(*[lit(p) for p in param]).to_plan(session))
else:
plan.hint.parameters.append(lit(param).to_plan(session))
return plan
class Filter(LogicalPlan):
def __init__(self, child: Optional["LogicalPlan"], filter: Column) -> None:
super().__init__(child)
self.filter = filter
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.filter.input.CopyFrom(self._child.plan(session))
plan.filter.condition.CopyFrom(self.filter.to_plan(session))
return plan
class Limit(LogicalPlan):
def __init__(self, child: Optional["LogicalPlan"], limit: int) -> None:
super().__init__(child)
self.limit = limit
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.limit.input.CopyFrom(self._child.plan(session))
plan.limit.limit = self.limit
return plan
class Tail(LogicalPlan):
def __init__(self, child: Optional["LogicalPlan"], limit: int) -> None:
super().__init__(child)
self.limit = limit
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.tail.input.CopyFrom(self._child.plan(session))
plan.tail.limit = self.limit
return plan
class Offset(LogicalPlan):
def __init__(self, child: Optional["LogicalPlan"], offset: int = 0) -> None:
super().__init__(child)
self.offset = offset
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.offset.input.CopyFrom(self._child.plan(session))
plan.offset.offset = self.offset
return plan
class Deduplicate(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
all_columns_as_keys: bool = False,
column_names: Optional[List[str]] = None,
within_watermark: bool = False,
) -> None:
super().__init__(child)
self.all_columns_as_keys = all_columns_as_keys
self.column_names = column_names
self.within_watermark = within_watermark
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.deduplicate.input.CopyFrom(self._child.plan(session))
plan.deduplicate.all_columns_as_keys = self.all_columns_as_keys
plan.deduplicate.within_watermark = self.within_watermark
if self.column_names is not None:
plan.deduplicate.column_names.extend(self.column_names)
return plan
class Sort(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
columns: List[Column],
is_global: bool,
) -> None:
super().__init__(child)
assert all(isinstance(c, Column) for c in columns)
assert isinstance(is_global, bool)
self.columns = columns
self.is_global = is_global
def _convert_col(
self, col: Column, session: "SparkConnectClient"
) -> proto.Expression.SortOrder:
if isinstance(col._expr, SortOrder):
return col._expr.to_plan(session).sort_order
else:
return SortOrder(col._expr).to_plan(session).sort_order
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.sort.input.CopyFrom(self._child.plan(session))
plan.sort.order.extend([self._convert_col(c, session) for c in self.columns])
plan.sort.is_global = self.is_global
return plan
class Drop(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
columns: List[Union[Column, str]],
) -> None:
super().__init__(child)
if len(columns) > 0:
assert all(isinstance(c, (Column, str)) for c in columns)
self._columns = columns
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.drop.input.CopyFrom(self._child.plan(session))
for c in self._columns:
if isinstance(c, Column):
plan.drop.columns.append(c.to_plan(session))
else:
plan.drop.column_names.append(c)
return plan
class Sample(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
lower_bound: float,
upper_bound: float,
with_replacement: bool,
seed: Optional[int],
deterministic_order: bool = False,
) -> None:
super().__init__(child)
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.with_replacement = with_replacement
self.seed = seed
self.deterministic_order = deterministic_order
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
plan.sample.input.CopyFrom(self._child.plan(session))
plan.sample.lower_bound = self.lower_bound
plan.sample.upper_bound = self.upper_bound
plan.sample.with_replacement = self.with_replacement
if self.seed is not None:
plan.sample.seed = self.seed
plan.sample.deterministic_order = self.deterministic_order
return plan
class Aggregate(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
group_type: str,
grouping_cols: Sequence[Column],
aggregate_cols: Sequence[Column],
pivot_col: Optional[Column],
pivot_values: Optional[Sequence[Any]],
) -> None:
super().__init__(child)
assert isinstance(group_type, str) and group_type in ["groupby", "rollup", "cube", "pivot"]
self._group_type = group_type
assert isinstance(grouping_cols, list) and all(isinstance(c, Column) for c in grouping_cols)
self._grouping_cols = grouping_cols
assert isinstance(aggregate_cols, list) and all(
isinstance(c, Column) for c in aggregate_cols
)
self._aggregate_cols = aggregate_cols
if group_type == "pivot":
assert pivot_col is not None and isinstance(pivot_col, Column)
assert pivot_values is None or isinstance(pivot_values, list)
else:
assert pivot_col is None
assert pivot_values is None
self._pivot_col = pivot_col
self._pivot_values = pivot_values
def plan(self, session: "SparkConnectClient") -> proto.Relation:
from pyspark.sql.connect.functions import lit
assert self._child is not None
plan = self._create_proto_relation()
plan.aggregate.input.CopyFrom(self._child.plan(session))
plan.aggregate.grouping_expressions.extend(
[c.to_plan(session) for c in self._grouping_cols]
)
plan.aggregate.aggregate_expressions.extend(
[c.to_plan(session) for c in self._aggregate_cols]
)
if self._group_type == "groupby":
plan.aggregate.group_type = proto.Aggregate.GroupType.GROUP_TYPE_GROUPBY
elif self._group_type == "rollup":
plan.aggregate.group_type = proto.Aggregate.GroupType.GROUP_TYPE_ROLLUP
elif self._group_type == "cube":
plan.aggregate.group_type = proto.Aggregate.GroupType.GROUP_TYPE_CUBE
elif self._group_type == "pivot":
plan.aggregate.group_type = proto.Aggregate.GroupType.GROUP_TYPE_PIVOT
assert self._pivot_col is not None
plan.aggregate.pivot.col.CopyFrom(self._pivot_col.to_plan(session))
if self._pivot_values is not None and len(self._pivot_values) > 0:
plan.aggregate.pivot.values.extend(
[lit(v).to_plan(session).literal for v in self._pivot_values]
)
return plan
class Join(LogicalPlan):
def __init__(
self,
left: Optional["LogicalPlan"],
right: "LogicalPlan",
on: Optional[Union[str, List[str], Column, List[Column]]],
how: Optional[str],
) -> None:
super().__init__(left)
self.left = cast(LogicalPlan, left)
self.right = right
self.on = on
if how is None:
join_type = proto.Join.JoinType.JOIN_TYPE_INNER
elif how == "inner":
join_type = proto.Join.JoinType.JOIN_TYPE_INNER
elif how in ["outer", "full", "fullouter"]:
join_type = proto.Join.JoinType.JOIN_TYPE_FULL_OUTER
elif how in ["leftouter", "left"]:
join_type = proto.Join.JoinType.JOIN_TYPE_LEFT_OUTER
elif how in ["rightouter", "right"]:
join_type = proto.Join.JoinType.JOIN_TYPE_RIGHT_OUTER
elif how in ["leftsemi", "semi"]:
join_type = proto.Join.JoinType.JOIN_TYPE_LEFT_SEMI
elif how in ["leftanti", "anti"]:
join_type = proto.Join.JoinType.JOIN_TYPE_LEFT_ANTI
elif how == "cross":
join_type = proto.Join.JoinType.JOIN_TYPE_CROSS
else:
raise IllegalArgumentException(
error_class="UNSUPPORTED_JOIN_TYPE",
message_parameters={"join_type": how},
)
self.how = join_type
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
plan.join.left.CopyFrom(self.left.plan(session))
plan.join.right.CopyFrom(self.right.plan(session))
if self.on is not None:
if not isinstance(self.on, list):
if isinstance(self.on, str):
plan.join.using_columns.append(self.on)
else:
plan.join.join_condition.CopyFrom(self.to_attr_or_expression(self.on, session))
elif len(self.on) > 0:
if isinstance(self.on[0], str):
plan.join.using_columns.extend(cast(str, self.on))
else:
merge_column = functools.reduce(lambda c1, c2: c1 & c2, self.on)
plan.join.join_condition.CopyFrom(cast(Column, merge_column).to_plan(session))
plan.join.join_type = self.how
return plan
def print(self, indent: int = 0) -> str:
i = " " * indent
o = " " * (indent + LogicalPlan.INDENT)
n = indent + LogicalPlan.INDENT * 2
return (
f"{i}<Join on={self.on} how={self.how}>\n{o}"
f"left=\n{self.left.print(n)}\n{o}right=\n{self.right.print(n)}"
)
def _repr_html_(self) -> str:
return f"""
<ul>
<li>
<b>Join</b><br />
Left: {self.left._repr_html_()}
Right: {self.right._repr_html_()}
</li>
</uL>
"""
class SetOperation(LogicalPlan):
def __init__(
self,
child: Optional["LogicalPlan"],
other: Optional["LogicalPlan"],
set_op: str,
is_all: bool = True,
by_name: bool = False,
allow_missing_columns: bool = False,
) -> None:
super().__init__(child)
self.other = other
self.by_name = by_name
self.is_all = is_all
self.set_op = set_op
self.allow_missing_columns = allow_missing_columns
def plan(self, session: "SparkConnectClient") -> proto.Relation:
assert self._child is not None
plan = self._create_proto_relation()
if self._child is not None:
plan.set_op.left_input.CopyFrom(self._child.plan(session))
if self.other is not None:
plan.set_op.right_input.CopyFrom(self.other.plan(session))
if self.set_op == "union":
plan.set_op.set_op_type = proto.SetOperation.SET_OP_TYPE_UNION
elif self.set_op == "intersect":
plan.set_op.set_op_type = proto.SetOperation.SET_OP_TYPE_INTERSECT
elif self.set_op == "except":
plan.set_op.set_op_type = proto.SetOperation.SET_OP_TYPE_EXCEPT
else:
raise PySparkNotImplementedError(
error_class="UNSUPPORTED_OPERATION",
message_parameters={"feature": self.set_op},
)
plan.set_op.is_all = self.is_all
plan.set_op.by_name = self.by_name
plan.set_op.allow_missing_columns = self.allow_missing_columns
return plan
def print(self, indent: int = 0) -> str:
assert self._child is not None
assert self.other is not None
i = " " * indent
o = " " * (indent + LogicalPlan.INDENT)
n = indent + LogicalPlan.INDENT * 2
return (
f"{i}SetOperation\n{o}child1=\n{self._child.print(n)}"
f"\n{o}child2=\n{self.other.print(n)}"
)
def _repr_html_(self) -> str:
assert self._child is not None
assert self.other is not None
return f"""
<ul>
<li>
<b>SetOperation</b><br />
Left: {self._child._repr_html_()}
Right: {self.other._repr_html_()}
</li>
</uL>
"""
class Repartition(LogicalPlan):
"""Repartition Relation into a different number of partitions."""
def __init__(self, child: Optional["LogicalPlan"], num_partitions: int, shuffle: bool) -> None:
super().__init__(child)
self._num_partitions = num_partitions
self._shuffle = shuffle
def plan(self, session: "SparkConnectClient") -> proto.Relation:
plan = self._create_proto_relation()
if self._child is not None:
plan.repartition.input.CopyFrom(self._child.plan(session))
plan.repartition.shuffle = self._shuffle
plan.repartition.num_partitions = self._num_partitions
return plan
class RepartitionByExpression(LogicalPlan):
"""Repartition Relation into a different number of partitions using Expression"""
def __init__(
self,
child: Optional["LogicalPlan"],
num_partitions: Optional[int],
columns: List["ColumnOrName"],
) -> None:
super().__init__(child)
self.num_partitions = num_partitions
self.columns = columns