You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by tw...@apache.org on 2022/02/07 16:20:37 UTC

[flink] branch master updated: [FLINK-24780][table-planner] Port time/date/timestamp casts to new structure.

This is an automated email from the ASF dual-hosted git repository.

twalthr pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git


The following commit(s) were added to refs/heads/master by this push:
     new 1fac1c4  [FLINK-24780][table-planner] Port time/date/timestamp casts to new structure.
1fac1c4 is described below

commit 1fac1c4f2d0fe4c9e6ac46b37326f93e8274c7e7
Author: Marios Trivyzas <ma...@gmail.com>
AuthorDate: Tue Feb 1 16:08:35 2022 +0200

    [FLINK-24780][table-planner] Port time/date/timestamp casts to new structure.
    
    Implement the time/date/timestamp related casts using the `CastRule`s structure
    and remove the relevant code from `ScalarOperatorGens`.
    
    This closes #18582.
---
 .../functions/casting/BinaryToStringCastRule.java  |  15 +-
 .../functions/casting/CastRulePredicate.java       |   7 +-
 .../functions/casting/CastRuleProvider.java        |  17 +-
 .../planner/functions/casting/CastRuleUtils.java   |   4 +
 .../functions/casting/DateToTimestampCastRule.java |  69 +++++++
 .../functions/casting/IdentityCastRule.java        |   8 -
 .../casting/NumericToTimestampCastRule.java        |  68 +++++++
 .../casting/RowDataToStringConverterImpl.java      |   2 +
 .../functions/casting/TimeToTimestampCastRule.java |  65 ++++++
 .../functions/casting/TimestampToDateCastRule.java |  73 +++++++
 .../casting/TimestampToNumericCastRule.java        |  65 ++++++
 .../functions/casting/TimestampToTimeCastRule.java |  74 +++++++
 .../casting/TimestampToTimestampCastRule.java      |  98 +++++++++
 .../planner/codegen/calls/BuiltInMethods.scala     |   5 +
 .../planner/codegen/calls/ScalarOperatorGens.scala | 223 ---------------------
 .../planner/functions/CastFunctionITCase.java      |   7 +-
 .../planner/functions/casting/CastRulesTest.java   | 141 +++++++++++--
 .../planner/expressions/TemporalTypesTest.scala    |  14 +-
 18 files changed, 679 insertions(+), 276 deletions(-)

diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/BinaryToStringCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/BinaryToStringCastRule.java
index 566584c..b4182f0 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/BinaryToStringCastRule.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/BinaryToStringCastRule.java
@@ -99,14 +99,13 @@ class BinaryToStringCastRule extends AbstractNullAwareCodeGeneratorCastRule<byte
             final String hexStringTerm = newName("hexString");
             writer.declStmt(String.class, hexStringTerm)
                     .assignStmt(hexStringTerm, staticCall(EncodingUtils.class, "hex", inputTerm));
-            writer =
-                    CharVarCharTrimPadCastRule.padAndTrimStringIfNeeded(
-                            writer,
-                            targetLogicalType,
-                            context.legacyBehaviour(),
-                            length,
-                            resultStringTerm,
-                            hexStringTerm);
+            CharVarCharTrimPadCastRule.padAndTrimStringIfNeeded(
+                    writer,
+                    targetLogicalType,
+                    context.legacyBehaviour(),
+                    length,
+                    resultStringTerm,
+                    hexStringTerm);
         }
         return writer
                 // Assign the result value
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRulePredicate.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRulePredicate.java
index 3b3c67f..d9952cb 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRulePredicate.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRulePredicate.java
@@ -23,10 +23,9 @@ import org.apache.flink.table.types.logical.LogicalType;
 import org.apache.flink.table.types.logical.LogicalTypeFamily;
 import org.apache.flink.table.types.logical.LogicalTypeRoot;
 
-import javax.annotation.Nullable;
-
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.Optional;
 import java.util.Set;
 import java.util.function.BiPredicate;
 
@@ -105,8 +104,8 @@ public class CastRulePredicate {
         return targetTypeFamilies;
     }
 
