org.apache.calcite.util.Static Java Examples

The following examples show how to use org.apache.calcite.util.Static. 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: PigRelBuilder.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Scans a table with its given schema and names.
 *
 * @param userSchema The schema of the table to scan
 * @param tableNames The names of the table to scan
 * @return This builder
 */
public RelBuilder scan(RelOptTable userSchema, String... tableNames) {
  // First, look up the database schema to find the table schema with the given names
  final List<String> names = ImmutableList.copyOf(tableNames);
  final RelOptTable systemSchema = relOptSchema.getTableForMember(names);

  // Now we may end up with two different schemas.
  if (systemSchema != null) {
    if (userSchema != null && !compatibleType(userSchema.getRowType(),
        systemSchema.getRowType())) {
      // If both schemas are valid, they must be compatible
      throw new IllegalArgumentException(
          "Pig script schema does not match database schema for table " + names + ".\n"
              + "\t Scrip schema: " + userSchema.getRowType().getFullTypeString() + "\n"
              + "\t Database schema: " + systemSchema.getRowType().getFullTypeString());
    }
    // We choose to use systemSchema if it is valid
    return scan(systemSchema);
  } else if (userSchema != null) {
    // If systemSchema is not valid, use userSchema if it is valid
    return scan(userSchema);
  } else {
    // At least one of them needs to be valid
    throw Static.RESOURCE.tableNotFound(String.join(".", names)).ex();
  }
}
 
Example #2
Source File: ResultSetEnumerable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Enumerator<T> enumeratorBasedOnStatement() {
  Connection connection = null;
  Statement statement = null;
  try {
    connection = dataSource.getConnection();
    statement = connection.createStatement();
    setTimeoutIfPossible(statement);
    if (statement.execute(sql)) {
      final ResultSet resultSet = statement.getResultSet();
      statement = null;
      connection = null;
      return new ResultSetEnumerator<>(resultSet, rowBuilderFactory);
    } else {
      Integer updateCount = statement.getUpdateCount();
      return Linq4j.singletonEnumerator((T) updateCount);
    }
  } catch (SQLException e) {
    throw Static.RESOURCE.exceptionWhilePerformingQueryOnJdbcSubSchema(sql)
        .ex(e);
  } finally {
    closeIfPossible(connection, statement);
  }
}
 
Example #3
Source File: ResultSetEnumerable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Enumerator<T> enumeratorBasedOnPreparedStatement() {
  Connection connection = null;
  PreparedStatement preparedStatement = null;
  try {
    connection = dataSource.getConnection();
    preparedStatement = connection.prepareStatement(sql);
    setTimeoutIfPossible(preparedStatement);
    preparedStatementEnricher.enrich(preparedStatement);
    if (preparedStatement.execute()) {
      final ResultSet resultSet = preparedStatement.getResultSet();
      preparedStatement = null;
      connection = null;
      return new ResultSetEnumerator<>(resultSet, rowBuilderFactory);
    } else {
      Integer updateCount = preparedStatement.getUpdateCount();
      return Linq4j.singletonEnumerator((T) updateCount);
    }
  } catch (SQLException e) {
    throw Static.RESOURCE.exceptionWhilePerformingQueryOnJdbcSubSchema(sql)
        .ex(e);
  } finally {
    closeIfPossible(connection, preparedStatement);
  }
}
 
Example #4
Source File: ResultSetEnumerable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private void setTimeoutIfPossible(Statement statement) throws SQLException {
  if (timeout == 0) {
    return;
  }
  long now = System.currentTimeMillis();
  long secondsLeft = (queryStart + timeout - now) / 1000;
  if (secondsLeft <= 0) {
    throw Static.RESOURCE.queryExecutionTimeoutReached(
        String.valueOf(timeout),
        String.valueOf(Instant.ofEpochMilli(queryStart))).ex();
  }
  if (secondsLeft > Integer.MAX_VALUE) {
    // Just ignore the timeout if it happens to be too big, we can't squeeze it into int
    return;
  }
  try {
    statement.setQueryTimeout((int) secondsLeft);
  } catch (SQLFeatureNotSupportedException e) {
    if (!timeoutSetFailed && LOGGER.isDebugEnabled()) {
      // We don't really want to print this again and again if enumerable is used multiple times
      LOGGER.debug("Failed to set query timeout " + secondsLeft + " seconds", e);
      timeoutSetFailed = true;
    }
  }
}
 
Example #5
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example #6
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example #7
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void validateLiteral(SqlLiteral literal) {
	if (literal.getTypeName() == DECIMAL) {
		final BigDecimal decimal = literal.getValueAs(BigDecimal.class);
		if (decimal.precision() > DecimalType.MAX_PRECISION) {
			throw newValidationError(
				literal,
				Static.RESOURCE.numberLiteralOutOfRange(decimal.toString()));
		}
	}
	super.validateLiteral(literal);
}
 
