Search in sources :

Example 1 with QueryImpl

use of org.drools.core.rule.QueryImpl in project drools by kiegroup.

the class RuleImpl method collectDependingQueries.

protected List<QueryImpl> collectDependingQueries(LinkedList<QueryImpl> accumulator) {
    if (usedQueries == null) {
        return accumulator;
    }
    for (QueryImpl query : usedQueries) {
        if (!accumulator.contains(query)) {
            accumulator.offerFirst(query);
            query.collectDependingQueries(accumulator);
        }
    }
    return accumulator;
}
Also used : QueryImpl(org.drools.core.rule.QueryImpl)

Example 2 with QueryImpl

use of org.drools.core.rule.QueryImpl in project drools by kiegroup.

the class QueryBuilder method build.

public Pattern build(final RuleBuildContext context, final QueryDescr queryDescr) {
    ObjectType queryObjectType = ClassObjectType.DroolsQuery_ObjectType;
    final Pattern pattern = new Pattern(context.getNextPatternId(), // offset is 0 by default
    0, queryObjectType, null);
    final InternalReadAccessor extractor = PatternBuilder.getFieldReadAccessor(context, queryDescr, pattern, "name", null, true);
    final QueryNameConstraint constraint = new QueryNameConstraint(extractor, queryDescr.getName());
    PatternBuilder.registerReadAccessor(context, queryObjectType, "name", constraint);
    // adds appropriate constraint to the pattern
    pattern.addConstraint(constraint);
    ObjectType argsObjectType = ClassObjectType.DroolsQuery_ObjectType;
    InternalReadAccessor arrayExtractor = PatternBuilder.getFieldReadAccessor(context, queryDescr, null, argsObjectType, "elements", null, true);
    QueryImpl query = ((QueryImpl) context.getRule());
    String[] params;
    String[] types;
    int numParams = queryDescr.getParameters().length;
    if (query.isAbductive()) {
        params = Arrays.copyOf(queryDescr.getParameters(), queryDescr.getParameters().length + 1);
        types = Arrays.copyOf(queryDescr.getParameterTypes(), queryDescr.getParameterTypes().length + 1);
    } else {
        params = queryDescr.getParameters();
        types = queryDescr.getParameterTypes();
    }
    Declaration[] declarations = new Declaration[params.length];
    Class<?> abductionReturnKlass = null;
    if (query.isAbductive()) {
        Abductive abductive = queryDescr.getTypedAnnotation(Abductive.class);
        abductionReturnKlass = abductive.target();
        params[numParams] = "";
        types[numParams] = abductionReturnKlass.getName();
    }
    int i = 0;
    try {
        for (i = 0; i < params.length; i++) {
            Declaration declr = pattern.addDeclaration(params[i]);
            // this bit is different, notice its the ArrayElementReader that we wire up to, not the declaration.
            ArrayElementReader reader = new ArrayElementReader(arrayExtractor, i, context.getDialect().getTypeResolver().resolveType(types[i]));
            PatternBuilder.registerReadAccessor(context, argsObjectType, "elements", reader);
            declr.setReadAccessor(reader);
            declarations[i] = declr;
        }
        query.setParameters(declarations);
    } catch (ClassNotFoundException e) {
        context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, "Unable to resolve type '" + types[i] + " for parameter" + params[i]));
    }
    context.setPrefixPattern(pattern);
    if (query.isAbductive()) {
        String returnName = "";
        try {
            AnnotationDescr ann = queryDescr.getAnnotation(Abductive.class);
            Object[] argsVal = ((Object[]) ann.getValue("args"));
            String[] args = argsVal != null ? Arrays.copyOf(argsVal, argsVal.length, String[].class) : null;
            returnName = types[numParams];
            ObjectType objectType = new ClassObjectType(abductionReturnKlass, false);
            objectType = context.getPkg().getClassFieldAccessorStore().wireObjectType(objectType, (AbductiveQuery) query);
            ((AbductiveQuery) query).setReturnType(objectType, params, args, declarations);
        } catch (NoSuchMethodException e) {
            context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, "Unable to resolve abducible constructor for type : " + returnName + " with types " + Arrays.toString(types)));
        } catch (IllegalArgumentException e) {
            context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, e.getMessage()));
        }
    }
    return pattern;
}
Also used : Pattern(org.drools.core.rule.Pattern) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) ClassObjectType(org.drools.core.base.ClassObjectType) Abductive(org.drools.core.beliefsystem.abductive.Abductive) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) QueryImpl(org.drools.core.rule.QueryImpl) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) AbductiveQuery(org.drools.core.rule.AbductiveQuery)

