org.apache.calcite.sql.SqlUtil Java Examples

The following examples show how to use org.apache.calcite.sql.SqlUtil. 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 File: Lattice.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void populateAliases(SqlNode from, List<String> aliases,
    String current) {
  if (from instanceof SqlJoin) {
    SqlJoin join = (SqlJoin) from;
    populateAliases(join.getLeft(), aliases, null);
    populateAliases(join.getRight(), aliases, null);
  } else if (from.getKind() == SqlKind.AS) {
    populateAliases(SqlUtil.stripAs(from), aliases,
        SqlValidatorUtil.getAlias(from, -1));
  } else {
    if (current == null) {
      current = SqlValidatorUtil.getAlias(from, -1);
    }
    aliases.add(current);
  }
}
 
Example #2
Source File: OracleSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(OracleSqlOperatorTable.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #3
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
public static SqlTimestampLiteral parseTimestampLiteral(String s,
    SqlParserPos pos) {
  final String dateStr = parseString(s);
  final DateTimeUtils.PrecisionTime pt =
      DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
          Format.PER_THREAD.get().timestamp, DateTimeUtils.UTC_ZONE, -1);
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIMESTAMP", s,
            RESOURCE.badFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING).str()));
  }
  final TimestampString ts =
      TimestampString.fromCalendarFields(pt.getCalendar())
          .withFraction(pt.getFraction());
  return SqlLiteral.createTimestamp(ts, pt.getPrecision(), pos);
}
 
Example #4
Source File: SqlValidatorUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Derives an alias for a node, and invents a mangled identifier if it
 * cannot.
 *
 * <p>Examples:
 *
 * <ul>
 * <li>Alias: "1 + 2 as foo" yields "foo"
 * <li>Identifier: "foo.bar.baz" yields "baz"
 * <li>Anything else yields "expr$<i>ordinal</i>"
 * </ul>
 *
 * @return An alias, if one can be derived; or a synthetic alias
 * "expr$<i>ordinal</i>" if ordinal &lt; 0; otherwise null
 */
public static String getAlias(SqlNode node, int ordinal) {
  switch (node.getKind()) {
  case AS:
    // E.g. "1 + 2 as foo" --> "foo"
    return ((SqlCall) node).operand(1).toString();

  case OVER:
    // E.g. "bids over w" --> "bids"
    return getAlias(((SqlCall) node).operand(0), ordinal);

  case IDENTIFIER:
    // E.g. "foo.bar" --> "bar"
    return Util.last(((SqlIdentifier) node).names);

  default:
    if (ordinal < 0) {
      return null;
    } else {
      return SqlUtil.deriveAliasFromOrdinal(ordinal);
    }
  }
}
 
Example #5
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static SqlTimestampLiteral parseTimestampLiteral(String s,
    SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Format format = Format.PER_THREAD.get();
  DateTimeUtils.PrecisionTime pt = null;
  // Allow timestamp literals with and without time fields (as does
  // PostgreSQL); TODO: require time fields except in Babel's lenient mode
  final DateFormat[] dateFormats = {format.timestamp, format.date};
  for (DateFormat dateFormat : dateFormats) {
    pt = DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
        dateFormat, DateTimeUtils.UTC_ZONE, -1);
    if (pt != null) {
      break;
    }
  }
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIMESTAMP", s,
            RESOURCE.badFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING).str()));
  }
  final TimestampString ts =
      TimestampString.fromCalendarFields(pt.getCalendar())
          .withFraction(pt.getFraction());
  return SqlLiteral.createTimestamp(ts, pt.getPrecision(), pos);
}
 
Example #6
Source File: MssqlSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    if (call.operandCount() != 3) {
      throw new IllegalArgumentException("MSSQL SUBSTRING requires FROM and FOR arguments");
    }
    SqlUtil.unparseFunctionSyntax(MSSQL_SUBSTRING, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }
      unparseFloor(writer, call);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #7
Source File: SqlFloorFunction.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Most dialects that natively support datetime floor will use this.
 * In those cases the call will look like TRUNC(datetime, 'year').
 *
 * @param writer SqlWriter
 * @param call SqlCall
 * @param funName Name of the sql function to call
 * @param datetimeFirst Specify the order of the datetime &amp; timeUnit
 * arguments
 */