Example #8
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override public SqlNode visit(SqlCall call) {
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();
	List<SqlNode> newOperands = new ArrayList<>();

	// This code is a workaround for CALCITE-2707
	if (call.getFunctionQuantifier() != null
		&& call.getFunctionQuantifier().getValue() == SqlSelectKeyword.DISTINCT) {
		final SqlParserPos pos = call.getParserPosition();
		throw SqlUtil.newContextException(pos, Static.RESOURCE.functionQuantifierNotAllowed(call.toString()));
	}
	// This code is a workaround for CALCITE-2707

	if (isLogicalNavigation(kind) || isPhysicalNavigation(kind)) {
		SqlNode inner = operands.get(0);
		SqlNode offset = operands.get(1);

		// merge two straight prev/next, update offset
		if (isPhysicalNavigation(kind)) {
			SqlKind innerKind = inner.getKind();
			if (isPhysicalNavigation(innerKind)) {
				List<SqlNode> innerOperands = ((SqlCall) inner).getOperandList();
				SqlNode innerOffset = innerOperands.get(1);
				SqlOperator newOperator = innerKind == kind
					? SqlStdOperatorTable.PLUS : SqlStdOperatorTable.MINUS;
				offset = newOperator.createCall(SqlParserPos.ZERO,
					offset, innerOffset);
				inner = call.getOperator().createCall(SqlParserPos.ZERO,
					innerOperands.get(0), offset);
			}
		}
		SqlNode newInnerNode =
			inner.accept(new NavigationExpander(call.getOperator(), offset));
		if (op != null) {
			newInnerNode = op.createCall(SqlParserPos.ZERO, newInnerNode,
				this.offset);
		}
		return newInnerNode;
	}

	if (operands.size() > 0) {
		for (SqlNode node : operands) {
			if (node != null) {
				SqlNode newNode = node.accept(new NavigationExpander());
				if (op != null) {
					newNode = op.createCall(SqlParserPos.ZERO, newNode, offset);
				}
				newOperands.add(newNode);
			} else {
				newOperands.add(null);
			}
		}
		return call.getOperator().createCall(SqlParserPos.ZERO, newOperands);
	} else {
		if (op == null) {
			return call;
		} else {
			return op.createCall(SqlParserPos.ZERO, call, offset);
		}
	}
}
 
Example #9
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override public Set<String> visit(SqlCall call) {
	boolean isSingle = false;
	Set<String> vars = new HashSet<>();
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();

	if (isSingleVarRequired(kind)) {
		isSingle = true;
		if (isPhysicalNavigation(kind)) {
			if (isMeasure) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionInMeasure(call.toString()));
			}
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			prevNextCount++;
		} else if (isLogicalNavigation(kind)) {
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			firstLastCount++;
		} else if (isAggregation(kind)) {
			// cannot apply aggregation in PREV/NEXT, FIRST/LAST
			if (firstLastCount != 0 || prevNextCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternAggregationInNavigation(call.toString()));
			}
			if (kind == SqlKind.COUNT && call.getOperandList().size() > 1) {
				throw newValidationError(call,
					Static.RESOURCE.patternCountFunctionArg());
			}
			aggregateCount++;
		}
	}

	if (isRunningOrFinal(kind) && !isMeasure) {
		throw newValidationError(call,
			Static.RESOURCE.patternRunningFunctionInDefine(call.toString()));
	}

	for (SqlNode node : operands) {
		if (node != null) {
			vars.addAll(
				node.accept(
					new PatternValidator(isMeasure, firstLastCount, prevNextCount,
						aggregateCount)));
		}
	}

	if (isSingle) {
		switch (kind) {
			case COUNT:
				if (vars.size() > 1) {
					throw newValidationError(call,
						Static.RESOURCE.patternCountFunctionArg());
				}
				break;
			default:
				if (operands.size() == 0
					|| !(operands.get(0) instanceof SqlCall)
					|| ((SqlCall) operands.get(0)).getOperator() != SqlStdOperatorTable.CLASSIFIER) {
					if (vars.isEmpty()) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionNullCheck(call.toString()));
					}
					if (vars.size() != 1) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionVariableCheck(call.toString()));
					}
				}
				break;
		}
	}
	return vars;
}
 
Example #10
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public void validateQuery(SqlNode node, SqlValidatorScope scope,
	RelDataType targetRowType) {
	final SqlValidatorNamespace ns = getNamespace(node, scope);
	if (node.getKind() == SqlKind.TABLESAMPLE) {
		List<SqlNode> operands = ((SqlCall) node).getOperandList();
		SqlSampleSpec sampleSpec = SqlLiteral.sampleValue(operands.get(1));
		if (sampleSpec instanceof SqlSampleSpec.SqlTableSampleSpec) {
			validateFeature(RESOURCE.sQLFeature_T613(), node.getParserPosition());
		} else if (sampleSpec
			instanceof SqlSampleSpec.SqlSubstitutionSampleSpec) {
			validateFeature(RESOURCE.sQLFeatureExt_T613_Substitution(),
				node.getParserPosition());
		}
	}

	validateNamespace(ns, targetRowType);
	switch (node.getKind()) {
		case EXTEND:
			// Until we have a dedicated namespace for EXTEND
			deriveType(scope, node);
	}
	if (node == top) {
		validateModality(node);
	}
	validateAccess(
		node,
		ns.getTable(),
		SqlAccessEnum.SELECT);

	if (node.getKind() == SqlKind.SNAPSHOT) {
		SqlSnapshot snapshot = (SqlSnapshot) node;
		SqlNode period = snapshot.getPeriod();
		RelDataType dataType = deriveType(scope, period);
		if (dataType.getSqlTypeName() != SqlTypeName.TIMESTAMP) {
			throw newValidationError(period,
					Static.RESOURCE.illegalExpressionForTemporal(dataType.getSqlTypeName().getName()));
		}
		if (!ns.getTable().isTemporal()) {
			List<String> qualifiedName = ns.getTable().getQualifiedName();
			String tableName = qualifiedName.get(qualifiedName.size() - 1);
			throw newValidationError(snapshot.getTableRef(),
					Static.RESOURCE.notTemporalTable(tableName));
		}
	}
}
 
