Search in sources :

Example 91 with QueryResults

use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.

the class BackwardChainingTest method testSubNetworksAndQueries.

@Test(timeout = 10000)
public void testSubNetworksAndQueries() {
    final String drl = "" + "package org.drools.compiler.test  \n" + "import java.util.List\n" + "import java.util.ArrayList\n" + "import java.util.Map\n" + "import java.util.HashMap\n" + "global List list\n" + "dialect \"mvel\"\n" + "\n" + "declare Location\n" + "    thing : String \n" + "    location : String \n" + "end" + "\n" + "declare Edible\n" + "   thing : String\n" + "end" + "\n" + "query whereFood( String x, String y ) \n" + "    Location(x, y;) Edible(x;) \n" + "end\n" + "\n" + "query look(String place, List food ) \n" + "    $s : String() // just here to give a OTN lookup point\n" + "    food := List() from accumulate( whereFood(thing, place;) ," + "                                    collectList( thing ) )\n" + "    exists( whereFood(thing, place;) )\n" + "    not( whereFood(thing, place;) and\n " + "         String( this == $s ) from thing )\n" + "end\n" + "\n" + "rule init when\n" + "then\n" + "        \n" + "        insert( new Location(\"apple\", \"kitchen\") );\n" + "        insert( new Location(\"crackers\", \"kitchen\") );\n" + "        insert( new Location(\"broccoli\", \"kitchen\") );\n" + "        insert( new Location(\"computer\", \"office\") );\n" + "        insert( new Edible(\"apple\") );\n" + "        insert( new Edible(\"crackers\") );\n" + "end\n" + "";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
    // Get the accumulate node, so we can test it's memory later
    // now check beta memory was correctly cleared
    final List<ObjectTypeNode> nodes = ((RuleBase) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (final ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == String.class) {
            node = n;
            break;
        }
    }
    assertNotNull(node);
    final BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
    final AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
    final ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
    final QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
    final FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
    final RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
    final NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
    final KieSession ksession = kbase.newKieSession();
    try {
        final InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) ksession);
        final AccumulateNode.AccumulateMemory accMemory = (AccumulateNode.AccumulateMemory) wm.getNodeMemory(accNode);
        final BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
        final FromNode.FromMemory fromMemory = (FromNode.FromMemory) wm.getNodeMemory(fromNode);
        final BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
        final List<Map<String, Object>> list = new ArrayList<>();
        ksession.setGlobal("list", list);
        final FactHandle fh = ksession.insert("bread");
        ksession.fireAllRules();
        final List food = new ArrayList();
        // Execute normal query and check no subnetwork tuples are left behind
        QueryResults results = ksession.getQueryResults("look", "kitchen", Variable.v);
        assertEquals(1, results.size());
        for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
            food.addAll((Collection) row.get("food"));
        }
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        assertEquals(0, notMemory.getRightTupleMemory().size());
        // Now execute an open query and ensure the memory is left populated
        food.clear();
        final List foodUpdated = new ArrayList();
        final LiveQuery query = ksession.openLiveQuery("look", new Object[] { "kitchen", Variable.v }, new ViewChangedEventListener() {

            public void rowUpdated(final Row row) {
                foodUpdated.addAll((Collection) row.get("food"));
            }

            public void rowDeleted(final Row row) {
            }

            public void rowInserted(final Row row) {
                food.addAll((Collection) row.get("food"));
            }
        });
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        assertEquals(0, notMemory.getRightTupleMemory().size());
        food.clear();
        // Now try again, make sure it only delete's it's own tuples
        results = ksession.getQueryResults("look", "kitchen", Variable.v);
        assertEquals(1, results.size());
        for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
            food.addAll((Collection) row.get("food"));
        }
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        assertEquals(0, notMemory.getRightTupleMemory().size());
        food.clear();
        // do an update and check it's  still memory size 2
        // however this time the food should be empty, as 'crackers' now blocks the not.
        ksession.update(fh, "crackers");
        ksession.fireAllRules();
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        assertEquals(1, existsMemory.getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, notMemory.getRightTupleMemory().size());
        assertEquals(0, foodUpdated.size());
        // do an update and check it's  still memory size 2
        // this time
        ksession.update(fh, "oranges");
        ksession.fireAllRules();
        assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
        assertEquals(1, existsMemory.getLeftTupleMemory().size());
        // This is zero, as it's held directly on the LeftTuple context
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        assertEquals(0, notMemory.getRightTupleMemory().size());
        assertEquals(2, food.size());
        assertContains(new String[] { "crackers", "apple" }, food);
        // Close the open
        query.close();
        assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
        assertEquals(0, existsMemory.getRightTupleMemory().size());
        assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
        assertEquals(0, notMemory.getRightTupleMemory().size());
    } finally {
        ksession.dispose();
    }
}
Also used : NotNode(org.drools.core.reteoo.NotNode) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) AccumulateNode(org.drools.core.reteoo.AccumulateNode) QueryElementNode(org.drools.core.reteoo.QueryElementNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ArrayList(java.util.ArrayList) FromNode(org.drools.core.reteoo.FromNode) ExistsNode(org.drools.core.reteoo.ExistsNode) LiveQuery(org.kie.api.runtime.rule.LiveQuery) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) BetaNode(org.drools.core.reteoo.BetaNode) BetaMemory(org.drools.core.reteoo.BetaMemory) QueryResults(org.kie.api.runtime.rule.QueryResults) ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) Collection(java.util.Collection) Row(org.kie.api.runtime.rule.Row) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 92 with QueryResults