public static void unparseDatetimeFunction(SqlWriter writer, SqlCall call,
    String funName, Boolean datetimeFirst) {
  SqlFunction func = new SqlFunction(funName, SqlKind.OTHER_FUNCTION,
      ReturnTypes.ARG0_NULLABLE_VARYING, null, null,
      SqlFunctionCategory.STRING);

  SqlCall call1;
  if (datetimeFirst) {
    call1 = call;
  } else {
    // switch order of operands
    SqlNode op1 = call.operand(0);
    SqlNode op2 = call.operand(1);

    call1 = call.getOperator().createCall(call.getParserPosition(), op2, op1);
  }

  SqlUtil.unparseFunctionSyntax(func, writer, call1);
}
 
Example #8
Source File: SqlSubstringFunction.java    From Bats with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(String opName) {
  StringBuilder ret = new StringBuilder();
  for (Ord<SqlTypeName> typeName : Ord.zip(SqlTypeName.STRING_TYPES)) {
    if (typeName.i > 0) {
      ret.append(NL);
    }
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER)));
    ret.append(NL);
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER,
                SqlTypeName.INTEGER)));
  }
  return ret.toString();
}
 
Example #9
Source File: OracleSqlDialect.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(SqlLibraryOperators.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #10
Source File: SqlValidatorUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Derives an alias for a node, and invents a mangled identifier if it
 * cannot.
 *
 * <p>Examples:
 *
 * <ul>
 * <li>Alias: "1 + 2 as foo" yields "foo"
 * <li>Identifier: "foo.bar.baz" yields "baz"
 * <li>Anything else yields "expr$<i>ordinal</i>"
 * </ul>
 *
 * @return An alias, if one can be derived; or a synthetic alias
 * "expr$<i>ordinal</i>" if ordinal &lt; 0; otherwise null
 */
public static String getAlias(SqlNode node, int ordinal) {
  switch (node.getKind()) {
  case AS:
    // E.g. "1 + 2 as foo" --> "foo"
    return ((SqlCall) node).operand(1).toString();

  case OVER:
    // E.g. "bids over w" --> "bids"
    return getAlias(((SqlCall) node).operand(0), ordinal);

  case IDENTIFIER:
    // E.g. "foo.bar" --> "bar"
    return Util.last(((SqlIdentifier) node).names);

  default:
    if (ordinal < 0) {
      return null;
    } else {
      return SqlUtil.deriveAliasFromOrdinal(ordinal);
    }
  }
}
 
Example #11
Source File: SqlRowOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
public RelDataType inferReturnType(
    final SqlOperatorBinding opBinding) {
  // The type of a ROW(e1,e2) expression is a record with the types
  // {e1type,e2type}.  According to the standard, field names are
  // implementation-defined.
  return opBinding.getTypeFactory().createStructType(
      new AbstractList<Map.Entry<String, RelDataType>>() {
        public Map.Entry<String, RelDataType> get(int index) {
          return Pair.of(
              SqlUtil.deriveAliasFromOrdinal(index),
              opBinding.getOperandType(index));
        }

        public int size() {
          return opBinding.getOperandCount();
        }
      });
}
 
Example #12
Source File: SqlOperatorBindingTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests {@link org.apache.calcite.sql.SqlUtil#isLiteral(SqlNode, boolean)},
 * which was added to enhance Calcite's public API
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1219">[CALCITE-1219]
 * Add a method to SqlOperatorBinding to determine whether operand is a
 * literal</a>.
 */
@Test void testSqlNodeLiteral() {
  final SqlNode literal = SqlLiteral.createExactNumeric(
      "0",
      SqlParserPos.ZERO);
  final SqlNode castLiteral = SqlStdOperatorTable.CAST.createCall(
      SqlParserPos.ZERO,
      literal,
      integerType);
  final SqlNode castCastLiteral = SqlStdOperatorTable.CAST.createCall(
      SqlParserPos.ZERO,
      castLiteral,
      integerType);

  // SqlLiteral is considered as a Literal
  assertSame(true, SqlUtil.isLiteral(literal, true));
  // CAST(SqlLiteral as type) is considered as a Literal
  assertSame(true, SqlUtil.isLiteral(castLiteral, true));
  // CAST(CAST(SqlLiteral as type) as type) is NOT considered as a Literal
  assertSame(false, SqlUtil.isLiteral(castCastLiteral, true));
}
 
Example #13
Source File: SqlOverlapsOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(String opName) {
  final String d = "DATETIME";
  final String i = "INTERVAL";
  String[] typeNames = {
      d, d,
      d, i,
      i, d,
      i, i
  };

  StringBuilder ret = new StringBuilder();
  for (int y = 0; y < typeNames.length; y += 2) {
    if (y > 0) {
      ret.append(NL);
    }
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(d, typeNames[y], d, typeNames[y + 1])));
  }
  return ret.toString();
}
 