Example #11
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override public SqlNode visit(SqlCall call) {
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();
	List<SqlNode> newOperands = new ArrayList<>();

	// This code is a workaround for CALCITE-2707
	if (call.getFunctionQuantifier() != null
		&& call.getFunctionQuantifier().getValue() == SqlSelectKeyword.DISTINCT) {
		final SqlParserPos pos = call.getParserPosition();
		throw SqlUtil.newContextException(pos, Static.RESOURCE.functionQuantifierNotAllowed(call.toString()));
	}
	// This code is a workaround for CALCITE-2707

	if (isLogicalNavigation(kind) || isPhysicalNavigation(kind)) {
		SqlNode inner = operands.get(0);
		SqlNode offset = operands.get(1);

		// merge two straight prev/next, update offset
		if (isPhysicalNavigation(kind)) {
			SqlKind innerKind = inner.getKind();
			if (isPhysicalNavigation(innerKind)) {
				List<SqlNode> innerOperands = ((SqlCall) inner).getOperandList();
				SqlNode innerOffset = innerOperands.get(1);
				SqlOperator newOperator = innerKind == kind
					? SqlStdOperatorTable.PLUS : SqlStdOperatorTable.MINUS;
				offset = newOperator.createCall(SqlParserPos.ZERO,
					offset, innerOffset);
				inner = call.getOperator().createCall(SqlParserPos.ZERO,
					innerOperands.get(0), offset);
			}
		}
		SqlNode newInnerNode =
			inner.accept(new NavigationExpander(call.getOperator(), offset));
		if (op != null) {
			newInnerNode = op.createCall(SqlParserPos.ZERO, newInnerNode,
				this.offset);
		}
		return newInnerNode;
	}

	if (operands.size() > 0) {
		for (SqlNode node : operands) {
			if (node != null) {
				SqlNode newNode = node.accept(new NavigationExpander());
				if (op != null) {
					newNode = op.createCall(SqlParserPos.ZERO, newNode, offset);
				}
				newOperands.add(newNode);
			} else {
				newOperands.add(null);
			}
		}
		return call.getOperator().createCall(SqlParserPos.ZERO, newOperands);
	} else {
		if (op == null) {
			return call;
		} else {
			return op.createCall(SqlParserPos.ZERO, call, offset);
		}
	}
}
 
Example #12
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override public Set<String> visit(SqlCall call) {
	boolean isSingle = false;
	Set<String> vars = new HashSet<>();
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();

	if (isSingleVarRequired(kind)) {
		isSingle = true;
		if (isPhysicalNavigation(kind)) {
			if (isMeasure) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionInMeasure(call.toString()));
			}
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			prevNextCount++;
		} else if (isLogicalNavigation(kind)) {
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			firstLastCount++;
		} else if (isAggregation(kind)) {
			// cannot apply aggregation in PREV/NEXT, FIRST/LAST
			if (firstLastCount != 0 || prevNextCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternAggregationInNavigation(call.toString()));
			}
			if (kind == SqlKind.COUNT && call.getOperandList().size() > 1) {
				throw newValidationError(call,
					Static.RESOURCE.patternCountFunctionArg());
			}
			aggregateCount++;
		}
	}

	if (isRunningOrFinal(kind) && !isMeasure) {
		throw newValidationError(call,
			Static.RESOURCE.patternRunningFunctionInDefine(call.toString()));
	}

	for (SqlNode node : operands) {
		if (node != null) {
			vars.addAll(
				node.accept(
					new PatternValidator(isMeasure, firstLastCount, prevNextCount,
						aggregateCount)));
		}
	}

	if (isSingle) {
		switch (kind) {
			case COUNT:
				if (vars.size() > 1) {
					throw newValidationError(call,
						Static.RESOURCE.patternCountFunctionArg());
				}
				break;
			default:
				if (operands.size() == 0
					|| !(operands.get(0) instanceof SqlCall)
					|| ((SqlCall) operands.get(0)).getOperator() != SqlStdOperatorTable.CLASSIFIER) {
					if (vars.isEmpty()) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionNullCheck(call.toString()));
					}
					if (vars.size() != 1) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionVariableCheck(call.toString()));
					}
				}
				break;
		}
	}
	return vars;
}