use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.

the class AccumulateTest method testAccumulateWithVarsOutOfHashOrder.

@Test(timeout = 10000)
public void testAccumulateWithVarsOutOfHashOrder() {
    // JBRULES-3494
    final String drl = "package com.sample;\n" + "\n" + "import java.util.List;\n" + "\n" + "declare MessageHolder\n" + "  id : String\n" + "  msg: String\n" + "end\n" + "\n" + "query getResults( String $mId, List $holders )\n" + "  accumulate(  \n" + "    $holder  : MessageHolder( id == $mId, $ans : msg ),\n" + "    $holders := collectList( $holder )\n" + "  ) \n" + "end\n" + "\n" + "rule \"Init\"\n" + "when\n" + "then\n" + "  insert( new MessageHolder( \"1\", \"x\" ) );\n" + "end\n";
    final InternalKnowledgeBase kbase = (InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("accumulate-test", kieBaseTestConfiguration);
    final KieSession ksession = kbase.newKieSession();
    try {
        kbase.addPackages(TestUtil.createKnowledgeBuilder(null, drl).getKnowledgePackages());
        ksession.fireAllRules();
        final QueryResults res = ksession.getQueryResults("getResults", "1", Variable.v);
        assertEquals(1, res.size());
        final Object o = res.iterator().next().get("$holders");
        assertTrue(o instanceof List);
        assertEquals(1, ((List) o).size());
    } finally {
        ksession.dispose();
    }
}
Also used : KieSession(org.kie.api.runtime.KieSession) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) QueryResults(org.kie.api.runtime.rule.QueryResults) Test(org.junit.Test)

Example 93 with QueryResults

use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.

the class AccumulateConsistencyTest method testMinMatchUnificationQuery.

@Test
public void testMinMatchUnificationQuery() {
    final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.List;\n" + "query getResults( String $name, List $persons )\n" + "  accumulate(  \n" + "    $p : Person( name == $name),\n" + "    $persons := collectList( $p )\n" + "  ) \n" + "end\n";
    final KieBase kieBase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("accumulate-test", kieBaseTestConfiguration, drl);
    KieSessionConfiguration kieSessionConfiguration = KieServices.get().newKieSessionConfiguration();
    kieSessionConfiguration.setProperty(AccumulateNullPropagationOption.PROPERTY_NAME, Boolean.toString(accumulateNullPropagation));
    final KieSession kieSession = kieBase.newKieSession(kieSessionConfiguration, null);
    try {
        kieSession.insert(new Person(0, "John", 20));
        kieSession.insert(new Person(1, "John", 19));
        final QueryResults results = kieSession.getQueryResults("getResults", "John", Variable.v);
        List<Person> persons = (List<Person>) results.iterator().next().get("$persons");
        assertEquals(2, persons.size());
    } finally {
        kieSession.dispose();
    }
}
Also used : KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Person(org.drools.testcoverage.common.model.Person) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) QueryResults(org.kie.api.runtime.rule.QueryResults) Test(org.junit.Test)

