cloud-fan commented on a change in pull request #32940:
URL: https://github.com/apache/spark/pull/32940#discussion_r656867600



##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/IntervalUtils.scala
##########
@@ -105,25 +105,46 @@ object IntervalUtils {
   private val yearMonthRegex = (s"^$yearMonthPatternString$$").r
   private val yearMonthLiteralRegex =
     
(s"(?i)^INTERVAL\\s+([+|-])?'$yearMonthPatternString'\\s+YEAR\\s+TO\\s+MONTH$$").r
+  private val yearMonthIndividualLiteralRegex =
+    (s"(?i)^INTERVAL\\s+([+|-])?'([+|-])?(\\d+)'\\s+(YEAR|MONTH)$$").r
 
   def castStringToYMInterval(
       input: UTF8String,
-      // TODO(SPARK-35768): Take into account year-month interval fields in 
cast
       startField: Byte,
       endField: Byte): Int = {
+
+    def truncatedMonth(month: String) : String = {
+      if (endField == YM.YEAR) "0" else month
+    }
+
+    def getSigh(firstSign: String, secondSign: String): Int = {
+      (firstSign, secondSign) match {
+        case ("-", "-") => 1
+        case ("-", _) => -1
+        case (_, "-") => -1
+        case (_, _) => 1
+      }
+    }
+
     input.trimAll().toString match {
-      case yearMonthRegex("-", year, month) => toYMInterval(year, month, -1)
-      case yearMonthRegex(_, year, month) => toYMInterval(year, month, 1)
+      case yearMonthRegex("-", year, month) => toYMInterval(year, 
truncatedMonth(month), -1)
+      case yearMonthRegex(_, year, month) => toYMInterval(year, 
truncatedMonth(month), 1)
       case yearMonthLiteralRegex(firstSign, secondSign, year, month) =>
-        (firstSign, secondSign) match {
-          case ("-", "-") => toYMInterval(year, month, 1)
-          case ("-", _) => toYMInterval(year, month, -1)
-          case (_, "-") => toYMInterval(year, month, -1)
-          case (_, _) => toYMInterval(year, month, 1)
+        toYMInterval(year, truncatedMonth(month), getSigh(firstSign, 
secondSign))
+      case yearMonthIndividualLiteralRegex(firstSign, secondSign, value, 
suffix) =>
+        suffix match {
+          case "YEAR" => toYMInterval(value, "0", getSigh(firstSign, 
secondSign))
+          case _ =>
+            val months = value.toLong
+            val year = (months / 12).toString
+            val month = (months % 12).toString

Review comment:
       This looks a bit inefficient. Under the hood, we just need the number of 
months for YM interval, and it's a waste to calculate year and month and then 
go back to num months.




-- 
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:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to