Skip to content

Commit

Permalink
Use first datetime operand as DATE_TRUNC return type
Browse files Browse the repository at this point in the history
  • Loading branch information
tjbanghart committed Mar 24, 2023
1 parent ba8bb5c commit be807b9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -974,11 +974,14 @@ static RelDataType deriveTypeSplit(SqlOperatorBinding operatorBinding,
SqlTypeFamily.ANY));

/** The "DATE_TRUNC(date, timeUnit)" function (BigQuery);
* truncates a DATE value to the beginning of a timeUnit. */
* truncates a DATE value to the beginning of a timeUnit.
*
* TODO(CALCITE-5290): Add `DATE_TRUNC` function consistent with Postgres. Currently, Postgres
* style calls can be parsed but fail validation. */
@LibraryOperator(libraries = {BIG_QUERY})
public static final SqlFunction DATE_TRUNC =
SqlBasicFunction.create("DATE_TRUNC",
ReturnTypes.DATE_NULLABLE,
ReturnTypes.FIRST_DATETIME_ARG,
OperandTypes.sequence("'DATE_TRUNC(<DATE>, <DATETIME_INTERVAL>)'",
OperandTypes.DATE, OperandTypes.dateInterval()),
SqlFunctionCategory.TIMEDATE)
Expand Down
17 changes: 17 additions & 0 deletions core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,23 @@ public static SqlCall stripSeparator(SqlCall call) {
return type1;
};

/**
* Type-inference strategy that uses the first operand that is a member of
* {@link SqlTypeFamily#DATETIME} as the return type.
*/
public static final SqlReturnTypeInference FIRST_DATETIME_ARG =
opBinding -> {
final int n = opBinding.getOperandCount();
RelDataType type1 = null;
for (int i = 0; i < n; i++) {
type1 = opBinding.getOperandType(i);
if (SqlTypeUtil.isDatetime(type1)) {
break;
}
}
return type1;
};

/**
* Type-inference strategy whereby the result type of a call is a nullable
* Boolean.
Expand Down

1 comment on commit be807b9

@tjbanghart
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.