Search in sources :

Example 1 with QueryCallPattern

use of org.drools.model.patterns.QueryCallPattern in project drools by kiegroup.

the class ViewFlowBuilder method viewItems2Condition.

private static CompositePatterns viewItems2Condition(BuildContext ctx, Condition.Type type, boolean topLevel) {
    List<Condition> conditions = new ArrayList<>();
    Map<Variable<?>, Condition> conditionMap = new HashMap<>();
    Map<String, Consequence> consequences = topLevel ? new LinkedHashMap<>() : null;
    Iterator<RuleItem> ruleItemIterator = ctx.ruleItems.iterator();
    while (ruleItemIterator.hasNext()) {
        Map<Variable<?>, InputViewItemImpl<?>> scopedInputs = type.createsScope() ? new LinkedHashMap<>(ctx.inputs) : ctx.inputs;
        RuleItem ruleItem = ruleItemIterator.next();
        if (ruleItem instanceof FixedValueItem) {
            conditions.add(new EvalImpl(((FixedValueItem) ruleItem).isValue()));
            continue;
        }
        if (ruleItem instanceof Consequence) {
            if (!topLevel) {
                throw new IllegalStateException("A consequence can be only a top level item");
            }
            Consequence consequence = (Consequence) ruleItem;
            String name = ruleItemIterator.hasNext() ? generateName("consequence") : RuleImpl.DEFAULT_CONSEQUENCE_NAME;
            consequences.put(name, consequence);
            conditions.add(new NamedConsequenceImpl(name, consequence.isBreaking()));
            continue;
        }
        if (ruleItem instanceof ConditionalConsequence) {
            if (!topLevel) {
                throw new IllegalStateException("A consequence can be only a top level item");
            }
            conditions.add(createConditionalNamedConsequence(consequences, (ConditionalConsequence) ruleItem));
            continue;
        }
        ViewItem viewItem = (ViewItem) ruleItem;
        if (viewItem instanceof CombinedExprViewItem) {
            CombinedExprViewItem combined = (CombinedExprViewItem) viewItem;
            conditions.add(viewItems2Condition(new BuildContext(ctx, combined.getExpressions(), scopedInputs), combined.getType(), false));
            continue;
        }
        if (viewItem instanceof QueryCallViewItem) {
            QueryCallViewItem query = ((QueryCallViewItem) viewItem);
            for (Argument arg : query.getArguments()) {
                if (arg instanceof Variable) {
                    ctx.usedVars.add(((Variable) arg));
                }
            }
            conditions.add(new QueryCallPattern(query));
            continue;
        }
        if (viewItem instanceof Binding) {
            Binding bindViewItem = (Binding) viewItem;
            PatternImpl pattern = (PatternImpl) conditionMap.get(bindViewItem.getInputVariable());
            if (pattern == null) {
                // This should probably be the bindViewItem.getBoundVariable() instead of the input
                // as the input variables can be many
                pattern = new PatternImpl(bindViewItem.getInputVariable());
                pattern.addWatchedProps(bindViewItem.getWatchedProps());
                ctx.usedVars.add(bindViewItem.getInputVariable());
                conditions.add(pattern);
                conditionMap.put(bindViewItem.getInputVariable(), pattern);
            }
            pattern.addBinding(bindViewItem);
            ctx.usedVars.add(viewItem.getFirstVariable());
            ctx.addBinding(bindViewItem);
            scopedInputs.putIfAbsent(viewItem.getFirstVariable(), (InputViewItemImpl) input(viewItem.getFirstVariable()));
            continue;
        }
        Variable<?> patterVariable = findPatterVariable(viewItem, scopedInputs.keySet());
        if (viewItem instanceof InputViewItemImpl) {
            scopedInputs.put(patterVariable, (InputViewItemImpl) viewItem);
            PatternImpl condition = new PatternImpl(patterVariable);
            condition.addWatchedProps(((InputViewItemImpl) viewItem).getWatchedProps());
            conditions.add(condition);
            conditionMap.put(patterVariable, condition);
            ctx.usedVars.add(patterVariable);
            continue;
        }
        if (viewItem instanceof ExistentialExprViewItem) {
            ExistentialExprViewItem existential = ((ExistentialExprViewItem) viewItem);
            if (patterVariable != null && !existential.isQueryExpression()) {
                registerInputsFromViewItem(existential.getExpression(), conditionMap, scopedInputs, patterVariable);
            }
            Condition condition = new PatternImpl(patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable));
            conditions.add(new ExistentialPatternImpl(viewItem2Condition(existential.getExpression(), condition, new BuildContext(ctx, new LinkedHashMap<>())), existential.getType()));
            continue;
        }
        if (ruleItem instanceof ExprViewItem && ctx.boundVars.contains(patterVariable)) {
            conditions.add(new EvalImpl(createConstraint((ExprViewItem) ruleItem)));
            continue;
        }
        ctx.usedVars.add(patterVariable);
        Condition condition;
        if (type == Type.AND) {
            condition = conditionMap.get(patterVariable);
            if (condition == null) {
                condition = new PatternImpl(patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable));
                conditions.add(condition);
                if (!(viewItem instanceof AccumulateExprViewItem)) {
                    conditionMap.put(patterVariable, condition);
                }
                scopedInputs.putIfAbsent(patterVariable, (InputViewItemImpl) input(patterVariable));
            }
        } else {
            condition = new PatternImpl(patterVariable);
            conditions.add(condition);
        }
        addInputFromVariableSource(scopedInputs, patterVariable);
        registerInputsFromViewItem(viewItem, conditionMap, scopedInputs, null);
        Condition modifiedPattern = viewItem2Condition(viewItem, condition, new BuildContext(ctx, scopedInputs));
        conditions.set(conditions.indexOf(condition), modifiedPattern);
        if (type == Type.AND && !(viewItem instanceof AccumulateExprViewItem)) {
            conditionMap.put(patterVariable, modifiedPattern);
        }
    }
    return new CompositePatterns(type, conditions, ctx.usedVars, consequences);
}
Also used : AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) TemporalExprViewItem(org.drools.model.view.TemporalExprViewItem) AbstractExprViewItem(org.drools.model.view.AbstractExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) Variable(org.drools.model.Variable) InputViewItemImpl(org.drools.model.view.InputViewItemImpl) Argument(org.drools.model.Argument) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) CompositePatterns(org.drools.model.patterns.CompositePatterns) NamedConsequenceImpl(org.drools.model.consequences.NamedConsequenceImpl) ConditionalNamedConsequenceImpl(org.drools.model.consequences.ConditionalNamedConsequenceImpl) PatternImpl(org.drools.model.patterns.PatternImpl) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) EvalImpl(org.drools.model.patterns.EvalImpl) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) RuleItem(org.drools.model.RuleItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) Condition(org.drools.model.Condition) Binding(org.drools.model.Binding) ConditionalConsequence(org.drools.model.ConditionalConsequence) ExprNViewItem(org.drools.model.view.ExprNViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) InputViewItem(org.drools.model.view.InputViewItem) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) ViewItem(org.drools.model.view.ViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) TemporalExprViewItem(org.drools.model.view.TemporalExprViewItem) AbstractExprViewItem(org.drools.model.view.AbstractExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) Consequence(org.drools.model.Consequence) ConditionalConsequence(org.drools.model.ConditionalConsequence) FixedValueItem(org.drools.model.view.FixedValueItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem)