-    public @Nullable BiPredicate<LogicalType, LogicalType> getCustomPredicate() {
-        return customPredicate;
+    public Optional<BiPredicate<LogicalType, LogicalType>> getCustomPredicate() {
+        return Optional.ofNullable(customPredicate);
     }
 
     public static Builder builder() {
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleProvider.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleProvider.java
index 961e81f..9986e7f 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleProvider.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleProvider.java
@@ -76,6 +76,14 @@ public class CastRuleProvider {
                 .addRule(StringToTimeCastRule.INSTANCE)
                 .addRule(StringToTimestampCastRule.INSTANCE)
                 .addRule(StringToBinaryCastRule.INSTANCE)
+                // Date/Time/Timestamp rules
+                .addRule(TimestampToTimestampCastRule.INSTANCE)
+                .addRule(TimestampToDateCastRule.INSTANCE)
+                .addRule(TimestampToTimeCastRule.INSTANCE)
+                .addRule(DateToTimestampCastRule.INSTANCE)
+                .addRule(TimeToTimestampCastRule.INSTANCE)
+                .addRule(NumericToTimestampCastRule.INSTANCE)
+                .addRule(TimestampToNumericCastRule.INSTANCE)
                 // To binary rules
                 .addRule(BinaryToBinaryCastRule.INSTANCE)
                 .addRule(RawToBinaryCastRule.INSTANCE)
@@ -152,7 +160,7 @@ public class CastRuleProvider {
      * Used by {@link CodeGeneratorCastRule}s which checks for nullability, rather than deferring
      * the check to the rules.
      */
-    static @Nullable CastCodeBlock generateAlwaysNonNullCodeBlock(
+    static CastCodeBlock generateAlwaysNonNullCodeBlock(
             CodeGeneratorCastRule.Context context,
             String inputTerm,
             LogicalType inputLogicalType,
@@ -205,7 +213,7 @@ public class CastRuleProvider {
             }
         }
 
-        if (predicate.getCustomPredicate() != null) {
+        if (predicate.getCustomPredicate().isPresent()) {
             rulesWithCustomPredicate.add(rule);
         }
 
@@ -217,7 +225,7 @@ public class CastRuleProvider {
         LogicalType targetType = unwrapDistinct(target);
 
         final Iterator<Object> targetTypeRootFamilyIterator =
-                Stream.<Object>concat(
+                Stream.concat(
                                 Stream.of(targetType),
                                 Stream.<Object>concat(
                                         Stream.of(targetType.getTypeRoot()),
@@ -253,7 +261,8 @@ public class CastRuleProvider {
                         r ->
                                 r.getPredicateDefinition()
                                         .getCustomPredicate()
-                                        .test(inputType, targetType))
+                                        .map(p -> p.test(inputType, targetType))
+                                        .orElse(false))
                 .findFirst()
                 .orElse(null);
     }
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleUtils.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleUtils.java
index df2e08e..bb1a8da 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleUtils.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/CastRuleUtils.java
@@ -43,6 +43,10 @@ final class CastRuleUtils {
         return legacyBehaviour ? strLiteral("null") : strLiteral("NULL");
     }
 
+    static String operator(Object left, String operator, Object right) {
+        return left + operator + right;
+    }
+
     static String staticCall(Class<?> clazz, String methodName, Object... args) {
         return methodCall(className(clazz), methodName, args);
     }
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/DateToTimestampCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/DateToTimestampCastRule.java
new file mode 100644
index 0000000..455c7f9
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/DateToTimestampCastRule.java
@@ -0,0 +1,69 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.planner.codegen.calls.BuiltInMethods;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.utils.DateTimeUtils;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.cast;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.operator;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.staticCall;
+
+/**
+ * {@link LogicalTypeRoot#DATE} to {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} cast rule.
+ */
+class DateToTimestampCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<Number, TimestampData> {
+
+    static final DateToTimestampCastRule INSTANCE = new DateToTimestampCastRule();
+
+    private DateToTimestampCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.DATE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+
+        if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            return staticCall(
+                    BuiltInMethods.TIMESTAMP_FROM_EPOCH_MILLIS(),
+                    operator(cast("long", inputTerm), "*", DateTimeUtils.MILLIS_PER_DAY));
+        } else if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            return staticCall(
+                    BuiltInMethods.DATE_TO_TIMESTAMP_WITH_LOCAL_TIME_ZONE(),
+                    inputTerm,
+                    context.getSessionTimeZoneTerm());
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/IdentityCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/IdentityCastRule.java
index 4771788..0deddb3 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/IdentityCastRule.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/IdentityCastRule.java
@@ -19,7 +19,6 @@
 package org.apache.flink.table.planner.functions.casting;
 
 import org.apache.flink.table.types.logical.LogicalType;
-import org.apache.flink.table.types.logical.LogicalTypeFamily;
 import org.apache.flink.table.types.logical.LogicalTypeRoot;
 import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
 
@@ -38,13 +37,6 @@ class IdentityCastRule extends AbstractCodeGeneratorCastRule<Object, Object>
 
     private static boolean isIdentityCast(
             LogicalType inputLogicalType, LogicalType targetLogicalType) {
-        // TODO string to string casting now behaves like string casting.
-        //  the discussion in FLINK-24413 will address it
-        if (inputLogicalType.is(LogicalTypeFamily.CHARACTER_STRING)
-                && targetLogicalType.is(LogicalTypeFamily.CHARACTER_STRING)) {
-            return true;
-        }
-
         // INTERVAL_YEAR_MONTH and INTEGER uses the same primitive int type
         if ((inputLogicalType.is(LogicalTypeRoot.INTERVAL_YEAR_MONTH)
                         && targetLogicalType.is(LogicalTypeRoot.INTEGER))
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/NumericToTimestampCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/NumericToTimestampCastRule.java
new file mode 100644
index 0000000..8bf0ae8
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/NumericToTimestampCastRule.java
@@ -0,0 +1,68 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+
+/**
+ * {@link LogicalTypeFamily#NUMERIC} to {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} cast rule. Disable cast conversion between
+ * Numeric type and Timestamp type and suggest to use {@code TO_TIMESTAMP()}/{@code
+ * TO_TIMESTAMP_LTZ()} instead.
+ */
+class NumericToTimestampCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<Number, TimestampData> {
+
+    static final NumericToTimestampCastRule INSTANCE = new NumericToTimestampCastRule();
+
+    private NumericToTimestampCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeFamily.NUMERIC)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+        if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            throw new ValidationException(
+                    "The cast from NUMERIC type to TIMESTAMP type "
+                            + "is not allowed. It's recommended to use "
+                            + "TO_TIMESTAMP(FROM_UNIXTIME(numeric_col)) "
+                            + "instead, note the numeric is in seconds.");
+        } else if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            throw new ValidationException(
+                    "The cast from NUMERIC type"
+                            + " to TIMESTAMP_LTZ type is not allowed. It's recommended to use"
+                            + " TO_TIMESTAMP_LTZ(numeric_col, precision) instead.");
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/RowDataToStringConverterImpl.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/RowDataToStringConverterImpl.java
index 5436bce..3698e7f 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/RowDataToStringConverterImpl.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/RowDataToStringConverterImpl.java
@@ -18,6 +18,7 @@
 
 package org.apache.flink.table.planner.functions.casting;
 
+import org.apache.flink.annotation.Internal;
 import org.apache.flink.annotation.VisibleForTesting;
 import org.apache.flink.table.data.RowData;
 import org.apache.flink.table.data.StringData;
@@ -36,6 +37,7 @@ import java.util.function.Function;
 import static org.apache.flink.table.api.DataTypes.STRING;
 
 /** {@link RowData} to {@link String} converter using {@link CastRule}. */
+@Internal
 public final class RowDataToStringConverterImpl implements RowDataToStringConverter {
 
     private final Function<RowData, String>[] columnConverters;
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimeToTimestampCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimeToTimestampCastRule.java
new file mode 100644
index 0000000..8ddc679
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimeToTimestampCastRule.java
@@ -0,0 +1,65 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.planner.codegen.calls.BuiltInMethods;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.staticCall;
+
+/**
+ * {@link LogicalTypeRoot#TIME_WITHOUT_TIME_ZONE} to {@link
+ * LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} cast rule.
+ */
+class TimeToTimestampCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<Number, TimestampData> {
+
+    static final TimeToTimestampCastRule INSTANCE = new TimeToTimestampCastRule();
+
+    private TimeToTimestampCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+
+        if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            return staticCall(BuiltInMethods.TIMESTAMP_FROM_EPOCH_MILLIS(), inputTerm);
+        } else if (targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            return staticCall(
+                    BuiltInMethods.TIME_TO_TIMESTAMP_WITH_LOCAL_TIME_ZONE(),
+                    inputTerm,
+                    context.getSessionTimeZoneTerm());
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToDateCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToDateCastRule.java
new file mode 100644
index 0000000..0d3858f
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToDateCastRule.java
@@ -0,0 +1,73 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.planner.codegen.calls.BuiltInMethods;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.utils.DateTimeUtils;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.cast;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.operator;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.staticCall;
+
+/**
+ * {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} to {@link LogicalTypeRoot#DATE}.
+ */
+class TimestampToDateCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<TimestampData, Number> {
+
+    static final TimestampToDateCastRule INSTANCE = new TimestampToDateCastRule();
+
+    private TimestampToDateCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .input(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .target(LogicalTypeRoot.DATE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+
+        if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            return cast(
+                    "int",
+                    operator(
+                            methodCall(inputTerm, "getMillisecond"),
+                            "/",
+                            DateTimeUtils.MILLIS_PER_DAY));
+        } else if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            return staticCall(
+                    BuiltInMethods.TIMESTAMP_WITH_LOCAL_TIME_ZONE_TO_DATE(),
+                    inputTerm,
+                    context.getSessionTimeZoneTerm());
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToNumericCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToNumericCastRule.java
new file mode 100644
index 0000000..677c58e
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToNumericCastRule.java
@@ -0,0 +1,65 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+
+/**
+ * {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} to {@link LogicalTypeFamily#NUMERIC} cast rule.
+ * Disable cast conversion between Timestamp type and Numeric type and suggest to use {@code
+ * UNIX_TIMESTAMP()} instead (for {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}.
+ */
+class TimestampToNumericCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<TimestampData, Number> {
+
+    static final TimestampToNumericCastRule INSTANCE = new TimestampToNumericCastRule();
+
+    private TimestampToNumericCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .input(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .target(LogicalTypeFamily.NUMERIC)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+        if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            throw new ValidationException(
+                    "The cast from TIMESTAMP type to NUMERIC type"
+                            + " is not allowed. It's recommended to use"
+                            + " UNIX_TIMESTAMP(CAST(timestamp_col AS STRING)) instead.");
+        } else if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            throw new ValidationException(
+                    "The cast from" + " TIMESTAMP_LTZ type to NUMERIC type is not allowed.");
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimeCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimeCastRule.java
new file mode 100644
index 0000000..c37c71f
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimeCastRule.java
@@ -0,0 +1,74 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.planner.codegen.calls.BuiltInMethods;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.utils.DateTimeUtils;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.cast;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.operator;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.staticCall;
+
+/**
+ * {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} to {@link
+ * LogicalTypeRoot#TIME_WITHOUT_TIME_ZONE}.
+ */
+class TimestampToTimeCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<TimestampData, Number> {
+
+    static final TimestampToTimeCastRule INSTANCE = new TimestampToTimeCastRule();
+
+    private TimestampToTimeCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .input(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+
+        if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            return cast(
+                    "int",
+                    operator(
+                            methodCall(inputTerm, "getMillisecond"),
+                            "%",
+                            DateTimeUtils.MILLIS_PER_DAY));
+        } else if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            return staticCall(
+                    BuiltInMethods.TIMESTAMP_WITH_LOCAL_TIME_ZONE_TO_TIME(),
+                    inputTerm,
+                    context.getSessionTimeZoneTerm());
+        } else {
+            throw new IllegalArgumentException("This is a bug. Please file an issue.");
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimestampCastRule.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimestampCastRule.java
new file mode 100644
index 0000000..f0dd747
--- /dev/null
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/TimestampToTimestampCastRule.java
@@ -0,0 +1,98 @@
+/*
+ * 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.flink.table.planner.functions.casting;
+
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.planner.codegen.calls.BuiltInMethods;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.TimestampKind;
+import org.apache.flink.table.types.logical.TimestampType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.staticCall;
+
+/**
+ * {@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link
+ * LogicalTypeRoot#TIMESTAMP_WITH_LOCAL_TIME_ZONE} to {@link
+ * LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}/{@link LogicalTypeRoot#TIMESTAMP_WITHOUT_TIME_ZONE}
+ * cast rule. Check and adjust if there is the precision changes.
+ */
+class TimestampToTimestampCastRule
+        extends AbstractExpressionCodeGeneratorCastRule<TimestampData, TimestampData> {
+
+    static final TimestampToTimestampCastRule INSTANCE = new TimestampToTimestampCastRule();
+
+    private TimestampToTimestampCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .input(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                        .target(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                        .build());
+    }
+
+    @Override
+    public String generateExpression(
+            CodeGeneratorCastRule.Context context,
+            String inputTerm,
+            LogicalType inputLogicalType,
+            LogicalType targetLogicalType) {
+        final int inputPrecision = LogicalTypeChecks.getPrecision(inputLogicalType);
+        int targetPrecision = LogicalTypeChecks.getPrecision(targetLogicalType);
+
+        if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                && targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            final TimestampKind inputTimestampKind = ((TimestampType) inputLogicalType).getKind();
+            final TimestampKind targetTimestampKind = ((TimestampType) targetLogicalType).getKind();
+            if (inputTimestampKind == TimestampKind.ROWTIME
+                    || inputTimestampKind == TimestampKind.PROCTIME
+                    || targetTimestampKind == TimestampKind.ROWTIME
+                    || targetTimestampKind == TimestampKind.PROCTIME) {
+                targetPrecision = 3;
+            }
+        }
+
+        final String operand;
+        if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)
+                && targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)) {
+            operand =
+                    staticCall(
+                            BuiltInMethods.TIMESTAMP_TO_TIMESTAMP_WITH_LOCAL_ZONE(),
+                            inputTerm,
+                            context.getSessionTimeZoneTerm());
+        } else if (inputLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE)
+                && targetLogicalType.is(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE)) {
+            operand =
+                    staticCall(
+                            BuiltInMethods.TIMESTAMP_WITH_LOCAL_ZONE_TO_TIMESTAMP(),
+                            inputTerm,
+                            context.getSessionTimeZoneTerm());
+        } else {
+            operand = inputTerm;
+        }
+
+        if (inputPrecision <= targetPrecision) {
+            return operand;
+        } else {
+            return staticCall(BuiltInMethods.TRUNCATE_SQL_TIMESTAMP(), operand, targetPrecision);
+        }
+    }
+}
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BuiltInMethods.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BuiltInMethods.scala
index 0b5e6a7..8866a31 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BuiltInMethods.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/BuiltInMethods.scala
@@ -269,6 +269,11 @@ object BuiltInMethods {
     "timestampWithLocalZoneToTimestamp",
     classOf[TimestampData], classOf[TimeZone])
 
+  val TIMESTAMP_FROM_EPOCH_MILLIS = Types.lookupMethod(
+    classOf[TimestampData],
+    "fromEpochMillis",
+    classOf[Long])
+
   val STRING_TO_DATE_WITH_FORMAT = Types.lookupMethod(
     classOf[DateTimeUtils],
     "parseDate",
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala
index 945038d..bb6ac5d 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/calls/ScalarOperatorGens.scala
@@ -39,7 +39,6 @@ import org.apache.flink.table.types.logical.LogicalTypeRoot._
 import org.apache.flink.table.types.logical._
 import org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getFieldTypes
 import org.apache.flink.table.types.logical.utils.LogicalTypeMerging.findCommonType
-import org.apache.flink.table.utils.DateTimeUtils
 import org.apache.flink.table.utils.DateTimeUtils.MILLIS_PER_DAY
 import org.apache.flink.util.Preconditions.checkArgument
 
@@ -1014,232 +1013,10 @@ object ScalarOperatorGens {
     // Fallback to old cast rules
     (operand.resultType.getTypeRoot, targetType.getTypeRoot) match {
 
-      // special case: cast from TimeIndicatorTypeInfo to SqlTimeTypeInfo
-      case (TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE)
-        if operand.resultType.asInstanceOf[TimestampType].getKind == TimestampKind.PROCTIME ||
-          operand.resultType.asInstanceOf[TimestampType].getKind == TimestampKind.ROWTIME ||
-          targetType.asInstanceOf[TimestampType].getKind == TimestampKind.PROCTIME ||
-          targetType.asInstanceOf[TimestampType].getKind == TimestampKind.ROWTIME =>
-        // just replace the DataType
-        operand.copy(resultType = new TimestampType(operand.resultType.isNullable, 3))
-
-      case (TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE) =>
-        val fromType = operand.resultType.asInstanceOf[TimestampType]
-        val toType = targetType.asInstanceOf[TimestampType]
-        if (fromType.getPrecision <= toType.getPrecision) {
-          operand.copy(resultType = targetType)
-        } else {
-          val method = qualifyMethod(BuiltInMethods.TRUNCATE_SQL_TIMESTAMP)
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              s"$method($operandTerm, ${toType.getPrecision})"
-          }
-        }
-
-      case (TIMESTAMP_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) =>
-        val fromType = operand.resultType.asInstanceOf[TimestampType]
-        val toType = targetType.asInstanceOf[LocalZonedTimestampType]
-        val method = qualifyMethod(BuiltInMethods.TIMESTAMP_TO_TIMESTAMP_WITH_LOCAL_ZONE)
-        if (fromType.getPrecision < toType.getPrecision) {
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              val timeZone = ctx.addReusableSessionTimeZone()
-              s"$method($operandTerm, $timeZone)"
-          }
-        } else {
-          val truncate_method = qualifyMethod(BuiltInMethods.TRUNCATE_SQL_TIMESTAMP)
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              val timeZone = ctx.addReusableSessionTimeZone()
-              s"$truncate_method($method($operandTerm, $timeZone), ${toType.getPrecision})"
-          }
-        }
-
-      case (TIMESTAMP_WITH_LOCAL_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE) =>
-        val fromType = operand.resultType.asInstanceOf[LocalZonedTimestampType]
-        val toType = targetType.asInstanceOf[TimestampType]
-        val method = qualifyMethod(BuiltInMethods.TIMESTAMP_WITH_LOCAL_ZONE_TO_TIMESTAMP)
-        if (fromType.getPrecision < toType.getPrecision) {
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              val zone = ctx.addReusableSessionTimeZone()
-              s"$method($operandTerm, $zone)"
-          }
-        } else {
-          val truncate_method = qualifyMethod(BuiltInMethods.TRUNCATE_SQL_TIMESTAMP)
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              val zone = ctx.addReusableSessionTimeZone()
-              s"$truncate_method($method($operandTerm, $zone), ${toType.getPrecision})"
-          }
-        }
-
-      case (TIMESTAMP_WITH_LOCAL_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) =>
-        val fromType = operand.resultType.asInstanceOf[LocalZonedTimestampType]
-        val toType = targetType.asInstanceOf[LocalZonedTimestampType]
-        if (fromType.getPrecision <= toType.getPrecision) {
-          operand.copy(resultType = targetType)
-        } else {
-          val method = qualifyMethod(BuiltInMethods.TRUNCATE_SQL_TIMESTAMP)
-          generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-            operandTerm =>
-              s"$method($operandTerm, ${toType.getPrecision})"
-          }
-        }
-
-      // TODO this identity casting is not really an identity casting,
-      //  because it doesn't perform precision/length trimming on types that requires it
-      //  E.g. it doesn't trim strings from one CHAR type to another with smaller size.
-      //  This should be addressed by FLINK-24403 subtasks
       // identity casting
       case (_, _) if isInteroperable(operand.resultType, targetType) =>
         operand.copy(resultType = targetType)
 
-      // Date -> Timestamp
-      case (DATE, TIMESTAMP_WITHOUT_TIME_ZONE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-          operandTerm =>
-            s"""
-               |$TIMESTAMP_DATA.fromEpochMillis(
-               |  $operandTerm * ${classOf[DateTimeUtils].getCanonicalName}.MILLIS_PER_DAY)
-           """.stripMargin
-        }
-
-      // Timestamp -> Date
-      case (TIMESTAMP_WITHOUT_TIME_ZONE, DATE) =>
-        val targetTypeTerm = primitiveTypeTermForType(targetType)
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-          operandTerm =>
-            s"""
-               |($targetTypeTerm) ($operandTerm.getMillisecond() /
-               |  ${classOf[DateTimeUtils].getCanonicalName}.MILLIS_PER_DAY)
-           """.stripMargin
-        }
-
-      // Time -> Timestamp
-      case (TIME_WITHOUT_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-          operandTerm => s"$TIMESTAMP_DATA.fromEpochMillis($operandTerm)"
-        }
-
-      // Timestamp -> Time
-      case (TIMESTAMP_WITHOUT_TIME_ZONE, TIME_WITHOUT_TIME_ZONE) =>
-        val targetTypeTerm = primitiveTypeTermForType(targetType)
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) {
-          operandTerm =>
-            s"($targetTypeTerm) ($operandTerm.getMillisecond() % " +
-              s"${classOf[DateTimeUtils].getCanonicalName}.MILLIS_PER_DAY)"
-        }
-
-      // Date -> Timestamp with local time zone
-      case (DATE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) { operandTerm =>
-          val zone = ctx.addReusableSessionTimeZone()
-          val method = qualifyMethod(BuiltInMethods.DATE_TO_TIMESTAMP_WITH_LOCAL_TIME_ZONE)
-          s"$method($operandTerm, $zone)"
-        }
-
-      // Timestamp with local time zone -> Date
-      case (TIMESTAMP_WITH_LOCAL_TIME_ZONE, DATE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) { operandTerm =>
-          val zone = ctx.addReusableSessionTimeZone()
-          val method = qualifyMethod(BuiltInMethods.TIMESTAMP_WITH_LOCAL_TIME_ZONE_TO_DATE)
-          s"$method($operandTerm, $zone)"
-        }
-
-      // Time -> Timestamp with local time zone
-      case (TIME_WITHOUT_TIME_ZONE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) { operandTerm =>
-          val zone = ctx.addReusableSessionTimeZone()
-          val method = qualifyMethod(BuiltInMethods.TIME_TO_TIMESTAMP_WITH_LOCAL_TIME_ZONE)
-          s"$method($operandTerm, $zone)"
-        }
-
-      // Timestamp with local time zone -> Time
-      case (TIMESTAMP_WITH_LOCAL_TIME_ZONE, TIME_WITHOUT_TIME_ZONE) =>
-        generateUnaryOperatorIfNotNull(ctx, targetType, operand) { operandTerm =>
-          val zone = ctx.addReusableSessionTimeZone()
-          val method = qualifyMethod(BuiltInMethods.TIMESTAMP_WITH_LOCAL_TIME_ZONE_TO_TIME)
-          s"$method($operandTerm, $zone)"
-        }
-
-      // Disable cast conversion between Numeric type and Timestamp type
-      case (TINYINT, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (SMALLINT, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (INTEGER, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (BIGINT, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (FLOAT, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (DOUBLE, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (DECIMAL, TIMESTAMP_WITHOUT_TIME_ZONE) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, TINYINT) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, SMALLINT) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, INTEGER) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, BIGINT) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, FLOAT) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, DOUBLE) |
-           (TIMESTAMP_WITHOUT_TIME_ZONE, DECIMAL) => {
-        if (TIMESTAMP_WITHOUT_TIME_ZONE.equals(targetType.getTypeRoot)) {
-          throw new ValidationException("The cast conversion from NUMERIC type to TIMESTAMP type" +
-            " is not allowed, it's recommended to use TO_TIMESTAMP(FROM_UNIXTIME(numeric_col))" +
-            " instead, note the numeric is in seconds.")
-        } else {
-          throw new ValidationException("The cast conversion from TIMESTAMP type to NUMERIC type" +
-            " is not allowed, it's recommended to use" +
-            " UNIX_TIMESTAMP(CAST(timestamp_col AS STRING)) instead.")
-        }
-      }
-
-      // Disable cast conversion between Numeric type and TimestampLtz type
-      case (TINYINT, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (SMALLINT, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (INTEGER, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (BIGINT, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (FLOAT, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (DOUBLE, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (DECIMAL, TIMESTAMP_WITH_LOCAL_TIME_ZONE) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, TINYINT) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, SMALLINT) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, INTEGER) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, BIGINT) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, FLOAT) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, DOUBLE) |
-           (TIMESTAMP_WITH_LOCAL_TIME_ZONE, DECIMAL) => {
-        if (TIMESTAMP_WITH_LOCAL_TIME_ZONE.equals(targetType.getTypeRoot)) {
-          throw new ValidationException("The cast conversion from NUMERIC type" +
-            " to TIMESTAMP_LTZ type is not allowed, it's recommended to use" +
-            " TO_TIMESTAMP_LTZ(numeric_col, precision) instead.")
-        } else {
-          throw new ValidationException("The cast conversion from" +
-            " TIMESTAMP_LTZ type to NUMERIC type is not allowed.")
-        }
-      }
-
-      // internal temporal casting
-      // Date -> Integer
-      // Time -> Integer
-      // Integer -> Date
-      // Integer -> Time
-      // Integer -> Interval Months
-      // Long -> Interval Millis
-      // Interval Months -> Integer
-      // Interval Millis -> Long
-      case (DATE, INTEGER) |
-           (TIME_WITHOUT_TIME_ZONE, INTEGER) |
-           (INTEGER, DATE) |
-           (INTEGER, TIME_WITHOUT_TIME_ZONE) |
-           (INTEGER, INTERVAL_YEAR_MONTH) |
-           (BIGINT, INTERVAL_DAY_TIME) |
-           (INTERVAL_YEAR_MONTH, INTEGER) |
-           (INTERVAL_DAY_TIME, BIGINT) =>
-        internalExprCasting(operand, targetType)
-
-      // internal reinterpretation of temporal types
-      // Date, Time, Interval Months -> Long
-      case (DATE, BIGINT)
-           | (TIME_WITHOUT_TIME_ZONE, BIGINT)
-           | (INTERVAL_YEAR_MONTH, BIGINT) =>
-        internalExprCasting(operand, targetType)
-
       case (_, _) =>
         throw new CodeGenException(
           s"Unsupported cast from '${operand.resultType}' to '$targetType'.")
diff --git a/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/CastFunctionITCase.java b/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/CastFunctionITCase.java
index ae9e595..bca137e 100644
--- a/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/CastFunctionITCase.java
+++ b/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/CastFunctionITCase.java
@@ -1300,11 +1300,12 @@ public class CastFunctionITCase extends BuiltInFunctionTestBase {
 
         private String specificErrorMsg(LogicalType colType, String defaultMsg) {
             if (isTimestampLtzToNumeric(colType, targetType.getLogicalType())) {
-                return "The cast conversion from TIMESTAMP_LTZ type to NUMERIC type is not allowed.";
+                return "The cast from TIMESTAMP_LTZ type to NUMERIC type is not allowed.";
             } else if (isNumericToTimestamp(colType, targetType.getLogicalType())) {
-                return "type is not allowed, it's recommended to use TO_TIMESTAMP";
+                return "type is not allowed. It's recommended to use TO_TIMESTAMP";
             } else if (isTimestampToNumeric(colType, targetType.getLogicalType())) {
-                return "type is not allowed, it's recommended to use UNIX_TIMESTAMP(CAST(timestamp_col AS STRING)) instead.";
+                return "type is not allowed. It's recommended to use "
+                        + "UNIX_TIMESTAMP(CAST(timestamp_col AS STRING)) instead.";
             } else {
                 return defaultMsg;
             }
diff --git a/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/casting/CastRulesTest.java b/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/casting/CastRulesTest.java
index a0327c5..59a23d4 100644
--- a/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/casting/CastRulesTest.java
+++ b/flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/casting/CastRulesTest.java
@@ -121,12 +121,14 @@ class CastRulesTest {
     private static final double DEFAULT_NEGATIVE_DOUBLE = -123.456789d;
 
     private static final int DATE = DateTimeUtils.toInternal(LocalDate.parse("2021-09-24"));
-    private static final int TIME = DateTimeUtils.toInternal(LocalTime.parse("12:34:56.123"));
+    private static final int TIME = DateTimeUtils.toInternal(LocalTime.parse("12:34:56.12345"));
     private static final StringData DATE_STRING = fromString("2021-09-24");
     private static final StringData TIME_STRING = fromString("12:34:56.123");
 
     private static final TimestampData TIMESTAMP =
             TimestampData.fromLocalDateTime(LocalDateTime.parse("2021-09-24T12:34:56.123456"));
+    private static final TimestampData TIMESTAMP_LTZ =
+            timestampDataFromInstant(2022, 1, 4, 12, 34, 56, 123456780);
     private static final StringData TIMESTAMP_STRING = fromString("2021-09-24 12:34:56.123456");
     private static final StringData TIMESTAMP_STRING_CET = fromString("2021-09-24 14:34:56.123456");
 
@@ -429,7 +431,15 @@ class CastRulesTest {
                                 STRING(),
                                 fromString("2021-09-27 12:34:56.123456789"),
                                 DateTimeUtils.toInternal(LocalDate.of(2021, 9, 27)))
-                        .fail(STRING(), fromString("2021/09/27"), TableException.class),
+                        .fail(STRING(), fromString("2021/09/27"), TableException.class)
+                        .fromCase(
+                                TIMESTAMP(9),
+                                TIMESTAMP,
+                                DateTimeUtils.toInternal(LocalDate.of(2021, 9, 24)))
+                        .fromCase(
+                                TIMESTAMP_LTZ(8),
+                                TIMESTAMP_LTZ,
+                                DateTimeUtils.toInternal(LocalDate.of(2022, 1, 4))),
                 CastTestSpecBuilder.testCastTo(TIME())
                         .fail(CHAR(3), fromString("foo"), TableException.class)
                         .fail(VARCHAR(5), fromString("Flink"), TableException.class)
@@ -443,6 +453,8 @@ class CastRulesTest {
                                 DateTimeUtils.toInternal(LocalTime.of(23, 45, 0)))
                         .fail(STRING(), fromString("2021-09-27"), TableException.class)
                         .fail(STRING(), fromString("2021-09-27 12:34:56"), TableException.class)
+                        // https://issues.apache.org/jira/browse/FLINK-17224 Currently, fractional
+                        // seconds are lost
                         .fromCase(
                                 STRING(),
                                 fromString("12:34:56.123456789"),
@@ -450,7 +462,15 @@ class CastRulesTest {
                         .fail(
                                 STRING(),
                                 fromString("2021-09-27 12:34:56.123456789"),
-                                TableException.class),
+                                TableException.class)
+                        .fromCase(
+                                TIMESTAMP(6),
+                                TIMESTAMP,
+                                DateTimeUtils.toInternal(LocalTime.of(12, 34, 56, 123_000_000)))
+                        .fromCase(
+                                TIMESTAMP_LTZ(8),
+                                TIMESTAMP_LTZ,
+                                DateTimeUtils.toInternal(LocalTime.of(11, 34, 56, 123_000_000))),
                 CastTestSpecBuilder.testCastTo(TIMESTAMP(9))
                         .fail(CHAR(3), fromString("foo"), TableException.class)
                         .fail(VARCHAR(5), fromString("Flink"), TableException.class)
@@ -458,14 +478,53 @@ class CastRulesTest {
                         .fromCase(
                                 STRING(),
                                 fromString("2021-09-27"),
-                                TimestampData.fromLocalDateTime(
-                                        LocalDateTime.of(2021, 9, 27, 0, 0, 0, 0)))
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 0))
                         .fail(STRING(), fromString("2021/09/27"), TableException.class)
                         .fromCase(
                                 STRING(),
                                 fromString("2021-09-27 12:34:56.123456789"),
-                                TimestampData.fromLocalDateTime(
-                                        LocalDateTime.of(2021, 9, 27, 12, 34, 56, 123456789))),
+                                timestampDataFromLocalDateTime(
+                                        2021, 9, 27, 12, 34, 56, 123_456_789))
+                        .fromCase(
+                                DATE(),
+                                DateTimeUtils.toInternal(LocalDate.of(2022, 1, 4)),
+                                timestampDataFromLocalDateTime(2022, 1, 4, 0, 0, 0, 0))
+                        // https://issues.apache.org/jira/browse/FLINK-17224 Currently, fractional
+                        // seconds are lost
+                        .fromCase(
+                                TIME(5),
+                                TIME,
+                                timestampDataFromLocalDateTime(1970, 1, 1, 12, 34, 56, 123_000_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(8),
+                                TIMESTAMP_LTZ,
+                                timestampDataFromLocalDateTime(
+                                        2022, 1, 4, 11, 34, 56, 123_456_780)),
+                CastTestSpecBuilder.testCastTo(TIMESTAMP(4))
+                        .fromCase(
+                                TIMESTAMP(2),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 120_000_000),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 120_000_000))
+                        .fromCase(
+                                TIMESTAMP(4),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_400_000),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP(7),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_456_700),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(2),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 120_000_000),
+                                timestampDataFromLocalDateTime(2021, 9, 26, 22, 0, 0, 120_000_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(4),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_400_000),
+                                timestampDataFromLocalDateTime(2021, 9, 26, 22, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(7),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_456_700),
+                                timestampDataFromLocalDateTime(2021, 9, 26, 22, 0, 0, 123_400_000)),
                 CastTestSpecBuilder.testCastTo(TIMESTAMP_LTZ(9))
                         .fail(CHAR(3), fromString("foo"), TableException.class)
                         .fail(VARCHAR(5), fromString("Flink"), TableException.class)
@@ -474,28 +533,58 @@ class CastRulesTest {
                                 STRING(),
                                 CET_CONTEXT,
                                 fromString("2021-09-27"),
-                                TimestampData.fromInstant(
-                                        LocalDateTime.of(2021, 9, 27, 0, 0, 0, 0)
-                                                .atZone(CET)
-                                                .toInstant()))
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 0))
                         .fromCase(
                                 STRING(),
                                 CET_CONTEXT,
                                 fromString("2021-09-27 12:34:56.123"),
-                                TimestampData.fromInstant(
-                                        LocalDateTime.of(2021, 9, 27, 12, 34, 56, 123000000)
-                                                .atZone(CET)
-                                                .toInstant()))
+                                timestampDataFromInstant(2021, 9, 27, 12, 34, 56, 123_000_000))
                         // https://issues.apache.org/jira/browse/FLINK-24446 Fractional seconds are
                         // lost
                         .fromCase(
                                 STRING(),
                                 CET_CONTEXT,
                                 fromString("2021-09-27 12:34:56.123456789"),
-                                TimestampData.fromInstant(
-                                        LocalDateTime.of(2021, 9, 27, 12, 34, 56, 0)
-                                                .atZone(CET)
-                                                .toInstant())),
+                                timestampDataFromInstant(2021, 9, 27, 12, 34, 56, 0))
+                        .fromCase(
+                                DATE(),
+                                DateTimeUtils.toInternal(LocalDate.of(2022, 1, 4)),
+                                timestampDataFromInstant(2022, 1, 4, 1, 0, 0, 0))
+                        // https://issues.apache.org/jira/browse/FLINK-17224 Currently, fractional
+                        // seconds are lost
+                        .fromCase(
+                                TIME(5),
+                                TIME,
+                                timestampDataFromInstant(1970, 1, 1, 13, 34, 56, 123_000_000))
+                        .fromCase(
+                                TIMESTAMP(6),
+                                TIMESTAMP,
+                                timestampDataFromInstant(2021, 9, 24, 14, 34, 56, 123_456_000)),
+                CastTestSpecBuilder.testCastTo(TIMESTAMP_LTZ(4))
+                        .fromCase(
+                                TIMESTAMP(2),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 120_000_000),
+                                timestampDataFromInstant(2021, 9, 27, 2, 0, 0, 120_000_000))
+                        .fromCase(
+                                TIMESTAMP(4),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_400_000),
+                                timestampDataFromInstant(2021, 9, 27, 2, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP(7),
+                                timestampDataFromLocalDateTime(2021, 9, 27, 0, 0, 0, 123_456_700),
+                                timestampDataFromInstant(2021, 9, 27, 2, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(2),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 120_000_000),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 120_000_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(4),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_400_000),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_400_000))
+                        .fromCase(
+                                TIMESTAMP_LTZ(7),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_456_700),
+                                timestampDataFromInstant(2021, 9, 27, 0, 0, 0, 123_400_000)),
                 CastTestSpecBuilder.testCastTo(STRING())
                         .fromCase(STRING(), null, null)
                         .fromCase(NULL(), null, BinaryStringDataUtil.NULL_STRING)
