-
Notifications
You must be signed in to change notification settings - Fork 28k
/
SparkConnectPlanner.scala
2165 lines (1941 loc) · 83.9 KB
/
SparkConnectPlanner.scala
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.
*/
package org.apache.spark.sql.connect.planner
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.google.common.collect.{Lists, Maps}
import com.google.protobuf.{Any => ProtoAny, ByteString}
import io.grpc.stub.StreamObserver
import org.apache.spark.{Partition, SparkEnv, TaskContext}
import org.apache.spark.api.python.{PythonEvalType, SimplePythonFunction}
import org.apache.spark.connect.proto
import org.apache.spark.connect.proto.{ExecutePlanResponse, SqlCommand}
import org.apache.spark.connect.proto.ExecutePlanResponse.SqlCommandResult
import org.apache.spark.connect.proto.Parse.ParseFormat
import org.apache.spark.ml.{functions => MLFunctions}
import org.apache.spark.sql.{Column, Dataset, Encoders, SparkSession}
import org.apache.spark.sql.catalyst.{expressions, AliasIdentifier, FunctionIdentifier}
import org.apache.spark.sql.catalyst.analysis.{GlobalTempView, LocalTempView, MultiAlias, ParameterizedQuery, UnresolvedAlias, UnresolvedAttribute, UnresolvedExtractValue, UnresolvedFunction, UnresolvedRegex, UnresolvedRelation, UnresolvedStar}
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.parser.{CatalystSqlParser, ParseException, ParserUtils}
import org.apache.spark.sql.catalyst.plans.{Cross, FullOuter, Inner, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter, UsingJoin}
import org.apache.spark.sql.catalyst.plans.logical
import org.apache.spark.sql.catalyst.plans.logical.{CollectMetrics, CommandResult, Deduplicate, Except, Intersect, LocalRelation, LogicalPlan, Project, Sample, Sort, SubqueryAlias, Union, Unpivot, UnresolvedHint}
import org.apache.spark.sql.catalyst.util.{CaseInsensitiveMap, CharVarcharUtils}
import org.apache.spark.sql.connect.artifact.SparkConnectArtifactManager
import org.apache.spark.sql.connect.common.{DataTypeProtoConverter, InvalidPlanInput, LiteralValueProtoConverter, UdfPacket}
import org.apache.spark.sql.connect.config.Connect.CONNECT_GRPC_ARROW_MAX_BATCH_SIZE
import org.apache.spark.sql.connect.plugin.SparkConnectPluginRegistry
import org.apache.spark.sql.connect.service.SparkConnectStreamHandler
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.execution.QueryExecution
import org.apache.spark.sql.execution.arrow.ArrowConverters
import org.apache.spark.sql.execution.command.CreateViewCommand
import org.apache.spark.sql.execution.datasources.LogicalRelation
import org.apache.spark.sql.execution.datasources.jdbc.{JDBCOptions, JDBCPartition, JDBCRelation}
import org.apache.spark.sql.execution.python.UserDefinedPythonFunction
import org.apache.spark.sql.internal.CatalogImpl
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils
final case class InvalidCommandInput(
private val message: String = "",
private val cause: Throwable = null)
extends Exception(message, cause)
class SparkConnectPlanner(val session: SparkSession) {
private lazy val pythonExec =
sys.env.getOrElse("PYSPARK_PYTHON", sys.env.getOrElse("PYSPARK_DRIVER_PYTHON", "python3"))
// The root of the query plan is a relation and we apply the transformations to it.
def transformRelation(rel: proto.Relation): LogicalPlan = {
val plan = rel.getRelTypeCase match {
// DataFrame API
case proto.Relation.RelTypeCase.SHOW_STRING => transformShowString(rel.getShowString)
case proto.Relation.RelTypeCase.READ => transformReadRel(rel.getRead)
case proto.Relation.RelTypeCase.PROJECT => transformProject(rel.getProject)
case proto.Relation.RelTypeCase.FILTER => transformFilter(rel.getFilter)
case proto.Relation.RelTypeCase.LIMIT => transformLimit(rel.getLimit)
case proto.Relation.RelTypeCase.OFFSET => transformOffset(rel.getOffset)
case proto.Relation.RelTypeCase.TAIL => transformTail(rel.getTail)
case proto.Relation.RelTypeCase.JOIN => transformJoin(rel.getJoin)
case proto.Relation.RelTypeCase.DEDUPLICATE => transformDeduplicate(rel.getDeduplicate)
case proto.Relation.RelTypeCase.SET_OP => transformSetOperation(rel.getSetOp)
case proto.Relation.RelTypeCase.SORT => transformSort(rel.getSort)
case proto.Relation.RelTypeCase.DROP => transformDrop(rel.getDrop)
case proto.Relation.RelTypeCase.AGGREGATE => transformAggregate(rel.getAggregate)
case proto.Relation.RelTypeCase.SQL => transformSql(rel.getSql)
case proto.Relation.RelTypeCase.LOCAL_RELATION =>
transformLocalRelation(rel.getLocalRelation)
case proto.Relation.RelTypeCase.SAMPLE => transformSample(rel.getSample)
case proto.Relation.RelTypeCase.RANGE => transformRange(rel.getRange)
case proto.Relation.RelTypeCase.SUBQUERY_ALIAS =>
transformSubqueryAlias(rel.getSubqueryAlias)
case proto.Relation.RelTypeCase.REPARTITION => transformRepartition(rel.getRepartition)
case proto.Relation.RelTypeCase.FILL_NA => transformNAFill(rel.getFillNa)
case proto.Relation.RelTypeCase.DROP_NA => transformNADrop(rel.getDropNa)
case proto.Relation.RelTypeCase.REPLACE => transformReplace(rel.getReplace)
case proto.Relation.RelTypeCase.SUMMARY => transformStatSummary(rel.getSummary)
case proto.Relation.RelTypeCase.DESCRIBE => transformStatDescribe(rel.getDescribe)
case proto.Relation.RelTypeCase.COV => transformStatCov(rel.getCov)
case proto.Relation.RelTypeCase.CORR => transformStatCorr(rel.getCorr)
case proto.Relation.RelTypeCase.APPROX_QUANTILE =>
transformStatApproxQuantile(rel.getApproxQuantile)
case proto.Relation.RelTypeCase.CROSSTAB =>
transformStatCrosstab(rel.getCrosstab)
case proto.Relation.RelTypeCase.FREQ_ITEMS => transformStatFreqItems(rel.getFreqItems)
case proto.Relation.RelTypeCase.SAMPLE_BY =>
transformStatSampleBy(rel.getSampleBy)
case proto.Relation.RelTypeCase.TO_SCHEMA => transformToSchema(rel.getToSchema)
case proto.Relation.RelTypeCase.TO_DF =>
transformToDF(rel.getToDf)
case proto.Relation.RelTypeCase.WITH_COLUMNS_RENAMED =>
transformWithColumnsRenamed(rel.getWithColumnsRenamed)
case proto.Relation.RelTypeCase.WITH_COLUMNS => transformWithColumns(rel.getWithColumns)
case proto.Relation.RelTypeCase.HINT => transformHint(rel.getHint)
case proto.Relation.RelTypeCase.UNPIVOT => transformUnpivot(rel.getUnpivot)
case proto.Relation.RelTypeCase.REPARTITION_BY_EXPRESSION =>
transformRepartitionByExpression(rel.getRepartitionByExpression)
case proto.Relation.RelTypeCase.MAP_PARTITIONS =>
transformMapPartitions(rel.getMapPartitions)
case proto.Relation.RelTypeCase.GROUP_MAP =>
transformGroupMap(rel.getGroupMap)
case proto.Relation.RelTypeCase.COLLECT_METRICS =>
transformCollectMetrics(rel.getCollectMetrics)
case proto.Relation.RelTypeCase.PARSE => transformParse(rel.getParse)
case proto.Relation.RelTypeCase.RELTYPE_NOT_SET =>
throw new IndexOutOfBoundsException("Expected Relation to be set, but is empty.")
// Catalog API (internal-only)
case proto.Relation.RelTypeCase.CATALOG => transformCatalog(rel.getCatalog)
// Handle plugins for Spark Connect Relation types.
case proto.Relation.RelTypeCase.EXTENSION =>
transformRelationPlugin(rel.getExtension)
case _ => throw InvalidPlanInput(s"${rel.getUnknown} not supported.")
}
if (rel.hasCommon && rel.getCommon.hasPlanId) {
plan.setTagValue(LogicalPlan.PLAN_ID_TAG, rel.getCommon.getPlanId)
}
plan
}
private def transformRelationPlugin(extension: ProtoAny): LogicalPlan = {
SparkConnectPluginRegistry.relationRegistry
// Lazily traverse the collection.
.view
// Apply the transformation.
.map(p => p.transform(extension, this))
// Find the first non-empty transformation or throw.
.find(_.nonEmpty)
.flatten
.getOrElse(throw InvalidPlanInput("No handler found for extension"))
}
private def transformCatalog(catalog: proto.Catalog): LogicalPlan = {
catalog.getCatTypeCase match {
case proto.Catalog.CatTypeCase.CURRENT_DATABASE =>
transformCurrentDatabase(catalog.getCurrentDatabase)
case proto.Catalog.CatTypeCase.SET_CURRENT_DATABASE =>
transformSetCurrentDatabase(catalog.getSetCurrentDatabase)
case proto.Catalog.CatTypeCase.LIST_DATABASES =>
transformListDatabases(catalog.getListDatabases)
case proto.Catalog.CatTypeCase.LIST_TABLES => transformListTables(catalog.getListTables)
case proto.Catalog.CatTypeCase.LIST_FUNCTIONS =>
transformListFunctions(catalog.getListFunctions)
case proto.Catalog.CatTypeCase.LIST_COLUMNS => transformListColumns(catalog.getListColumns)
case proto.Catalog.CatTypeCase.GET_DATABASE => transformGetDatabase(catalog.getGetDatabase)
case proto.Catalog.CatTypeCase.GET_TABLE => transformGetTable(catalog.getGetTable)
case proto.Catalog.CatTypeCase.GET_FUNCTION => transformGetFunction(catalog.getGetFunction)
case proto.Catalog.CatTypeCase.DATABASE_EXISTS =>
transformDatabaseExists(catalog.getDatabaseExists)
case proto.Catalog.CatTypeCase.TABLE_EXISTS => transformTableExists(catalog.getTableExists)
case proto.Catalog.CatTypeCase.FUNCTION_EXISTS =>
transformFunctionExists(catalog.getFunctionExists)
case proto.Catalog.CatTypeCase.CREATE_EXTERNAL_TABLE =>
transformCreateExternalTable(catalog.getCreateExternalTable)
case proto.Catalog.CatTypeCase.CREATE_TABLE => transformCreateTable(catalog.getCreateTable)
case proto.Catalog.CatTypeCase.DROP_TEMP_VIEW =>
transformDropTempView(catalog.getDropTempView)
case proto.Catalog.CatTypeCase.DROP_GLOBAL_TEMP_VIEW =>
transformDropGlobalTempView(catalog.getDropGlobalTempView)
case proto.Catalog.CatTypeCase.RECOVER_PARTITIONS =>
transformRecoverPartitions(catalog.getRecoverPartitions)
case proto.Catalog.CatTypeCase.IS_CACHED => transformIsCached(catalog.getIsCached)
case proto.Catalog.CatTypeCase.CACHE_TABLE => transformCacheTable(catalog.getCacheTable)
case proto.Catalog.CatTypeCase.UNCACHE_TABLE =>
transformUncacheTable(catalog.getUncacheTable)
case proto.Catalog.CatTypeCase.CLEAR_CACHE => transformClearCache(catalog.getClearCache)
case proto.Catalog.CatTypeCase.REFRESH_TABLE =>
transformRefreshTable(catalog.getRefreshTable)
case proto.Catalog.CatTypeCase.REFRESH_BY_PATH =>
transformRefreshByPath(catalog.getRefreshByPath)
case proto.Catalog.CatTypeCase.CURRENT_CATALOG =>
transformCurrentCatalog(catalog.getCurrentCatalog)
case proto.Catalog.CatTypeCase.SET_CURRENT_CATALOG =>
transformSetCurrentCatalog(catalog.getSetCurrentCatalog)
case proto.Catalog.CatTypeCase.LIST_CATALOGS =>
transformListCatalogs(catalog.getListCatalogs)
case other => throw InvalidPlanInput(s"$other not supported.")
}
}
private def transformShowString(rel: proto.ShowString): LogicalPlan = {
val showString = Dataset
.ofRows(session, transformRelation(rel.getInput))
.showString(rel.getNumRows, rel.getTruncate, rel.getVertical)
LocalRelation.fromProduct(
output = AttributeReference("show_string", StringType, false)() :: Nil,
data = Tuple1.apply(showString) :: Nil)
}
private def transformSql(sql: proto.SQL): LogicalPlan = {
val args = sql.getArgsMap.asScala.toMap
val parser = session.sessionState.sqlParser
val parsedPlan = parser.parsePlan(sql.getQuery)
if (args.nonEmpty) {
ParameterizedQuery(parsedPlan, args.mapValues(parser.parseExpression).toMap)
} else {
parsedPlan
}
}
private def transformSubqueryAlias(alias: proto.SubqueryAlias): LogicalPlan = {
val aliasIdentifier =
if (alias.getQualifierCount > 0) {
AliasIdentifier.apply(alias.getAlias, alias.getQualifierList.asScala.toSeq)
} else {
AliasIdentifier.apply(alias.getAlias)
}
SubqueryAlias(aliasIdentifier, transformRelation(alias.getInput))
}
/**
* All fields of [[proto.Sample]] are optional. However, given those are proto primitive types,
* we cannot differentiate if the field is not or set when the field's value equals to the type
* default value. In the future if this ever become a problem, one solution could be that to
* wrap such fields into proto messages.
*/
private def transformSample(rel: proto.Sample): LogicalPlan = {
val plan = if (rel.getDeterministicOrder) {
val input = Dataset.ofRows(session, transformRelation(rel.getInput))
// It is possible that the underlying dataframe doesn't guarantee the ordering of rows in its
// constituent partitions each time a split is materialized which could result in
// overlapping splits. To prevent this, we explicitly sort each input partition to make the
// ordering deterministic. Note that MapTypes cannot be sorted and are explicitly pruned out
// from the sort order.
val sortOrder = input.logicalPlan.output
.filter(attr => RowOrdering.isOrderable(attr.dataType))
.map(SortOrder(_, Ascending))
if (sortOrder.nonEmpty) {
Sort(sortOrder, global = false, input.logicalPlan)
} else {
input.cache()
input.logicalPlan
}
} else {
transformRelation(rel.getInput)
}
Sample(
rel.getLowerBound,
rel.getUpperBound,
rel.getWithReplacement,
if (rel.hasSeed) rel.getSeed else Utils.random.nextLong,
plan)
}
private def transformRepartition(rel: proto.Repartition): LogicalPlan = {
logical.Repartition(rel.getNumPartitions, rel.getShuffle, transformRelation(rel.getInput))
}
private def transformRange(rel: proto.Range): LogicalPlan = {
val start = rel.getStart
val end = rel.getEnd
val step = rel.getStep
val numPartitions = if (rel.hasNumPartitions) {
rel.getNumPartitions
} else {
session.leafNodeDefaultParallelism
}
logical.Range(start, end, step, numPartitions)
}
private def transformNAFill(rel: proto.NAFill): LogicalPlan = {
if (rel.getValuesCount == 0) {
throw InvalidPlanInput(s"values must contains at least 1 item!")
}
if (rel.getValuesCount > 1 && rel.getValuesCount != rel.getColsCount) {
throw InvalidPlanInput(
s"When values contains more than 1 items, " +
s"values and cols should have the same length!")
}
val dataset = Dataset.ofRows(session, transformRelation(rel.getInput))
val cols = rel.getColsList.asScala.toArray
val values = rel.getValuesList.asScala.toArray
if (values.length == 1) {
val value = values.head
value.getLiteralTypeCase match {
case proto.Expression.Literal.LiteralTypeCase.BOOLEAN =>
if (cols.nonEmpty) {
dataset.na.fill(value = value.getBoolean, cols = cols).logicalPlan
} else {
dataset.na.fill(value = value.getBoolean).logicalPlan
}
case proto.Expression.Literal.LiteralTypeCase.LONG =>
if (cols.nonEmpty) {
dataset.na.fill(value = value.getLong, cols = cols).logicalPlan
} else {
dataset.na.fill(value = value.getLong).logicalPlan
}
case proto.Expression.Literal.LiteralTypeCase.DOUBLE =>
if (cols.nonEmpty) {
dataset.na.fill(value = value.getDouble, cols = cols).logicalPlan
} else {
dataset.na.fill(value = value.getDouble).logicalPlan
}
case proto.Expression.Literal.LiteralTypeCase.STRING =>
if (cols.nonEmpty) {
dataset.na.fill(value = value.getString, cols = cols).logicalPlan
} else {
dataset.na.fill(value = value.getString).logicalPlan
}
case other => throw InvalidPlanInput(s"Unsupported value type: $other")
}
} else {
val valueMap = mutable.Map.empty[String, Any]
cols.zip(values).foreach { case (col, value) =>
valueMap.update(col, LiteralValueProtoConverter.toCatalystValue(value))
}
dataset.na.fill(valueMap = valueMap.toMap).logicalPlan
}
}
private def transformNADrop(rel: proto.NADrop): LogicalPlan = {
val dataset = Dataset.ofRows(session, transformRelation(rel.getInput))
val cols = rel.getColsList.asScala.toArray
(cols.nonEmpty, rel.hasMinNonNulls) match {
case (true, true) =>
dataset.na.drop(minNonNulls = rel.getMinNonNulls, cols = cols).logicalPlan
case (true, false) =>
dataset.na.drop(cols = cols).logicalPlan
case (false, true) =>
dataset.na.drop(minNonNulls = rel.getMinNonNulls).logicalPlan
case (false, false) =>
dataset.na.drop().logicalPlan
}
}
private def transformReplace(rel: proto.NAReplace): LogicalPlan = {
val replacement = mutable.Map.empty[Any, Any]
rel.getReplacementsList.asScala.foreach { replace =>
replacement.update(
LiteralValueProtoConverter.toCatalystValue(replace.getOldValue),
LiteralValueProtoConverter.toCatalystValue(replace.getNewValue))
}
if (rel.getColsCount == 0) {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.na
.replace("*", replacement.toMap)
.logicalPlan
} else {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.na
.replace(rel.getColsList.asScala.toSeq, replacement.toMap)
.logicalPlan
}
}
private def transformStatSummary(rel: proto.StatSummary): LogicalPlan = {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.summary(rel.getStatisticsList.asScala.toSeq: _*)
.logicalPlan
}
private def transformStatDescribe(rel: proto.StatDescribe): LogicalPlan = {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.describe(rel.getColsList.asScala.toSeq: _*)
.logicalPlan
}
private def transformStatCov(rel: proto.StatCov): LogicalPlan = {
val cov = Dataset
.ofRows(session, transformRelation(rel.getInput))
.stat
.cov(rel.getCol1, rel.getCol2)
LocalRelation.fromProduct(
output = AttributeReference("cov", DoubleType, false)() :: Nil,
data = Tuple1.apply(cov) :: Nil)
}
private def transformStatCorr(rel: proto.StatCorr): LogicalPlan = {
val df = Dataset.ofRows(session, transformRelation(rel.getInput))
val corr = if (rel.hasMethod) {
df.stat.corr(rel.getCol1, rel.getCol2, rel.getMethod)
} else {
df.stat.corr(rel.getCol1, rel.getCol2)
}
LocalRelation.fromProduct(
output = AttributeReference("corr", DoubleType, false)() :: Nil,
data = Tuple1.apply(corr) :: Nil)
}
private def transformStatApproxQuantile(rel: proto.StatApproxQuantile): LogicalPlan = {
val cols = rel.getColsList.asScala.toArray
val probabilities = rel.getProbabilitiesList.asScala.map(_.doubleValue()).toArray
val approxQuantile = Dataset
.ofRows(session, transformRelation(rel.getInput))
.stat
.approxQuantile(cols, probabilities, rel.getRelativeError)
LocalRelation.fromProduct(
output =
AttributeReference("approx_quantile", ArrayType(ArrayType(DoubleType)), false)() :: Nil,
data = Tuple1.apply(approxQuantile) :: Nil)
}
private def transformStatCrosstab(rel: proto.StatCrosstab): LogicalPlan = {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.stat
.crosstab(rel.getCol1, rel.getCol2)
.logicalPlan
}
private def transformStatFreqItems(rel: proto.StatFreqItems): LogicalPlan = {
val cols = rel.getColsList.asScala.toSeq
val df = Dataset.ofRows(session, transformRelation(rel.getInput))
if (rel.hasSupport) {
df.stat.freqItems(cols, rel.getSupport).logicalPlan
} else {
df.stat.freqItems(cols).logicalPlan
}
}
private def transformStatSampleBy(rel: proto.StatSampleBy): LogicalPlan = {
val fractions = rel.getFractionsList.asScala.toSeq.map { protoFraction =>
val stratum = transformLiteral(protoFraction.getStratum) match {
case Literal(s, StringType) if s != null => s.toString
case literal => literal.value
}
(stratum, protoFraction.getFraction)
}
Dataset
.ofRows(session, transformRelation(rel.getInput))
.stat
.sampleBy(
col = Column(transformExpression(rel.getCol)),
fractions = fractions.toMap,
seed = if (rel.hasSeed) rel.getSeed else Utils.random.nextLong)
.logicalPlan
}
private def transformToSchema(rel: proto.ToSchema): LogicalPlan = {
val schema = transformDataType(rel.getSchema)
assert(schema.isInstanceOf[StructType])
Dataset
.ofRows(session, transformRelation(rel.getInput))
.to(schema.asInstanceOf[StructType])
.logicalPlan
}
private def transformToDF(rel: proto.ToDF): LogicalPlan = {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.toDF(rel.getColumnNamesList.asScala.toSeq: _*)
.logicalPlan
}
private def transformMapPartitions(rel: proto.MapPartitions): LogicalPlan = {
val commonUdf = rel.getFunc
val pythonUdf = transformPythonUDF(commonUdf)
pythonUdf.evalType match {
case PythonEvalType.SQL_MAP_PANDAS_ITER_UDF =>
logical.MapInPandas(
pythonUdf,
pythonUdf.dataType.asInstanceOf[StructType].toAttributes,
transformRelation(rel.getInput))
case PythonEvalType.SQL_MAP_ARROW_ITER_UDF =>
logical.PythonMapInArrow(
pythonUdf,
pythonUdf.dataType.asInstanceOf[StructType].toAttributes,
transformRelation(rel.getInput))
case _ =>
throw InvalidPlanInput(s"Function with EvalType: ${pythonUdf.evalType} is not supported")
}
}
private def transformGroupMap(rel: proto.GroupMap): LogicalPlan = {
val pythonUdf = transformPythonUDF(rel.getFunc)
val cols =
rel.getGroupingExpressionsList.asScala.toSeq.map(expr => Column(transformExpression(expr)))
Dataset
.ofRows(session, transformRelation(rel.getInput))
.groupBy(cols: _*)
.flatMapGroupsInPandas(pythonUdf)
.logicalPlan
}
private def transformWithColumnsRenamed(rel: proto.WithColumnsRenamed): LogicalPlan = {
Dataset
.ofRows(session, transformRelation(rel.getInput))
.withColumnsRenamed(rel.getRenameColumnsMapMap)
.logicalPlan
}
private def transformWithColumns(rel: proto.WithColumns): LogicalPlan = {
val (colNames, cols, metadata) =
rel.getAliasesList.asScala.toSeq.map { alias =>
if (alias.getNameCount != 1) {
throw InvalidPlanInput(s"""WithColumns require column name only contains one name part,
|but got ${alias.getNameList.toString}""".stripMargin)
}
val metadata = if (alias.hasMetadata && alias.getMetadata.nonEmpty) {
Metadata.fromJson(alias.getMetadata)
} else {
Metadata.empty
}
(alias.getName(0), Column(transformExpression(alias.getExpr)), metadata)
}.unzip3
Dataset
.ofRows(session, transformRelation(rel.getInput))
.withColumns(colNames, cols, metadata)
.logicalPlan
}
private def transformHint(rel: proto.Hint): LogicalPlan = {
def extractValue(expr: Expression): Any = {
expr match {
case Literal(s, StringType) if s != null =>
UnresolvedAttribute.quotedString(s.toString)
case literal: Literal => literal.value
case UnresolvedFunction(Seq("array"), arguments, _, _, _) =>
arguments.map(extractValue).toArray
case other =>
throw InvalidPlanInput(
s"Expression should be a Literal or CreateMap or CreateArray, " +
s"but got ${other.getClass} $other")
}
}
val params = rel.getParametersList.asScala.toSeq.map(transformExpression).map(extractValue)
UnresolvedHint(rel.getName, params, transformRelation(rel.getInput))
}
private def transformUnpivot(rel: proto.Unpivot): LogicalPlan = {
val ids = rel.getIdsList.asScala.toArray.map { expr =>
Column(transformExpression(expr))
}
if (!rel.hasValues) {
Unpivot(
Some(ids.map(_.named)),
None,
None,
rel.getVariableColumnName,
Seq(rel.getValueColumnName),
transformRelation(rel.getInput))
} else {
val values = rel.getValues.getValuesList.asScala.toArray.map { expr =>
Column(transformExpression(expr))
}
Unpivot(
Some(ids.map(_.named)),
Some(values.map(v => Seq(v.named))),
None,
rel.getVariableColumnName,
Seq(rel.getValueColumnName),
transformRelation(rel.getInput))
}
}
private def transformRepartitionByExpression(
rel: proto.RepartitionByExpression): LogicalPlan = {
val numPartitionsOpt = if (rel.hasNumPartitions) {
Some(rel.getNumPartitions)
} else {
None
}
val partitionExpressions = rel.getPartitionExprsList.asScala.map(transformExpression).toSeq
logical.RepartitionByExpression(
partitionExpressions,
transformRelation(rel.getInput),
numPartitionsOpt)
}
private def transformCollectMetrics(rel: proto.CollectMetrics): LogicalPlan = {
val metrics = rel.getMetricsList.asScala.toSeq.map { expr =>
Column(transformExpression(expr))
}
CollectMetrics(rel.getName, metrics.map(_.named), transformRelation(rel.getInput))
}
private def transformDeduplicate(rel: proto.Deduplicate): LogicalPlan = {
if (!rel.hasInput) {
throw InvalidPlanInput("Deduplicate needs a plan input")
}
if (rel.getAllColumnsAsKeys && rel.getColumnNamesCount > 0) {
throw InvalidPlanInput("Cannot deduplicate on both all columns and a subset of columns")
}
if (!rel.getAllColumnsAsKeys && rel.getColumnNamesCount == 0) {
throw InvalidPlanInput(
"Deduplicate requires to either deduplicate on all columns or a subset of columns")
}
val queryExecution = new QueryExecution(session, transformRelation(rel.getInput))
val resolver = session.sessionState.analyzer.resolver
val allColumns = queryExecution.analyzed.output
if (rel.getAllColumnsAsKeys) {
Deduplicate(allColumns, queryExecution.analyzed)
} else {
val toGroupColumnNames = rel.getColumnNamesList.asScala.toSeq
val groupCols = toGroupColumnNames.flatMap { (colName: String) =>
// It is possibly there are more than one columns with the same name,
// so we call filter instead of find.
val cols = allColumns.filter(col => resolver(col.name, colName))
if (cols.isEmpty) {
throw InvalidPlanInput(s"Invalid deduplicate column ${colName}")
}
cols
}
Deduplicate(groupCols, queryExecution.analyzed)
}
}
private def transformDataType(t: proto.DataType): DataType = {
t.getKindCase match {
case proto.DataType.KindCase.UNPARSED =>
parseDatatypeString(t.getUnparsed.getDataTypeString)
case _ => DataTypeProtoConverter.toCatalystType(t)
}
}
private[connect] def parseDatatypeString(sqlText: String): DataType = {
val parser = session.sessionState.sqlParser
try {
parser.parseTableSchema(sqlText)
} catch {
case e: ParseException =>
try {
parser.parseDataType(sqlText)
} catch {
case _: ParseException =>
try {
parser.parseDataType(s"struct<${sqlText.trim}>")
} catch {
case _: ParseException =>
throw e
}
}
}
}
private def transformLocalRelation(rel: proto.LocalRelation): LogicalPlan = {
var schema: StructType = null
if (rel.hasSchema) {
val schemaType = DataType.parseTypeWithFallback(
rel.getSchema,
parseDatatypeString,
fallbackParser = DataType.fromJson)
schema = schemaType match {
case s: StructType => s
case d => StructType(Seq(StructField("value", d)))
}
}
if (rel.hasData) {
val (rows, structType) = ArrowConverters.fromBatchWithSchemaIterator(
Iterator(rel.getData.toByteArray),
TaskContext.get())
if (structType == null) {
throw InvalidPlanInput(s"Input data for LocalRelation does not produce a schema.")
}
val attributes = structType.toAttributes
val proj = UnsafeProjection.create(attributes, attributes)
val data = rows.map(proj)
if (schema == null) {
logical.LocalRelation(attributes, data.map(_.copy()).toSeq)
} else {
def udtToSqlType(dt: DataType): DataType = dt match {
case udt: UserDefinedType[_] => udt.sqlType
case StructType(fields) =>
val newFields = fields.map { case StructField(name, dataType, nullable, metadata) =>
StructField(name, udtToSqlType(dataType), nullable, metadata)
}
StructType(newFields)
case ArrayType(elementType, containsNull) =>
ArrayType(udtToSqlType(elementType), containsNull)
case MapType(keyType, valueType, valueContainsNull) =>
MapType(udtToSqlType(keyType), udtToSqlType(valueType), valueContainsNull)
case _ => dt
}
val sqlTypeOnlySchema = udtToSqlType(schema).asInstanceOf[StructType]
val project = Dataset
.ofRows(session, logicalPlan = logical.LocalRelation(attributes))
.toDF(sqlTypeOnlySchema.names: _*)
.to(sqlTypeOnlySchema)
.logicalPlan
.asInstanceOf[Project]
val proj = UnsafeProjection.create(project.projectList, project.child.output)
logical.LocalRelation(schema.toAttributes, data.map(proj).map(_.copy()).toSeq)
}
} else {
if (schema == null) {
throw InvalidPlanInput(
s"Schema for LocalRelation is required when the input data is not provided.")
}
LocalRelation(schema.toAttributes, data = Seq.empty)
}
}
private def transformReadRel(rel: proto.Read): LogicalPlan = {
rel.getReadTypeCase match {
case proto.Read.ReadTypeCase.NAMED_TABLE =>
val multipartIdentifier =
CatalystSqlParser.parseMultipartIdentifier(rel.getNamedTable.getUnparsedIdentifier)
UnresolvedRelation(multipartIdentifier)
case proto.Read.ReadTypeCase.DATA_SOURCE =>
val localMap = CaseInsensitiveMap[String](rel.getDataSource.getOptionsMap.asScala.toMap)
val reader = session.read
if (rel.getDataSource.hasFormat) {
reader.format(rel.getDataSource.getFormat)
}
localMap.foreach { case (key, value) => reader.option(key, value) }
if (rel.getDataSource.getFormat == "jdbc" && rel.getDataSource.getPredicatesCount > 0) {
if (!localMap.contains(JDBCOptions.JDBC_URL) ||
!localMap.contains(JDBCOptions.JDBC_TABLE_NAME)) {
throw InvalidPlanInput(s"Invalid jdbc params, please specify jdbc url and table.")
}
val url = rel.getDataSource.getOptionsMap.get(JDBCOptions.JDBC_URL)
val table = rel.getDataSource.getOptionsMap.get(JDBCOptions.JDBC_TABLE_NAME)
val options = new JDBCOptions(url, table, localMap)
val predicates = rel.getDataSource.getPredicatesList.asScala.toArray
val parts: Array[Partition] = predicates.zipWithIndex.map { case (part, i) =>
JDBCPartition(part, i): Partition
}
val relation = JDBCRelation(parts, options)(session)
LogicalRelation(relation)
} else if (rel.getDataSource.getPredicatesCount == 0) {
if (rel.getDataSource.hasSchema && rel.getDataSource.getSchema.nonEmpty) {
DataType.parseTypeWithFallback(
rel.getDataSource.getSchema,
StructType.fromDDL,
fallbackParser = DataType.fromJson) match {
case s: StructType => reader.schema(s)
case other => throw InvalidPlanInput(s"Invalid schema $other")
}
}
if (rel.getDataSource.getPathsCount == 0) {
reader.load().queryExecution.analyzed
} else if (rel.getDataSource.getPathsCount == 1) {
reader.load(rel.getDataSource.getPaths(0)).queryExecution.analyzed
} else {
reader.load(rel.getDataSource.getPathsList.asScala.toSeq: _*).queryExecution.analyzed
}
} else {
throw InvalidPlanInput(
s"Predicates are not supported for ${rel.getDataSource.getFormat} data sources.")
}
case _ => throw InvalidPlanInput(s"Does not support ${rel.getReadTypeCase.name()}")
}
}
private def transformParse(rel: proto.Parse): LogicalPlan = {
def dataFrameReader = {
val localMap = CaseInsensitiveMap[String](rel.getOptionsMap.asScala.toMap)
val reader = session.read
if (rel.hasSchema) {
DataTypeProtoConverter.toCatalystType(rel.getSchema) match {
case s: StructType => reader.schema(s)
case other => throw InvalidPlanInput(s"Invalid schema dataType $other")
}
}
localMap.foreach { case (key, value) => reader.option(key, value) }
reader
}
def ds: Dataset[String] = Dataset(session, transformRelation(rel.getInput))(Encoders.STRING)
rel.getFormat match {
case ParseFormat.PARSE_FORMAT_CSV =>
dataFrameReader.csv(ds).queryExecution.analyzed
case ParseFormat.PARSE_FORMAT_JSON =>
dataFrameReader.json(ds).queryExecution.analyzed
case _ => throw InvalidPlanInput("Does not support " + rel.getFormat.name())
}
}
private def transformFilter(rel: proto.Filter): LogicalPlan = {
assert(rel.hasInput)
val baseRel = transformRelation(rel.getInput)
logical.Filter(condition = transformExpression(rel.getCondition), child = baseRel)
}
private def transformProject(rel: proto.Project): LogicalPlan = {
val baseRel = if (rel.hasInput) {
transformRelation(rel.getInput)
} else {
logical.OneRowRelation()
}
val projection = rel.getExpressionsList.asScala.toSeq
.map(transformExpression)
.map(toNamedExpression)
logical.Project(projectList = projection, child = baseRel)
}
/**
* Transforms an input protobuf expression into the Catalyst expression. This is usually not
* called directly. Typically the planner will traverse the expressions automatically, only
* plugins are expected to manually perform expression transformations.
*
* @param exp
* the input expression
* @return
* Catalyst expression
*/
def transformExpression(exp: proto.Expression): Expression = {
exp.getExprTypeCase match {
case proto.Expression.ExprTypeCase.LITERAL => transformLiteral(exp.getLiteral)
case proto.Expression.ExprTypeCase.UNRESOLVED_ATTRIBUTE =>
transformUnresolvedAttribute(exp.getUnresolvedAttribute)
case proto.Expression.ExprTypeCase.UNRESOLVED_FUNCTION =>
transformUnregisteredFunction(exp.getUnresolvedFunction)
.getOrElse(transformUnresolvedFunction(exp.getUnresolvedFunction))
case proto.Expression.ExprTypeCase.ALIAS => transformAlias(exp.getAlias)
case proto.Expression.ExprTypeCase.EXPRESSION_STRING =>
transformExpressionString(exp.getExpressionString)
case proto.Expression.ExprTypeCase.UNRESOLVED_STAR =>
transformUnresolvedStar(exp.getUnresolvedStar)
case proto.Expression.ExprTypeCase.CAST => transformCast(exp.getCast)
case proto.Expression.ExprTypeCase.UNRESOLVED_REGEX =>
transformUnresolvedRegex(exp.getUnresolvedRegex)
case proto.Expression.ExprTypeCase.UNRESOLVED_EXTRACT_VALUE =>
transformUnresolvedExtractValue(exp.getUnresolvedExtractValue)
case proto.Expression.ExprTypeCase.UPDATE_FIELDS =>
transformUpdateFields(exp.getUpdateFields)
case proto.Expression.ExprTypeCase.SORT_ORDER => transformSortOrder(exp.getSortOrder)
case proto.Expression.ExprTypeCase.LAMBDA_FUNCTION =>
transformLambdaFunction(exp.getLambdaFunction)
case proto.Expression.ExprTypeCase.UNRESOLVED_NAMED_LAMBDA_VARIABLE =>
transformUnresolvedNamedLambdaVariable(exp.getUnresolvedNamedLambdaVariable)
case proto.Expression.ExprTypeCase.WINDOW =>
transformWindowExpression(exp.getWindow)
case proto.Expression.ExprTypeCase.EXTENSION =>
transformExpressionPlugin(exp.getExtension)
case proto.Expression.ExprTypeCase.COMMON_INLINE_USER_DEFINED_FUNCTION =>
transformCommonInlineUserDefinedFunction(exp.getCommonInlineUserDefinedFunction)
case proto.Expression.ExprTypeCase.DISTRIBUTED_SEQUENCE_ID =>
transformDistributedSequenceID(exp.getDistributedSequenceId)
case _ =>
throw InvalidPlanInput(
s"Expression with ID: ${exp.getExprTypeCase.getNumber} is not supported")
}
}
private def toNamedExpression(expr: Expression): NamedExpression = expr match {
case named: NamedExpression => named
case expr => UnresolvedAlias(expr)
}
private def transformUnresolvedAttribute(
attr: proto.Expression.UnresolvedAttribute): UnresolvedAttribute = {
val expr = UnresolvedAttribute.quotedString(attr.getUnparsedIdentifier)
if (attr.hasPlanId) {
expr.setTagValue(LogicalPlan.PLAN_ID_TAG, attr.getPlanId)
}
expr
}
private def transformExpressionPlugin(extension: ProtoAny): Expression = {
SparkConnectPluginRegistry.expressionRegistry
// Lazily traverse the collection.
.view
// Apply the transformation.
.map(p => p.transform(extension, this))
// Find the first non-empty transformation or throw.
.find(_.nonEmpty)
.flatten
.getOrElse(throw InvalidPlanInput("No handler found for extension"))
}
/**
* Transforms the protocol buffers literals into the appropriate Catalyst literal expression.
* @return
* Expression
*/
private def transformLiteral(lit: proto.Expression.Literal): Literal = {
LiteralExpressionProtoConverter.toCatalystExpression(lit)
}
private def transformLimit(limit: proto.Limit): LogicalPlan = {
logical.Limit(
limitExpr = expressions.Literal(limit.getLimit, IntegerType),
transformRelation(limit.getInput))
}
private def transformTail(tail: proto.Tail): LogicalPlan = {
logical.Tail(
limitExpr = expressions.Literal(tail.getLimit, IntegerType),
transformRelation(tail.getInput))
}
private def transformOffset(offset: proto.Offset): LogicalPlan = {
logical.Offset(
offsetExpr = expressions.Literal(offset.getOffset, IntegerType),
transformRelation(offset.getInput))
}
/**
* Translates a scalar function from proto to the Catalyst expression.
*
* TODO(SPARK-40546) We need to homogenize the function names for binary operators.
*
* @param fun
* Proto representation of the function call.
* @return
*/
private def transformUnresolvedFunction(
fun: proto.Expression.UnresolvedFunction): Expression = {
if (fun.getIsUserDefinedFunction) {
UnresolvedFunction(
session.sessionState.sqlParser.parseFunctionIdentifier(fun.getFunctionName),
fun.getArgumentsList.asScala.map(transformExpression).toSeq,
isDistinct = fun.getIsDistinct)
} else {
UnresolvedFunction(
FunctionIdentifier(fun.getFunctionName),
fun.getArgumentsList.asScala.map(transformExpression).toSeq,
isDistinct = fun.getIsDistinct)
}
}
/**
* Translates a user-defined function from proto to the Catalyst expression.
*
* @param fun
* Proto representation of the function call.
* @return
* Expression.
*/
private def transformCommonInlineUserDefinedFunction(
fun: proto.CommonInlineUserDefinedFunction): Expression = {
fun.getFunctionCase match {
case proto.CommonInlineUserDefinedFunction.FunctionCase.PYTHON_UDF =>
transformPythonUDF(fun)
case proto.CommonInlineUserDefinedFunction.FunctionCase.SCALAR_SCALA_UDF =>
transformScalarScalaUDF(fun)
case _ =>
throw InvalidPlanInput(
s"Function with ID: ${fun.getFunctionCase.getNumber} is not supported")
}
}
/**
* Translates a Scalar Scala user-defined function from proto to the Catalyst expression.
*
* @param fun
* Proto representation of the Scalar Scalar user-defined function.
* @return
* ScalaUDF.
*/
private def transformScalarScalaUDF(fun: proto.CommonInlineUserDefinedFunction): ScalaUDF = {
val udf = fun.getScalarScalaUdf
val udfPacket =
Utils.deserialize[UdfPacket](
udf.getPayload.toByteArray,
SparkConnectArtifactManager.classLoaderWithArtifacts)
ScalaUDF(
function = udfPacket.function,
dataType = udfPacket.outputEncoder.dataType,
children = fun.getArgumentsList.asScala.map(transformExpression).toSeq,
inputEncoders = udfPacket.inputEncoders.map(e => Option(ExpressionEncoder(e))),
outputEncoder = Option(ExpressionEncoder(udfPacket.outputEncoder)),