jonmio commented on code in PR #51057:
URL: https://github.com/apache/spark/pull/51057#discussion_r2136627997


##########
sql/connect/server/src/main/scala/org/apache/spark/sql/connect/pipelines/PipelinesHandler.scala:
##########
@@ -0,0 +1,288 @@
+/*
+ * 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.pipelines
+
+import scala.jdk.CollectionConverters._
+
+import com.google.protobuf.{Timestamp => ProtoTimestamp}
+import io.grpc.stub.StreamObserver
+
+import org.apache.spark.connect.proto
+import org.apache.spark.connect.proto.{ExecutePlanResponse, 
PipelineCommandResult, Relation}
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connect.common.DataTypeProtoConverter
+import org.apache.spark.sql.connect.service.SessionHolder
+import org.apache.spark.sql.pipelines.Language.Python
+import org.apache.spark.sql.pipelines.QueryOriginType
+import org.apache.spark.sql.pipelines.common.RunState.{CANCELED, FAILED}
+import org.apache.spark.sql.pipelines.graph.{FlowAnalysis, 
GraphIdentifierManager, IdentifierHelper, PipelineUpdateContextImpl, 
QueryContext, QueryOrigin, SqlGraphRegistrationContext, Table, TemporaryView, 
UnresolvedFlow}
+import org.apache.spark.sql.pipelines.logging.{PipelineEvent, RunProgress}
+import org.apache.spark.sql.types.StructType
+
+/** Handler for SparkConnect PipelineCommands */
+private[connect] object PipelinesHandler extends Logging {
+
+  /**
+   * Handles the pipeline command
+   * @param sessionHolder
+   *   Context about the session state
+   * @param cmd
+   *   Command to be handled
+   * @param responseObserver
+   *   The response observer where the response will be sent
+   * @param sparkSession
+   *   The spark session
+   * @param transformRelationFunc
+   *   Function used to convert a relation to a LogicalPlan. This is used when 
determining the
+   *   LogicalPlan that a flow returns.
+   * @return
+   *   The response after handling the command
+   */
+  def handlePipelinesCommand(
+      sessionHolder: SessionHolder,
+      cmd: proto.PipelineCommand,
+      responseObserver: StreamObserver[ExecutePlanResponse],
+      sparkSession: SparkSession,
+      transformRelationFunc: Relation => LogicalPlan): PipelineCommandResult = 
{
+    // Currently most commands do not include any information in the response. 
We just send back
+    // an empty response to the client to indicate that the command was 
handled successfully
+    val defaultResponse = PipelineCommandResult.getDefaultInstance
+    cmd.getCommandTypeCase match {
+      case proto.PipelineCommand.CommandTypeCase.CREATE_DATAFLOW_GRAPH =>
+        val createdGraphId = createDataflowGraph(cmd.getCreateDataflowGraph)
+        PipelineCommandResult
+          .newBuilder()
+          .setCreateDataflowGraphResult(
+            PipelineCommandResult.CreateDataflowGraphResult.newBuilder
+              .setDataflowGraphId(createdGraphId)
+              .build())
+          .build()
+      case proto.PipelineCommand.CommandTypeCase.DROP_DATAFLOW_GRAPH =>
+        logInfo(s"Drop pipeline cmd received: $cmd")
+        
DataflowGraphRegistry.dropDataflowGraph(cmd.getDropDataflowGraph.getDataflowGraphId)
+        defaultResponse
+      case proto.PipelineCommand.CommandTypeCase.DEFINE_DATASET =>
+        logInfo(s"Define pipelines dataset cmd received: $cmd")
+        defineDataset(cmd.getDefineDataset, sparkSession)
+        defaultResponse
+      case proto.PipelineCommand.CommandTypeCase.DEFINE_FLOW =>
+        logInfo(s"Define pipelines flow cmd received: $cmd")
+        defineFlow(cmd.getDefineFlow, transformRelationFunc, sparkSession)
+        defaultResponse
+      case proto.PipelineCommand.CommandTypeCase.START_RUN =>
+        logInfo(s"Start pipeline cmd received: $cmd")
+        startRun(cmd.getStartRun, responseObserver, sessionHolder)
+        defaultResponse
+      case proto.PipelineCommand.CommandTypeCase.DEFINE_SQL_GRAPH_ELEMENTS =>
+        logInfo(s"Register sql datasets cmd received: $cmd")
+        defineSqlGraphElements(cmd.getDefineSqlGraphElements, sparkSession)
+        defaultResponse
+      case other => throw new UnsupportedOperationException(s"$other not 
supported")
+    }
+  }
+
+  private def createDataflowGraph(cmd: 
proto.PipelineCommand.CreateDataflowGraph): String = {
+    val defaultCatalog = Option
+      .when(cmd.hasDefaultCatalog)(cmd.getDefaultCatalog)
+      .getOrElse {
+        logInfo(
+          s"No default catalog was supplied. Falling back to the session 
catalog `spark_catalog`).")
+        "spark_catalog"
+      }
+
+    val defaultDatabase = Option
+      .when(cmd.hasDefaultDatabase)(cmd.getDefaultDatabase)
+      .getOrElse {
+        logInfo(s"No default catalog was supplied. Falling back to 
`default`).")
+        "default"
+      }
+
+    val defaultSqlConf = cmd.getSqlConfMap.asScala.toMap
+
+    DataflowGraphRegistry.createDataflowGraph(
+      defaultCatalog = defaultCatalog,
+      defaultDatabase = defaultDatabase,
+      defaultSqlConf = defaultSqlConf)
+  }
+
+  private def defineSqlGraphElements(
+      cmd: proto.PipelineCommand.DefineSqlGraphElements,
+      session: SparkSession): Unit = {
+    val dataflowGraphId = cmd.getDataflowGraphId
+
+    val graphElementRegistry = 
DataflowGraphRegistry.getDataflowGraphOrThrow(dataflowGraphId)
+    val sqlGraphElementRegistrationContext = new 
SqlGraphRegistrationContext(graphElementRegistry)
+    sqlGraphElementRegistrationContext.processSqlFile(cmd.getSqlText, 
cmd.getSqlFilePath, session)
+  }
+
+  private def defineDataset(
+      dataset: proto.PipelineCommand.DefineDataset,
+      sparkSession: SparkSession): Unit = {
+    val dataflowGraphId = dataset.getDataflowGraphId
+    val graphElementRegistry = 
DataflowGraphRegistry.getDataflowGraphOrThrow(dataflowGraphId)
+
+    dataset.getDatasetType match {
+      case proto.DatasetType.MATERIALIZED_VIEW | proto.DatasetType.TABLE =>
+        val tableIdentifier =
+          GraphIdentifierManager.parseTableIdentifier(dataset.getDatasetName, 
sparkSession)
+        graphElementRegistry.registerTable(
+          Table(
+            identifier = tableIdentifier,
+            comment = Option(dataset.getComment),
+            specifiedSchema = Option.when(dataset.hasSchema)(
+              DataTypeProtoConverter
+                .toCatalystType(dataset.getSchema)
+                .asInstanceOf[StructType]),
+            partitionCols = Option(dataset.getPartitionColsList.asScala.toSeq)
+              .filter(_.nonEmpty),
+            properties = dataset.getTablePropertiesMap.asScala.toMap,
+            baseOrigin = QueryOrigin(
+              objectType = Option(QueryOriginType.Table.toString),
+              objectName = Option(tableIdentifier.unquotedString),
+              language = Option(Python())),

Review Comment:
   Currently all the SQL code goes through `defineSqlGraphElement` so anything 
going through this path is Python. However, it's not being used right now so 
I'm happy to remove it



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to