Example 2 with QueryCallPattern

use of org.drools.model.patterns.QueryCallPattern in project drools by kiegroup.

the class KiePackagesBuilder method buildAccumulate.

private RuleConditionElement buildAccumulate(RuleContext ctx, GroupElement group, AccumulatePattern accumulatePattern) {
    Pattern pattern = null;
    boolean isGroupBy = accumulatePattern instanceof GroupByPattern;
    if (accumulatePattern.getAccumulateFunctions() != null) {
        if (!isGroupBy && accumulatePattern.getAccumulateFunctions().length == 1) {
            // non groupby with single accumulates can be optimized to directly return the result, rather than place in an array of 1
            pattern = ctx.getPattern(accumulatePattern.getAccumulateFunctions()[0].getResult());
        } else if (accumulatePattern.getAccumulateFunctions().length > 0 && ctx.getPattern(accumulatePattern.getAccumulateFunctions()[0].getResult()) != null) {
            // Illegal executable model. Cannot have groupby or multi accumulate mapped to a single result object.
            throw new RuntimeException("Only single accumulate functions, with no group by can optimize the result pattern to be the function return value");
        }
    }
    boolean existingPattern = pattern != null;
    if (!existingPattern) {
        ObjectType type = !isGroupBy && accumulatePattern.getAccumulateFunctions().length == 1 ? new ClassObjectType(accumulatePattern.getAccumulateFunctions()[0].getResult().getType()) : // groupby or multi function accumulate
        JAVA_CLASS_ARRAY_TYPE;
        pattern = new Pattern(ctx.getNextPatternIndex(), type);
    }
    PatternImpl<?> sourcePattern = (PatternImpl<?>) accumulatePattern.getPattern();
    Set<String> usedVariableName = new LinkedHashSet<>();
    if (sourcePattern != null) {
        for (Variable v : sourcePattern.getInputVariables()) {
            usedVariableName.add(v.getName());
        }
    }
    RuleConditionElement source;
    if (accumulatePattern.isQuerySource()) {
        source = buildQueryPattern(ctx, ((QueryCallPattern) accumulatePattern.getCondition()));
    } else if (accumulatePattern.isCompositePatterns()) {
        CompositePatterns compositePatterns = (CompositePatterns) accumulatePattern.getCondition();
        GroupElement allSubConditions = new GroupElement(conditionToGroupElementType(compositePatterns.getType()));
        for (Condition c : compositePatterns.getSubConditions()) {
            recursivelyAddConditions(ctx, group, allSubConditions, c);
        }
        source = allSubConditions.getChildren().size() == 1 ? allSubConditions.getChildren().get(0) : allSubConditions;
    } else {
        source = buildPattern(ctx, group, accumulatePattern);
    }
    Collection<Binding> bindings = new ArrayList<>();
    if (sourcePattern != null) {
        bindings.addAll(sourcePattern.getBindings());
        bindings.add(new SelfPatternBiding<>(sourcePattern.getPatternVariable()));
    } else {
        // No pattern is associated. It likely uses inner bindings
        addInnerBindings(bindings, accumulatePattern.getAccumulateFunctions(), accumulatePattern.getCondition());
    }
    pattern.setSource(buildAccumulate(ctx, accumulatePattern, source, pattern, usedVariableName, bindings));
    return existingPattern ? null : pattern;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) EvalCondition(org.drools.core.rule.EvalCondition) Condition(org.drools.model.Condition) Binding(org.drools.model.Binding) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) AccumulatePattern(org.drools.model.AccumulatePattern) Pattern(org.drools.core.rule.Pattern) GroupByPattern(org.drools.model.GroupByPattern) PrototypeVariable(org.drools.model.PrototypeVariable) Variable(org.drools.model.Variable) ClassObjectType(org.drools.core.base.ClassObjectType) GroupElement(org.drools.core.rule.GroupElement) ArrayList(java.util.ArrayList) RuleConditionElement(org.drools.core.rule.RuleConditionElement) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) CompositePatterns(org.drools.model.patterns.CompositePatterns) GroupByPattern(org.drools.model.GroupByPattern) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) PatternImpl(org.drools.model.patterns.PatternImpl) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl)

