Skip to content

Commit acb5a8b

Browse files
committed
Fix divide function with a UDF
Signed-off-by: Yuanchun Shen <yuanchu@amazon.com>
1 parent 920f711 commit acb5a8b

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.calcite.udf.mathUDF;
7+
8+
import org.opensearch.sql.calcite.udf.UserDefinedFunction;
9+
10+
public class DivideFunction implements UserDefinedFunction {
11+
12+
@Override
13+
public Object eval(Object... args) {
14+
double dividend = ((Number) args[0]).doubleValue();
15+
double divisor = ((Number) args[1]).doubleValue();
16+
return dividend / divisor;
17+
}
18+
}

core/src/main/java/org/opensearch/sql/calcite/utils/BuiltinFunctionUtils.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
import org.opensearch.sql.calcite.udf.datetimeUDF.YearWeekFunction;
9191
import org.opensearch.sql.calcite.udf.mathUDF.CRC32Function;
9292
import org.opensearch.sql.calcite.udf.mathUDF.ConvFunction;
93+
import org.opensearch.sql.calcite.udf.mathUDF.DivideFunction;
9394
import org.opensearch.sql.calcite.udf.mathUDF.EulerFunction;
9495
import org.opensearch.sql.calcite.udf.mathUDF.ModFunction;
9596
import org.opensearch.sql.calcite.udf.mathUDF.SqrtFunction;
@@ -138,7 +139,7 @@ static SqlOperator translate(String op) {
138139
case "*":
139140
return SqlStdOperatorTable.MULTIPLY;
140141
case "/":
141-
return SqlStdOperatorTable.DIVIDE;
142+
return TransferUserDefinedFunction(DivideFunction.class, "/", ReturnTypes.DOUBLE);
142143
// Built-in String Functions
143144
case "ASCII":
144145
return SqlStdOperatorTable.ASCII;

integ-test/src/test/java/org/opensearch/sql/calcite/standalone/CalcitePPLBuiltinFunctionIT.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,4 +377,14 @@ public void testSignAndRound() {
377377
actual, schema("name", "string"), schema("age", "integer"), schema("thirty_one", "double"));
378378
verifyDataRows(actual, rows("Hello", 30, 31));
379379
}
380+
381+
@Test
382+
public void testDivide() {
383+
JSONObject actual =
384+
executeQuery(
385+
String.format(
386+
"source=%s | where name = 'Hello' | eval res1 = 22 / 7, res2 = age / 11 | fields res1", TEST_INDEX_STATE_COUNTRY));
387+
verifySchema(actual, schema("res1", "double"));
388+
verifyDataRows(actual, closeTo(3.142857142857143, 2.727272727272727));
389+
}
380390
}

0 commit comments

Comments
 (0)