Login  Register

[GitHub] [carbondata] Zhangshunyu commented on a change in pull request #4032: [CARBONDATA-4065] Support MERGE INTO SQL Command

Posted by GitBox on Jan 04, 2021; 7:25am
URL: http://apache-carbondata-dev-mailing-list-archive.168.s1.nabble.com/GitHub-carbondata-Pickupolddriver-opened-a-new-pull-request-4032-WIP-Add-MERGE-INTO-SQL-Command-suppa-tp103917p105258.html


Zhangshunyu commented on a change in pull request #4032:
URL: https://github.com/apache/carbondata/pull/4032#discussion_r551151350



##########
File path: integration/spark/src/main/java/org/apache/spark/sql/CarbonAntlrSqlVisitor.java
##########
@@ -0,0 +1,353 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.spark.sql.catalyst.expressions.Expression;
+import org.apache.spark.sql.catalyst.parser.ParseException;
+import org.apache.spark.sql.catalyst.parser.ParserInterface;
+import org.apache.spark.sql.execution.command.mutation.merge.DeleteAction;
+import org.apache.spark.sql.execution.command.mutation.merge.InsertAction;
+import org.apache.spark.sql.execution.command.mutation.merge.MergeAction;
+import org.apache.spark.sql.execution.command.mutation.merge.UpdateAction;
+import org.apache.spark.sql.merge.model.CarbonJoinExpression;
+import org.apache.spark.sql.merge.model.CarbonMergeIntoModel;
+import org.apache.spark.sql.merge.model.ColumnModel;
+import org.apache.spark.sql.merge.model.TableModel;
+import org.apache.spark.sql.parser.CarbonSqlBaseBaseVisitor;
+import org.apache.spark.sql.parser.CarbonSqlBaseParser;
+import org.apache.spark.util.SparkUtil;
+
+public class CarbonAntlrSqlVisitor extends CarbonSqlBaseBaseVisitor {
+
+  private final ParserInterface sparkParser;
+
+  public CarbonAntlrSqlVisitor(ParserInterface sparkParser) {
+    this.sparkParser = sparkParser;
+  }
+
+  @Override
+  public String visitTableAlias(CarbonSqlBaseParser.TableAliasContext ctx) {
+    if (null == ctx.children) {
+      return null;
+    }
+    String res = ctx.getChild(1).getText();
+    System.out.println(res);
+    return res;
+  }
+
+  @Override
+  public MergeAction visitAssignmentList(CarbonSqlBaseParser.AssignmentListContext ctx) {
+    //  UPDATE SET assignmentList
+    Map<Column, Column> map = new HashMap<>();
+    for (int currIdx = 0; currIdx < ctx.getChildCount(); currIdx++) {
+      if (ctx.getChild(currIdx) instanceof CarbonSqlBaseParser.AssignmentContext) {
+        //Assume the actions are all use to pass value
+        String left = ctx.getChild(currIdx).getChild(0).getText();
+        if (left.split("\\.").length > 1) {
+          left = left.split("\\.")[1];
+        }
+        String right = ctx.getChild(currIdx).getChild(2).getText();
+        Column rightColumn = null;
+        try {
+          Expression expression = sparkParser.parseExpression(right);
+          rightColumn = new Column(expression);
+        } catch (Exception ex) {
+          // todo throw EX here

Review comment:
       @QiangCai handled

##########
File path: integration/spark/src/main/java/org/apache/spark/sql/CarbonMergeIntoSQLCommand.scala
##########
@@ -0,0 +1,121 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.command.AtomicRunnableCommand
+import org.apache.spark.sql.execution.command.mutation.merge._
+import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.merge.model.{CarbonMergeIntoModel, TableModel}
+import org.apache.spark.util.SparkUtil._
+import org.apache.spark.util.TableAPIUtil
+
+case class CarbonMergeIntoSQLCommand(mergeInto: CarbonMergeIntoModel)
+  extends AtomicRunnableCommand {
+
+  override def processMetadata(sparkSession: SparkSession): Seq[Row] = {
+    Seq.empty
+  }
+
+  override def processData(sparkSession: SparkSession): Seq[Row] = {
+    val sourceTable: TableModel = mergeInto.getSource
+    val targetTable: TableModel = mergeInto.getTarget
+    val mergeCondition: Expression = mergeInto.getMergeCondition
+    val mergeExpression: Seq[Expression] = convertExpressionList(mergeInto.getMergeExpressions)
+    val mergeActions: Seq[MergeAction] = convertMergeActionList(mergeInto.getMergeActions)
+
+    // validate the table
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (sourceTable.getDatabase == null) {
+        "default"
+      } else {
+        sourceTable.getDatabase
+      },
+      sourceTable.getTable)
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (targetTable.getDatabase == null) {
+        "default"
+      } else {
+        targetTable.getDatabase
+      },

Review comment:
       @QiangCai handled

##########
File path: integration/spark/src/main/java/org/apache/spark/sql/CarbonMergeIntoSQLCommand.scala
##########
@@ -0,0 +1,121 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.command.AtomicRunnableCommand
+import org.apache.spark.sql.execution.command.mutation.merge._
+import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.merge.model.{CarbonMergeIntoModel, TableModel}
+import org.apache.spark.util.SparkUtil._
+import org.apache.spark.util.TableAPIUtil
+
+case class CarbonMergeIntoSQLCommand(mergeInto: CarbonMergeIntoModel)
+  extends AtomicRunnableCommand {
+
+  override def processMetadata(sparkSession: SparkSession): Seq[Row] = {
+    Seq.empty
+  }
+
+  override def processData(sparkSession: SparkSession): Seq[Row] = {
+    val sourceTable: TableModel = mergeInto.getSource
+    val targetTable: TableModel = mergeInto.getTarget
+    val mergeCondition: Expression = mergeInto.getMergeCondition
+    val mergeExpression: Seq[Expression] = convertExpressionList(mergeInto.getMergeExpressions)
+    val mergeActions: Seq[MergeAction] = convertMergeActionList(mergeInto.getMergeActions)
+
+    // validate the table
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (sourceTable.getDatabase == null) {
+        "default"
+      } else {
+        sourceTable.getDatabase
+      },
+      sourceTable.getTable)
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (targetTable.getDatabase == null) {
+        "default"
+      } else {
+        targetTable.getDatabase
+      },
+      targetTable.getTable)
+
+    val srcDf = sparkSession.sql(s"""SELECT * FROM ${ sourceTable.getTable }""")
+    val tgDf = sparkSession.sql(s"""SELECT * FROM ${ targetTable.getTable }""")

Review comment:
       @QiangCai handled

##########
File path: integration/spark/src/main/java/org/apache/spark/sql/CarbonMergeIntoSQLCommand.scala
##########
@@ -0,0 +1,121 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.command.AtomicRunnableCommand
+import org.apache.spark.sql.execution.command.mutation.merge._
+import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.merge.model.{CarbonMergeIntoModel, TableModel}
+import org.apache.spark.util.SparkUtil._
+import org.apache.spark.util.TableAPIUtil
+
+case class CarbonMergeIntoSQLCommand(mergeInto: CarbonMergeIntoModel)
+  extends AtomicRunnableCommand {
+
+  override def processMetadata(sparkSession: SparkSession): Seq[Row] = {
+    Seq.empty
+  }
+
+  override def processData(sparkSession: SparkSession): Seq[Row] = {
+    val sourceTable: TableModel = mergeInto.getSource
+    val targetTable: TableModel = mergeInto.getTarget
+    val mergeCondition: Expression = mergeInto.getMergeCondition
+    val mergeExpression: Seq[Expression] = convertExpressionList(mergeInto.getMergeExpressions)
+    val mergeActions: Seq[MergeAction] = convertMergeActionList(mergeInto.getMergeActions)
+
+    // validate the table
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (sourceTable.getDatabase == null) {
+        "default"
+      } else {
+        sourceTable.getDatabase
+      },
+      sourceTable.getTable)
+    TableAPIUtil.validateTableExists(sparkSession,
+      if (targetTable.getDatabase == null) {
+        "default"
+      } else {
+        targetTable.getDatabase
+      },
+      targetTable.getTable)
+
+    val srcDf = sparkSession.sql(s"""SELECT * FROM ${ sourceTable.getTable }""")
+    val tgDf = sparkSession.sql(s"""SELECT * FROM ${ targetTable.getTable }""")
+
+    var matches = Seq.empty[MergeMatch]

Review comment:
       @QiangCai handled

##########
File path: integration/spark/src/main/scala/org/apache/spark/sql/parser/CarbonExtensionSqlParser.scala
##########
@@ -37,35 +37,42 @@ class CarbonExtensionSqlParser(
 ) extends SparkSqlParser(conf) {
 
   val parser = new CarbonExtensionSpark2SqlParser
+  val antlrParser = new CarbonAntlrParser(this)
 
   override def parsePlan(sqlText: String): LogicalPlan = {
     parser.synchronized {
       CarbonEnv.getInstance(sparkSession)
     }
     CarbonUtils.updateSessionInfoToCurrentThread(sparkSession)
     try {
-      val plan = parser.parse(sqlText)
-      plan
+      parser.parse(sqlText)
     } catch {
       case ce: MalformedCarbonCommandException =>
         throw ce
-      case ex: Throwable =>
+      case _: Throwable =>
         try {
-          val parsedPlan = initialParser.parsePlan(sqlText)
-          CarbonScalaUtil.cleanParserThreadLocals
-          parsedPlan
+          antlrParser.parse(sqlText)
         } catch {
-          case mce: MalformedCarbonCommandException =>
-            throw mce
-          case e: Throwable =>
-            e.printStackTrace(System.err)
-            CarbonScalaUtil.cleanParserThreadLocals
-            CarbonException.analysisException(
-              s"""== Parser1: ${parser.getClass.getName} ==
-                 |${ex.getMessage}
-                 |== Parser2: ${initialParser.getClass.getName} ==
-                 |${e.getMessage}
+          case ce: MalformedCarbonCommandException =>
+            throw ce
+          case ex: Throwable =>
+            try {
+              val parsedPlan = initialParser.parsePlan(sqlText)
+              CarbonScalaUtil.cleanParserThreadLocals
+              parsedPlan
+            } catch {
+              case mce: MalformedCarbonCommandException =>
+                throw mce
+              case e: Throwable =>
+                e.printStackTrace(System.err)
+                CarbonScalaUtil.cleanParserThreadLocals
+                CarbonException.analysisException(
+                  s"""== Parser1: ${ parser.getClass.getName } ==
+                     |${ ex.getMessage }
+                     |== Parser2: ${ initialParser.getClass.getName } ==
+                     |${ e.getMessage }

Review comment:
       @QiangCai handled

##########
File path: integration/spark/src/test/scala/org/apache/carbondata/spark/testsuite/iud/MergeIntoCarbonTableTestCase.scala
##########
@@ -0,0 +1,294 @@
+/*
+ * 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.carbondata.spark.testsuite.iud
+
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.test.util.QueryTest
+import org.scalatest.BeforeAndAfterEach
+
+class MergeIntoCarbonTableTestCase extends QueryTest with BeforeAndAfterEach {

Review comment:
       @QiangCai handled




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
[hidden email]