use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.
the class SqlValidatorImpl method validateMatchRecognize.
@Override
public void validateMatchRecognize(SqlCall call) {
final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call;
final MatchRecognizeScope scope = (MatchRecognizeScope) getMatchRecognizeScope(matchRecognize);
final MatchRecognizeNamespace ns = getNamespace(call).unwrap(MatchRecognizeNamespace.class);
assert ns.rowType == null;
// rows per match
final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch();
final boolean allRows = rowsPerMatch != null && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS;
final RelDataTypeFactory.Builder typeBuilder = typeFactory.builder();
// parse PARTITION BY column
SqlNodeList partitionBy = matchRecognize.getPartitionList();
if (partitionBy != null) {
for (SqlNode node : partitionBy) {
SqlIdentifier identifier = (SqlIdentifier) node;
identifier.validate(this, scope);
RelDataType type = deriveType(scope, identifier);
String name = identifier.names.get(1);
typeBuilder.add(name, type);
}
}
// parse ORDER BY column
SqlNodeList orderBy = matchRecognize.getOrderList();
if (orderBy != null) {
for (SqlNode node : orderBy) {
node.validate(this, scope);
SqlIdentifier identifier = null;
if (node instanceof SqlBasicCall) {
identifier = (SqlIdentifier) ((SqlBasicCall) node).getOperands()[0];
} else {
identifier = (SqlIdentifier) node;
}
if (allRows) {
RelDataType type = deriveType(scope, identifier);
String name = identifier.names.get(1);
if (!typeBuilder.nameExists(name)) {
typeBuilder.add(name, type);
}
}
}
}
if (allRows) {
final SqlValidatorNamespace sqlNs = getNamespace(matchRecognize.getTableRef());
final RelDataType inputDataType = sqlNs.getRowType();
for (RelDataTypeField fs : inputDataType.getFieldList()) {
if (!typeBuilder.nameExists(fs.getName())) {
typeBuilder.add(fs);
}
}
}
// retrieve pattern variables used in pattern and subset
SqlNode pattern = matchRecognize.getPattern();
PatternVarVisitor visitor = new PatternVarVisitor(scope);
pattern.accept(visitor);
SqlLiteral interval = matchRecognize.getInterval();
if (interval != null) {
interval.validate(this, scope);
if (((SqlIntervalLiteral) interval).signum() < 0) {
throw newValidationError(interval, RESOURCE.intervalMustBeNonNegative(interval.toValue()));
}
if (orderBy == null || orderBy.size() == 0) {
throw newValidationError(interval, RESOURCE.cannotUseWithinWithoutOrderBy());
}
SqlNode firstOrderByColumn = orderBy.getList().get(0);
SqlIdentifier identifier;
if (firstOrderByColumn instanceof SqlBasicCall) {
identifier = (SqlIdentifier) ((SqlBasicCall) firstOrderByColumn).getOperands()[0];
} else {
identifier = (SqlIdentifier) firstOrderByColumn;
}
RelDataType firstOrderByColumnType = deriveType(scope, identifier);
if (firstOrderByColumnType.getSqlTypeName() != SqlTypeName.TIMESTAMP) {
throw newValidationError(interval, RESOURCE.firstColumnOfOrderByMustBeTimestamp());
}
SqlNode expand = expand(interval, scope);
RelDataType type = deriveType(scope, expand);
setValidatedNodeType(interval, type);
}
validateDefinitions(matchRecognize, scope);
SqlNodeList subsets = matchRecognize.getSubsetList();
if (subsets != null && subsets.size() > 0) {
for (SqlNode node : subsets) {
List<SqlNode> operands = ((SqlCall) node).getOperandList();
String leftString = ((SqlIdentifier) operands.get(0)).getSimple();
if (scope.getPatternVars().contains(leftString)) {
throw newValidationError(operands.get(0), RESOURCE.patternVarAlreadyDefined(leftString));
}
scope.addPatternVar(leftString);
for (SqlNode right : (SqlNodeList) operands.get(1)) {
SqlIdentifier id = (SqlIdentifier) right;
if (!scope.getPatternVars().contains(id.getSimple())) {
throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple()));
}
scope.addPatternVar(id.getSimple());
}
}
}
// validate AFTER ... SKIP TO
final SqlNode skipTo = matchRecognize.getAfter();
if (skipTo instanceof SqlCall) {
final SqlCall skipToCall = (SqlCall) skipTo;
final SqlIdentifier id = skipToCall.operand(0);
if (!scope.getPatternVars().contains(id.getSimple())) {
throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple()));
}
}
List<Map.Entry<String, RelDataType>> measureColumns = validateMeasure(matchRecognize, scope, allRows);
for (Map.Entry<String, RelDataType> c : measureColumns) {
if (!typeBuilder.nameExists(c.getKey())) {
typeBuilder.add(c.getKey(), c.getValue());
}
}
final RelDataType rowType = typeBuilder.build();
if (matchRecognize.getMeasureList().size() == 0) {
ns.setType(getNamespace(matchRecognize.getTableRef()).getRowType());
} else {
ns.setType(rowType);
}
}
use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.
the class SqlUserDefinedTableMacro method getValue.
private static Object getValue(SqlNode right) throws NonLiteralException {
switch(right.getKind()) {
case ARRAY_VALUE_CONSTRUCTOR:
final List<Object> list = Lists.newArrayList();
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) {
// currently NULL is the only default value
return null;
}
throw new NonLiteralException();
}
}
use of org.apache.calcite.sql.SqlLiteral in project drill by apache.
the class ExplainHandler method rewrite.
@Override
public SqlNode rewrite(SqlNode sqlNode) throws RelConversionException, ForemanSetupException {
SqlExplain node = unwrap(sqlNode, SqlExplain.class);
SqlLiteral op = node.operand(2);
SqlExplain.Depth depth = (SqlExplain.Depth) op.getValue();
if (node.getDetailLevel() != null) {
level = node.getDetailLevel();
}
switch(depth) {
case LOGICAL:
mode = ResultMode.LOGICAL;
break;
case PHYSICAL:
mode = ResultMode.PHYSICAL;
break;
default:
throw new UnsupportedOperationException("Unknown depth " + depth);
}
return node.operand(0);
}
use of org.apache.calcite.sql.SqlLiteral in project drill by apache.
the class RefreshMetadataHandler method getPlan.
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ForemanSetupException {
final SqlRefreshMetadata refreshTable = unwrap(sqlNode, SqlRefreshMetadata.class);
try {
final SchemaPlus schema = findSchema(config.getConverter().getDefaultSchema(), refreshTable.getSchemaPath());
if (schema == null) {
return direct(false, "Storage plugin or workspace does not exist [%s]", SchemaUtilites.SCHEMA_PATH_JOINER.join(refreshTable.getSchemaPath()));
}
final String tableName = refreshTable.getName();
final SqlNodeList columnList = getColumnList(refreshTable);
final Set<SchemaPath> columnSet = getColumnRootSegments(columnList);
final SqlLiteral allColumns = refreshTable.getAllColumns();
if (tableName.contains("*") || tableName.contains("?")) {
return direct(false, "Glob path %s not supported for metadata refresh", tableName);
}
final Table table = schema.getTable(tableName);
if (table == null) {
return direct(false, "Table %s does not exist.", tableName);
}
if (!(table instanceof DrillTable)) {
return notSupported(tableName);
}
final DrillTable drillTable = (DrillTable) table;
final Object selection = drillTable.getSelection();
if (selection instanceof FileSelection && ((FileSelection) selection).isEmptyDirectory()) {
return direct(false, "Table %s is empty and doesn't contain any parquet files.", tableName);
}
if (!(selection instanceof FormatSelection)) {
return notSupported(tableName);
}
final FormatSelection formatSelection = (FormatSelection) selection;
FormatPluginConfig formatConfig = formatSelection.getFormat();
if (!((formatConfig instanceof ParquetFormatConfig) || ((formatConfig instanceof NamedFormatPluginConfig) && ((NamedFormatPluginConfig) formatConfig).getName().equals("parquet")))) {
return notSupported(tableName);
}
// Always create filesystem object using process user, since it owns the metadata file
final DrillFileSystem fs = ImpersonationUtil.createFileSystem(ImpersonationUtil.getProcessUserName(), drillTable.getPlugin().getFormatPlugin(formatConfig).getFsConf());
final Path selectionRoot = formatSelection.getSelection().getSelectionRoot();
if (!fs.getFileStatus(selectionRoot).isDirectory()) {
return notSupported(tableName);
}
if (!(formatConfig instanceof ParquetFormatConfig)) {
formatConfig = new ParquetFormatConfig();
}
final ParquetReaderConfig readerConfig = ParquetReaderConfig.builder().withFormatConfig((ParquetFormatConfig) formatConfig).withOptions(context.getOptions()).build();
Metadata.createMeta(fs, selectionRoot, readerConfig, allColumns.booleanValue(), columnSet);
return direct(true, "Successfully updated metadata for table %s.", tableName);
} catch (Exception e) {
logger.error("Failed to update metadata for table '{}'", refreshTable.getName(), e);
return DirectPlan.createDirectPlan(context, false, String.format("Error: %s", e.getMessage()));
}
}
use of org.apache.calcite.sql.SqlLiteral in project drill by apache.
the class DropAllAliasesHandler method getPlan.
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ForemanSetupException, IOException {
checkAliasesEnabled();
SqlDropAllAliases node = unwrap(sqlNode, SqlDropAllAliases.class);
String aliasTarget = ((SqlLiteral) node.getAliasKind()).toValue();
AliasRegistry aliasRegistry = getAliasRegistry(aliasTarget);
boolean isPublicAlias = ((SqlLiteral) node.getIsPublic()).booleanValue();
if (isPublicAlias) {
deletePublicAliases(node.getUser(), aliasRegistry);
} else {
deleteUserAliases(node.getUser(), aliasRegistry);
}
return DirectPlan.createDirectPlan(context, true, String.format("%s aliases dropped successfully", StringUtils.capitalize(aliasTarget.toLowerCase(Locale.ROOT))));
}
Aggregations