本文将分享com.facebook.presto.sql.tree.Extract的实例源码的详细内容,此外,我们还将为大家带来关于com.facebook.presto.sql.tree.Array
本文将分享com.facebook.presto.sql.tree.Extract的实例源码的详细内容,此外,我们还将为大家带来关于com.facebook.presto.sql.tree.ArrayConstructor的实例源码、com.facebook.presto.sql.tree.BooleanLiteral的实例源码、com.facebook.presto.sql.tree.Cast的实例源码、com.facebook.presto.sql.tree.CoalesceExpression的实例源码的相关知识,希望对你有所帮助。
本文目录一览:- com.facebook.presto.sql.tree.Extract的实例源码
- com.facebook.presto.sql.tree.ArrayConstructor的实例源码
- com.facebook.presto.sql.tree.BooleanLiteral的实例源码
- com.facebook.presto.sql.tree.Cast的实例源码
- com.facebook.presto.sql.tree.CoalesceExpression的实例源码
com.facebook.presto.sql.tree.Extract的实例源码
@Override public Expression rewriteExtract(Extract node,Void context,ExpressionTreeRewriter<Void> treeRewriter) { Expression value = treeRewriter.rewrite(node.getExpression(),context); switch (node.getField()) { case YEAR: return new FunctionCall(new Qualifiedname("year"),ImmutableList.of(value)); case QUARTER: return new FunctionCall(new Qualifiedname("quarter"),ImmutableList.of(value)); case MONTH: return new FunctionCall(new Qualifiedname("month"),ImmutableList.of(value)); case WEEK: return new FunctionCall(new Qualifiedname("week"),ImmutableList.of(value)); case DAY: case DAY_OF_MONTH: return new FunctionCall(new Qualifiedname("day"),ImmutableList.of(value)); case DAY_OF_WEEK: case DOW: return new FunctionCall(new Qualifiedname("day_of_week"),ImmutableList.of(value)); case DAY_OF_YEAR: case DOY: return new FunctionCall(new Qualifiedname("day_of_year"),ImmutableList.of(value)); case YEAR_OF_WEEK: case YOW: return new FunctionCall(new Qualifiedname("year_of_week"),ImmutableList.of(value)); case HOUR: return new FunctionCall(new Qualifiedname("hour"),ImmutableList.of(value)); case MINUTE: return new FunctionCall(new Qualifiedname("minute"),ImmutableList.of(value)); case SECOND: return new FunctionCall(new Qualifiedname("second"),ImmutableList.of(value)); case TIMEZONE_MINUTE: return new FunctionCall(new Qualifiedname("timezone_minute"),ImmutableList.of(value)); case TIMEZONE_HOUR: return new FunctionCall(new Qualifiedname("timezone_hour"),ImmutableList.of(value)); } throw new UnsupportedOperationException("not yet implemented: " + node.getField()); }
@Override protected Type visitExtract(Extract node,StackableAstVisitorContext<AnalysisContext> context) { Type type = process(node.getExpression(),context); if (!isDateTimeType(type)) { throw new SemanticException(TYPE_MISMATCH,node.getExpression(),"Type of argument to extract must be DATE,TIME,TIMESTAMP,or INTERVAL (actual %s)",type); } Extract.Field field = node.getField(); if ((field == TIMEZONE_HOUR || field == TIMEZONE_MINUTE) && !(type.equals(TIME_WITH_TIME_ZONE) || type.equals(TIMESTAMP_WITH_TIME_ZONE))) { throw new SemanticException(TYPE_MISMATCH,"Type of argument to extract time zone field must have a time zone (actual %s)",type); } expressionTypes.put(node,BIGINT); return BIGINT; }
@Override protected String visitExtract(Extract node,Void context) { return "EXTRACT(" + node.getField() + " FROM " + process(node.getExpression(),context) + ")"; }
@Override protected String visitExtract(Extract node,StackableAstVisitorContext<Integer> indent) { return "EXTRACT(" + node.getField() + " FROM " + process(node.getExpression(),indent) + ")"; }
@Override protected Boolean visitExtract(Extract node,Void context) { return process(node.getExpression(),context); }
@Override public Node visitExtract(sqlbaseParser.ExtractContext context) { return new Extract(getLocation(context),(Expression) visit(context.valueExpression()),Extract.Field.valueOf(context.identifier().getText().toupperCase())); }
@Override protected String visitExtract(Extract node,Boolean unmangleNames) { return "EXTRACT(" + node.getField() + " FROM " + process(node.getExpression(),unmangleNames) + ")"; }
@Override protected String visitExtract(Extract node,unmangleNames) + ")"; }
com.facebook.presto.sql.tree.ArrayConstructor的实例源码
@Override protected Object visitArrayConstructor(ArrayConstructor node,Object context) { Type elementType = ((ArrayType) expressionTypes.get(node)).getElementType(); BlockBuilder arrayBlockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(),node.getValues().size()); for (Expression expression : node.getValues()) { Object value = process(expression,context); if (value instanceof Expression) { return visitFunctionCall(new FunctionCall(Qualifiedname.of(ArrayConstructor.ARRAY_CONSTRUCTOR),node.getValues()),context); } writeNativeValue(elementType,arrayBlockBuilder,value); } return arrayBlockBuilder.build(); }
@Test public void testArraySubscript() throws Exception { assertExpression("ARRAY [1,2][1]",new SubscriptExpression( new ArrayConstructor(ImmutableList.<Expression>of(new LongLiteral("1"),new LongLiteral("2"))),new LongLiteral("1")) ); try { assertExpression("CASE WHEN TRUE THEN ARRAY[1,2] END[1]",null); fail(); } catch (RuntimeException e) { // Expected } }
@Override protected String visitArrayConstructor(ArrayConstructor node,Void context) { ImmutableList.Builder<String> valueStrings = ImmutableList.builder(); for (Expression value : node.getValues()) { valueStrings.add(sqlFormatter.formatsql(value)); } return "ARRAY[" + Joiner.on(",").join(valueStrings.build()) + "]"; }
@Override protected String visitArrayConstructor(ArrayConstructor node,StackableAstVisitorContext<Integer> indent) { ImmutableList.Builder<String> valueStrings = ImmutableList.builder(); for (Expression value : node.getValues()) { valueStrings.add(formatExpression(value,parameters,indent.getContext() + 1)); } return "ARRAY[" + Joiner.on(",").join(valueStrings.build()) + "]"; }
@Override protected RowExpression visitArrayConstructor(ArrayConstructor node,Void context) { List<RowExpression> arguments = node.getValues().stream() .map(value -> process(value,context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream() .map(RowExpression::getType) .collect(toImmutableList()); return call(arrayConstructorSignature(types.get(node),argumentTypes),types.get(node),arguments); }
@Override protected Type visitArrayConstructor(ArrayConstructor node,StackableAstVisitorContext<AnalysisContext> context) { Type type = coercetoSingleType(context,"All ARRAY elements must be the same type: %s",node.getValues()); Type arrayType = typeManager.getParameterizedType(ARRAY.getName(),ImmutableList.of(type.getTypeSignature()),ImmutableList.of()); expressionTypes.put(node,arrayType); return arrayType; }
@Override protected String visitArrayConstructor(ArrayConstructor node,Boolean unmangleNames) { ImmutableList.Builder<String> valueStrings = ImmutableList.builder(); for (Expression value : node.getValues()) { valueStrings.add(formatsql(value,unmangleNames)); } return "ARRAY[" + Joiner.on(",").join(valueStrings.build()) + "]"; }
@Test public void testArrayConstructor() throws Exception { assertExpression("ARRAY []",new ArrayConstructor(ImmutableList.<Expression>of())); assertExpression("ARRAY [1,2]",new ArrayConstructor(ImmutableList.<Expression>of(new LongLiteral("1"),new LongLiteral("2")))); assertExpression("ARRAY [1.0,2.5]",new ArrayConstructor(ImmutableList.<Expression>of(new DoubleLiteral("1.0"),new DoubleLiteral("2.5")))); assertExpression("ARRAY ['hi']",new ArrayConstructor(ImmutableList.<Expression>of(new StringLiteral("hi")))); assertExpression("ARRAY ['hi','hello']",new ArrayConstructor(ImmutableList.<Expression>of(new StringLiteral("hi"),new StringLiteral("hello")))); }
@Override protected String visitArrayConstructor(ArrayConstructor node,").join(valueStrings.build()) + "]"; }
@Override protected Boolean visitArrayConstructor(ArrayConstructor node,Void context) { return node.getValues().stream().allMatch(expression -> process(expression,context)); }
@Override public Node visitArrayConstructor(sqlbaseParser.ArrayConstructorContext context) { return new ArrayConstructor(getLocation(context),visit(context.expression(),Expression.class)); }
com.facebook.presto.sql.tree.BooleanLiteral的实例源码
@Override public PhysicalOperation visitProject(ProjectNode node,LocalExecutionPlanContext context) { PlanNode sourceNode; Expression filterExpression; if (node.getSource() instanceof FilterNode) { FilterNode filterNode = (FilterNode) node.getSource(); sourceNode = filterNode.getSource(); filterExpression = filterNode.getPredicate(); } else { sourceNode = node.getSource(); filterExpression = BooleanLiteral.TRUE_LIteraL; } List<Symbol> outputSymbols = node.getoutputSymbols(); return visitScanFilterandProject(context,node.getId(),sourceNode,filterExpression,node.getAssignments(),outputSymbols); }
private PlanNode rewriteFilterSource(FilterNode filterNode,PlanNode source,Symbol rowNumberSymbol,int upperBound) { ExtractionResult extractionResult = fromPredicate(Metadata,session,filterNode.getPredicate(),types); TupleDomain<Symbol> tupleDomain = extractionResult.getTupleDomain(); if (!isEqualRange(tupleDomain,rowNumberSymbol,upperBound)) { return new FilterNode(filterNode.getId(),source,filterNode.getPredicate()); } // Remove the row number domain because it is absorbed into the node Map<Symbol,Domain> newDomains = tupleDomain.getDomains().get().entrySet().stream() .filter(entry -> !entry.getKey().equals(rowNumberSymbol)) .collect(toMap(Map.Entry::getKey,Map.Entry::getValue)); // Construct a new predicate TupleDomain<Symbol> newTupleDomain = TupleDomain.withColumnDomains(newDomains); Expression newPredicate = ExpressionUtils.combineConjuncts( extractionResult.getRemainingExpression(),toPredicate(newTupleDomain)); if (newPredicate.equals(BooleanLiteral.TRUE_LIteraL)) { return source; } return new FilterNode(filterNode.getId(),newPredicate); }
/** * Extracts the literal value from an expression (if expression is supported) * @param expression * @param state * @return a Long,Boolean,Double or String object */ private Object getLiteralValue(Expression expression,QueryState state){ if(expression instanceof LongLiteral) return ((LongLiteral)expression).getValue(); else if(expression instanceof BooleanLiteral) return ((BooleanLiteral)expression).getValue(); else if(expression instanceof DoubleLiteral) return ((DoubleLiteral)expression).getValue(); else if(expression instanceof StringLiteral) return ((StringLiteral)expression).getValue(); else if(expression instanceof ArithmeticUnaryExpression){ ArithmeticUnaryExpression unaryExp = (ArithmeticUnaryExpression)expression; Sign sign = unaryExp.getSign(); Number num = (Number)getLiteralValue(unaryExp.getValue(),state); if(sign == Sign.MINUS){ if(num instanceof Long) return -1*num.longValue(); else if(num instanceof Double) return -1*num.doubleValue(); else { state.addException("Unsupported numeric literal expression encountered : "+num.getClass()); return null; } } return num; } else if(expression instanceof FunctionCall){ FunctionCall fc = (FunctionCall)expression; if(fc.getName().toString().equals("Now")) return new Date(); else state.addException("Function '"+fc.getName()+"' is not supported"); }else if(expression instanceof CurrentTime){ CurrentTime ct = (CurrentTime)expression; if(ct.getType() == CurrentTime.Type.DATE) return new LocalDate().toDate(); else if(ct.getType() == CurrentTime.Type.TIME) return new Date(new LocalTime(DateTimeZone.UTC).getMillisOfDay()); else if(ct.getType() == CurrentTime.Type.TIMESTAMP) return new Date(); else if(ct.getType() == CurrentTime.Type.LOCALTIME) return new Date(new LocalTime(DateTimeZone.UTC).getMillisOfDay()); else if(ct.getType() == CurrentTime.Type.LOCALTIMESTAMP) return new Date(); else state.addException("CurrentTime function '"+ct.getType()+"' is not supported"); }else state.addException("Literal type "+expression.getClass().getSimpleName()+" is not supported"); return null; }
private Object getobject(Literal literal){ Object value = null; if(literal instanceof LongLiteral) value = ((LongLiteral)literal).getValue(); else if(literal instanceof BooleanLiteral) value = ((BooleanLiteral)literal).getValue(); else if(literal instanceof DoubleLiteral) value = ((DoubleLiteral)literal).getValue(); else if(literal instanceof StringLiteral) value = ((StringLiteral)literal).getValue(); else if(literal instanceof TimeLiteral) value = ((TimeLiteral)literal).getValue(); else if(literal instanceof TimestampLiteral) value = ((TimestampLiteral)literal).getValue(); return value; }
private Object getLiteralValue(Expression expression) throws sqlException{ if(expression instanceof LongLiteral) return ((LongLiteral)expression).getValue(); else if(expression instanceof BooleanLiteral) return ((BooleanLiteral)expression).getValue(); else if(expression instanceof DoubleLiteral) return ((DoubleLiteral)expression).getValue(); else if(expression instanceof StringLiteral) return ((StringLiteral)expression).getValue(); throw new sqlException("Unsupported literal type: "+expression); }
@Override public PlanNode visitFilter(FilterNode node,RewriteContext<Void> context) { PlanNode source = context.rewrite(node.getSource()); Expression canonicalized = canonicalizeExpression(node.getPredicate()); if (canonicalized.equals(BooleanLiteral.TRUE_LIteraL)) { return source; } return new FilterNode(node.getId(),canonicalized); }
@Override public PlanNode optimize(PlanNode plan,Session session,Map<Symbol,Type> types,SymbolAllocator symbolAllocator,PlanNodeIdAllocator idAllocator) { requireNonNull(plan,"plan is null"); requireNonNull(session,"session is null"); requireNonNull(types,"types is null"); requireNonNull(idAllocator,"idAllocator is null"); return SimplePlanRewriter.rewriteWith(new Rewriter(symbolAllocator,idAllocator,Metadata,sqlParser,session),plan,BooleanLiteral.TRUE_LIteraL); }
@Override public PlanNode visitPlan(PlanNode node,RewriteContext<Expression> context) { PlanNode rewrittenNode = context.defaultRewrite(node,BooleanLiteral.TRUE_LIteraL); if (!context.get().equals(BooleanLiteral.TRUE_LIteraL)) { // Drop in a FilterNode b/c we cannot push our predicate down any further rewrittenNode = new FilterNode(idAllocator.getNextId(),rewrittenNode,context.get()); } return rewrittenNode; }
@Override public PlanNode visitTableScan(TableScanNode node,RewriteContext<Expression> context) { Expression predicate = simplifyExpression(context.get()); if (!BooleanLiteral.TRUE_LIteraL.equals(predicate)) { return new FilterNode(idAllocator.getNextId(),node,predicate); } return node; }
@Override public PlanNode visitTableScan(TableScanNode node,RewriteContext<Void> context) { if (node.getLayout().isPresent()) { return node; } return planTableScan(node,BooleanLiteral.TRUE_LIteraL); }
@Test public void testJoinPrecedence() { assertStatement("SELECT * FROM a CROSS JOIN b LEFT JOIN c ON true",simpleQuery( selectList(new AllColumns()),new Join( Join.Type.LEFT,new Join( Join.Type.CROSS,new Table(Qualifiedname.of("a")),new Table(Qualifiedname.of("b")),Optional.empty() ),new Table(Qualifiedname.of("c")),Optional.of(new JoinOn(BooleanLiteral.TRUE_LIteraL))))); assertStatement("SELECT * FROM a CROSS JOIN b NATURAL JOIN c CROSS JOIN d NATURAL JOIN e",new Join( Join.Type.INNER,new Join( Join.Type.INNER,new Join( Join.Type.CROSS,Optional.empty() ),Optional.of(new NaturalJoin())),new Table(Qualifiedname.of("d")),new Table(Qualifiedname.of("e")),Optional.of(new NaturalJoin())))); }
@Override protected String visitBooleanLiteral(BooleanLiteral node,Void context) { return String.valueOf(node.getValue()); }
@Override protected String visitBooleanLiteral(BooleanLiteral node,StackableAstVisitorContext<Integer> indent) { return String.valueOf(node.getValue()); }
@Override protected IComparison visitExpression(Expression node,QueryState state) { if( node instanceof LogicalBinaryExpression){ LogicalBinaryExpression boolExp = (LogicalBinaryExpression)node; IComparison left = boolExp.getLeft().accept(this,state); IComparison right = boolExp.getRight().accept(this,state); return new BooleanComparison(left,right,boolExp.getType() == Type.AND); }else if( node instanceof ComparisonExpression){ ComparisonExpression compareExp = (ComparisonExpression)node; Column column = new SelectParser().visitExpression(compareExp.getLeft(),state); Column leftCol = state.getheading().getColumnByLabel(column.getLabel()); if(leftCol == null){ state.addException("Having reference "+column+" not found in SELECT clause"); return null; } // right hand side is a concrete literal to compare with if(compareExp.getRight() instanceof Literal){ Object value; if(compareExp.getRight() instanceof LongLiteral) value = ((LongLiteral)compareExp.getRight()).getValue(); else if(compareExp.getRight() instanceof BooleanLiteral) value = ((BooleanLiteral)compareExp.getRight()).getValue(); else if(compareExp.getRight() instanceof DoubleLiteral) value = ((DoubleLiteral)compareExp.getRight()).getValue(); else if(compareExp.getRight() instanceof StringLiteral) value = ((StringLiteral)compareExp.getRight()).getValue(); else { state.addException("Unable to get value from "+compareExp.getRight()); return null; } return new SimpleComparison(leftCol,compareExp.getType(),(Number)value); // right hand side refers to another column } else if(compareExp.getRight() instanceof DereferenceExpression || compareExp.getRight() instanceof QualifiednameReference){ String col2; if(compareExp.getLeft() instanceof DereferenceExpression){ // parse columns like 'reference.field' col2 = SelectParser.visitDereferenceExpression((DereferenceExpression)compareExp.getRight()); }else{ col2 = ((QualifiednameReference)compareExp.getRight()).getName().toString(); } col2 = heading.findOriginal(state.originalsql(),col2,"having.+","\\W"); Column rightCol = state.getheading().getColumnByLabel(col2); if(rightCol == null){ state.addException("column "+col2+" not found in SELECT clause"); return null; } return new SimpleComparison(leftCol,rightCol); }else { // unkNown right hand side so state.addException("Unable to get value from "+compareExp.getRight()); return null; } }else if( node instanceof NotExpression){ state.addException("NOT is currently not supported,use '<>' instead"); }else{ state.addException("Unable to parse "+node+" ("+node.getClass().getName()+") is not a supported expression"); } return null; }
@Override protected RowExpression visitBooleanLiteral(BooleanLiteral node,Void context) { return constant(node.getValue(),BOOLEAN); }
@Override protected Object visitBooleanLiteral(BooleanLiteral node,ConnectorSession session) { return node.getValue(); }
@Override protected Object visitBooleanLiteral(BooleanLiteral node,Object context) { return node.equals(BooleanLiteral.TRUE_LIteraL); }
@Override public PlanWithProperties visitTableScan(TableScanNode node,Context context) { return planTableScan(node,BooleanLiteral.TRUE_LIteraL,context); }
private PlanWithProperties planTableScan(TableScanNode node,Expression predicate,Context context) { // don't include non-deterministic predicates Expression deterministicPredicate = stripNonDeterministicConjuncts(predicate); DomainTranslator.ExtractionResult decomposedPredicate = DomainTranslator.fromPredicate( Metadata,deterministicPredicate,symbolAllocator.getTypes()); TupleDomain<ColumnHandle> simplifiedConstraint = decomposedPredicate.getTupleDomain() .transform(node.getAssignments()::get) .intersect(node.getCurrentConstraint()); Map<ColumnHandle,Symbol> assignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse(); Expression constraint = combineConjuncts( deterministicPredicate,DomainTranslator.toPredicate(node.getCurrentConstraint().transform(assignments::get))); // Layouts will be returned in order of the connector's preference List<TableLayoutResult> layouts = Metadata.getLayouts( session,node.getTable(),new Constraint<>(simplifiedConstraint,bindings -> !shouldPrune(constraint,bindings)),Optional.of(node.getoutputSymbols().stream() .map(node.getAssignments()::get) .collect(toImmutableSet()))); if (layouts.isEmpty()) { return new PlanWithProperties( new ValuesNode(idAllocator.getNextId(),node.getoutputSymbols(),ImmutableList.of()),ActualProperties.undistributed()); } // Filter out layouts that cannot supply all the required columns layouts = layouts.stream() .filter(layoutHasAllNeededOutputs(node)) .collect(toList()); checkState(!layouts.isEmpty(),"No usable layouts for %s",node); List<PlanWithProperties> possiblePlans = layouts.stream() .map(layout -> { TableScanNode tableScan = new TableScanNode( node.getId(),Optional.of(layout.getLayout().getHandle()),simplifiedConstraint.intersect(layout.getLayout().getPredicate()),Optional.ofNullable(node.getoriginalConstraint()).orElse(predicate)); PlanWithProperties result = new PlanWithProperties(tableScan,deriveProperties(tableScan,ImmutableList.of())); Expression resultingPredicate = combineConjuncts( DomainTranslator.toPredicate(layout.getUnenforcedConstraint().transform(assignments::get)),stripDeterministicConjuncts(predicate),decomposedPredicate.getRemainingExpression()); if (!BooleanLiteral.TRUE_LIteraL.equals(resultingPredicate)) { return withDerivedProperties( new FilterNode(idAllocator.getNextId(),result.getNode(),resultingPredicate),ImmutableList.of())); } return result; }) .collect(toList()); return pickPlan(possiblePlans,context); }
private PlanNode planTableScan(TableScanNode node,Expression predicate) { DomainTranslator.ExtractionResult decomposedPredicate = DomainTranslator.fromPredicate( Metadata,predicate,symbolAllocator.getTypes()); TupleDomain<ColumnHandle> simplifiedConstraint = decomposedPredicate.getTupleDomain() .transform(node.getAssignments()::get) .intersect(node.getCurrentConstraint()); List<TableLayoutResult> layouts = Metadata.getLayouts( session,bindings -> true),Optional.of(ImmutableSet.copyOf(node.getAssignments().values()))); if (layouts.isEmpty()) { return new ValuesNode(idAllocator.getNextId(),ImmutableList.of()); } TableLayoutResult layout = layouts.get(0); TableScanNode result = new TableScanNode( node.getId(),Optional.ofNullable(node.getoriginalConstraint()).orElse(predicate)); Map<ColumnHandle,Symbol> assignments = ImmutableBiMap.copyOf(node.getAssignments()).inverse(); Expression resultingPredicate = combineConjuncts( decomposedPredicate.getRemainingExpression(),DomainTranslator.toPredicate(layout.getUnenforcedConstraint().transform(assignments::get))); if (!BooleanLiteral.TRUE_LIteraL.equals(resultingPredicate)) { return new FilterNode(idAllocator.getNextId(),result,resultingPredicate); } return result; }
@Override public PlanNode visitTableScan(TableScanNode node,RewriteContext<Context> context) { return planTableScan(node,context.get()); }
@Override protected ExtractionResult visitBooleanLiteral(BooleanLiteral node,Boolean complement) { boolean value = complement ? !node.getValue() : node.getValue(); return new ExtractionResult(value ? TupleDomain.all() : TupleDomain.none(),TRUE_LIteraL); }
@Override protected Type visitBooleanLiteral(BooleanLiteral node,StackableAstVisitorContext<AnalysisContext> context) { expressionTypes.put(node,BOOLEAN); return BOOLEAN; }
@Test public void testTableScan() throws Exception { // Effective predicate is True if there is no effective predicate Map<Symbol,ColumnHandle> assignments = Maps.filterKeys(scanAssignments,Predicates.in(ImmutableList.of(A,B,C,D))); PlanNode node = new TableScanNode( newId(),DUAL_TABLE_HANDLE,ImmutableList.copyOf(assignments.keySet()),assignments,Optional.empty(),TupleDomain.all(),null); Expression effectivePredicate = EffectivePredicateExtractor.extract(node,TYPES); Assert.assertEquals(effectivePredicate,BooleanLiteral.TRUE_LIteraL); node = new TableScanNode( newId(),TupleDomain.none(),null); effectivePredicate = EffectivePredicateExtractor.extract(node,FALSE_LIteraL); node = new TableScanNode( newId(),TupleDomain.withColumnDomains(ImmutableMap.of(scanAssignments.get(A),Domain.singleValue(BIGINT,1L))),TYPES); Assert.assertEquals(normalizeConjuncts(effectivePredicate),normalizeConjuncts(equals(number(1L),AE))); node = new TableScanNode( newId(),TupleDomain.withColumnDomains(ImmutableMap.of( scanAssignments.get(A),1L),scanAssignments.get(B),2L))),normalizeConjuncts(equals(number(2L),BE),equals(number(1L),BooleanLiteral.TRUE_LIteraL); }
@Override public Node visitBooleanValue(sqlbaseParser.BooleanValueContext context) { return new BooleanLiteral(getLocation(context),context.getText()); }
@Override protected String visitBooleanLiteral(BooleanLiteral node,Boolean unmangleNames) { return String.valueOf(node.getValue()); }
@Override protected String visitBooleanLiteral(BooleanLiteral node,Boolean unmangleNames) { return String.valueOf(node.getValue()); }
com.facebook.presto.sql.tree.Cast的实例源码
@Override public Type visitCast(Cast node,StackableAstVisitorContext<AnalysisContext> context) { Type type = typeManager.getType(parseTypeSignature(node.getType())); if (type == null) { throw new SemanticException(TYPE_MISMATCH,node,"UnkNown type: " + node.getType()); } if (type.equals(UNKNowN)) { throw new SemanticException(TYPE_MISMATCH,"UNKNowN is not a valid type"); } Type value = process(node.getExpression(),context); if (!value.equals(UNKNowN)) { try { functionRegistry.getCoercion(value,type); } catch (OperatorNotFoundException e) { throw new SemanticException(TYPE_MISMATCH,"Cannot cast %s to %s",value,type); } } expressionTypes.put(node,type); return type; }
@Override protected RowExpression visitCast(Cast node,Void context) { RowExpression value = process(node.getExpression(),context); if (node.isSafe()) { return call(tryCastSignature(types.get(node),value.getType()),types.get(node),value); } return call(castSignature(types.get(node),value); }
@Override public Object visitCast(Cast node,Object context) { Object value = process(node.getExpression(),context); if (value instanceof Expression) { return new Cast((Expression) value,node.getType(),node.isSafe()); } // hack!!! don't optimize CASTs for types that cannot be represented in the sql AST // Todo: this will not be an issue when we migrate to RowExpression tree for this,which allows arbitrary literals. if (optimize && !FunctionRegistry.isSupportedLiteralType(expressionTypes.get(node))) { return new Cast(toExpression(value,expressionTypes.get(node.getExpression())),node.isSafe()); } if (value == null) { return null; } Type type = Metadata.getType(parseTypeSignature(node.getType())); if (type == null) { throw new IllegalArgumentException("Unsupported type: " + node.getType()); } Signature operator = Metadata.getFunctionRegistry().getCoercion(expressionTypes.get(node.getExpression()),type); try { return invoke(session,Metadata.getFunctionRegistry().getScalarFunctionImplementation(operator),ImmutableList.of(value)); } catch (RuntimeException e) { if (node.isSafe()) { return null; } throw e; } }
@VisibleForTesting @NotNull public 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 public String visitCast(Cast node,Void context) { return (node.isSafe() ? "TRY_CAST" : "CAST") + "(" + process(node.getExpression(),context) + " AS " + node.getType() + ")"; }
@Override public String visitCast(Cast node,StackableAstVisitorContext<Integer> indent) { return (node.isSafe() ? "TRY_CAST" : "CAST") + "(" + process(node.getExpression(),indent) + " AS " + node.getType() + ")"; }
@Override protected Boolean visitCast(Cast node,Void context) { return process(node.getExpression(),context); }
@Override public Node visitCast(sqlbaseParser.CastContext context) { boolean isTryCast = context.TRY_CAST() != null; return new Cast(getLocation(context),(Expression) visit(context.expression()),getType(context.type()),isTryCast); }
@Override public String visitCast(Cast node,Boolean unmangleNames) { return (node.isSafe() ? "TRY_CAST" : "CAST") + "(" + process(node.getExpression(),unmangleNames) + " AS " + node.getType() + ")"; }
private static void assertCast(String type,String expected) { assertExpression("CAST(null AS " + type + ")",new Cast(new NullLiteral(),expected)); }
@Override public String visitCast(Cast node,unmangleNames) + " AS " + node.getType() + ")"; }
com.facebook.presto.sql.tree.CoalesceExpression的实例源码
@Override protected Object visitCoalesceExpression(CoalesceExpression node,Object context) { Type type = type(node); List<Object> values = node.getoperands().stream() .map(value -> processWithExceptionHandling(value,context)) .filter(value -> value != null) .collect(Collectors.toList()); if ((!values.isEmpty() && !(values.get(0) instanceof Expression)) || values.size() == 1) { return values.get(0); } List<Expression> expressions = values.stream() .map(value -> toExpression(value,type)) .collect(Collectors.toList()); if (expressions.isEmpty()) { return null; } return new CoalesceExpression(expressions); }
@Override protected RowExpression visitCoalesceExpression(CoalesceExpression node,Void context) { List<RowExpression> arguments = node.getoperands().stream() .map(value -> process(value,context)) .collect(toImmutableList()); List<Type> argumentTypes = arguments.stream().map(RowExpression::getType).collect(toImmutableList()); return call(coalesceSignature(types.get(node),argumentTypes),types.get(node),arguments); }
private static Expression oneIfNull(Optional<Symbol> symbol) { if (symbol.isPresent()) { return new CoalesceExpression(new QualifiednameReference(symbol.get().toQualifiedname()),new LongLiteral("1")); } else { return new LongLiteral("1"); } }
@Override protected Type visitCoalesceExpression(CoalesceExpression node,StackableAstVisitorContext<AnalysisContext> context) { Type type = coercetoSingleType(context,"All COALESCE operands must be the same type: %s",node.getoperands()); expressionTypes.put(node,type); return type; }
@Override protected String visitCoalesceExpression(CoalesceExpression node,Void context) { return "COALESCE(" + joinExpressions(node.getoperands()) + ")"; }
@Override protected String visitCoalesceExpression(CoalesceExpression node,StackableAstVisitorContext<Integer> indent) { return "COALESCE(" + joinExpressions(node.getoperands(),indent) + ")"; }
private static Expression orNullHashCode(Expression expression) { return new CoalesceExpression(expression,new LongLiteral(String.valueOf(TypeUtils.NULL_HASH_CODE))); }
@Override protected Boolean visitCoalesceExpression(CoalesceExpression node,Void context) { return node.getoperands().stream().allMatch(expression -> process(expression,context)); }
@Override protected String visitCoalesceExpression(CoalesceExpression node,Boolean unmangleNames) { return "COALESCE(" + joinExpressions(node.getoperands(),unmangleNames) + ")"; }
public static SelectItem aliasednullToEmpty(String column,String alias) { return new SingleColumn(new CoalesceExpression(nameReference(column),new StringLiteral("")),alias); }
@Override protected String visitCoalesceExpression(CoalesceExpression node,unmangleNames) + ")"; }
今天的关于com.facebook.presto.sql.tree.Extract的实例源码的分享已经结束,谢谢您的关注,如果想了解更多关于com.facebook.presto.sql.tree.ArrayConstructor的实例源码、com.facebook.presto.sql.tree.BooleanLiteral的实例源码、com.facebook.presto.sql.tree.Cast的实例源码、com.facebook.presto.sql.tree.CoalesceExpression的实例源码的相关知识,请在本站进行查询。
本文标签: