Java Code Examples for org.apache.calcite.sql.SqlUtil

The following examples show how to use org.apache.calcite.sql.SqlUtil. 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: Bats   Source File: Lattice.java    License: 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 Project: Bats   Source File: SqlParserUtil.java    License: 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 3
Source Project: Bats   Source File: SqlValidatorUtil.java    License: 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 4
Source Project: Bats   Source File: OracleSqlDialect.java    License: 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 5
Source Project: Bats   Source File: MssqlSqlDialect.java    License: 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 6
Source Project: Bats   Source File: SqlFloorFunction.java    License: 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 7
Source Project: Bats   Source File: SqlSubstringFunction.java    License: 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 8
Source Project: Bats   Source File: SqlRowOperator.java    License: 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 9
Source Project: calcite   Source File: SqlOperatorBindingTest.java    License: 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 10
Source Project: Bats   Source File: SqlOverlapsOperator.java    License: 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 11
Source Project: kareldb   Source File: SqlDropTableExtension.java    License: 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 12
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 13
Source Project: flink   Source File: SqlValidatorImpl.java    License: 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 14
Source Project: flink   Source File: FlinkCalciteSqlValidator.java    License: 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 15
Source Project: flink   Source File: FlinkCalciteSqlValidator.java    License: 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 16
Source Project: calcite   Source File: ServerDdlExecutor.java    License: 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 17
Source Project: calcite   Source File: Lattice.java    License: 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 18
Source Project: calcite   Source File: RelToSqlConverter.java    License: 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 19
Source Project: calcite   Source File: SqlParserUtil.java    License: 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 20
Source Project: calcite   Source File: SqlValidatorUtil.java    License: 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 21
Source Project: calcite   Source File: OracleSqlDialect.java    License: 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 22
Source Project: calcite   Source File: MssqlSqlDialect.java    License: 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 23
Source Project: calcite   Source File: SqlFloorFunction.java    License: 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 24
Source Project: calcite   Source File: SqlSubstringFunction.java    License: 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 25
Source Project: calcite   Source File: SqlRowOperator.java    License: 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 26
Source Project: calcite   Source File: SqlOverlapsOperator.java    License: 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 27
Source Project: Bats   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlDateLiteral parseDateLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Calendar cal =
      DateTimeUtils.parseDateFormat(dateStr, Format.PER_THREAD.get().date,
          DateTimeUtils.UTC_ZONE);
  if (cal == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("DATE", s,
            RESOURCE.badFormat(DateTimeUtils.DATE_FORMAT_STRING).str()));
  }
  final DateString d = DateString.fromCalendarFields(cal);
  return SqlLiteral.createDate(d, pos);
}
 
Example 28
Source Project: Bats   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlTimeLiteral parseTimeLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final DateTimeUtils.PrecisionTime pt =
      DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
          Format.PER_THREAD.get().time, DateTimeUtils.UTC_ZONE, -1);
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIME", s,
            RESOURCE.badFormat(DateTimeUtils.TIME_FORMAT_STRING).str()));
  }
  final TimeString t = TimeString.fromCalendarFields(pt.getCalendar())
      .withFraction(pt.getFraction());
  return SqlLiteral.createTime(t, pt.getPrecision(), pos);
}
 
Example 29
Source Project: Bats   Source File: SqlParserUtil.java    License: 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 30
Source Project: Bats   Source File: SqlUserDefinedTableMacro.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getValue(SqlNode right) throws NonLiteralException {
  switch (right.getKind()) {
  case ARRAY_VALUE_CONSTRUCTOR:
    final List<Object> list = new ArrayList<>();
    for (SqlNode o : ((SqlCall) right).getOperandList()) {
      list.add(getValue(o));
    }
    return ImmutableNullableList.copyOf(list);
  case MAP_VALUE_CONSTRUCTOR:
    final ImmutableMap.Builder<Object, Object> builder2 =
        ImmutableMap.builder();
    final List<SqlNode> operands = ((SqlCall) right).getOperandList();
    for (int i = 0; i < operands.size(); i += 2) {
      final SqlNode key = operands.get(i);
      final SqlNode value = operands.get(i + 1);
      builder2.put(getValue(key), getValue(value));
    }
    return builder2.build();
  default:
    if (SqlUtil.isNullLiteral(right, true)) {
      return null;
    }
    if (SqlUtil.isLiteral(right)) {
      return ((SqlLiteral) right).getValue();
    }
    if (right.getKind() == SqlKind.DEFAULT) {
      return null; // currently NULL is the only default value
    }
    throw new NonLiteralException();
  }
}