Example 3 with QueryCallPattern

use of org.drools.model.patterns.QueryCallPattern in project drools by kiegroup.

the class KiePackagesBuilder method buildQueryPattern.

private RuleConditionElement buildQueryPattern(RuleContext ctx, QueryCallPattern queryPattern) {
    Pattern pattern = new Pattern(ctx.getNextPatternIndex(), // tupleIndex is 0 by default
    0, // patternIndex is 0 by default
    0, ClassObjectType.ObjectArray_ObjectType, null);
    QueryArgument[] arguments = new QueryArgument[queryPattern.getArguments().length];
    List<Integer> varIndexList = new ArrayList<>();
    List<Declaration> requiredDeclarations = new ArrayList<>();
    for (int i = 0; i < queryPattern.getArguments().length; i++) {
        Argument arg = queryPattern.getArguments()[i];
        if (arg instanceof Variable) {
            Variable var = ((Variable) arg);
            Declaration decl = ctx.getDeclaration(var);
            if (decl != null) {
                requiredDeclarations.add(decl);
                arguments[i] = new QueryArgument.Declr(decl);
            } else {
                ArrayElementReader reader = new ArrayElementReader(new SelfReferenceClassFieldReader(Object[].class), i, arg.getType());
                Declaration varDeclaration = pattern.addDeclaration(var.getName());
                varDeclaration.setReadAccessor(reader);
                ctx.addDeclaration(var, varDeclaration);
                arguments[i] = QueryArgument.VAR;
                varIndexList.add(i);
            }
        } else if (arg instanceof Value) {
            arguments[i] = new QueryArgument.Literal(((Value) arg).getValue());
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return new QueryElement(pattern, queryPattern.getQuery().getName(), arguments, varIndexList.stream().mapToInt(i -> i).toArray(), requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]), queryPattern.isOpen(), // TODO: query.isAbductive() );
    false);
}
Also used : QueryCallPattern(org.drools.model.patterns.QueryCallPattern) AccumulatePattern(org.drools.model.AccumulatePattern) Pattern(org.drools.core.rule.Pattern) GroupByPattern(org.drools.model.GroupByPattern) QueryArgument(org.drools.core.rule.QueryArgument) PrototypeVariable(org.drools.model.PrototypeVariable) Variable(org.drools.model.Variable) QueryArgument(org.drools.core.rule.QueryArgument) Argument(org.drools.model.Argument) ArrayList(java.util.ArrayList) QueryElement(org.drools.core.rule.QueryElement) SingleConstraint(org.drools.model.SingleConstraint) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) LambdaConstraint(org.drools.modelcompiler.constraints.LambdaConstraint) UnificationConstraint(org.drools.modelcompiler.constraints.UnificationConstraint) EntryPoint(org.drools.model.EntryPoint) AbstractConstraint(org.drools.modelcompiler.constraints.AbstractConstraint) Constraint(org.drools.model.Constraint) CombinedConstraint(org.drools.modelcompiler.constraints.CombinedConstraint) AbstractSingleConstraint(org.drools.model.constraints.AbstractSingleConstraint) DSL.entryPoint(org.drools.model.DSL.entryPoint) SalienceInteger(org.drools.core.base.SalienceInteger) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) Value(org.drools.model.Value) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) WindowDeclaration(org.drools.core.rule.WindowDeclaration) TypeDeclarationUtil.createTypeDeclaration(org.drools.modelcompiler.util.TypeDeclarationUtil.createTypeDeclaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 4 with QueryCallPattern

use of org.drools.model.patterns.QueryCallPattern in project drools by kiegroup.

the class ViewPatternBuilder method ruleItem2Condition.

public static Condition ruleItem2Condition(RuleItem ruleItem) {
    if (ruleItem instanceof PatternDefImpl) {
        PatternDefImpl<?> patternDef = (PatternDefImpl) ruleItem;
        Variable<?> patternVariable = patternDef.getFirstVariable();
        PatternImpl pattern = new PatternImpl(patternVariable, patternVariable instanceof Exchange ? Condition.Type.RECEIVER : Condition.Type.PATTERN);
        for (PatternItem patternItem : patternDef.getItems()) {
            if (patternItem instanceof PatternExprImpl) {
                pattern.addConstraint(((PatternExprImpl) patternItem).asConstraint(patternDef));
            } else if (patternItem instanceof PatternBindingImpl) {
                pattern.addBinding(((PatternBindingImpl) patternItem).asBinding(patternDef));
            } else {
                throw new UnsupportedOperationException("Unknown pattern item type: " + patternItem);
            }
        }
        pattern.addWatchedProps(patternDef.getWatch());
        pattern.setPassive(patternDef.isPassive());
        return pattern;
    }
    if (ruleItem instanceof FixedValueItem) {
        return new EvalImpl(((FixedValueItem) ruleItem).isValue());
    }
    if (ruleItem instanceof QueryCallViewItem) {
        return new QueryCallPattern((QueryCallViewItem) ruleItem);
    }
    if (ruleItem instanceof CombinedExprViewItem) {
        CombinedExprViewItem combined = (CombinedExprViewItem) ruleItem;
        List<Condition> conditions = new ArrayList<>();
        for (ViewItem expr : combined.getExpressions()) {
            conditions.add(ruleItem2Condition(expr));
        }
        return new CompositePatterns(combined.getType(), conditions);
    }
    if (ruleItem instanceof ExistentialExprViewItem) {
        ExistentialExprViewItem existential = (ExistentialExprViewItem) ruleItem;
        return new ExistentialPatternImpl(ruleItem2Condition(existential.getExpression()), existential.getType());
    }
    if (ruleItem instanceof GroupByExprViewItem) {
        GroupByExprViewItem groupBy = (GroupByExprViewItem) ruleItem;
        return new GroupByPatternImpl(ruleItem2Condition(groupBy.getExpr()), groupBy.getVars(), groupBy.getVarKey(), groupBy.getGroupingFunction(), groupBy.getAccumulateFunctions());
    }
    if (ruleItem instanceof AccumulateExprViewItem) {
        AccumulateExprViewItem acc = (AccumulateExprViewItem) ruleItem;
        return new AccumulatePatternImpl(ruleItem2Condition(acc.getExpr()), null, acc.getAccumulateFunctions());
    }
    if (ruleItem instanceof ExprViewItem) {
        return new EvalImpl(createConstraint((ExprViewItem) ruleItem));
    }
    if (ruleItem instanceof ExchangeDefImpl) {
        ExchangeDefImpl<?> exchangeDef = (ExchangeDefImpl) ruleItem;
        return new PatternImpl(exchangeDef.getFirstVariable(), Condition.Type.SENDER);
    }
    throw new UnsupportedOperationException("Unknown " + ruleItem);
}
Also used : AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) ExchangeDefImpl(org.drools.model.PatternDSL.ExchangeDefImpl) PatternItem(org.drools.model.PatternDSL.PatternItem) ArrayList(java.util.ArrayList) CompositePatterns(org.drools.model.patterns.CompositePatterns) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) PatternImpl(org.drools.model.patterns.PatternImpl) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) EvalImpl(org.drools.model.patterns.EvalImpl) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) Condition(org.drools.model.Condition) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) ViewItem(org.drools.model.view.ViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) FixedValueItem(org.drools.model.view.FixedValueItem) PatternExprImpl(org.drools.model.PatternDSL.PatternExprImpl) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) PatternBindingImpl(org.drools.model.PatternDSL.PatternBindingImpl) PatternDefImpl(org.drools.model.PatternDSL.PatternDefImpl)

