Refine search
@Test public void testPosition() { assertExpression("position('a' in 'b')", new FunctionCall(QualifiedName.of("strpos"), ImmutableList.of( new StringLiteral("b"), new StringLiteral("a")))); assertExpression("position('a' in ('b'))", new FunctionCall(QualifiedName.of("strpos"), ImmutableList.of( new StringLiteral("b"), new StringLiteral("a")))); }
@Override public Node visitInterval(SqlBaseParser.IntervalContext context) { return new IntervalLiteral( getLocation(context), ((StringLiteral) visit(context.string())).getValue(), Optional.ofNullable(context.sign) .map(AstBuilder::getIntervalSign) .orElse(IntervalLiteral.Sign.POSITIVE), getIntervalFieldType((Token) context.from.getChild(0).getPayload()), Optional.ofNullable(context.to) .map((x) -> x.getChild(0).getPayload()) .map(Token.class::cast) .map(AstBuilder::getIntervalFieldType)); }
private Regex getConstantPattern(LikePredicate node) { Regex result = likePatternCache.get(node); if (result == null) { StringLiteral pattern = (StringLiteral) node.getPattern(); if (node.getEscape().isPresent()) { Slice escape = ((StringLiteral) node.getEscape().get()).getSlice(); result = LikeFunctions.likePattern(pattern.getSlice(), escape); } else { result = LikeFunctions.likePattern(pattern.getSlice()); } likePatternCache.put(node, result); } return result; }
@Override protected Node visitShowSchemas(ShowSchemas node, Void context) { if (!node.getCatalog().isPresent() && !session.getCatalog().isPresent()) { throw new SemanticException(CATALOG_NOT_SPECIFIED, node, "Catalog must be specified when session catalog is not set"); } String catalog = node.getCatalog().map(Identifier::getValue).orElseGet(() -> session.getCatalog().get()); accessControl.checkCanShowSchemas(session.getRequiredTransactionId(), session.getIdentity(), catalog); Optional<Expression> predicate = Optional.empty(); Optional<String> likePattern = node.getLikePattern(); if (likePattern.isPresent()) { predicate = Optional.of(new LikePredicate( identifier("schema_name"), new StringLiteral(likePattern.get()), node.getEscape().map(StringLiteral::new))); } return simpleQuery( selectList(aliasedName("schema_name", "Schema")), from(catalog, TABLE_SCHEMATA), predicate, Optional.of(ordering(ascending("schema_name")))); }
@Override public Node visitNormalize(SqlBaseParser.NormalizeContext context) { Expression str = (Expression) visit(context.valueExpression()); String normalForm = Optional.ofNullable(context.normalForm()).map(ParserRuleContext::getText).orElse("NFC"); return new FunctionCall(getLocation(context), QualifiedName.of("normalize"), ImmutableList.of(str, new StringLiteral(getLocation(context), normalForm))); }
@Override protected Node visitShowCatalogs(ShowCatalogs node, Void context) { List<Expression> rows = listCatalogs(session, metadata, accessControl).keySet().stream() .map(name -> row(new StringLiteral(name))) .collect(toList()); Optional<Expression> predicate = Optional.empty(); Optional<String> likePattern = node.getLikePattern(); if (likePattern.isPresent()) { predicate = Optional.of(new LikePredicate(identifier("Catalog"), new StringLiteral(likePattern.get()), Optional.empty())); } return simpleQuery( selectList(new AllColumns()), aliased(new Values(rows), "catalogs", ImmutableList.of("Catalog")), predicate, Optional.of(ordering(ascending("Catalog")))); }
private static Row createDescribeOutputRow(Field field, Analysis analysis) { LongLiteral typeSize = new LongLiteral("0"); if (field.getType() instanceof FixedWidthType) { typeSize = new LongLiteral(String.valueOf(((FixedWidthType) field.getType()).getFixedSize())); } String columnName; if (field.getName().isPresent()) { columnName = field.getName().get(); } else { int columnIndex = ImmutableList.copyOf(analysis.getOutputDescriptor().getVisibleFields()).indexOf(field); columnName = "_col" + columnIndex; } Optional<QualifiedObjectName> originTable = field.getOriginTable(); return row( new StringLiteral(columnName), new StringLiteral(originTable.map(QualifiedObjectName::getCatalogName).orElse("")), new StringLiteral(originTable.map(QualifiedObjectName::getSchemaName).orElse("")), new StringLiteral(originTable.map(QualifiedObjectName::getObjectName).orElse("")), new StringLiteral(field.getType().getDisplayName()), typeSize, new BooleanLiteral(String.valueOf(field.isAliased()))); }
@Override protected Node visitShowGrants(ShowGrants showGrants, Void context) String catalogName = session.getCatalog().orElse(null); Optional<Expression> predicate = Optional.empty(); if (tableName.isPresent()) { QualifiedObjectName qualifiedTableName = createQualifiedObjectName(session, showGrants, tableName.get()); new CatalogSchemaName(catalogName, qualifiedTableName.getSchemaName())); predicate = Optional.of(equal(identifier("table_name"), new StringLiteral(qualifiedTableName.getObjectName())));
@Override public Node visitColumnDefinition(SqlBaseParser.ColumnDefinitionContext context) { Optional<String> comment = Optional.empty(); if (context.COMMENT() != null) { comment = Optional.of(((StringLiteral) visit(context.string())).getValue()); } List<Property> properties = ImmutableList.of(); if (context.properties() != null) { properties = visit(context.properties().property(), Property.class); } return new ColumnDefinition( getLocation(context), (Identifier) visit(context.identifier()), getType(context.type()), properties, comment); }
@Override protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate( identifier("table_name"), new StringLiteral(likePattern.get()), showTables.getEscape().map(StringLiteral::new)); predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }
private static PlanNode addPartitioningNodes(Context context, PlanNode node, Symbol partitionSymbol, KdbTree kdbTree, Expression geometry, Optional<Expression> radius) { Assignments.Builder projections = Assignments.builder(); for (Symbol outputSymbol : node.getOutputSymbols()) { projections.putIdentity(outputSymbol); } ImmutableList.Builder<Expression> partitioningArguments = ImmutableList.<Expression>builder() .add(new Cast(new StringLiteral(KdbTreeUtils.toJson(kdbTree)), KDB_TREE_TYPENAME)) .add(geometry); radius.map(partitioningArguments::add); FunctionCall partitioningFunction = new FunctionCall(QualifiedName.of("spatial_partitions"), partitioningArguments.build()); Symbol partitionsSymbol = context.getSymbolAllocator().newSymbol(partitioningFunction, new ArrayType(INTEGER)); projections.put(partitionsSymbol, partitioningFunction); return new UnnestNode( context.getIdAllocator().getNextId(), new ProjectNode(context.getIdAllocator().getNextId(), node, projections.build()), node.getOutputSymbols(), ImmutableMap.of(partitionsSymbol, ImmutableList.of(partitionSymbol)), Optional.empty()); }
@Test public void testExecuteWithUsing() { assertStatement("EXECUTE myquery USING 1, 'abc', ARRAY ['hello']", new Execute(identifier("myquery"), ImmutableList.of(new LongLiteral("1"), new StringLiteral("abc"), new ArrayConstructor(ImmutableList.of(new StringLiteral("hello")))))); }
@Test public void testAtTimeZone() { assertStatement("SELECT timestamp '2012-10-31 01:00 UTC' AT TIME ZONE 'America/Los_Angeles'", new Query( Optional.empty(), new QuerySpecification( selectList( new AtTimeZone(new TimestampLiteral("2012-10-31 01:00 UTC"), new StringLiteral("America/Los_Angeles"))), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()), Optional.empty(), Optional.empty())); }
private Row createColumnStatsRow(String columnName, Type type, ColumnStatistics columnStatistics) { ImmutableList.Builder<Expression> rowValues = ImmutableList.builder(); rowValues.add(new StringLiteral(columnName)); rowValues.add(createEstimateRepresentation(columnStatistics.getDataSize())); rowValues.add(createEstimateRepresentation(columnStatistics.getDistinctValuesCount())); rowValues.add(createEstimateRepresentation(columnStatistics.getNullsFraction())); rowValues.add(NULL_DOUBLE); rowValues.add(toStringLiteral(type, columnStatistics.getRange().map(DoubleRange::getMin))); rowValues.add(toStringLiteral(type, columnStatistics.getRange().map(DoubleRange::getMax))); return new Row(rowValues.build()); }
@Override protected Node visitShowColumns(ShowColumns showColumns, Void context) { QualifiedObjectName tableName = createQualifiedObjectName(session, showColumns, showColumns.getTable()); if (!metadata.getView(session, tableName).isPresent() && !metadata.getTableHandle(session, tableName).isPresent()) { throw new SemanticException(MISSING_TABLE, showColumns, "Table '%s' does not exist", tableName); } return simpleQuery( selectList( aliasedName("column_name", "Column"), aliasedName("data_type", "Type"), aliasedNullToEmpty("extra_info", "Extra"), aliasedNullToEmpty("comment", "Comment")), from(tableName.getCatalogName(), TABLE_COLUMNS), logicalAnd( equal(identifier("table_schema"), new StringLiteral(tableName.getSchemaName())), equal(identifier("table_name"), new StringLiteral(tableName.getObjectName()))), ordering(ascending("ordinal_position"))); }
private static void assertLike(byte[] value, String pattern, boolean expected) { Expression predicate = new LikePredicate( rawStringLiteral(Slices.wrappedBuffer(value)), new StringLiteral(pattern), Optional.empty()); assertEquals(evaluate(predicate), expected); }
ImmutableList.Builder<Expression> rows = ImmutableList.builder(); SortedMap<String, ConnectorId> catalogNames = listCatalogs(session, metadata, accessControl); List<SessionPropertyValue> sessionProperties = metadata.getSessionPropertyManager().getAllSessionProperties(session, catalogNames); String defaultValue = sessionProperty.getDefaultValue(); rows.add(row( new StringLiteral(sessionProperty.getFullyQualifiedName()), new StringLiteral(nullToEmpty(value)), new StringLiteral(nullToEmpty(defaultValue)), new StringLiteral(sessionProperty.getType()), new StringLiteral(sessionProperty.getDescription()), TRUE_LITERAL)); rows.add(row(new StringLiteral(""), new StringLiteral(""), new StringLiteral(""), new StringLiteral(""), new StringLiteral(""), FALSE_LITERAL)); new Values(rows.build()), "session", ImmutableList.of("name", "value", "default", "type", "description", "include")), identifier("include"));
private static Expression createFailureFunction(RuntimeException exception, Type type) { requireNonNull(exception, "Exception is null"); String failureInfo = JsonCodec.jsonCodec(FailureInfo.class).toJson(Failures.toFailure(exception).toFailureInfo()); FunctionCall jsonParse = new FunctionCall(QualifiedName.of("json_parse"), ImmutableList.of(new StringLiteral(failureInfo))); FunctionCall failureFunction = new FunctionCall(QualifiedName.of("fail"), ImmutableList.of(jsonParse)); return new Cast(failureFunction, type.getTypeSignature().toString()); }
@Override protected Node visitShowFunctions(ShowFunctions node, Void context) ImmutableList.Builder<Expression> rows = ImmutableList.builder(); for (SqlFunction function : metadata.listFunctions()) { rows.add(row( new StringLiteral(function.getSignature().getName()), new StringLiteral(function.getSignature().getReturnType().toString()), new StringLiteral(Joiner.on(", ").join(function.getSignature().getArgumentTypes())), new StringLiteral(getFunctionType(function)), function.isDeterministic() ? TRUE_LITERAL : FALSE_LITERAL, new StringLiteral(nullToEmpty(function.getDescription())))); selectAll(columns.entrySet().stream() .map(entry -> aliasedName(entry.getKey(), entry.getValue())) .collect(toImmutableList())), aliased(new Values(rows.build()), "functions", ImmutableList.copyOf(columns.keySet())), ordering( new SortItem(
public static Query singleValueQuery(String columnName, String value) { Relation values = values(row(new StringLiteral((value)))); return simpleQuery( selectList(new AllColumns()), aliased(values, "t", ImmutableList.of(columnName))); }