Example 3 with QueryImpl

use of org.drools.core.rule.QueryImpl in project drools by kiegroup.

the class QueryTest method testQueryCallingQuery.

@Test
public void testQueryCallingQuery() {
    String str = "import " + Relationship.class.getCanonicalName() + ";" + "query isRelatedTo(String x, String y)\n" + "    isRelatedTo2(x, y;)\n" + "end\n" + "query isRelatedTo2(String x, String y)\n" + "    Relationship(x, y;)\n" + "end";
    KieSession ksession = getKieSession(str);
    ksession.insert(new Relationship("A", "B"));
    ksession.insert(new Relationship("B", "C"));
    QueryResults results = ksession.getQueryResults("isRelatedTo", "A", "B");
    assertEquals(1, results.size());
    String paramName = ((QueryImpl) ksession.getKieBase().getQuery("defaultpkg", "isRelatedTo")).getParameters()[1].getIdentifier();
    assertEquals("B", results.iterator().next().get(paramName));
}
Also used : QueryImpl(org.drools.core.rule.QueryImpl) Relationship(org.drools.modelcompiler.domain.Relationship) KieSession(org.kie.api.runtime.KieSession) QueryResults(org.kie.api.runtime.rule.QueryResults) Test(org.junit.Test)

Example 4 with QueryImpl

use of org.drools.core.rule.QueryImpl in project drools by kiegroup.

the class PatternDSLTest method testQueryInvokingQuery2.

