Java Code Examples for org.apache.calcite.sql.fun.SqlTrimFunction

The following examples show how to use org.apache.calcite.sql.fun.SqlTrimFunction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: flink   Source File: RexNodeConverter.java    License: Apache License 2.0 6 votes vote down vote up
private RexNode convertTrim(List<Expression> children) {
	ValueLiteralExpression removeLeadingExpr = (ValueLiteralExpression) children.get(0);
	Boolean removeLeading = extractValue(removeLeadingExpr, Boolean.class);
	ValueLiteralExpression removeTrailingExpr = (ValueLiteralExpression) children.get(1);
	Boolean removeTrailing = extractValue(removeTrailingExpr, Boolean.class);
	RexNode trimString = children.get(2).accept(this);
	RexNode str = children.get(3).accept(this);
	Enum trimMode;
	if (removeLeading && removeTrailing) {
		trimMode = SqlTrimFunction.Flag.BOTH;
	} else if (removeLeading) {
		trimMode = SqlTrimFunction.Flag.LEADING;
	} else if (removeTrailing) {
		trimMode = SqlTrimFunction.Flag.TRAILING;
	} else {
		throw new IllegalArgumentException("Unsupported trim mode.");
	}
	return relBuilder.call(
			FlinkSqlOperatorTable.TRIM,
			relBuilder.getRexBuilder().makeFlag(trimMode),
			trimString,
			str);
}
 
Example 2
Source Project: dremio-oss   Source File: TrimFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FunctionRender render(FunctionRenderer renderer, RexCall call) {
  checkArity(call, 3);

  RexNode op0 = call.getOperands().get(0);
  if (op0 instanceof RexLiteral) {
    final FunctionRender trimChar = call.getOperands().get(1).accept(renderer.getVisitor());
    final FunctionRender inputStr = call.getOperands().get(2).accept(renderer.getVisitor());
    if (TRIM_CHAR.equals(trimChar.getScript())) {
      if (((RexLiteral) op0).getValue() == SqlTrimFunction.Flag.BOTH) {
        return new FunctionRender(inputStr.getScript() + ".trim()", inputStr.getNulls());
      }
    }
  }
  throw new UnsupportedOperationException("incorrect arguments for trim function");
}
 
Example 3
Source Project: flink   Source File: CustomizedConvertRule.java    License: Apache License 2.0 6 votes vote down vote up
private static RexNode convertTrim(CallExpression call, ConvertContext context) {
	checkArgumentNumber(call, 4);
	List<Expression> children = call.getChildren();
	ValueLiteralExpression removeLeadingExpr = (ValueLiteralExpression) children.get(0);
	Boolean removeLeading = extractValue(removeLeadingExpr, Boolean.class);
	ValueLiteralExpression removeTrailingExpr = (ValueLiteralExpression) children.get(1);
	Boolean removeTrailing = extractValue(removeTrailingExpr, Boolean.class);
	RexNode trimString = context.toRexNode(children.get(2));
	RexNode str = context.toRexNode(children.get(3));
	Enum trimMode;
	if (removeLeading && removeTrailing) {
		trimMode = SqlTrimFunction.Flag.BOTH;
	} else if (removeLeading) {
		trimMode = SqlTrimFunction.Flag.LEADING;
	} else if (removeTrailing) {
		trimMode = SqlTrimFunction.Flag.TRAILING;
	} else {
		throw new IllegalArgumentException("Unsupported trim mode.");
	}
	return context.getRelBuilder().call(
		FlinkSqlOperatorTable.TRIM,
		context.getRelBuilder().getRexBuilder().makeFlag(trimMode),
		trimString,
		str);
}
 
Example 4
Source Project: calcite   Source File: RexImpTable.java    License: Apache License 2.0 6 votes vote down vote up
@Override Expression implementSafe(final RexToLixTranslator translator,
    final RexCall call, final List<Expression> argValueList) {
  final boolean strict = !translator.conformance.allowExtendedTrim();
  final Object value = translator.getLiteralValue(argValueList.get(0));
  SqlTrimFunction.Flag flag = (SqlTrimFunction.Flag) value;
  return Expressions.call(
      BuiltInMethod.TRIM.method,
      Expressions.constant(
          flag == SqlTrimFunction.Flag.BOTH
          || flag == SqlTrimFunction.Flag.LEADING),
      Expressions.constant(
          flag == SqlTrimFunction.Flag.BOTH
          || flag == SqlTrimFunction.Flag.TRAILING),
      argValueList.get(1),
      argValueList.get(2),
      Expressions.constant(strict));
}
 
Example 5
Source Project: calcite   Source File: RelToSqlConverterUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Unparses TRIM function with value as space.
 *
 * <p>For example :
 *
 * <blockquote><pre>
 * SELECT TRIM(both ' ' from "ABC") &rarr; SELECT TRIM(ABC)
 * </pre></blockquote>
 *
 * @param writer writer
 * @param call the call
 */
