Skip to content

Commit

Permalink
[INLONG-11192][SDK] Transform SQL supports TIMEDIFF function (#11200)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zkplo authored Oct 9, 2024
1 parent 00bb1d2 commit e300cee
Show file tree
Hide file tree
Showing 2 changed files with 186 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* 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 org.apache.inlong.sdk.transform.process.utils.DateUtil;

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

import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.List;

/**
* TimeDiffFunction -> TIMEDIFF(expr1,expr2)
* description:
* - return NULL if expr1 or expr2 is NULL and the conversion types of expr1 and expr2 are different
* - returns expr1 − expr2 expressed as a time value.
* Note: expr1 and expr2 are strings converted to TIME or DATETIME expressions.
*/
@TransformFunction(names = {"timediff", "time_diff"})
@Slf4j
public class TimeDiffFunction implements ValueParser {

private final ValueParser leftDateParser;
private final ValueParser rightDateParser;

public TimeDiffFunction(Function expr) {
List<Expression> expressions = expr.getParameters().getExpressions();
leftDateParser = OperatorTools.buildParser(expressions.get(0));
rightDateParser = OperatorTools.buildParser(expressions.get(1));
}

@Override
public Object parse(SourceData sourceData, int rowIndex, Context context) {
Object leftDateObj = leftDateParser.parse(sourceData, rowIndex, context);
Object rightDateObj = rightDateParser.parse(sourceData, rowIndex, context);
if (leftDateObj == null || rightDateObj == null) {
return null;
}
String leftDate = OperatorTools.parseString(leftDateObj);
String rightDate = OperatorTools.parseString(rightDateObj);
if (leftDate.isEmpty() || rightDate.isEmpty()) {
return null;
}
boolean leftHasTime = leftDate.indexOf(' ') != -1;
boolean rightHasTime = rightDate.indexOf(' ') != -1;

boolean leftHasMicros = leftDate.indexOf('.') != -1;
boolean rightHasMicros = rightDate.indexOf('.') != -1;

try {
Temporal left = null, right = null;
if (leftHasTime && rightHasTime) {
left = DateUtil.parseLocalDateTime(leftDate);
right = DateUtil.parseLocalDateTime(rightDate);
} else if (!leftHasTime && !rightHasTime) {
left = DateUtil.parseLocalTime(leftDate);
right = DateUtil.parseLocalTime(rightDate);
}
if (left == null || right == null) {
return null;
}
long nanoDifference = ChronoUnit.NANOS.between(right, left);

// Convert nanoseconds to total seconds and remaining microseconds
long totalSeconds = nanoDifference / 1_000_000_000;
long microseconds = Math.abs((nanoDifference % 1_000_000_000) / 1_000);

// Handle negative duration
boolean isNegative = nanoDifference < 0;

// Convert totalSeconds to hours, minutes, and seconds
long absTotalSeconds = Math.abs(totalSeconds);
long hours = absTotalSeconds / 3600;
long minutes = (absTotalSeconds % 3600) / 60;
long seconds = absTotalSeconds % 60;

String between = String.format("%s%02d:%02d:%02d", isNegative ? "-" : "",
Math.abs(hours), Math.abs(minutes), Math.abs(seconds));

if (leftHasMicros || rightHasMicros) {
between += String.format(".%06d", Math.abs(microseconds));
}
return between;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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.temporal;

import org.apache.inlong.sdk.transform.decode.SourceDecoderFactory;
import org.apache.inlong.sdk.transform.encode.SinkEncoderFactory;
import org.apache.inlong.sdk.transform.pojo.TransformConfig;
import org.apache.inlong.sdk.transform.process.TransformProcessor;

import org.junit.Assert;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;

public class TestTimeDiffFunction extends AbstractFunctionTemporalTestBase {

@Test
public void testTimeDiffFunction() throws Exception {
String transformSql = null;
TransformConfig config = null;
TransformProcessor<String, String> processor = null;
List<String> output = null;

transformSql = "select timediff(string1,string2) from source";
config = new TransformConfig(transformSql);
processor = TransformProcessor
.create(config, SourceDecoderFactory.createCsvDecoder(csvSource),
SinkEncoderFactory.createKvEncoder(kvSink));
// case1: TIMEDIFF('2000-01-01 00:00:00','2000-01-01 00:00:00.000001')
output = processor.transform("2000-01-01 00:00:00|2000-01-01 00:00:00.000001", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=-00:00:00.000001", output.get(0));

// case2: TIMEDIFF('2008-12-31 23:59:59.000001','2008-12-30 01:01:01.000002')
output = processor.transform("2008-12-31 23:59:59|2008-12-30 01:01:01.000002", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=46:58:57.999998", output.get(0));

// case3: TIMEDIFF('00:00:00','00:00:01')
output = processor.transform("00:00:00|00:00:01", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=-00:00:01", output.get(0));

// case4: TIMEDIFF('23:59:59.000001','01:01:01.000002')
output = processor.transform("23:59:59|01:01:01.000002", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=22:58:57.999998", output.get(0));

// case5: TIMEDIFF('2008-12-31 23:59:59.000001','01:01:01.000002')
output = processor.transform("2008-12-31 23:59:59|01:01:01.000002", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=", output.get(0));

// case6: TIMEDIFF('2008-12-31 23:59:59.000001','0001-12-31 01:01:01.000002')
output = processor.transform("2008-12-31 23:59:59|0001-12-31 01:01:01.000002", new HashMap<>());
Assert.assertEquals(1, output.size());
Assert.assertEquals("result=", output.get(0));
}
}

0 comments on commit e300cee

Please sign in to comment.