Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package org.opensearch.sql.calcite;

import com.google.common.collect.ImmutableList;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -176,6 +177,13 @@ public RexNode makeCast(
String.format(Locale.ROOT, "Cannot cast from %s to %s", argExprType, udt.name()));
};
}
// Calcite rewrites BOOLEAN -> exact numeric casts into CASE expressions, but has no such
// rewrite for approximate numeric targets, so the generated code passes a boolean to
// Primitive.numberValueRoundDown(Number) and fails to compile. Map TRUE/FALSE to 1.0/0.0 here,
// matching the integer casts and the v2 engine.
else if (SqlTypeUtil.isBoolean(sourceType) && SqlTypeUtil.isApproximateNumeric(type)) {
return makeCastBooleanToApproximateNumeric(type, exp);
}
// Use a custom operator when casting floating point or decimal number to a character type.
// This patch is necessary because in Calcite, 0.0F is cast to 0E0, decimal 0.x to x
else if ((SqlTypeUtil.isApproximateNumeric(sourceType) || SqlTypeUtil.isDecimal(sourceType))
Expand All @@ -191,4 +199,26 @@ else if (sqlType == SqlTypeName.VARBINARY
}
return super.makeCast(pos, type, exp, matchNullability, safe, format);
}

/**
* Casts a BOOLEAN expression to an approximate numeric type (FLOAT/REAL or DOUBLE): TRUE becomes
* 1.0, FALSE becomes 0.0 and NULL stays NULL.
*/
private RexNode makeCastBooleanToApproximateNumeric(RelDataType toType, RexNode exp) {
final RelDataType literalType = typeFactory.createTypeWithNullability(toType, false);
final RexNode casted =
makeCall(
toType,
SqlStdOperatorTable.CASE,
ImmutableList.of(
exp, makeApproxLiteral(BigDecimal.ONE, literalType), makeZeroLiteral(literalType)));
if (!exp.getType().isNullable()) {
return casted;
}
return makeCall(
toType,
SqlStdOperatorTable.CASE,
ImmutableList.of(
makeCall(SqlStdOperatorTable.IS_NOT_NULL, exp), casted, makeNullLiteral(toType)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.opensearch.sql.calcite.utils.OpenSearchTypeFactory.TYPE_FACTORY;

import java.util.Locale;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.type.SqlTypeName;
import org.junit.jupiter.api.Test;
import org.opensearch.sql.expression.function.PPLBuiltinOperators;
Expand Down Expand Up @@ -87,4 +89,44 @@ void castIntegerToVarbinaryDoesNotEmitBinaryPlaceholder() {
"non-VARCHAR → VARBINARY must not emit BINARY placeholder");
}
}

/**
* BOOLEAN → DOUBLE/FLOAT casts must be rewritten into a CASE expression, because Calcite's code
* generator cannot convert a boolean to an approximate numeric type.
*/
@Test
void castNullableBooleanToApproximateNumericEmitsNullSafeCase() {
RelDataType nullableBoolean =
TYPE_FACTORY.createTypeWithNullability(
TYPE_FACTORY.createSqlType(SqlTypeName.BOOLEAN), true);
RexNode booleanRef = REX_BUILDER.makeInputRef(nullableBoolean, 0);

for (SqlTypeName target : new SqlTypeName[] {SqlTypeName.DOUBLE, SqlTypeName.REAL}) {
RelDataType targetType =
TYPE_FACTORY.createTypeWithNullability(TYPE_FACTORY.createSqlType(target), true);

RexNode result = REX_BUILDER.makeCast(targetType, booleanRef, true, true);

assertEquals(SqlKind.CASE, result.getKind());
assertEquals(target, result.getType().getSqlTypeName());
assertEquals(
String.format(
Locale.ROOT,
"CASE(IS NOT NULL($0), CASE($0, 1.0E0:%1$s, 0.0E0:%1$s), null:%1$s)",
target),
result.toString());
}
}

@Test
void castNotNullBooleanToDoubleEmitsCase() {
RexNode booleanRef =
REX_BUILDER.makeInputRef(TYPE_FACTORY.createSqlType(SqlTypeName.BOOLEAN), 0);
RelDataType doubleType = TYPE_FACTORY.createSqlType(SqlTypeName.DOUBLE);

RexNode result = REX_BUILDER.makeCast(doubleType, booleanRef);

assertEquals(SqlKind.CASE, result.getKind());
assertEquals("CASE($0, 1.0E0:DOUBLE, 0.0E0:DOUBLE)", result.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,26 +135,21 @@ public void testCastBOOLEAN() throws IOException {
TEST_INDEX_DATATYPE_NONNUMERIC));
verifyDataRows(actual, rows(1));

// TODO the calcite codegen cannot handle this case. The generated java code is
// return ((Number)org.apache.calcite.linq4j.tree.Primitive.of(float.class)
//
// .numberValueRoundDown((org.apache.calcite.runtime.SqlFunctions.toBoolean(input_value)))).floatValue();
// No applicable constructor/method found for actual parameters "boolean"; candidates are:
// "public java.lang.Object
// org.apache.calcite.linq4j.tree.Primitive.numberValueRoundDown(java.lang.Number)"
// actual =
// executeQuery(
// String.format(
// "source=%s | eval a = cast(boolean_value as FLOAT) | fields a",
// TEST_INDEX_DATATYPE_NONNUMERIC));
// verifyDataRows(actual, rows(1));
//
// actual =
// executeQuery(
// String.format(
// "source=%s | eval a = cast(boolean_value as DOUBLE) | fields a",
// TEST_INDEX_DATATYPE_NONNUMERIC));
// verifyDataRows(actual, rows(1));
actual =
executeQuery(
String.format(
"source=%s | eval a = cast(boolean_value as FLOAT) | fields a",
TEST_INDEX_DATATYPE_NONNUMERIC));
verifySchema(actual, schema("a", "float"));
verifyDataRows(actual, rows(1.0));

actual =
executeQuery(
String.format(
"source=%s | eval a = cast(boolean_value as DOUBLE) | fields a",
TEST_INDEX_DATATYPE_NONNUMERIC));
verifySchema(actual, schema("a", "double"));
verifyDataRows(actual, rows(1.0));

actual =
executeQuery(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Issue #5987: cast(<boolean> as double) and cast(<boolean> as float) failed with a 500 because the
# generated code could not convert a boolean to a floating point number. They must return 1.0 for
# true and 0.0 for false, matching cast(<boolean> as int), and keep null as null.

setup:
- do:
query.settings:
body:
transient:
plugins.calcite.enabled : true
- do:
indices.create:
index: issue5987
body:
settings:
number_of_shards: 1
number_of_replicas: 0
mappings:
properties:
id:
type: integer
b:
type: boolean
- do:
bulk:
index: issue5987
refresh: true
body:
- '{"index": {}}'
- '{"id": 1, "b": true}'
- '{"index": {}}'
- '{"id": 2, "b": false}'
- '{"index": {}}'
- '{"id": 3}'

---
teardown:
- do:
query.settings:
body:
transient:
plugins.calcite.enabled : null
- do:
indices.delete:
index: issue5987
ignore_unavailable: true

---
"Cast boolean to double and float":
- skip:
features:
- headers
- do:
headers:
Content-Type: 'application/json'
ppl:
body:
query: source=issue5987 | sort id | eval i = cast(b as int), d = cast(b as double), f = cast(b as float) | fields id, i, d, f

- match: { "schema": [ { "name": "id", "type": "int" }, { "name": "i", "type": "int" }, { "name": "d", "type": "double" }, { "name": "f", "type": "float" } ] }
- match: { "datarows": [ [ 1, 1, 1.0, 1.0 ], [ 2, 0, 0.0, 0.0 ], [ 3, null, null, null ] ] }
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,28 @@ public void testChainedCast2() {
+ "FROM `scott`.`EMP`";
verifyPPLToSparkSQL(root, expectedSparkSql);
}

@Test
public void testCastBooleanToApproximateNumeric() {
// COMM is null for 10 of the 14 EMP rows, so COMM > 0 covers true, false and null booleans.
String ppl =
"source=EMP | where EMPNO in (7369, 7499, 7844) | eval i = cast(COMM > 0 as int), d ="
+ " cast(COMM > 0 as double), f = cast(COMM > 0 as float) | fields EMPNO, i, d, f";
RelNode root = getRelNode(ppl);
String expectedResult =
""
+ "EMPNO=7369; i=null; d=null; f=null\n"
+ "EMPNO=7499; i=1; d=1.0; f=1.0\n"
+ "EMPNO=7844; i=0; d=0.0; f=0.0\n";
verifyResult(root, expectedResult);
}

@Test
public void testCastBooleanLiteralToApproximateNumeric() {
String ppl =
"source=EMP | eval d = cast(true as double), f = cast(false as float) | fields d, f |"
+ " head 1";
RelNode root = getRelNode(ppl);
verifyResult(root, "d=1.0; f=0.0\n");
}
}
Loading