@@ -1444,4 +1533,18 @@ class CastRulesTest {
             return Arrays.stream(testSpecs);
         }
     }
+
+    private static TimestampData timestampDataFromLocalDateTime(
+            int years, int months, int days, int hours, int minutes, int seconds, int nanos) {
+        return TimestampData.fromLocalDateTime(
+                LocalDateTime.of(years, months, days, hours, minutes, seconds, nanos));
+    }
+
+    private static TimestampData timestampDataFromInstant(
+            int years, int months, int days, int hours, int minutes, int seconds, int nanos) {
+        return TimestampData.fromInstant(
+                LocalDateTime.of(years, months, days, hours, minutes, seconds, nanos)
+                        .atZone(CET)
+                        .toInstant());
+    }
 }
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/expressions/TemporalTypesTest.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/expressions/TemporalTypesTest.scala
index 03a73bd..6d46f7c 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/expressions/TemporalTypesTest.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/expressions/TemporalTypesTest.scala
@@ -284,11 +284,11 @@ class TemporalTypesTest extends ExpressionTestBase {
 
   @Test
   def tesInvalidCastBetweenNumericAndTimestampLtz(): Unit = {
-    val castFromTimestampLtzExceptionMsg = "The cast conversion from TIMESTAMP_LTZ type to" +
+    val castFromTimestampLtzExceptionMsg = "The cast from TIMESTAMP_LTZ type to" +
       " NUMERIC type is not allowed."
 
-    val castToTimestampLtzExceptionMsg = "The cast conversion from NUMERIC type to TIMESTAMP_LTZ" +
-      " type is not allowed, it's recommended to use" +
+    val castToTimestampLtzExceptionMsg = "The cast from NUMERIC type to TIMESTAMP_LTZ" +
+      " type is not allowed. It's recommended to use" +
       " TO_TIMESTAMP_LTZ(numeric_col, precision) instead."
 
     // TINYINT -> TIMESTAMP_LTZ
@@ -364,12 +364,12 @@ class TemporalTypesTest extends ExpressionTestBase {
 
   @Test
   def tesInvalidCastBetweenNumericAndTimestamp(): Unit = {
-    val castFromTimestampExceptionMsg = "The cast conversion from TIMESTAMP type to NUMERIC type" +
-      " is not allowed, it's recommended to use" +
+    val castFromTimestampExceptionMsg = "The cast from TIMESTAMP type to NUMERIC type" +
+      " is not allowed. It's recommended to use" +
       " UNIX_TIMESTAMP(CAST(timestamp_col AS STRING)) instead."
 
-    val castToTimestampExceptionMsg = "The cast conversion from NUMERIC type to TIMESTAMP type" +
-      " is not allowed, it's recommended to use TO_TIMESTAMP(FROM_UNIXTIME(numeric_col))" +
+    val castToTimestampExceptionMsg = "The cast from NUMERIC type to TIMESTAMP type" +
+      " is not allowed. It's recommended to use TO_TIMESTAMP(FROM_UNIXTIME(numeric_col))" +
       " instead, note the numeric is in seconds."
 
     testExpectedSqlException(