@Test
public void testQueryInvokingQuery2() {
    final org.drools.model.Query2Def<java.lang.String, java.lang.String> queryDef_isRelatedTo2 = query("isRelatedTo2", java.lang.String.class, "x", java.lang.String.class, "y");
    final org.drools.model.Query2Def<java.lang.String, java.lang.String> queryDef_isRelatedTo = query("isRelatedTo", java.lang.String.class, "x", java.lang.String.class, "y");
    org.drools.model.Query isRelatedTo_build = queryDef_isRelatedTo.build(queryDef_isRelatedTo2.call(true, queryDef_isRelatedTo.getArg1(), queryDef_isRelatedTo.getArg2()));
    final org.drools.model.Variable<org.drools.modelcompiler.domain.Relationship> var_$pattern_Relationship$4$ = declarationOf(org.drools.modelcompiler.domain.Relationship.class, "$pattern_Relationship$4$");
    org.drools.model.Query isRelatedTo2_build = queryDef_isRelatedTo2.build(pattern(var_$pattern_Relationship$4$).expr("$expr$63$", queryDef_isRelatedTo2.getArg1(), (_this, x) -> org.drools.modelcompiler.util.EvaluationUtil.areNullSafeEquals(_this.getStart(), x), betaIndexedBy(java.lang.String.class, org.drools.model.Index.ConstraintType.EQUAL, 0, _this -> _this.getStart(), x -> x), reactOn("start")).expr("$expr$64$", queryDef_isRelatedTo2.getArg2(), (_this, y) -> org.drools.modelcompiler.util.EvaluationUtil.areNullSafeEquals(_this.getEnd(), y), betaIndexedBy(java.lang.String.class, org.drools.model.Index.ConstraintType.EQUAL, 1, _this -> _this.getEnd(), y -> y), reactOn("end")));
    Model model = new ModelImpl().addQuery(isRelatedTo_build).addQuery(isRelatedTo2_build);
    KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
    KieSession ksession = kieBase.newKieSession();
    ksession.insert(new Relationship("A", "B"));
    ksession.insert(new Relationship("B", "C"));
    QueryResults results = ksession.getQueryResults("isRelatedTo", "A", "B");
    assertEquals(1, results.size());
    String paramName = ((QueryImpl) ksession.getKieBase().getQuery("defaultpkg", "isRelatedTo")).getParameters()[1].getIdentifier();
    assertEquals("B", results.iterator().next().get(paramName));
}
Also used : CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Man(org.drools.modelcompiler.domain.Man) Global(org.drools.model.Global) Toy(org.drools.modelcompiler.domain.Toy) PatternDSL.reactOn(org.drools.model.PatternDSL.reactOn) DSL(org.drools.model.DSL) Relationship(org.drools.modelcompiler.domain.Relationship) BaseModelTest.getObjectsIntoList(org.drools.modelcompiler.BaseModelTest.getObjectsIntoList) Assert.assertThat(org.junit.Assert.assertThat) Query2Def(org.drools.model.Query2Def) PatternDSL.declarationOf(org.drools.model.PatternDSL.declarationOf) Child(org.drools.modelcompiler.domain.Child) ClassObjectFilter(org.kie.api.runtime.ClassObjectFilter) QueryResults(org.kie.api.runtime.rule.QueryResults) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) QueryImpl(org.drools.core.rule.QueryImpl) PatternDSL.rule(org.drools.model.PatternDSL.rule) EventProcessingOption(org.kie.api.conf.EventProcessingOption) Collection(java.util.Collection) Index(org.drools.model.Index) PatternDSL.on(org.drools.model.PatternDSL.on) PatternDSL.pattern(org.drools.model.PatternDSL.pattern) List(java.util.List) Query(org.drools.model.Query) PatternDSL.or(org.drools.model.PatternDSL.or) PatternDSL.globalOf(org.drools.model.PatternDSL.globalOf) Person(org.drools.modelcompiler.domain.Person) PatternDSL.valueOf(org.drools.model.PatternDSL.valueOf) ModelImpl(org.drools.model.impl.ModelImpl) BitMask(org.drools.model.BitMask) PatternDSL.execute(org.drools.model.PatternDSL.execute) StockTick(org.drools.modelcompiler.domain.StockTick) PatternDSL.after(org.drools.model.PatternDSL.after) ClockType(org.drools.core.ClockType) ArrayList(java.util.ArrayList) Result(org.drools.modelcompiler.domain.Result) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Adult(org.drools.modelcompiler.domain.Adult) PatternDSL.alphaIndexedBy(org.drools.model.PatternDSL.alphaIndexedBy) PatternDSL.query(org.drools.model.PatternDSL.query) PatternDSL.reactiveFrom(org.drools.model.PatternDSL.reactiveFrom) KieServices(org.kie.api.KieServices) Woman(org.drools.modelcompiler.domain.Woman) KieBase(org.kie.api.KieBase) Model(org.drools.model.Model) PatternDSL.and(org.drools.model.PatternDSL.and) Variable(org.drools.model.Variable) Test(org.junit.Test) PatternDSL.accumulate(org.drools.model.PatternDSL.accumulate) PatternDSL.not(org.drools.model.PatternDSL.not) PatternDSL.when(org.drools.model.PatternDSL.when) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) FactHandle(org.kie.api.runtime.rule.FactHandle) PatternDSL.accFunction(org.drools.model.PatternDSL.accFunction) TimeUnit(java.util.concurrent.TimeUnit) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) ClockTypeOption(org.kie.api.runtime.conf.ClockTypeOption) Assert.assertNull(org.junit.Assert.assertNull) Rule(org.drools.model.Rule) PatternDSL.betaIndexedBy(org.drools.model.PatternDSL.betaIndexedBy) Assert.assertEquals(org.junit.Assert.assertEquals) QueryResults(org.kie.api.runtime.rule.QueryResults) Query(org.drools.model.Query) QueryImpl(org.drools.core.rule.QueryImpl) KieBase(org.kie.api.KieBase) Relationship(org.drools.modelcompiler.domain.Relationship) Model(org.drools.model.Model) KieSession(org.kie.api.runtime.KieSession) ModelImpl(org.drools.model.impl.ModelImpl) Test(org.junit.Test)