Example #14
Source File: Lattice.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void populateAliases(SqlNode from, List<String> aliases,
    @Nullable String current) {
  if (from instanceof SqlJoin) {
    SqlJoin join = (SqlJoin) from;
    populateAliases(join.getLeft(), aliases, null);
    populateAliases(join.getRight(), aliases, null);
  } else if (from.getKind() == SqlKind.AS) {
    populateAliases(SqlUtil.stripAs(from), aliases,
        SqlValidatorUtil.getAlias(from, -1));
  } else {
    if (current == null) {
      current = SqlValidatorUtil.getAlias(from, -1);
    }
    aliases.add(current);
  }
}
 
Example #15
Source File: MssqlSqlDialect.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    if (call.operandCount() != 3) {
      throw new IllegalArgumentException("MSSQL SUBSTRING requires FROM and FOR arguments");
    }
    SqlUtil.unparseFunctionSyntax(MSSQL_SUBSTRING, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }
      unparseFloor(writer, call);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #16
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateJoin(SqlJoin join, SqlValidatorScope scope) {
	// Due to the improper translation of lateral table left outer join in Calcite, we need to
	// temporarily forbid the common predicates until the problem is fixed (see FLINK-7865).
	if (join.getJoinType() == JoinType.LEFT &&
			SqlUtil.stripAs(join.getRight()).getKind() == SqlKind.COLLECTION_TABLE) {
		final SqlNode condition = join.getCondition();
		if (condition != null &&
				(!SqlUtil.isLiteral(condition) || ((SqlLiteral) condition).getValueAs(Boolean.class) != Boolean.TRUE)) {
			throw new ValidationException(
				String.format(
					"Left outer joins with a table function do not accept a predicate such as %s. " +
					"Only literal TRUE is accepted.",
					condition));
		}
	}
	super.validateJoin(join, scope);
}
 
Example #17
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateJoin(SqlJoin join, SqlValidatorScope scope) {
	// Due to the improper translation of lateral table left outer join in Calcite, we need to
	// temporarily forbid the common predicates until the problem is fixed (see FLINK-7865).
	if (join.getJoinType() == JoinType.LEFT &&
			SqlUtil.stripAs(join.getRight()).getKind() == SqlKind.COLLECTION_TABLE) {
		final SqlNode condition = join.getCondition();
		if (condition != null &&
				(!SqlUtil.isLiteral(condition) || ((SqlLiteral) condition).getValueAs(Boolean.class) != Boolean.TRUE)) {
			throw new ValidationException(
				String.format(
					"Left outer joins with a table function do not accept a predicate such as %s. " +
					"Only literal TRUE is accepted.",
					condition));
		}
	}
	super.validateJoin(join, scope);
}
 
Example #18
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the SELECT statement that putatively feeds rows into an UPDATE
 * statement to be updated.
 *
 * @param call Call to the UPDATE operator
 * @return select statement
 */
protected SqlSelect createSourceSelectForUpdate(SqlUpdate call) {
	final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
	selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));
	int ordinal = 0;
	for (SqlNode exp : call.getSourceExpressionList()) {
		// Force unique aliases to avoid a duplicate for Y with
		// SET X=Y
		String alias = SqlUtil.deriveAliasFromOrdinal(ordinal);
		selectList.add(SqlValidatorUtil.addAlias(exp, alias));
		++ordinal;
	}
	SqlNode sourceTable = call.getTargetTable();
	if (call.getAlias() != null) {
		sourceTable =
			SqlValidatorUtil.addAlias(
				sourceTable,
				call.getAlias().getSimple());
	}
	return new SqlSelect(SqlParserPos.ZERO, null, selectList, sourceTable,
		call.getCondition(), null, null, null, null, null, null);
}
 
Example #19
Source File: SqlRowOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
public RelDataType inferReturnType(
    final SqlOperatorBinding opBinding) {
  // The type of a ROW(e1,e2) expression is a record with the types
  // {e1type,e2type}.  According to the standard, field names are
  // implementation-defined.
  return opBinding.getTypeFactory().createStructType(
      new AbstractList<Map.Entry<String, RelDataType>>() {
        public Map.Entry<String, RelDataType> get(int index) {
          return Pair.of(
              SqlUtil.deriveAliasFromOrdinal(index),
              opBinding.getOperandType(index));
        }

        public int size() {
          return opBinding.getOperandCount();
        }
      });
}
 
Example #20
Source File: SqlSubstringFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(String opName) {
  StringBuilder ret = new StringBuilder();
  for (Ord<SqlTypeName> typeName : Ord.zip(SqlTypeName.STRING_TYPES)) {
    if (typeName.i > 0) {
      ret.append(NL);
    }
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER)));
    ret.append(NL);
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(typeName.e, SqlTypeName.INTEGER,
                SqlTypeName.INTEGER)));
  }
  return ret.toString();
}
 
