Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[INLONG-10873][SDK] Transform support factorial function #10874

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
@@ -0,0 +1,117 @@
/*
* 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.inlong.sdk.transform.process.function;

import org.apache.inlong.sdk.transform.decode.SourceData;
import org.apache.inlong.sdk.transform.process.Context;
import org.apache.inlong.sdk.transform.process.operator.OperatorTools;
import org.apache.inlong.sdk.transform.process.parser.ValueParser;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Function;

import java.math.BigDecimal;

/**
* FactorialFunction
* description: factorial(numeric)--returns the factorial of a non-negative
* integer
*/
@Slf4j
public class FactorialFunction implements ValueParser {

private final ValueParser numberParser;

/**
* Constructor
*
* @param expr
*/
public FactorialFunction(Function expr) {
if (expr == null || expr.getParameters() == null || expr.getParameters().getExpressions() == null
|| expr.getParameters().getExpressions().isEmpty()
|| expr.getParameters().getExpressions().get(0) == null) {
log.error("Invalid expression for factorial function.");
numberParser = null;
} else {
numberParser = OperatorTools.buildParser(expr.getParameters().getExpressions().get(0));
}
}

/**
* parse
*
* @param sourceData
* @param rowIndex
* @return
*/
@Override
public Object parse(SourceData sourceData, int rowIndex, Context context) {
if (numberParser == null) {
log.error("Number parser is not initialized.");
return null;
}

Object numberObj;
try {
numberObj = numberParser.parse(sourceData, rowIndex, context);
} catch (Exception e) {
log.error("Error parsing number object", e);
return null;
}

if (numberObj == null) {
log.warn("Parsed number object is null.");
return null;
}

BigDecimal numberValue;
try {
numberValue = OperatorTools.parseBigDecimal(numberObj);
} catch (Exception e) {
log.error("Error converting parsed object to BigDecimal", e);
return null;
}

// Ensure the number is a non-negative integer
if (numberValue.scale() > 0 || numberValue.compareTo(BigDecimal.ZERO) < 0) {
log.warn("Factorial is only defined for non-negative integers. Invalid input: {}", numberValue);
return null;
}

return factorial(numberValue.intValue());
}

/**
* Helper method to calculate factorial
*
* @param n
* @return
*/
private BigDecimal factorial(int n) {
if (n < 0) {
log.error("Factorial is not defined for negative numbers.");
return null;
}
BigDecimal result = BigDecimal.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigDecimal.valueOf(i));
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.apache.inlong.sdk.transform.process.function.DateExtractFunction.DateExtractFunctionType;
import org.apache.inlong.sdk.transform.process.function.DateFormatFunction;
import org.apache.inlong.sdk.transform.process.function.ExpFunction;
import org.apache.inlong.sdk.transform.process.function.FactorialFunction;
import org.apache.inlong.sdk.transform.process.function.FloorFunction;
import org.apache.inlong.sdk.transform.process.function.FromUnixTimeFunction;
import org.apache.inlong.sdk.transform.process.function.LnFunction;
Expand Down Expand Up @@ -131,6 +132,7 @@ public class OperatorTools {
func -> new TimestampExtractFunction(TimestampExtractFunction.TimestampExtractFunctionType.SECOND,
func));
functionMap.put("round", RoundFunction::new);
functionMap.put("factorial", FactorialFunction::new);
functionMap.put("from_unixtime", FromUnixTimeFunction::new);
functionMap.put("unix_timestamp", UnixTimestampFunction::new);
functionMap.put("to_timestamp", ToTimestampFunction::new);
Expand Down Expand Up @@ -203,6 +205,7 @@ public static ValueParser buildParser(Expression expr) {

/**
* parseBigDecimal
*
* @param value
* @return
*/
Expand Down Expand Up @@ -236,6 +239,7 @@ public static Timestamp parseTimestamp(Object value) {

/**
* compareValue
*
* @param left
* @param right
* @return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,46 @@ public void testLog10Function() throws Exception {
Assert.assertEquals(output2.get(0), "result=3.0");
}

@Test
public void testFactorialFunction() throws Exception {

List<FieldInfo> fields = new ArrayList<>();
FieldInfo numeric1 = new FieldInfo();
numeric1.setName("numeric1");
fields.add(numeric1);

CsvSourceInfo csvSource = new CsvSourceInfo("UTF-8", '|', '\\', fields);
KvSinkInfo kvSink = new KvSinkInfo("UTF-8", fields);

String transformSql = "select factorial(numeric1) as numeric1 from source";

TransformConfig config = new TransformConfig(transformSql);

TransformProcessor<String, String> processor = TransformProcessor
.create(config, SourceDecoderFactory.createCsvDecoder(csvSource),
SinkEncoderFactory.createKvEncoder(kvSink));

// case1: Valid input - 5!
List<String> output1 = processor.transform("5|4|6|8");
Assert.assertEquals(1, output1.size());
Assert.assertEquals("numeric1=120", output1.get(0));

// case2: Valid input - 0!
List<String> output2 = processor.transform("0|4|6|8");
Assert.assertEquals(1, output2.size());
Assert.assertEquals("numeric1=1", output2.get(0));

// case3: Non-integer input (5.5) should return null
List<String> output3 = processor.transform("5.5|4|6|8");
Assert.assertEquals(1, output3.size());
Assert.assertNull(output3.get(0));

// case4: Negative input (-5) should return null
List<String> output4 = processor.transform("-5|4|6|8");
Assert.assertEquals(1, output4.size());
Assert.assertNull(output4.get(0));
}

@Test
public void testLog2Function() throws Exception {
String transformSql = "select log2(numeric1) from source";
Expand Down
Loading