Example 5 with QueryImpl

use of org.drools.core.rule.QueryImpl in project drools by kiegroup.

the class PatternBuilder method buildQuery.

private RuleConditionElement buildQuery(RuleBuildContext context, PatternDescr descr, PatternDescr patternDescr) {
    RuleConditionElement rce = null;
    // it might be a recursive query, so check for same names
    if (context.getRule().getName().equals(patternDescr.getObjectType())) {
        // it's a query so delegate to the QueryElementBuilder
        rce = buildQueryElement(context, descr, (QueryImpl) context.getRule());
    }
    if (rce == null) {
        // look up the query in the current package
        RuleImpl rule = context.getPkg().getRule(patternDescr.getObjectType());
        if (rule instanceof QueryImpl) {
            // it's a query so delegate to the QueryElementBuilder
            rce = buildQueryElement(context, descr, (QueryImpl) rule);
        }
    }
    if (rce == null) {
        // the query may have been imported, so try package imports
        for (String importName : context.getDialect().getTypeResolver().getImports()) {
            importName = importName.trim();
            int pos = importName.indexOf('*');
            if (pos >= 0) {
                String pkgName = importName.substring(0, pos - 1);
                PackageRegistry pkgReg = context.getKnowledgeBuilder().getPackageRegistry(pkgName);
                if (pkgReg != null) {
                    RuleImpl rule = pkgReg.getPackage().getRule(patternDescr.getObjectType());
                    if (rule instanceof QueryImpl) {
                        // it's a query so delegate to the QueryElementBuilder
                        rce = buildQueryElement(context, descr, (QueryImpl) rule);
                        break;
                    }
                }
            }
        }
    }
    if (rce == null) {
        // this isn't a query either, so log an error
        registerDescrBuildError(context, patternDescr, "Unable to resolve ObjectType '" + patternDescr.getObjectType() + "'");
    }
    return rce;
}
Also used : QueryImpl(org.drools.core.rule.QueryImpl) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) RuleConditionElement(org.drools.core.rule.RuleConditionElement) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) NegConstraint(org.drools.core.rule.constraint.NegConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint)

Aggregations

QueryImpl (org.drools.core.rule.QueryImpl)6 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 List (java.util.List)1 TimeUnit (java.util.concurrent.TimeUnit)1 Assertions (org.assertj.core.api.Assertions)1 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)1 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)1 AnnotationDescr (org.drools.compiler.lang.descr.AnnotationDescr)1 ClockType (org.drools.core.ClockType)1 ClassObjectType (org.drools.core.base.ClassObjectType)1 ArrayElementReader (org.drools.core.base.extractors.ArrayElementReader)1 Abductive (org.drools.core.beliefsystem.abductive.Abductive)1 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)1 AbductiveQuery (org.drools.core.rule.AbductiveQuery)1 Declaration (org.drools.core.rule.Declaration)1 Pattern (org.drools.core.rule.Pattern)1 PredicateConstraint (org.drools.core.rule.PredicateConstraint)1 RuleConditionElement (org.drools.core.rule.RuleConditionElement)1 EvaluatorConstraint (org.drools.core.rule.constraint.EvaluatorConstraint)1