Example #21
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the SELECT statement that putatively feeds rows into an UPDATE
 * statement to be updated.
 *
 * @param call Call to the UPDATE operator
 * @return select statement
 */
protected SqlSelect createSourceSelectForUpdate(SqlUpdate call) {
	final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
	selectList.add(SqlIdentifier.star(SqlParserPos.ZERO));
	int ordinal = 0;
	for (SqlNode exp : call.getSourceExpressionList()) {
		// Force unique aliases to avoid a duplicate for Y with
		// SET X=Y
		String alias = SqlUtil.deriveAliasFromOrdinal(ordinal);
		selectList.add(SqlValidatorUtil.addAlias(exp, alias));
		++ordinal;
	}
	SqlNode sourceTable = call.getTargetTable();
	if (call.getAlias() != null) {
		sourceTable =
			SqlValidatorUtil.addAlias(
				sourceTable,
				call.getAlias().getSimple());
	}
	return new SqlSelect(SqlParserPos.ZERO, null, selectList, sourceTable,
		call.getCondition(), null, null, null, null, null, null);
}
 
Example #22
Source File: SqlOverlapsOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
public String getAllowedSignatures(String opName) {
  final String d = "DATETIME";
  final String i = "INTERVAL";
  String[] typeNames = {
      d, d,
      d, i,
      i, d,
      i, i
  };

  StringBuilder ret = new StringBuilder();
  for (int y = 0; y < typeNames.length; y += 2) {
    if (y > 0) {
      ret.append(NL);
    }
    ret.append(
        SqlUtil.getAliasedSignature(this, opName,
            ImmutableList.of(d, typeNames[y], d, typeNames[y + 1])));
  }
  return ret.toString();
}
 
Example #23
Source File: SqlDropTableExtension.java    From kareldb with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CalcitePrepare.Context context) {
    final List<String> path = context.getDefaultSchemaPath();
    CalciteSchema schema = context.getRootSchema();
    for (String p : path) {
        schema = schema.getSubSchema(p, true);
    }

    final Pair<CalciteSchema, String> pair =
        SqlDdlNodes.schema(context, true, name);
    switch (getKind()) {
        case DROP_TABLE:
            Schema schemaPlus = schema.plus().unwrap(Schema.class);
            boolean existed = schemaPlus.dropTable(name.getSimple());
            pair.left.removeTable(name.getSimple());
            if (!existed && !ifExists) {
                throw SqlUtil.newContextException(name.getParserPosition(),
                    RESOURCE.tableNotFound(name.getSimple()));
            }
            break;
        default:
            throw new AssertionError(getKind());
    }
}
 
Example #24
Source File: SqlFloorFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Most dialects that natively support datetime floor will use this.
 * In those cases the call will look like TRUNC(datetime, 'year').
 *
 * @param writer SqlWriter
 * @param call SqlCall
 * @param funName Name of the sql function to call
 * @param datetimeFirst Specify the order of the datetime &amp; timeUnit
 * arguments
 */
public static void unparseDatetimeFunction(SqlWriter writer, SqlCall call,
    String funName, Boolean datetimeFirst) {
  SqlFunction func = new SqlFunction(funName, SqlKind.OTHER_FUNCTION,
      ReturnTypes.ARG0_NULLABLE_VARYING, null, null,
      SqlFunctionCategory.STRING);

  SqlCall call1;
  if (datetimeFirst) {
    call1 = call;
  } else {
    // switch order of operands
    SqlNode op1 = call.operand(0);
    SqlNode op2 = call.operand(1);

    call1 = call.getOperator().createCall(call.getParserPosition(), op2, op1);
  }

  SqlUtil.unparseFunctionSyntax(func, writer, call1);
}
 
Example #25
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Executes a {@code CREATE VIEW} command. */
public void execute(SqlCreateView create,
    CalcitePrepare.Context context) {
  final Pair<CalciteSchema, String> pair =
      schema(context, true, create.name);
  final SchemaPlus schemaPlus = pair.left.plus();
  for (Function function : schemaPlus.getFunctions(pair.right)) {
    if (function.getParameters().isEmpty()) {
      if (!create.getReplace()) {
        throw SqlUtil.newContextException(create.name.getParserPosition(),
            RESOURCE.viewExists(pair.right));
      }
      pair.left.removeFunction(pair.right);
    }
  }
  final SqlNode q = renameColumns(create.columnList, create.query);
  final String sql = q.toSqlString(CalciteSqlDialect.DEFAULT).getSql();
  final ViewTableMacro viewTableMacro =
      ViewTable.viewMacro(schemaPlus, sql, pair.left.path(null),
          context.getObjectPath(), false);
  final TranslatableTable x = viewTableMacro.apply(ImmutableList.of());
  Util.discard(x);
  schemaPlus.add(pair.right, viewTableMacro);
}
 