Example 94 with QueryResults

use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.

the class QueryCommand method execute.

public QueryResults execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
    if (this.arguments == null || this.arguments.isEmpty()) {
        this.arguments = Collections.emptyList();
    }
    for (int j = 0; j < arguments.size(); j++) {
        if (arguments.get(j) instanceof Variable) {
            arguments.set(j, Variable.v);
        }
    }
    QueryResults results = ksession.getQueryResults(name, this.arguments.toArray());
    if (this.outIdentifier != null) {
        ((RegistryContext) context).lookup(ExecutionResultImpl.class).setResult(this.outIdentifier, new FlatQueryResults((QueryResultsImpl) results));
    }
    return results;
}
Also used : QueryResultsImpl(org.drools.core.QueryResultsImpl) Variable(org.kie.api.runtime.rule.Variable) ExecutionResultImpl(org.drools.core.runtime.impl.ExecutionResultImpl) KieSession(org.kie.api.runtime.KieSession) RegistryContext(org.kie.internal.command.RegistryContext) FlatQueryResults(org.drools.core.runtime.rule.impl.FlatQueryResults) FlatQueryResults(org.drools.core.runtime.rule.impl.FlatQueryResults) QueryResults(org.kie.api.runtime.rule.QueryResults)

Example 95 with QueryResults

use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.

the class BasicUpdateTest method verifyFactsWithQuery.

private <T> void verifyFactsWithQuery(final Class<T> expectedClassOfFacts, final String queryToGetFacts, final T... factsToVerify) {
    final QueryResults results = ksession.getQueryResults(queryToGetFacts);
    assertThat(results).isNotEmpty();
    final QueryResultsRow resultsRow = results.iterator().next();
    assertThat(resultsRow.get("$" + queryToGetFacts)).isInstanceOf(List.class);
    final List<Object> objects = (List<Object>) resultsRow.get("$" + queryToGetFacts);
    assertThat(objects).hasSize(factsToVerify.length);
    assertThat(objects).hasOnlyElementsOfType(expectedClassOfFacts);
    assertThat(objects).containsAll(Arrays.asList(factsToVerify));
}
Also used : QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) ArrayList(java.util.ArrayList) List(java.util.List) QueryResults(org.kie.api.runtime.rule.QueryResults)

Aggregations

QueryResults (org.kie.api.runtime.rule.QueryResults)120 Test (org.junit.Test)103 KieSession (org.kie.api.runtime.KieSession)87 ArrayList (java.util.ArrayList)45 KieBase (org.kie.api.KieBase)43 List (java.util.List)35 QueryResultsRow (org.kie.api.runtime.rule.QueryResultsRow)34 FlatQueryResults (org.drools.core.runtime.rule.impl.FlatQueryResults)22 FactHandle (org.kie.api.runtime.rule.FactHandle)22 Person (org.drools.modelcompiler.domain.Person)21 Arrays (java.util.Arrays)12 Collection (java.util.Collection)12 Assertions (org.assertj.core.api.Assertions)11 Map (java.util.Map)10 Relationship (org.drools.modelcompiler.domain.Relationship)9 Assert.assertEquals (org.junit.Assert.assertEquals)9 IOException (java.io.IOException)8 TimeUnit (java.util.concurrent.TimeUnit)7 ClockType (org.drools.core.ClockType)7 SessionPseudoClock (org.kie.api.time.SessionPseudoClock)7