Aggregations

ArrayList (java.util.ArrayList)4 QueryCallPattern (org.drools.model.patterns.QueryCallPattern)4 Condition (org.drools.model.Condition)3 Variable (org.drools.model.Variable)3 CompositePatterns (org.drools.model.patterns.CompositePatterns)3 ExistentialPatternImpl (org.drools.model.patterns.ExistentialPatternImpl)3 PatternImpl (org.drools.model.patterns.PatternImpl)3 Pattern (org.drools.core.rule.Pattern)2 AccumulatePattern (org.drools.model.AccumulatePattern)2 Argument (org.drools.model.Argument)2 Binding (org.drools.model.Binding)2 GroupByPattern (org.drools.model.GroupByPattern)2 PrototypeVariable (org.drools.model.PrototypeVariable)2 AccumulatePatternImpl (org.drools.model.patterns.AccumulatePatternImpl)2 EvalImpl (org.drools.model.patterns.EvalImpl)2 GroupByPatternImpl (org.drools.model.patterns.GroupByPatternImpl)2 AccumulateExprViewItem (org.drools.model.view.AccumulateExprViewItem)2 CombinedExprViewItem (org.drools.model.view.CombinedExprViewItem)2 ExistentialExprViewItem (org.drools.model.view.ExistentialExprViewItem)2 ExprViewItem (org.drools.model.view.ExprViewItem)2