Example #26
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Project e) {
  e.getVariablesSet();
  Result x = visitChild(0, e.getInput());
  parseCorrelTable(e, x);
  if (isStar(e.getProjects(), e.getInput().getRowType(), e.getRowType())) {
    return x;
  }
  final Builder builder =
      x.builder(e, Clause.SELECT);
  final List<SqlNode> selectList = new ArrayList<>();
  for (RexNode ref : e.getProjects()) {
    SqlNode sqlExpr = builder.context.toSql(null, ref);
    if (SqlUtil.isNullLiteral(sqlExpr, false)) {
      sqlExpr = castNullType(sqlExpr, e.getRowType().getFieldList().get(selectList.size()));
    }
    addSelect(selectList, sqlExpr, e.getRowType());
  }

  builder.setSelect(new SqlNodeList(selectList, POS));
  return builder.result();
}
 
Example #27
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static SqlIntervalLiteral parseIntervalLiteral(SqlParserPos pos,
    int sign, String s, SqlIntervalQualifier intervalQualifier) {
  final String intervalStr = parseString(s);
  if (intervalStr.equals("")) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalIntervalLiteral(s + " "
            + intervalQualifier.toString(), pos.toString()));
  }
  return SqlLiteral.createInterval(sign, intervalStr, intervalQualifier, pos);
}
 
Example #28
Source File: SqlToOperationConverter.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Convert insert into statement. */
private Operation convertSqlInsert(RichSqlInsert insert) {
	// Get sink table name.
	List<String> targetTablePath = ((SqlIdentifier) insert.getTargetTableID()).names;
	// Get sink table hints.
	HintStrategyTable hintStrategyTable = flinkPlanner.config()
			.getSqlToRelConverterConfig()
			.getHintStrategyTable();
	List<RelHint> tableHints = SqlUtil.getRelHint(hintStrategyTable, insert.getTableHints());
	Map<String, String> dynamicOptions = FlinkHints.getHintedOptions(tableHints);

	UnresolvedIdentifier unresolvedIdentifier = UnresolvedIdentifier.of(targetTablePath);
	ObjectIdentifier identifier = catalogManager.qualifyIdentifier(unresolvedIdentifier);

	PlannerQueryOperation query = (PlannerQueryOperation) SqlToOperationConverter.convert(
		flinkPlanner,
		catalogManager,
		insert.getSource())
		.orElseThrow(() -> new TableException(
			"Unsupported node type " + insert.getSource().getClass().getSimpleName()));

	return new CatalogSinkModifyOperation(
		identifier,
		query,
		insert.getStaticPartitionKVs(),
		insert.isOverwrite(),
		dynamicOptions);
}
 
Example #29
Source File: DremioArgChecker.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private boolean checkOp(Checker checker, SqlCallBinding callBinding, SqlNode node, int iFormalOperand,
    boolean throwOnFailure) {

  if (SqlUtil.isNullLiteral(node, false)) {
    if (throwOnFailure) {
      throw callBinding.getValidator().newValidationError(node,
          RESOURCE.nullIllegal());
    } else {
      return false;
    }
  }
  RelDataType type = callBinding.getValidator().deriveType(callBinding.getScope(), node);
  SqlTypeName typeName = type.getSqlTypeName();

  // Pass type checking for operators if it's of type 'ANY'.
  if (typeName.getFamily() == SqlTypeFamily.ANY && allowAny) {
    return true;
  }

  if (!checker.check(type)) {
    if (throwOnFailure) {
      throw callBinding.newValidationSignatureError();
    }
    return false;
  }
  return true;
}
 
Example #30
Source File: SameOperandTypeExceptLastOperandChecker.java    From calcite with Apache License 2.0 5 votes vote down vote up
public String getAllowedSignatures(SqlOperator op, String opName) {
  final String typeName = getTypeName();
  if (nOperands == -1) {
    return SqlUtil.getAliasedSignature(op, opName,
        ImmutableList.of(typeName, typeName, "..."));
  } else {
    List<String> types = Collections.nCopies(nOperands - 1, typeName);
    types.add(lastOperandTypeName);
    return SqlUtil.getAliasedSignature(op, opName, types);
  }
}