private static void unparseTrimWithSpace(
    SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
  final String operatorName;
  final SqlLiteral trimFlag = call.operand(0);
  switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
  case LEADING:
    operatorName = "LTRIM";
    break;
  case TRAILING:
    operatorName = "RTRIM";
    break;
  default:
    operatorName = call.getOperator().getName();
    break;
  }
  final SqlWriter.Frame trimFrame = writer.startFunCall(operatorName);
  call.operand(2).unparse(writer, leftPrec, rightPrec);
  writer.endFunCall(trimFrame);
}
 
Example 6
Source Project: calcite   Source File: RelToSqlConverterUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates regex pattern based on the TRIM flag.
 *
 * @param call     SqlCall contains the values that need to be trimmed
 * @param trimFlag the trimFlag, either BOTH, LEADING or TRAILING
 * @return the regex pattern of the character to be trimmed
 */
public static SqlCharStringLiteral createRegexPatternLiteral(SqlNode call, SqlLiteral trimFlag) {
  final String regexPattern = ((SqlCharStringLiteral) call).toValue();
  String escaped = escapeSpecialChar(regexPattern);
  final StringBuilder builder = new StringBuilder();
  switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
  case LEADING:
    builder.append("^(").append(escaped).append(")*");
    break;
  case TRAILING:
    builder.append("(").append(escaped).append(")*$");
    break;
  default:
    builder.append("^(")
        .append(escaped)
        .append(")*|(")
        .append(escaped)
        .append(")*$");
    break;
  }
  return SqlLiteral.createCharString(builder.toString(),
    call.getParserPosition());
}
 
Example 7
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testTrim() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder b = RelBuilder.create(config);
  final RelNode rel =
      b.scan("EMP")
          .project(
              b.alias(
                  b.call(SqlStdOperatorTable.TRIM,
                      b.literal(SqlTrimFunction.Flag.BOTH),
                      b.literal(" "),
                      b.field("ENAME")),
                  "trimmed_ename"))
          .build();

  RelJsonWriter jsonWriter = new RelJsonWriter();
  rel.explain(jsonWriter);
  String relJson = jsonWriter.asString();
  final RelOptSchema schema = getSchema(rel);
  final String s = deserializeAndDumpToTextFormat(schema, relJson);
  final String expected = ""
      + "LogicalProject(trimmed_ename=[TRIM(FLAG(BOTH), ' ', $1)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 8
Source Project: calcite   Source File: SqlJdbcFunctionCall.java    License: Apache License 2.0 5 votes vote down vote up
private MakeCall trim(SqlTrimFunction.Flag flag) {
  return new SimpleMakeCall(SqlStdOperatorTable.TRIM) {
    @Override public SqlCall createCall(SqlParserPos pos,
        SqlNode... operands) {
      assert 1 == operands.length;
      return super.createCall(pos, flag.symbol(pos),
          SqlLiteral.createCharString(" ", SqlParserPos.ZERO),
          operands[0]);
    }
  };
}
 
Example 9
Source Project: calcite   Source File: BigQuerySqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * For usage of TRIM, LTRIM and RTRIM in BQ see
 * <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#trim">
 *  BQ Trim Function</a>.
 */
private void unparseTrim(SqlWriter writer, SqlCall call, int leftPrec,
    int rightPrec) {
  final String operatorName;
  SqlLiteral trimFlag = call.operand(0);
  SqlLiteral valueToTrim = call.operand(1);
  switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
  case LEADING:
    operatorName = "LTRIM";
    break;
  case TRAILING:
    operatorName = "RTRIM";
    break;
  default:
    operatorName = call.getOperator().getName();
    break;
  }
  final SqlWriter.Frame trimFrame = writer.startFunCall(operatorName);
  call.operand(2).unparse(writer, leftPrec, rightPrec);

  // If the trimmed character is a non-space character, add it to the target SQL.
  // eg: TRIM(BOTH 'A' from 'ABCD'
  // Output Query: TRIM('ABC', 'A')
  if (!valueToTrim.toValue().matches("\\s+")) {
    writer.literal(",");
    call.operand(1).unparse(writer, leftPrec, rightPrec);
  }
  writer.endFunCall(trimFrame);
}
 
Example 10
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 4 votes vote down vote up
TrimConvertlet(SqlTrimFunction.Flag flag) {
  this.flag = flag;
}
 
Example 11
Source Project: calcite   Source File: StandardConvertletTable.java    License: Apache License 2.0 4 votes vote down vote up
TrimConvertlet(SqlTrimFunction.Flag flag) {
  this.flag = flag;
}