You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kie.apache.org by ma...@apache.org on 2025/10/08 07:18:31 UTC
(incubator-kie-drools) branch main updated: [Incubator-kie-issue #2030] Query tests cleanup (#6475)
This is an automated email from the ASF dual-hosted git repository.
mariofusco pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-kie-drools.git
The following commit(s) were added to refs/heads/main by this push:
new 8129266123 [Incubator-kie-issue #2030] Query tests cleanup (#6475)
8129266123 is described below
commit 8129266123dc4177c467a06607e1f5b49c17e71c
Author: Paolo Bizzarri <pi...@gmail.com>
AuthorDate: Wed Oct 8 09:18:27 2025 +0200
[Incubator-kie-issue #2030] Query tests cleanup (#6475)
* Cleanup of Query Tests
* Split in tests
* Playing around with some code
* Removed caching experimenti
* Cleaning query tests
* Cleanup of query tests
* Fixed header issues
* Fixed code reviews
* Removed files added by mistake
---
.../java/org/drools/core/reteoo/ReteDumper.java | 4 +
.../session/StatefulKnowledgeSessionImpl.java | 7 +-
.../drools/mvel/integrationtests/Query3Test.java | 233 ----
.../drools/mvel/integrationtests/QueryTest.java | 1373 --------------------
.../integrationtests/{ => query}/Query2Test.java | 43 +-
.../query/QueryArgumentUnificationTest.java | 157 +++
.../mvel/integrationtests/query/QueryLiveTest.java | 323 +++++
.../query/QueryMatchingPropertiesTest.java | 475 +++++++
.../mvel/integrationtests/query/QueryTest.java | 861 ++++++++++++
.../query/QueryWithErrorsTest.java | 137 ++
.../mvel/integrationtests/test_QueryWithParams.drl | 39 -
.../mvel/integrationtests/test_TwoQuerries.drl | 31 -
12 files changed, 1982 insertions(+), 1701 deletions(-)
diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ReteDumper.java b/drools-core/src/main/java/org/drools/core/reteoo/ReteDumper.java
index 5eb604daab..950b7296f3 100644
--- a/drools-core/src/main/java/org/drools/core/reteoo/ReteDumper.java
+++ b/drools-core/src/main/java/org/drools/core/reteoo/ReteDumper.java
@@ -23,7 +23,9 @@ import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
+import java.util.Map;
import java.util.Set;
+import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -197,9 +199,11 @@ public class ReteDumper {
private void dumpNode( BaseNode node, String ident, Set<BaseNode> visitedNodes, BiConsumer<BaseNode, String> consumer ) {
consumer.accept( node, ident );
+
if (!visitedNodes.add( node )) {
return;
}
+
NetworkNode[] sinks = node.getSinks();
if (sinks != null) {
for (NetworkNode sink : sinks) {
diff --git a/drools-kiesession/src/main/java/org/drools/kiesession/session/StatefulKnowledgeSessionImpl.java b/drools-kiesession/src/main/java/org/drools/kiesession/session/StatefulKnowledgeSessionImpl.java
index 427741c1b7..264837b2d2 100644
--- a/drools-kiesession/src/main/java/org/drools/kiesession/session/StatefulKnowledgeSessionImpl.java
+++ b/drools-kiesession/src/main/java/org/drools/kiesession/session/StatefulKnowledgeSessionImpl.java
@@ -39,7 +39,6 @@ import org.drools.core.base.NonCloningQueryViewListener;
import org.drools.core.base.QueryRowWithSubruleIndex;
import org.drools.core.base.StandardQueryViewChangedEventListener;
import org.drools.core.common.ActivationsManager;
-import org.drools.core.common.BaseNode;
import org.drools.core.common.ConcurrentNodeMemories;
import org.drools.core.common.EndOperationListener;
import org.drools.core.common.EventSupport;
@@ -69,7 +68,6 @@ import org.drools.core.phreak.RuleAgendaItem;
import org.drools.core.reteoo.AsyncReceiveNode;
import org.drools.core.reteoo.EntryPointNode;
import org.drools.core.reteoo.LeftInputAdapterNode;
-import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.ObjectTypeNode;
import org.drools.core.reteoo.PathMemory;
import org.drools.core.reteoo.QueryTerminalNode;
@@ -149,6 +147,8 @@ import static org.drools.base.base.ClassObjectType.InitialFact_ObjectType;
import static org.drools.base.reteoo.PropertySpecificUtil.allSetButTraitBitMask;
import static org.drools.util.ClassUtils.rawType;
+
+
public class StatefulKnowledgeSessionImpl extends AbstractRuntime
implements
StatefulKnowledgeSession,
@@ -249,6 +249,8 @@ public class StatefulKnowledgeSessionImpl extends AbstractRuntime
private Consumer<PropagationEntry> workingMemoryActionListener;
private boolean tmsEnabled;
+
+
// ------------------------------------------------------------
// Constructors
@@ -659,7 +661,6 @@ public class StatefulKnowledgeSessionImpl extends AbstractRuntime
}
this.handleFactory.destroyFactHandle( handle);
-
return new QueryResultsImpl( (List<QueryRowWithSubruleIndex>) queryObject.getQueryResultCollector().getResults(),
decls.toArray( new Map[decls.size()] ),
this,
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query3Test.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query3Test.java
deleted file mode 100644
index 8cf7c6e97a..0000000000
--- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query3Test.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.drools.mvel.integrationtests;
-
-
-import java.util.stream.Stream;
-
-import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
-import org.drools.testcoverage.common.util.KieBaseUtil;
-import org.drools.testcoverage.common.util.TestParametersUtil2;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-import org.kie.api.KieBase;
-import org.kie.api.runtime.KieSession;
-import org.kie.api.runtime.rule.FactHandle;
-import org.kie.api.runtime.rule.QueryResults;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class Query3Test {
-
- public static Stream<KieBaseTestConfiguration> parameters() {
- return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
- }
-
- private KieBase knowledgeBase;
-
- public void setUp(KieBaseTestConfiguration kieBaseTestConfiguration) {
- String text = "";
- text += "package org.drools.integrationtests\n";
- text += "import " + Query3Test.Bar.class.getCanonicalName() + "\n";
- text += "import " + Query3Test.Foo.class.getCanonicalName() + "\n";
- text += "import " + Query3Test.Foo2.class.getCanonicalName() + "\n";
- text += "query \"testDifferent\"\n";
- text += " foo : Foo();\n";
- text += " bar : Bar(id == foo.id)\n";
- text += "end\n";
- text += "query \"testSame\"\n";
- text += " foo : Foo();\n";
- text += " foo2 : Foo(id == foo.id);\n";
- text += "end\n";
- text += "query \"testExtends\"\n";
- text += " foo : Foo();\n";
- text += " foo2 : Foo2(id == foo.id);\n";
- text += "end\n";
-
- knowledgeBase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, text);
- }
-
- private void doIt(Object o1,
- Object o2,
- String query,
- int expected,
- boolean doUpdate,
- boolean doRetract) {
- KieSession knowledgeSession = knowledgeBase.newKieSession();
- try {
- knowledgeSession.insert( o1 );
- FactHandle handle2 = knowledgeSession.insert( o2 );
- if ( doUpdate ) {
- knowledgeSession.update( handle2,
- o2 );
- } else if ( doRetract ) {
- knowledgeSession.retract( handle2 );
- handle2 = knowledgeSession.insert( o2 );
- }
- QueryResults queryResults = knowledgeSession.getQueryResults( query );
- assertThat(queryResults.size()).isEqualTo(expected);
- } finally {
- knowledgeSession.dispose();
- }
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testDifferent(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Bar bar = new Bar();
- bar.setId( "x" );
- doIt( foo,
- bar,
- "testDifferent",
- 1,
- false,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testDifferentWithUpdate(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Bar bar = new Bar();
- bar.setId( "x" );
- doIt( foo,
- bar,
- "testDifferent",
- 1,
- true,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testSame(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Foo foo2 = new Foo();
- foo2.setId( "x" );
- doIt( foo,
- foo2,
- "testSame",
- 4,
- false,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testSameWithUpdate(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Foo foo2 = new Foo();
- foo2.setId( "x" );
- doIt( foo,
- foo2,
- "testSame",
- 4,
- true,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testExtends(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Foo2 foo2 = new Foo2();
- foo2.setId( "x" );
- doIt( foo,
- foo2,
- "testExtends",
- 2,
- false,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testExtendsWithUpdate(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Foo2 foo2 = new Foo2();
- foo2.setId( "x" );
- doIt( foo,
- foo2,
- "testExtends",
- 2,
- true,
- false );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testExtendsWithRetract(KieBaseTestConfiguration kieBaseTestConfiguration) {
- setUp(kieBaseTestConfiguration);
- Foo foo = new Foo();
- foo.setId( "x" );
- Foo2 foo2 = new Foo2();
- foo2.setId( "x" );
- doIt( foo,
- foo2,
- "testExtends",
- 2,
- false,
- true );
- }
-
- public static class Bar {
-
- private String id;
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- }
-
- public static class Foo {
-
- private String id;
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- }
-
- public static class Foo2 extends Foo {
-
- }
-}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/QueryTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/QueryTest.java
deleted file mode 100644
index 15175cabe6..0000000000
--- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/QueryTest.java
+++ /dev/null
@@ -1,1373 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.drools.mvel.integrationtests;
-
-import org.drools.base.base.ClassObjectType;
-import org.drools.base.base.DroolsQuery;
-import org.drools.base.base.ObjectType;
-import org.drools.commands.runtime.FlatQueryResults;
-import org.drools.core.QueryResultsImpl;
-import org.drools.core.common.InternalFactHandle;
-import org.drools.core.impl.InternalRuleBase;
-import org.drools.core.reteoo.EntryPointNode;
-import org.drools.core.reteoo.ObjectTypeNode;
-import org.drools.core.reteoo.ReteDumper;
-import org.drools.kiesession.session.StatefulKnowledgeSessionImpl;
-import org.drools.mvel.compiler.Address;
-import org.drools.mvel.compiler.Cheese;
-import org.drools.mvel.compiler.DomainObject;
-import org.drools.mvel.compiler.InsertedObject;
-import org.drools.mvel.compiler.Interval;
-import org.drools.mvel.compiler.Person;
-import org.drools.mvel.compiler.Worker;
-import org.drools.mvel.compiler.oopath.model.Thing;
-import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
-import org.drools.testcoverage.common.util.KieBaseUtil;
-import org.drools.testcoverage.common.util.KieUtil;
-import org.drools.testcoverage.common.util.TestParametersUtil2;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.TestInfo;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-import org.kie.api.KieBase;
-import org.kie.api.builder.KieBuilder;
-import org.kie.api.builder.Message;
-import org.kie.api.runtime.KieSession;
-import org.kie.api.runtime.conf.QueryListenerOption;
-import org.kie.api.runtime.rule.FactHandle;
-import org.kie.api.runtime.rule.LiveQuery;
-import org.kie.api.runtime.rule.QueryResults;
-import org.kie.api.runtime.rule.QueryResultsRow;
-import org.kie.api.runtime.rule.Row;
-import org.kie.api.runtime.rule.Variable;
-import org.kie.api.runtime.rule.ViewChangedEventListener;
-
-import jakarta.xml.bind.JAXBContext;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class QueryTest {
-
- public static Stream<KieBaseTestConfiguration> parameters() {
- return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
- }
-
- @BeforeEach
- public void before(TestInfo info) {
- System.out.println( "] " + info.getTestMethod().get().getName());
- }
-
- private static QueryResults getQueryResults(KieSession session, String queryName, Object... arguments ) throws Exception {
- QueryResultsImpl results = (QueryResultsImpl) session.getQueryResults( queryName, arguments );
-
- FlatQueryResults flatResults = new FlatQueryResults(results);
-
- assertThat(flatResults.size()).as("Query results size").isEqualTo(results.size());
- assertThat(flatResults.getIdentifiers().length).as("Query results identifiers").isEqualTo(results.getIdentifiers().length);
- Set<String> resultIds = new TreeSet<String>(Arrays.asList(results.getIdentifiers()));
- Set<String> flatIds = new TreeSet<String>(Arrays.asList(flatResults.getIdentifiers()));
- assertThat(resultIds.toArray()).as("Flat query results identifiers").isEqualTo(flatIds.toArray());
-
- FlatQueryResults copyFlatResults = roundTrip(flatResults);
- String [] identifiers = results.getIdentifiers();
- Iterator<QueryResultsRow> copyFlatIter = copyFlatResults.iterator();
- for( int i = 0; i < results.size(); ++i ) {
- QueryResultsRow row = results.get(i);
- assertThat(copyFlatIter.hasNext()).as("Round-tripped flat query results contain less rows than original query results").isTrue();
- QueryResultsRow copyRow = copyFlatIter.next();
- for( String id : identifiers ) {
- Object obj = row.get(id);
- if( obj != null ) {
- Object copyObj = copyRow.get(id);
- assertThat(obj != null && obj.equals(copyObj)).as("Flat query result [" + i + "] does not contain result: '" + id + "': " + obj + "/" + copyObj).isTrue();
- }
- FactHandle fh = row.getFactHandle(id);
- FactHandle copyFh = copyRow.getFactHandle(id);
- if( fh != null ) {
- assertThat(copyFh).as( "Flat query result [" + i + "] does not contain facthandle: '" + ((InternalFactHandle) fh).getId() + "'").isNotNull();
- String fhStr = fh.toExternalForm();
- fhStr = fhStr.substring(0, fhStr.lastIndexOf(":"));
- String copyFhStr = copyFh.toExternalForm();
- copyFhStr = copyFhStr.substring(0, copyFhStr.lastIndexOf(":"));
- assertThat(copyFhStr).as("Unequal fact handles for fact handle '" + ((InternalFactHandle) fh).getId() + "':").isEqualTo(fhStr);
- }
- }
- }
-
- // check identifiers
- Set<String> copyFlatIds = new TreeSet<String>(Arrays.asList(copyFlatResults.getIdentifiers()));
- assertThat(copyFlatIds.toArray() ).as("Flat query results identifiers").isEqualTo(flatIds.toArray());
- return copyFlatResults;
- }
-
-
- private static <T> T roundTrip( Object obj ) throws Exception {
- Class[] classes = { obj.getClass() };
- JAXBContext ctx = getJaxbContext(classes);
- String xmlOut = marshall(ctx, obj);
- return unmarshall(ctx, xmlOut);
- }
-
- private static <T> T unmarshall( JAXBContext ctx, String xmlIn ) throws Exception {
- ByteArrayInputStream xmlStrInputStream = new ByteArrayInputStream(xmlIn.getBytes(Charset.forName("UTF-8")));
- Object out = ctx.createUnmarshaller().unmarshal(xmlStrInputStream);
- return (T) out;
- }
-
- private static String marshall( JAXBContext ctx, Object obj ) throws Exception {
- StringWriter writer = new StringWriter();
- ctx.createMarshaller().marshal(obj, writer);
- return writer.getBuffer().toString();
- }
-
- private static JAXBContext getJaxbContext( Class<?>... classes ) throws Exception {
- List<Class<?>> jaxbClassList = new ArrayList<Class<?>>();
- jaxbClassList.addAll(Arrays.asList(classes));
- jaxbClassList.add(Cheese.class);
- jaxbClassList.add(InsertedObject.class);
- jaxbClassList.add(Person.class);
- Class<?>[] jaxbClasses = jaxbClassList.toArray(new Class[jaxbClassList.size()]);
- return JAXBContext.newInstance(jaxbClasses);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQuery2(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_Query.drl");
- KieSession session = kbase.newKieSession();
-
- session.fireAllRules();
-
- QueryResults results = getQueryResults(session, "assertedobjquery" );
- assertThat(results.size()).isEqualTo(1);
- assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject("value1" ));
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithParams(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_QueryWithParams.drl");
- KieSession session = kbase.newKieSession();
-
- session.fireAllRules();
-
- String queryName = "assertedobjquery";
- String [] arguments = new String[]{"value1"};
- QueryResultsImpl resultsImpl = (QueryResultsImpl) session.getQueryResults( queryName, arguments );
-
- QueryResults results = getQueryResults( session, queryName, arguments );
-
- assertThat(results.size()).isEqualTo(1);
- InsertedObject value = new InsertedObject( "value1" );
- assertThat(results.iterator().next().get("assertedobj")).isEqualTo(value);
-
- results = getQueryResults( session, "assertedobjquery", new String[]{"value3"} );
-
- assertThat(results.size()).isEqualTo(0);
-
- results = getQueryResults( session, "assertedobjquery2", new String[]{null, "value2"} );
- assertThat(results.size()).isEqualTo(1);
- assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject( "value2" ));
-
- results = getQueryResults(session, "assertedobjquery2", new String[]{"value3", "value2"} );
-
- assertThat(results.size()).isEqualTo(1);
- assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject( "value2" ));
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithMultipleResultsOnKnowledgeApi(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Cheese \n";
- str += "query cheeses \n";
- str += " stilton : Cheese(type == 'stilton') \n";
- str += " cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession session = kbase.newKieSession();
-
-
- Cheese stilton1 = new Cheese( "stilton", 1 );
- Cheese cheddar1 = new Cheese( "cheddar", 1 );
- Cheese stilton2 = new Cheese( "stilton", 2 );
- Cheese cheddar2 = new Cheese( "cheddar", 2 );
- Cheese stilton3 = new Cheese( "stilton", 3 );
- Cheese cheddar3 = new Cheese( "cheddar", 3 );
-
- Set set = new HashSet();
- List list = new ArrayList();
- list.add( stilton1 );
- list.add( cheddar1 );
- set.add( list );
-
- list = new ArrayList();
- list.add( stilton2 );
- list.add( cheddar2 );
- set.add( list );
-
- list = new ArrayList();
- list.add( stilton3 );
- list.add( cheddar3 );
- set.add( list );
-
- session.insert( stilton1 );
- session.insert( stilton2 );
- session.insert( stilton3 );
- session.insert( cheddar1 );
- session.insert( cheddar2 );
- session.insert( cheddar3 );
-
- org.kie.api.runtime.rule.QueryResults results = getQueryResults(session, "cheeses" );
- assertThat(results.size()).isEqualTo(3);
- assertThat(results.getIdentifiers().length).isEqualTo(2);
-
- Set newSet = new HashSet();
- for ( org.kie.api.runtime.rule.QueryResultsRow result : results ) {
- list = new ArrayList();
- list.add( result.get( "stilton" ) );
- list.add( result.get( "cheddar" ) );
- newSet.add( list );
- }
- assertThat(newSet).isEqualTo(set);
-
- FlatQueryResults flatResults = new FlatQueryResults( ((StatefulKnowledgeSessionImpl) session).getQueryResults( "cheeses" ) );
-
- newSet = new HashSet();
- for ( org.kie.api.runtime.rule.QueryResultsRow result : flatResults ) {
- list = new ArrayList();
- list.add( result.get( "stilton" ) );
- list.add( result.get( "cheddar" ) );
- newSet.add( list );
- }
- assertThat(newSet).isEqualTo(set);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testTwoQuerries(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- // @see JBRULES-410 More than one Query definition causes an incorrect
- // Rete network to be built.
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_TwoQuerries.drl");
- KieSession session = kbase.newKieSession();
-
- final Cheese stilton = new Cheese( "stinky",
- 5 );
- session.insert( stilton );
- final Person per1 = new Person( "stinker",
- "smelly feet",
- 70 );
- final Person per2 = new Person( "skunky",
- "smelly armpits",
- 40 );
-
- session.insert( per1 );
- session.insert( per2 );
-
- QueryResults results = getQueryResults( session, "find stinky cheeses" );
- assertThat(results.size()).isEqualTo(1);
-
- results = getQueryResults( session, "find pensioners" );
- assertThat(results.size()).isEqualTo(1);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testDoubleQueryWithExists(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_DoubleQueryWithExists.drl");
- KieSession session = kbase.newKieSession();
-
- final Person p1 = new Person( "p1",
- "stilton",
- 20 );
- p1.setStatus( "europe" );
- final FactHandle c1FactHandle = session.insert( p1 );
- final Person p2 = new Person( "p2",
- "stilton",
- 30 );
- p2.setStatus( "europe" );
- final FactHandle c2FactHandle = session.insert( p2 );
- final Person p3 = new Person( "p3",
- "stilton",
- 40 );
- p3.setStatus( "europe" );
- final FactHandle c3FactHandle = session.insert( p3 );
- session.fireAllRules();
-
- QueryResults results = session.getQueryResults( "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(2);
-
- // europe=[ 1, 2 ], america=[ 3 ]
- p3.setStatus( "america" );
- session.update( c3FactHandle,
- p3 );
- session.fireAllRules();
- results = session.getQueryResults( "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(1);
-
- // europe=[ 1 ], america=[ 2, 3 ]
- p2.setStatus( "america" );
- session.update( c2FactHandle,
- p2 );
- session.fireAllRules();
- results = session.getQueryResults( "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(1);
-
- // europe=[ ], america=[ 1, 2, 3 ]
- p1.setStatus( "america" );
- session.update( c1FactHandle,
- p1 );
- session.fireAllRules();
- results = getQueryResults( session, "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(2);
-
- // europe=[ 2 ], america=[ 1, 3 ]
- p2.setStatus( "europe" );
- session.update( c2FactHandle,
- p2 );
- session.fireAllRules();
- results = getQueryResults( session, "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(1);
-
- // europe=[ 1, 2 ], america=[ 3 ]
- p1.setStatus( "europe" );
- session.update( c1FactHandle,
- p1 );
- session.fireAllRules();
- results = session.getQueryResults( "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(1);
-
- // europe=[ 1, 2, 3 ], america=[ ]
- p3.setStatus( "europe" );
- session.update( c3FactHandle,
- p3 );
- session.fireAllRules();
- results = session.getQueryResults( "2 persons with the same status" );
- assertThat(results.size()).isEqualTo(2);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithCollect(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_Query.drl");
- KieSession session = kbase.newKieSession();
- session.fireAllRules();
-
- QueryResults results = getQueryResults( session, "collect objects" );
- assertThat(results.size()).isEqualTo(1);
-
- final QueryResultsRow row = results.iterator().next();
- final List list = (List) row.get( "$list" );
-
- assertThat(list.size()).isEqualTo(2);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testDroolsQueryCleanup(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "test_QueryMemoryLeak.drl");
-
- KieSession ksession = kbase.newKieSession();
-
- String workerId = "B1234";
- Worker worker = new Worker();
- worker.setId( workerId );
-
- FactHandle handle = ksession.insert( worker );
- ksession.fireAllRules();
-
- assertThat(handle).isNotNull();
-
- Object retractedWorker = null;
- for ( int i = 0; i < 100; i++ ) {
- retractedWorker = ksession.getQueryResults("getWorker",
- new Object[]{workerId});
- }
-
- assertThat(retractedWorker).isNotNull();
-
- StatefulKnowledgeSessionImpl sessionImpl = (StatefulKnowledgeSessionImpl) ksession;
-
- Collection<EntryPointNode> entryPointNodes = ((InternalRuleBase)kbase).getRete().getEntryPointNodes().values();
-
- EntryPointNode defaultEntryPointNode = null;
- for ( EntryPointNode epNode : entryPointNodes ) {
- if ( epNode.getEntryPoint().getEntryPointId().equals( "DEFAULT" ) ) {
- defaultEntryPointNode = epNode;
- break;
- }
- }
- assertThat(defaultEntryPointNode).isNotNull();
-
- Map<ObjectType, ObjectTypeNode> obnodes = defaultEntryPointNode.getObjectTypeNodes();
-
- ObjectType key = new ClassObjectType( DroolsQuery.class );
- ObjectTypeNode droolsQueryNode = obnodes.get( key );
- Iterator<InternalFactHandle> it = droolsQueryNode.getFactHandlesIterator(sessionImpl);
- assertThat(it.hasNext()).isFalse();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueriesWithVariableUnification(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Person \n";
- str += "query peeps( String $name, String $likes, int $age ) \n";
- str += " $p : Person( $name := name, $likes := likes, $age := age ) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- Person p1 = new Person( "darth",
- "stilton",
- 100 );
- Person p2 = new Person( "yoda",
- "stilton",
- 300 );
- Person p3 = new Person( "luke",
- "brie",
- 300 );
- Person p4 = new Person( "bobba",
- "cheddar",
- 300 );
-
- ksession.insert( p1 );
- ksession.insert( p2 );
- ksession.insert( p3 );
- ksession.insert( p4 );
-
- QueryResults results = getQueryResults(ksession, "peeps", Variable.v, Variable.v, Variable.v);
- assertThat(results.size()).isEqualTo(4);
- List names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(4);
- assertThat(names.contains("luke")).isTrue();
- assertThat(names.contains("yoda")).isTrue();
- assertThat(names.contains("bobba")).isTrue();
- assertThat(names.contains("darth")).isTrue();
-
- results = getQueryResults(ksession, "peeps", Variable.v, Variable.v, 300);
- assertThat(results.size()).isEqualTo(3);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(3);
- assertThat(names.contains("luke")).isTrue();
- assertThat(names.contains("yoda")).isTrue();
- assertThat(names.contains("bobba")).isTrue();
-
- results = getQueryResults(ksession, "peeps", Variable.v, "stilton", 300);
- assertThat(results.size()).isEqualTo(1);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(1);
- assertThat(names.contains("yoda")).isTrue();
-
- results = ksession.getQueryResults("peeps",
- Variable.v, "stilton", Variable.v);
- assertThat(results.size()).isEqualTo(2);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(2);
- assertThat(names.contains("yoda")).isTrue();
- assertThat(names.contains("darth")).isTrue();
-
- results = ksession.getQueryResults("peeps",
- "darth", Variable.v, Variable.v);
- assertThat(results.size()).isEqualTo(1);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(1);
- assertThat(names.contains("darth")).isTrue();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueriesWithVariableUnificationOnPatterns(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Person \n";
- str += "query peeps( Person $p, String $name, String $likes, int $age ) \n";
- str += " $p := Person( $name := name, $likes := likes, $age := age ) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- Person p1 = new Person( "darth",
- "stilton",
- 100 );
- Person p2 = new Person( "yoda",
- "stilton",
- 300 );
- Person p3 = new Person( "luke",
- "brie",
- 300 );
- Person p4 = new Person( "bobba",
- "cheddar",
- 300 );
-
- ksession.insert( p1 );
- ksession.insert( p2 );
- ksession.insert( p3 );
- ksession.insert( p4 );
-
- org.kie.api.runtime.rule.QueryResults results = ksession.getQueryResults("peeps",
- Variable.v, Variable.v, Variable.v, Variable.v);
- assertThat(results.size()).isEqualTo(4);
- List names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(4);
- assertThat(names.contains("luke")).isTrue();
- assertThat(names.contains("yoda")).isTrue();
- assertThat(names.contains("bobba")).isTrue();
- assertThat(names.contains("darth")).isTrue();
-
- results = ksession.getQueryResults("peeps",
- p1, Variable.v, Variable.v, Variable.v);
- assertThat(results.size()).isEqualTo(1);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.size()).isEqualTo(1);
- assertThat(names.contains("darth")).isTrue();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueriesWithVariableUnificationOnNestedFields(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Person \n";
- str += "query peeps( String $name, String $likes, String $street) \n";
- str += " $p : Person( $name := name, $likes := likes, $street := address.street ) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- Person p1 = new Person( "darth",
- "stilton",
- 100 );
- p1.setAddress( new Address( "s1" ) );
-
- Person p2 = new Person( "yoda",
- "stilton",
- 300 );
- p2.setAddress( new Address( "s2" ) );
-
- ksession.insert( p1 );
- ksession.insert( p2 );
-
- QueryResults results = getQueryResults(ksession, "peeps", Variable.v, Variable.v, Variable.v);
- assertThat(results.size()).isEqualTo(2);
- List names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.contains("yoda")).isTrue();
- assertThat(names.contains("darth")).isTrue();
-
- results = getQueryResults(ksession, "peeps", Variable.v, Variable.v, "s1");
- assertThat(results.size()).isEqualTo(1);
- names = new ArrayList();
- for ( org.kie.api.runtime.rule.QueryResultsRow row : results ) {
- names.add( ((Person) row.get( "$p" )).getName() );
- }
- assertThat(names.contains("darth")).isTrue();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testOpenQuery(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Cheese \n";
- str += "query cheeses(String $type1, String $type2) \n";
- str += " stilton : Cheese(type == $type1, $sprice : price) \n";
- str += " cheddar : Cheese(type == $type2, $cprice : price == stilton.price) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- Cheese stilton1 = new Cheese( "stilton",
- 1 );
- Cheese cheddar1 = new Cheese( "cheddar",
- 1 );
- Cheese stilton2 = new Cheese( "stilton",
- 2 );
- Cheese cheddar2 = new Cheese( "cheddar",
- 2 );
- Cheese stilton3 = new Cheese( "stilton",
- 3 );
- Cheese cheddar3 = new Cheese( "cheddar",
- 3 );
-
- FactHandle s1Fh = ksession.insert( stilton1 );
- ksession.insert( stilton2 );
- ksession.insert( stilton3 );
- ksession.insert( cheddar1 );
- ksession.insert( cheddar2 );
- FactHandle c3Fh = ksession.insert( cheddar3 );
-
- final List<Object[]> updated = new ArrayList<Object[]>();
- final List<Object[]> removed = new ArrayList<Object[]>();
- final List<Object[]> added = new ArrayList<Object[]>();
-
- ViewChangedEventListener listener = new ViewChangedEventListener() {
- public void rowUpdated( Row row ) {
- Object[] array = new Object[6];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- array[2] = row.get( "$sprice" );
- array[3] = row.get( "$cprice" );
- array[4] = row.get( "$type1" );
- array[5] = row.get( "$type2" );
- updated.add( array );
- }
-
- public void rowDeleted( Row row ) {
- Object[] array = new Object[6];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- array[2] = row.get( "$sprice" );
- array[3] = row.get( "$cprice" );
- array[4] = row.get( "$type1" );
- array[5] = row.get( "$type2" );
- removed.add( array );
- }
-
- public void rowInserted( Row row ) {
- Object[] array = new Object[6];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- array[2] = row.get( "$sprice" );
- array[3] = row.get( "$cprice" );
- array[4] = row.get( "$type1" );
- array[5] = row.get( "$type2" );
- added.add( array );
- }
- };
-
- // Open the LiveQuery
- LiveQuery query = ksession.openLiveQuery( "cheeses",
- new Object[]{"stilton", "cheddar"},
- listener );
-
- ksession.fireAllRules();
-
- // Assert that on opening we have three rows added
- assertThat(added.size()).isEqualTo(3);
- assertThat(removed.size()).isEqualTo(0);
- assertThat(updated.size()).isEqualTo(0);
-
- // Assert that the identifiers where retrievable
- assertThat(added.get(2)[0]).isSameAs(stilton1);
- assertThat(added.get(2)[1]).isSameAs(cheddar1);
- assertThat(added.get(2)[2]).isEqualTo(1);
- assertThat(added.get(2)[3]).isEqualTo(1);
- assertThat(added.get(2)[4]).isEqualTo("stilton");
- assertThat(added.get(2)[5]).isEqualTo("cheddar");
-
- // And that we have correct values from those rows
- assertThat(added.get(0)[3]).isEqualTo(3);
- assertThat(added.get(1)[3]).isEqualTo(2);
- assertThat(added.get(2)[3]).isEqualTo(1);
-
- // Do an update that causes a match to become untrue, thus triggering a removed
- cheddar3.setPrice( 4 );
- ksession.update( c3Fh,
- cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(3);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(0);
-
- assertThat(removed.get(0)[3]).isEqualTo(4);
-
- // Now make that partial true again, and thus another added
- cheddar3.setPrice( 3 );
- ksession.update( c3Fh,
- cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(0);
-
- assertThat(added.get(3)[3]).isEqualTo(3);
-
- // check a standard update
- cheddar3.setOldPrice( 0 );
- ksession.update( c3Fh,
- cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(1);
-
- assertThat(updated.get(0)[3]).isEqualTo(3);
-
- // Check a standard retract
- ksession.retract( s1Fh );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(2);
- assertThat(updated.size()).isEqualTo(1);
-
- assertThat(removed.get(1)[3]).isEqualTo(1);
-
- // Close the query, we should get removed events for each row
- query.close();
-
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(4);
- assertThat(updated.size()).isEqualTo(1);
-
- assertThat(removed.get(3)[3]).isEqualTo(2);
- assertThat(removed.get(2)[3]).isEqualTo(3);
-
- // Check that updates no longer have any impact.
- ksession.update( c3Fh,
- cheddar3 );
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(4);
- assertThat(updated.size()).isEqualTo(1);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testStandardQueryListener(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
- runQueryListenerTest(kieBaseTestConfiguration, QueryListenerOption.STANDARD );
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testNonCloningQueryListener(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
- runQueryListenerTest(kieBaseTestConfiguration, QueryListenerOption.LIGHTWEIGHT );
- }
-
- public void runQueryListenerTest(KieBaseTestConfiguration kieBaseTestConfiguration , QueryListenerOption option) throws IOException, ClassNotFoundException {
- String str = "";
- str += "package org.drools.mvel.integrationtests\n";
- str += "import " + Cheese.class.getCanonicalName() + " \n";
- str += "query cheeses(String $type) \n";
- str += " $cheese : Cheese(type == $type) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- // insert some data into the session
- for ( int i = 0; i < 10000; i++ ) {
- ksession.insert( new Cheese( i % 2 == 0 ? "stilton" : "brie" ) );
- }
-
- // query the session
- List<Cheese> cheeses;
- for ( int i = 0; i < 100; i++ ) {
- org.kie.api.runtime.rule.QueryResults queryResults = ksession.getQueryResults( "cheeses",
- "stilton");
- cheeses = new ArrayList<Cheese>();
- for ( QueryResultsRow row : queryResults ) {
- cheeses.add( (Cheese) row.get( "$cheese" ) );
- }
-
- assertThat(cheeses.size()).isEqualTo(5000);
- }
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithEval(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
- // [Regression in 5.2.0.M2]: NPE during rule evaluation on MVELPredicateExpression.evaluate(MVELPredicateExpression.java:82)
-
- String str = "package org.drools.mvel.integrationtests\n" +
- "import " + DomainObject.class.getCanonicalName() + " \n" +
- "query queryWithEval \n" +
- " $do: DomainObject()\n" +
- " not DomainObject( id == $do.id, eval(interval.isAfter($do.getInterval())))\n" +
- "end";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- DomainObject do1 = new DomainObject();
- do1.setId( 1 );
- do1.setInterval( new Interval( 10,
- 5 ) );
- DomainObject do2 = new DomainObject();
- do2.setId( 1 );
- do2.setInterval( new Interval( 20,
- 5 ) );
- ksession.insert( do1 );
- ksession.insert( do2 );
-
- org.kie.api.runtime.rule.QueryResults results = ksession.getQueryResults( "queryWithEval" );
- assertThat(results.size()).isEqualTo(1);
- assertThat(results.iterator().next().get("$do")).isEqualTo(do2);
-
- ksession.dispose();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithIncompatibleArgs(KieBaseTestConfiguration kieBaseTestConfiguration) {
- String drl = "global java.util.List list; " +
- "" +
- "query foo( String $s, String $s, String $s ) end " +
- "" +
- "rule React \n" +
- "when\n" +
- " $i : Integer() " +
- " foo( $i, $x, $i ; ) " +
- "then\n" +
- "end";
-
- KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
- List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
- assertThat(errors.size()).isEqualTo(2);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithSyntaxError(KieBaseTestConfiguration kieBaseTestConfiguration) {
- String drl = "global java.util.List list; " +
- "" +
- "query foo( Integer $i ) end " +
- "" +
- "rule React \n" +
- "when\n" +
- " $i : Integer() " +
- " foo( $i ) " + // missing ";" should result in 1 compilation error
- "then\n" +
- "end";
-
- KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
- List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
- assertThat(errors.size()).isEqualTo(1);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithWrongParamNumber(KieBaseTestConfiguration kieBaseTestConfiguration) {
- String drl = "global java.util.List list; " +
- "" +
- "query foo( Integer $i ) end " +
- "" +
- "rule React \n" +
- "when\n" +
- " $i : Integer() " +
- " $j : Integer() " +
- " foo( $i, $j ; ) " +
- "then\n" +
- "end";
-
- KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
- List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
- assertThat(errors.size()).isEqualTo(1);
- }
-
-
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testGlobalsInQueries(KieBaseTestConfiguration kieBaseTestConfiguration) {
- String drl = "\n" +
- "package com.sample\n" +
- "\n" +
- "global java.lang.String AString;\n" +
- "global java.util.List list;\n" +
- "\n" +
- "declare AThing\n" +
- " name: String @key\n" +
- "end\n" +
- "\n" +
- "rule init\n" +
- " when\n" +
- " then\n" +
- " insert( new AThing( AString ) );\n" +
- " insert( new AThing( 'Holla' ) );\n" +
- "end\n" +
- "\n" +
- "query test( String $in ) \n" +
- " AThing( $in; )\n" +
- "end\n" +
- "\n" +
- "rule spot\n" +
- " when\n" +
- " test( \"Hello\"; )\n" +
- " AThing( \"Hello\"; )\n" +
- " test( AString; )\n" +
- " AThing( AString; )" +
- " then\n" +
- " list.add( AString + \" World\" );\n" +
- "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
- KieSession ks = kbase.newKieSession();
-
- ArrayList list = new ArrayList();
- ks.setGlobal( "AString", "Hello" );
- ks.setGlobal( "list", list );
- ks.fireAllRules();
-
- assertThat(list).isEqualTo(List.of("Hello World"));
- }
-
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithClassArg(KieBaseTestConfiguration kieBaseTestConfiguration) {
- //DROOLS-590
- String drl = "global java.util.List list; " +
- "" +
- "declare Foo end " +
- "" +
- "query bar( Class $c ) " +
- " Class( this.getName() == $c.getName() ) " +
- "end " +
- "query bar2( Class $c ) " +
- " Class( this == $c ) " +
- "end " +
- "" +
- "rule Init when then insert( Foo.class ); end " +
- "" +
- "rule React1 " +
- "when " +
- " bar( Foo.class ; ) " +
- "then " +
- " list.add( 'aa' ); " +
- "end " +
-
- "rule React2 " +
- "when\n" +
- " bar2( Foo.class ; ) " +
- "then " +
- " list.add( 'bb' ); " +
- "end";
-
- List list = new ArrayList( );
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
- KieSession ks = kbase.newKieSession();
- ks.setGlobal( "list", list );
- ks.fireAllRules();
-
- assertThat(list).isEqualTo(Arrays.asList("aa", "bb"));
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testPassGlobalToNestedQuery(KieBaseTestConfiguration kieBaseTestConfiguration) {
- // DROOLS-851
- String drl = "global java.util.List list;\n" +
- "global Integer number;\n" +
- "\n" +
- "query findString( String $out )\n" +
- " findStringWithLength( number, $out; )\n" +
- "end\n" +
- "query findStringWithLength( int $in, String $out )\n" +
- " $out := String( $in := length )\n" +
- "end\n" +
- "\n" +
- "rule R when\n" +
- " findString( $s; )\n" +
- "then\n" +
- " list.add( $s );\n" +
- "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
- KieSession ks = kbase.newKieSession();
-
- ArrayList list = new ArrayList();
- ks.setGlobal( "list", list );
- ks.setGlobal( "number", 3 );
-
- ks.insert( "Hi" );
- ks.insert( "Bye" );
- ks.insert( "Hello" );
- ks.fireAllRules();
-
- assertThat(list).isEqualTo(List.of("Bye"));
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithAccessorAsArgument(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- // DROOLS-414
- String str =
- "import org.drools.mvel.compiler.Person\n" +
- "global java.util.List persons;\n" +
- "\n" +
- "query contains(String $s, String $c)\n" +
- " $s := String( this.contains( $c ) )\n" +
- "end\n" +
- "\n" +
- "rule R when\n" +
- " $p : Person()\n" +
- " contains( $p.name, \"a\"; )\n" +
- "then\n" +
- " persons.add( $p );\n" +
- "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- List<Person> personsWithA = new ArrayList<Person>();
- ksession.setGlobal("persons", personsWithA);
-
- ksession.insert("Mark");
- ksession.insert("Edson");
- ksession.insert("Mario");
- ksession.insert(new Person("Mark"));
- ksession.insert(new Person("Edson"));
- ksession.insert(new Person("Mario"));
- ksession.fireAllRules();
-
- assertThat(personsWithA.size()).isEqualTo(2);
- for (Person p : personsWithA) {
- assertThat(p.getName().equals("Mark") || p.getName().equals("Mario")).isTrue();
- }
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithExpressionAsArgument(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- // DROOLS-414
- String str =
- "import org.drools.mvel.compiler.Person\n" +
- "global java.util.List persons;\n" +
- "\n" +
- "query checkLength(String $s, int $l)\n" +
- " $s := String( length == $l )\n" +
- "end\n" +
- "\n" +
- "rule R when\n" +
- " $i : Integer()\n" +
- " $p : Person()\n" +
- " checkLength( $p.name, 1 + $i + $p.age; )\n" +
- "then\n" +
- " persons.add( $p );\n" +
- "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- List<Person> list = new ArrayList<Person>();
- ksession.setGlobal("persons", list);
-
- ksession.insert(1);
- ksession.insert("Mark");
- ksession.insert("Edson");
- ksession.insert("Mario");
- ksession.insert(new Person("Mark", 2));
- ksession.insert(new Person("Edson", 3));
- ksession.insert(new Person("Mario", 4));
- ksession.fireAllRules();
-
- System.out.println(list);
- assertThat(list.size()).isEqualTo(2);
- for (Person p : list) {
- assertThat(p.getName().equals("Mark") || p.getName().equals("Edson")).isTrue();
- }
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testNotExistingDeclarationInQuery(KieBaseTestConfiguration kieBaseTestConfiguration) {
- // DROOLS-414
- String drl =
- "import org.drools.compiler.Person\n" +
- "global java.util.List persons;\n" +
- "\n" +
- "query checkLength(String $s, int $l)\n" +
- " $s := String( length == $l )\n" +
- "end\n" +
- "\n" +
- "rule R when\n" +
- " $i : Integer()\n" +
- " $p : Person()\n" +
- " checkLength( $p.name, 1 + $x + $p.age; )\n" +
- "then\n" +
- " persons.add( $p );\n" +
- "end\n";
-
- KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
- List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
- assertThat(errors.isEmpty()).as("Should have an error").isFalse();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryInSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) {
- // DROOLS-1386
- String str = "query myquery(Integer $i)\n" +
- " $i := Integer()\n" +
- "end\n" +
- "\n" +
- "rule R when\n" +
- " String()\n" +
- " accumulate (myquery($i;);\n" +
- " $result_count : count(1)\n" +
- " )\n" +
- " eval($result_count > 0)\n" +
- "then\n" +
- "end\n\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- FactHandle iFH = ksession.insert( 1 );
- FactHandle sFH = ksession.insert( "" );
-
- ksession.fireAllRules();
-
- ksession.update( iFH, 1 );
- ksession.delete( sFH );
-
- ksession.fireAllRules();
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testOpenQueryNoParams(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- // RHDM-717
- String str = "";
- str += "package org.drools.mvel.compiler.test \n";
- str += "import org.drools.mvel.compiler.Cheese \n";
- str += "query cheeses \n";
- str += " stilton : Cheese(type == 'stilton') \n";
- str += " cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
- str += "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
-
- Cheese stilton1 = new Cheese( "stilton", 1 );
- Cheese cheddar1 = new Cheese( "cheddar", 1 );
- Cheese stilton2 = new Cheese( "stilton", 2 );
- Cheese cheddar2 = new Cheese( "cheddar", 2 );
- Cheese stilton3 = new Cheese( "stilton", 3 );
- Cheese cheddar3 = new Cheese( "cheddar", 3 );
-
- FactHandle s1Fh = ksession.insert( stilton1 );
- ksession.insert( stilton2 );
- ksession.insert( stilton3 );
- ksession.insert( cheddar1 );
- ksession.insert( cheddar2 );
- FactHandle c3Fh = ksession.insert( cheddar3 );
-
- final List<Object[]> updated = new ArrayList<Object[]>();
- final List<Object[]> removed = new ArrayList<Object[]>();
- final List<Object[]> added = new ArrayList<Object[]>();
-
- ViewChangedEventListener listener = new ViewChangedEventListener() {
- public void rowUpdated( Row row ) {
- Object[] array = new Object[2];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- updated.add( array );
- }
-
- public void rowDeleted( Row row ) {
- Object[] array = new Object[2];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- removed.add( array );
- }
-
- public void rowInserted( Row row ) {
- Object[] array = new Object[2];
- array[0] = row.get( "stilton" );
- array[1] = row.get( "cheddar" );
- added.add( array );
- }
- };
-
- // Open the LiveQuery
- LiveQuery query = ksession.openLiveQuery( "cheeses",null, listener );
-
- ksession.fireAllRules();
-
- // Assert that on opening we have three rows added
- assertThat(added.size()).isEqualTo(3);
- assertThat(removed.size()).isEqualTo(0);
- assertThat(updated.size()).isEqualTo(0);
-
- // Do an update that causes a match to become untrue, thus triggering a removed
- cheddar3.setPrice( 4 );
- ksession.update( c3Fh, cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(3);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(0);
-
- // Now make that partial true again, and thus another added
- cheddar3.setPrice( 3 );
- ksession.update( c3Fh, cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(0);
-
- // check a standard update
- cheddar3.setOldPrice( 0 );
- ksession.update( c3Fh, cheddar3 );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(1);
- assertThat(updated.size()).isEqualTo(1);
-
- // Check a standard retract
- ksession.retract( s1Fh );
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(2);
- assertThat(updated.size()).isEqualTo(1);
-
- // Close the query, we should get removed events for each row
- query.close();
-
- ksession.fireAllRules();
-
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(4);
- assertThat(updated.size()).isEqualTo(1);
-
- // Check that updates no longer have any impact.
- ksession.update( c3Fh, cheddar3 );
- assertThat(added.size()).isEqualTo(4);
- assertThat(removed.size()).isEqualTo(4);
- assertThat(updated.size()).isEqualTo(1);
- }
-
- public static class Question {}
- public static class QuestionVisible {
- private final Question question;
- public QuestionVisible( Question question ) {
- this.question = question;
- }
- public Question getQuestion() {
- return question;
- }
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithOptionalOr(KieBaseTestConfiguration kieBaseTestConfiguration) {
- // DROOLS-1386
- String str =
- "package org.test\n" +
- "import " + Question.class.getCanonicalName() + "\n" +
- "import " + QuestionVisible.class.getCanonicalName() + "\n" +
- "query QuestionsKnowledge\n" +
- " $question: Question()\n" +
- " $visible: QuestionVisible(question == $question) or not QuestionVisible(question == $question)\n" +
- "end\n";
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
- KieSession ksession = kbase.newKieSession();
- Question question = new Question();
- ksession.insert( question );
- QueryResults results = ksession.getQueryResults("QuestionsKnowledge");
- assertThat(results.size()).isEqualTo(1);
- QueryResultsRow row = results.iterator().next();
- assertThat(row.get("$question")).isSameAs(question);
-
- QuestionVisible questionVisible = new QuestionVisible( question );
- ksession.insert( questionVisible );
- results = ksession.getQueryResults("QuestionsKnowledge");
- assertThat(results.size()).isEqualTo(1);
- row = results.iterator().next();
- assertThat(row.get("$question")).isSameAs(question);
- assertThat(row.get("$visible")).isSameAs(questionVisible);
- }
-
- @ParameterizedTest(name = "KieBase type={0}")
- @MethodSource("parameters")
- public void testQueryWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) {
- final String drl =
- "import org.drools.mvel.compiler.oopath.model.Thing;\n" +
- "query isContainedIn( Thing $x, Thing $y )\n" +
- " $y := Thing() from $x.children\n" +
- "or\n" +
- " ( $z := Thing() from $x.children and isContainedIn( $z, $y; ) )\n" +
- "end\n";
-
- final Thing smartphone = new Thing("smartphone");
- final List<String> itemList = Arrays.asList("display", "keyboard", "processor");
- itemList.stream().map(item -> new Thing(item)).forEach((thing) -> smartphone.addChild(thing));
-
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
- KieSession ksession = kbase.newKieSession();
-
- ReteDumper.dumpRete(ksession);
-
- ksession.insert(smartphone);
-
- final QueryResults queryResults = ksession.getQueryResults("isContainedIn", smartphone, Variable.v);
- final List<String> resultList = StreamSupport.stream(queryResults.spliterator(), false)
- .map(row -> ((Thing) row.get("$y")).getName()).collect(Collectors.toList());
- assertThat(resultList).as("Query does not contain all items").containsAll(itemList);
-
- ksession.dispose();
- }
-}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query2Test.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/Query2Test.java
similarity index 64%
rename from drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query2Test.java
rename to drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/Query2Test.java
index 1ff7108f1c..7618d86da2 100644
--- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/Query2Test.java
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/Query2Test.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.drools.mvel.integrationtests;
+package org.drools.mvel.integrationtests.query;
import java.util.stream.Stream;
@@ -39,31 +39,30 @@ public class Query2Test {
@ParameterizedTest(name = "KieBase type={0}")
@MethodSource("parameters")
public void testEvalRewrite(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
- String str = "" +
- "package org.drools.mvel.compiler;\n" +
- "global java.util.List results;\n" +
- "rule \"eval rewrite\"\n" +
- " when\n" +
- " $o1 : OrderItem( order.number == 11, $seq : seq == 1 )\n" +
- //" $o2 : OrderItem( order.number == $o1.order.number, seq != $seq )\n" +
- " $o2 : Order( items[(Integer) 1] == $o1 ) \n" +
- " then\n" +
- " System.out.println( $o1 + \":\" + $o2 );\n" +
- "end \n";
+ String drl = """
+ package org.drools.mvel.compiler;
+ global java.util.List results;
- KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
+ rule "eval rewrite"
+ when
+ $o1 : OrderItem(order.number == 11, $seq : seq == 1)
+ // $o2 : OrderItem(order.number == $o1.order.number, seq != $seq)
+ $o2 : Order(items[(Integer) 1] == $o1)
+ then
+ System.out.println($o1 + ":" + $o2);
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
- final Order order1 = new Order( 11,
- "Bob" );
- final OrderItem item11 = new OrderItem( order1,
- 1 );
- final OrderItem item12 = new OrderItem( order1,
- 2 );
+ final Order order1 = new Order(11, "Bob");
+ final OrderItem item11 = new OrderItem(order1, 1);
+ final OrderItem item12 = new OrderItem(order1, 2);
- ksession.insert( order1 );
- ksession.insert( item11 );
- ksession.insert( item12 );
+ ksession.insert(order1);
+ ksession.insert(item11);
+ ksession.insert(item12);
ksession.fireAllRules();
}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryArgumentUnificationTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryArgumentUnificationTest.java
new file mode 100644
index 0000000000..fde35a832b
--- /dev/null
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryArgumentUnificationTest.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.mvel.integrationtests.query;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.stream.Stream;
+
+import org.drools.mvel.compiler.Address;
+import org.drools.mvel.compiler.Person;
+import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
+import org.drools.testcoverage.common.util.KieBaseUtil;
+import org.drools.testcoverage.common.util.TestParametersUtil2;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.kie.api.KieBase;
+import org.kie.api.runtime.KieSession;
+import org.kie.api.runtime.rule.QueryResults;
+import org.kie.api.runtime.rule.Variable;
+
+public class QueryArgumentUnificationTest {
+
+ public static Stream<KieBaseTestConfiguration> parameters() {
+ return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueriesWithVariableUnification(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.compiler.test
+ import org.drools.mvel.compiler.Person
+
+ query peeps(String $name, String $likes, int $age)
+ $p : Person($name := name, $likes := likes, $age := age)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ Person p1 = new Person("darth", "stilton", 100);
+ Person p2 = new Person("yoda", "stilton", 300);
+ Person p3 = new Person("luke", "brie", 300);
+ Person p4 = new Person("bobba", "cheddar", 300);
+
+ ksession.insert(p1);
+ ksession.insert(p2);
+ ksession.insert(p3);
+ ksession.insert(p4);
+
+ QueryResults results = ksession.getQueryResults("peeps", Variable.v, Variable.v, Variable.v);
+ assertThat(results).hasSize(4);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("luke", "yoda", "bobba","darth");
+
+ results = ksession.getQueryResults("peeps", Variable.v, Variable.v, 300);
+ assertThat(results).hasSize(3);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("luke", "yoda", "bobba");
+
+ results = ksession.getQueryResults("peeps", Variable.v, "stilton", 300);
+ assertThat(results).hasSize(1);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("yoda");
+
+ results = ksession.getQueryResults("peeps", Variable.v, "stilton", Variable.v);
+ assertThat(results).hasSize(2);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("yoda", "darth");
+
+ results = ksession.getQueryResults("peeps", "darth", Variable.v, Variable.v);
+ assertThat(results).hasSize(1);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("darth");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueriesWithVariableUnificationOnPatterns(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.compiler.test
+ import org.drools.mvel.compiler.Person
+
+ query peeps(Person $p, String $name, String $likes, int $age)
+ $p := Person($name := name, $likes := likes, $age := age)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ Person p1 = new Person("darth", "stilton", 100);
+ Person p2 = new Person("yoda", "stilton", 300);
+ Person p3 = new Person("luke", "brie", 300);
+ Person p4 = new Person("bobba", "cheddar", 300);
+
+ ksession.insert(p1);
+ ksession.insert(p2);
+ ksession.insert(p3);
+ ksession.insert(p4);
+
+ QueryResults results = ksession.getQueryResults("peeps", Variable.v, Variable.v, Variable.v, Variable.v);
+ assertThat(results).hasSize(4);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("luke", "yoda", "bobba","darth");
+
+ results = ksession.getQueryResults("peeps", p1, Variable.v, Variable.v, Variable.v);
+
+ assertThat(results).hasSize(1);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("darth");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueriesWithVariableUnificationOnNestedFields(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.compiler.test
+ import org.drools.mvel.compiler.Person
+
+ query peeps(String $name, String $likes, String $street)
+ $p : Person($name := name, $likes := likes, $street := address.street)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ Person p1 = new Person("darth", "stilton", 100);
+ p1.setAddress(new Address("s1"));
+
+ Person p2 = new Person("yoda", "stilton", 300);
+ p2.setAddress(new Address("s2"));
+
+ ksession.insert(p1);
+ ksession.insert(p2);
+
+ QueryResults results = ksession.getQueryResults("peeps", Variable.v, Variable.v, Variable.v);
+ assertThat(results).hasSize(2);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("yoda", "darth");
+
+ results = ksession.getQueryResults("peeps", Variable.v, Variable.v, "s1");
+ assertThat(results).hasSize(1);
+ assertThat(results).extracting(r -> ((Person) r.get("$p")).getName()).containsExactlyInAnyOrder("darth");
+ }
+
+}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryLiveTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryLiveTest.java
new file mode 100644
index 0000000000..dd36f6361f
--- /dev/null
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryLiveTest.java
@@ -0,0 +1,323 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.mvel.integrationtests.query;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.drools.mvel.compiler.Cheese;
+import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
+import org.drools.testcoverage.common.util.KieBaseUtil;
+import org.drools.testcoverage.common.util.TestParametersUtil2;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.kie.api.KieBase;
+import org.kie.api.runtime.KieSession;
+import org.kie.api.runtime.rule.FactHandle;
+import org.kie.api.runtime.rule.LiveQuery;
+import org.kie.api.runtime.rule.Row;
+import org.kie.api.runtime.rule.ViewChangedEventListener;
+
+public class QueryLiveTest {
+
+
+ public static Stream<KieBaseTestConfiguration> parameters() {
+ return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testOpenQuery(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.compiler.test
+ import org.drools.mvel.compiler.Cheese
+
+ query cheeses(String $type1, String $type2)
+ stilton : Cheese(type == $type1, $sprice : price)
+ cheddar : Cheese(type == $type2, $cprice : price == stilton.price)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ Cheese stilton1 = new Cheese("stilton", 1);
+ Cheese cheddar1 = new Cheese("cheddar", 1);
+ Cheese stilton2 = new Cheese("stilton", 2);
+ Cheese cheddar2 = new Cheese("cheddar", 2);
+ Cheese stilton3 = new Cheese("stilton", 3);
+ Cheese cheddar3 = new Cheese("cheddar", 3);
+
+ FactHandle s1Fh = ksession.insert(stilton1);
+ ksession.insert(stilton2);
+ ksession.insert(stilton3);
+ ksession.insert(cheddar1);
+ ksession.insert(cheddar2);
+ FactHandle c3Fh = ksession.insert(cheddar3);
+
+ final List<Object[]> updated = new ArrayList<Object[]>();
+ final List<Object[]> removed = new ArrayList<Object[]>();
+ final List<Object[]> added = new ArrayList<Object[]>();
+
+ ViewChangedEventListener listener = new ViewChangedEventListener() {
+ public void rowUpdated(Row row) {
+ Object[] array = new Object[6];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ array[2] = row.get("$sprice");
+ array[3] = row.get("$cprice");
+ array[4] = row.get("$type1");
+ array[5] = row.get("$type2");
+ updated.add(array);
+ }
+
+ public void rowDeleted(Row row) {
+ Object[] array = new Object[6];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ array[2] = row.get("$sprice");
+ array[3] = row.get("$cprice");
+ array[4] = row.get("$type1");
+ array[5] = row.get("$type2");
+ removed.add(array);
+ }
+
+ public void rowInserted(Row row) {
+ Object[] array = new Object[6];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ array[2] = row.get("$sprice");
+ array[3] = row.get("$cprice");
+ array[4] = row.get("$type1");
+ array[5] = row.get("$type2");
+ added.add(array);
+ }
+ };
+
+ // Open the LiveQuery
+ LiveQuery query = ksession.openLiveQuery("cheeses",
+ new Object[]{"stilton", "cheddar"},
+ listener);
+
+ ksession.fireAllRules();
+
+ // Assert that on opening we have three rows added
+ assertThat(added).hasSize(3);
+ assertThat(removed).hasSize(0);
+ assertThat(updated).hasSize(0);
+
+ // Assert that the identifiers where retrievable
+ assertThat(added.get(2)[0]).isSameAs(stilton1);
+ assertThat(added.get(2)[1]).isSameAs(cheddar1);
+ assertThat(added.get(2)[2]).isEqualTo(1);
+ assertThat(added.get(2)[3]).isEqualTo(1);
+ assertThat(added.get(2)[4]).isEqualTo("stilton");
+ assertThat(added.get(2)[5]).isEqualTo("cheddar");
+
+ // And that we have correct values from those rows
+ assertThat(added.get(0)[3]).isEqualTo(3);
+ assertThat(added.get(1)[3]).isEqualTo(2);
+ assertThat(added.get(2)[3]).isEqualTo(1);
+
+ // Do an update that causes a match to become untrue, thus triggering a removed
+ cheddar3.setPrice(4);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(3);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(0);
+
+ assertThat(removed.get(0)[3]).isEqualTo(4);
+
+ // Now make that partial true again, and thus another added
+ cheddar3.setPrice(3);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(0);
+
+ assertThat(added.get(3)[3]).isEqualTo(3);
+
+ // check a standard update
+ cheddar3.setOldPrice(0);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(1);
+
+ assertThat(updated.get(0)[3]).isEqualTo(3);
+
+ // Check a standard retract
+ ksession.retract(s1Fh);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(2);
+ assertThat(updated).hasSize(1);
+
+ assertThat(removed.get(1)[3]).isEqualTo(1);
+
+ // Close the query, we should get removed events for each row
+ query.close();
+
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(4);
+ assertThat(updated).hasSize(1);
+
+ assertThat(removed.get(3)[3]).isEqualTo(2);
+ assertThat(removed.get(2)[3]).isEqualTo(3);
+
+ // Check that updates no longer have any impact.
+ ksession.update(c3Fh,
+ cheddar3);
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(4);
+ assertThat(updated).hasSize(1);
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testOpenQueryNoParams(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ // RHDM-717
+ String drl = """
+ package org.drools.mvel.compiler.test
+ import org.drools.mvel.compiler.Cheese
+
+ query cheeses
+ stilton : Cheese(type == 'stilton')
+ cheddar : Cheese(type == 'cheddar', price == stilton.price)
+ end
+ """;
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ Cheese stilton1 = new Cheese("stilton", 1);
+ Cheese cheddar1 = new Cheese("cheddar", 1);
+ Cheese stilton2 = new Cheese("stilton", 2);
+ Cheese cheddar2 = new Cheese("cheddar", 2);
+ Cheese stilton3 = new Cheese("stilton", 3);
+ Cheese cheddar3 = new Cheese("cheddar", 3);
+
+ FactHandle s1Fh = ksession.insert(stilton1);
+ ksession.insert(stilton2);
+ ksession.insert(stilton3);
+ ksession.insert(cheddar1);
+ ksession.insert(cheddar2);
+ FactHandle c3Fh = ksession.insert(cheddar3);
+
+ final List<Object[]> updated = new ArrayList<Object[]>();
+ final List<Object[]> removed = new ArrayList<Object[]>();
+ final List<Object[]> added = new ArrayList<Object[]>();
+
+ ViewChangedEventListener listener = new ViewChangedEventListener() {
+ public void rowUpdated(Row row) {
+ Object[] array = new Object[2];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ updated.add(array);
+ }
+
+ public void rowDeleted(Row row) {
+ Object[] array = new Object[2];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ removed.add(array);
+ }
+
+ public void rowInserted(Row row) {
+ Object[] array = new Object[2];
+ array[0] = row.get("stilton");
+ array[1] = row.get("cheddar");
+ added.add(array);
+ }
+ };
+
+ // Open the LiveQuery
+ LiveQuery query = ksession.openLiveQuery("cheeses",null, listener);
+
+ ksession.fireAllRules();
+
+ // Assert that on opening we have three rows added
+ assertThat(added).hasSize(3);
+ assertThat(removed).hasSize(0);
+ assertThat(updated).hasSize(0);
+
+ // Do an update that causes a match to become untrue, thus triggering a removed
+ cheddar3.setPrice(4);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(3);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(0);
+
+ // Now make that partial true again, and thus another added
+ cheddar3.setPrice(3);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(0);
+
+ // check a standard update
+ cheddar3.setOldPrice(0);
+ ksession.update(c3Fh, cheddar3);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(1);
+ assertThat(updated).hasSize(1);
+
+ // Check a standard retract
+ ksession.retract(s1Fh);
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(2);
+ assertThat(updated).hasSize(1);
+
+ // Close the query, we should get removed events for each row
+ query.close();
+
+ ksession.fireAllRules();
+
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(4);
+ assertThat(updated).hasSize(1);
+
+ // Check that updates no longer have any impact.
+ ksession.update(c3Fh, cheddar3);
+ assertThat(added).hasSize(4);
+ assertThat(removed).hasSize(4);
+ assertThat(updated).hasSize(1);
+ }
+
+}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryMatchingPropertiesTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryMatchingPropertiesTest.java
new file mode 100644
index 0000000000..73ee30aba7
--- /dev/null
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryMatchingPropertiesTest.java
@@ -0,0 +1,475 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.mvel.integrationtests.query;
+
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
+import org.drools.testcoverage.common.util.TestParametersUtil2;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.kie.api.KieBase;
+import org.kie.api.runtime.KieSession;
+import org.kie.api.runtime.rule.FactHandle;
+import org.kie.api.runtime.rule.QueryResults;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.drools.testcoverage.common.util.KieBaseUtil.getKieBaseFromKieModuleFromDrl;
+
+public class QueryMatchingPropertiesTest {
+
+ public static Stream<KieBaseTestConfiguration> parameters() {
+ return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
+ }
+
+ public final static String MATCH_FOO = """
+ package org.drools.integrationtests
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.Foo
+
+ query "MatchFoo"
+ foo : Foo();
+ end
+ """;
+
+
+ public final static String MATCH_FOO_WITH_FOO_ON_ID = """
+ package org.drools.integrationtests
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.Foo
+
+ query "MatchFooWithFooOnId"
+ foo : Foo();
+ foo2 : Foo(id == foo.id);
+ end
+ """;
+
+ public final static String MATCH_FOO_WITH_BAR_ON_ID = """
+ package org.drools.integrationtests
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.Bar
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.Foo
+
+ query "MatchFooWithBarOnId"
+ foo : Foo();
+ bar : Bar(id == foo.id)
+ end
+ """;
+
+ public final static String MATCH_FOO_WITH_SUPERFOO_ON_ID = """
+ package org.drools.integrationtests
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.Foo
+ import org.drools.mvel.integrationtests.query.QueryMatchingPropertiesTest.SuperFoo
+
+ query "MatchFooWithSuperFooOnId"
+ foo : Foo();
+ superFoo : SuperFoo(id == foo.id)
+ end
+ """;
+
+
+ private KieSession kieSession;
+
+ private int counter;
+
+ @AfterEach
+ public void tearDown() {
+ if (kieSession != null) {
+ kieSession.dispose();
+ }
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOnly(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Bar bar = bar(foo.id);
+ kieSession.insert(bar);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFoo");
+
+
+ assertThat(queryResults).hasSize(1);
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneBarSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_BAR_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Bar bar = bar(foo.id);
+ kieSession.insert(bar);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithBarOnId");
+
+ assertThat(queryResults).hasSize(1);
+ assertThat(queryResults).isSameAs(queryResults);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneBarDifferentId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_BAR_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Bar bar = bar(differentIdFrom(foo.id));
+ kieSession.insert(bar);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithBarOnId");
+
+ assertThat(queryResults.toList()).hasSize(0);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneBarSameIdChangedToDifferentId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_BAR_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Bar bar = bar(foo.id);
+ FactHandle handleForBar = kieSession.insert(bar);
+
+ Bar changedBar = bar(differentIdFrom(foo.id));
+ kieSession.update(handleForBar, changedBar);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithBarOnId");
+
+ assertThat(queryResults.toList()).hasSize(0);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFoo(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(1).containsExactlyInAnyOrder(
+ fooFoo(foo, foo));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void twoFoosSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Foo foo2 = foo(foo.id);
+ kieSession.insert(foo2);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(4).containsExactlyInAnyOrder(
+ fooFoo(foo, foo),
+ fooFoo(foo2, foo),
+ fooFoo(foo, foo2),
+ fooFoo(foo2, foo2));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void twoFoosDifferentId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Foo foo2 = foo(differentIdFrom(foo.id));
+ kieSession.insert(foo2);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(2).containsExactlyInAnyOrder(
+ fooFoo(foo, foo),
+ fooFoo(foo2, foo2));
+}
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void twoFoosSameIdUpdatePreservingId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Foo foo2 = foo(foo.id);
+ FactHandle handleForFoo = kieSession.insert(foo2);
+
+ kieSession.update(handleForFoo, foo2);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(4).containsExactlyInAnyOrder(
+ fooFoo(foo, foo),
+ fooFoo(foo2, foo),
+ fooFoo(foo, foo2),
+ fooFoo(foo2, foo2));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void twoFoosSameIdChangedToToDifferenId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Foo foo2 = foo(foo.id);
+ FactHandle handleForFoo2 = kieSession.insert(foo2);
+
+ Foo changedFoo2 = foo(differentIdFrom(foo.id));
+ kieSession.update(handleForFoo2, changedFoo2);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(2).containsExactlyInAnyOrder(
+ fooFoo(foo, foo),
+ fooFoo(changedFoo2, changedFoo2));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void twoFoosDifferentIdChangedToSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_FOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ Foo foo2 = foo(differentIdFrom(foo.id));
+ FactHandle handleForFoo2 = kieSession.insert(foo2);
+
+ Foo changedFoo2 = foo(foo.id);
+
+ kieSession.update(handleForFoo2, changedFoo2);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(4).containsExactlyInAnyOrder(
+ fooFoo(foo, foo),
+ fooFoo(changedFoo2, foo),
+ fooFoo(foo, changedFoo2),
+ fooFoo(changedFoo2, changedFoo2));
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(foo.id);
+ kieSession.insert(superFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(2).containsExactlyInAnyOrder(
+ fooSuperFoo(foo, superFoo),
+ fooSuperFoo(superFoo, superFoo));
+
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooDifferentId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(differentIdFrom(foo.id));
+ kieSession.insert(superFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(1).containsExactlyInAnyOrder(
+ fooSuperFoo(superFoo, superFoo));
+
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooDifferentIdChangedToSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(differentIdFrom(foo.id));
+ FactHandle handleForSuperFoo = kieSession.insert(superFoo);
+
+ SuperFoo changedSuperFoo = superFoo(foo.id);
+ kieSession.update(handleForSuperFoo, changedSuperFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(2).containsExactlyInAnyOrder(
+ fooSuperFoo(foo, changedSuperFoo),
+ fooSuperFoo(changedSuperFoo, changedSuperFoo));
+
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooSameIdUpdateToSameId(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(foo.id);
+ FactHandle handleForSuperFoo = kieSession.insert(superFoo);
+
+ kieSession.update(handleForSuperFoo, superFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(2).containsExactlyInAnyOrder(
+ fooSuperFoo(foo, superFoo),
+ fooSuperFoo(superFoo, superFoo));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooSameIdRemoveOneFoo(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ FactHandle handleForFoo = kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(foo.id);
+ kieSession.insert(superFoo);
+
+ kieSession.delete(handleForFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(1).containsExactlyInAnyOrder(
+ fooSuperFoo(superFoo, superFoo));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void oneFooOneSuperFooSameIdRemoveOneSuperFoo(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ kieSession = createSession(kieBaseTestConfiguration, MATCH_FOO_WITH_SUPERFOO_ON_ID);
+
+ Foo foo = foo("x");
+ kieSession.insert(foo);
+ SuperFoo superFoo = superFoo(foo.id);
+ FactHandle handleForSuperFoo = kieSession.insert(superFoo);
+
+ kieSession.delete(handleForSuperFoo);
+
+ QueryResults queryResults = kieSession.getQueryResults("MatchFooWithSuperFooOnId");
+
+ assertThat(queryResults.toList()).hasSize(0);
+ }
+
+
+ public static class Bar {
+
+ private String id;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String toString() {
+ return "Bar [id = " + getId() + " ]";
+ }
+
+ }
+
+ public static class Foo {
+
+ private String id;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String toString() {
+ return "Foo [id = " + getId() + " ]";
+ }
+
+ }
+
+ public static class SuperFoo extends Foo {
+
+ public String toString() {
+ return "SuperFoo [id = " + getId() + " ]";
+ }
+ }
+
+ private KieSession createSession(KieBaseTestConfiguration kieBaseTestConfiguration, String drl) {
+ KieBase knowledgeBase = getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ return knowledgeBase.newKieSession();
+ }
+
+ private String differentIdFrom(String id) {
+ counter++;
+ return id + counter;
+ }
+
+ private static Bar bar(String id) {
+ Bar bar = new Bar();
+ bar.setId(id);
+ return bar;
+ }
+
+ private static Foo foo(String id) {
+ Foo foo = new Foo();
+ foo.setId(id);
+ return foo;
+ }
+
+ private static SuperFoo superFoo(String id) {
+ SuperFoo superFoo = new SuperFoo();
+ superFoo.setId(id);
+ return superFoo;
+ }
+
+ private static Map<String, Object> fooFoo(Foo foo, Foo foo2) {
+ return Map.of("foo", foo, "foo2", foo2);
+ }
+
+ private static Map<String, Object> fooSuperFoo(Foo foo, SuperFoo superFoo) {
+ return Map.of("foo", foo, "superFoo", superFoo);
+ }
+
+ private static Map<String, Object> fooBar(Foo foo, Bar bar) {
+ return Map.of("foo", foo, "bar", bar);
+ }
+
+}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryTest.java
new file mode 100644
index 0000000000..405160abb2
--- /dev/null
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryTest.java
@@ -0,0 +1,861 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.mvel.integrationtests.query;
+
+import org.drools.base.base.ClassObjectType;
+import org.drools.base.base.DroolsQuery;
+import org.drools.base.base.ObjectType;
+import org.drools.commands.runtime.FlatQueryResults;
+import org.drools.core.QueryResultsImpl;
+import org.drools.core.common.InternalFactHandle;
+import org.drools.core.impl.InternalRuleBase;
+import org.drools.core.reteoo.EntryPointNode;
+import org.drools.core.reteoo.ObjectTypeNode;
+import org.drools.kiesession.session.StatefulKnowledgeSessionImpl;
+import org.drools.mvel.compiler.Cheese;
+import org.drools.mvel.compiler.DomainObject;
+import org.drools.mvel.compiler.InsertedObject;
+import org.drools.mvel.compiler.Interval;
+import org.drools.mvel.compiler.Person;
+import org.drools.mvel.compiler.Worker;
+import org.drools.mvel.compiler.oopath.model.Thing;
+import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
+import org.drools.testcoverage.common.util.KieBaseUtil;
+import org.drools.testcoverage.common.util.TestParametersUtil2;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.kie.api.KieBase;
+import org.kie.api.runtime.KieSession;
+import org.kie.api.runtime.conf.QueryListenerOption;
+import org.kie.api.runtime.rule.FactHandle;
+import org.kie.api.runtime.rule.QueryResults;
+import org.kie.api.runtime.rule.QueryResultsRow;
+import org.kie.api.runtime.rule.Variable;
+
+import jakarta.xml.bind.JAXBContext;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
+
+public class QueryTest {
+
+ public static Stream<KieBaseTestConfiguration> parameters() {
+ return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
+ }
+
+ private static QueryResults getQueryResults(KieSession session, String queryName, Object... arguments) throws Exception {
+ QueryResultsImpl results = (QueryResultsImpl) session.getQueryResults(queryName, arguments);
+
+ FlatQueryResults flatResults = new FlatQueryResults(results);
+
+ assertThat(flatResults).as("Query results size").hasSameSizeAs(results);
+ assertThat(flatResults.getIdentifiers()).as("Query results identifiers").hasSameSizeAs(results.getIdentifiers());
+ Set<String> resultIds = new TreeSet<String>(Arrays.asList(results.getIdentifiers()));
+ Set<String> flatIds = new TreeSet<String>(Arrays.asList(flatResults.getIdentifiers()));
+ assertThat(resultIds.toArray()).as("Flat query results identifiers").isEqualTo(flatIds.toArray());
+
+ FlatQueryResults copyFlatResults = roundTrip(flatResults);
+ String [] identifiers = results.getIdentifiers();
+ Iterator<QueryResultsRow> copyFlatIter = copyFlatResults.iterator();
+ for(int i = 0; i < results.size(); ++i) {
+ QueryResultsRow row = results.get(i);
+ assertThat(copyFlatIter.hasNext()).as("Round-tripped flat query results contain less rows than original query results").isTrue();
+ QueryResultsRow copyRow = copyFlatIter.next();
+ for(String id : identifiers) {
+ Object obj = row.get(id);
+ if(obj != null) {
+ Object copyObj = copyRow.get(id);
+ assertThat(obj != null && obj.equals(copyObj)).as("Flat query result [" + i + "] does not contain result: '" + id + "': " + obj + "/" + copyObj).isTrue();
+ }
+ FactHandle fh = row.getFactHandle(id);
+ FactHandle copyFh = copyRow.getFactHandle(id);
+ if(fh != null) {
+ assertThat(copyFh).as("Flat query result [" + i + "] does not contain facthandle: '" + fh.getId() + "'").isNotNull();
+ String fhStr = fh.toExternalForm();
+ fhStr = fhStr.substring(0, fhStr.lastIndexOf(":"));
+ String copyFhStr = copyFh.toExternalForm();
+ copyFhStr = copyFhStr.substring(0, copyFhStr.lastIndexOf(":"));
+ assertThat(copyFhStr).as("Unequal fact handles for fact handle '" + fh.getId() + "':").isEqualTo(fhStr);
+ }
+ }
+ }
+
+ // check identifiers
+ Set<String> copyFlatIds = new TreeSet<String>(Arrays.asList(copyFlatResults.getIdentifiers()));
+ assertThat(copyFlatIds.toArray()).as("Flat query results identifiers").isEqualTo(flatIds.toArray());
+ return copyFlatResults;
+ }
+
+
+ private static <T> T roundTrip(Object obj) throws Exception {
+ Class[] classes = { obj.getClass() };
+ JAXBContext ctx = getJaxbContext(classes);
+ String xmlOut = marshall(ctx, obj);
+ return unmarshall(ctx, xmlOut);
+ }
+
+ private static <T> T unmarshall(JAXBContext ctx, String xmlIn) throws Exception {
+ ByteArrayInputStream xmlStrInputStream = new ByteArrayInputStream(xmlIn.getBytes(Charset.forName("UTF-8")));
+ Object out = ctx.createUnmarshaller().unmarshal(xmlStrInputStream);
+ return (T) out;
+ }
+
+ private static String marshall(JAXBContext ctx, Object obj) throws Exception {
+ StringWriter writer = new StringWriter();
+ ctx.createMarshaller().marshal(obj, writer);
+ return writer.getBuffer().toString();
+ }
+
+ private static JAXBContext getJaxbContext(Class<?>... classes) throws Exception {
+ List<Class<?>> jaxbClassList = new ArrayList<Class<?>>();
+ jaxbClassList.addAll(Arrays.asList(classes));
+ jaxbClassList.add(Cheese.class);
+ jaxbClassList.add(InsertedObject.class);
+ jaxbClassList.add(Person.class);
+ Class<?>[] jaxbClasses = jaxbClassList.toArray(new Class[jaxbClassList.size()]);
+ return JAXBContext.newInstance(jaxbClasses);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQuery2(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.compiler.integrationtests;
+
+ import org.drools.mvel.compiler.InsertedObject;
+ import java.util.ArrayList;
+
+ rule rule1
+ when
+ then
+ insert( new InsertedObject( "value1") );
+ insert( new InsertedObject( "value2") );
+ end
+
+ query "assertedobjquery"
+ assertedobj : InsertedObject( value=="value1" )
+ end
+
+ query "collect objects"
+ $list : ArrayList() from collect( InsertedObject() )
+ end
+ """;
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+
+ session.fireAllRules();
+
+ QueryResults results = getQueryResults(session, "assertedobjquery");
+ assertThat(results).hasSize(1);
+ assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject("value1"));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithParams(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.integrationtests;
+
+ import org.drools.mvel.compiler.InsertedObject;
+
+ rule rule1
+ when
+ then
+ insert( new InsertedObject( "value1") );
+ insert( new InsertedObject( "value2") );
+ end
+
+ query "assertedobjquery" ( String $value )
+ assertedobj : InsertedObject( value == $value )
+ end
+
+
+ query "assertedobjquery2" ( String $value1, String $value2 )
+ assertedobj : InsertedObject( value == $value2 )
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+
+ session.fireAllRules();
+
+ QueryResults results = getQueryResults(session, "assertedobjquery", "value1");
+
+ assertThat(results).hasSize(1);
+ InsertedObject value = new InsertedObject("value1");
+ assertThat(results.iterator().next().get("assertedobj")).isEqualTo(value);
+
+ results = getQueryResults(session, "assertedobjquery", "value3");
+
+ assertThat(results).hasSize(0);
+
+ results = getQueryResults(session, "assertedobjquery2", null, "value2");
+ assertThat(results).hasSize(1);
+ assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject("value2"));
+
+ results = getQueryResults(session, "assertedobjquery2", "value3", "value2");
+
+ assertThat(results).hasSize(1);
+ assertThat(results.iterator().next().get("assertedobj")).isEqualTo(new InsertedObject("value2"));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithMultipleResultsOnKnowledgeApi(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.integrationtests;
+ import org.drools.mvel.compiler.Cheese;
+ query cheeses
+ stilton : Cheese(type == 'stilton')
+ cheddar : Cheese(type == 'cheddar', price == stilton.price)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+
+
+ Cheese stilton1 = new Cheese("stilton", 1);
+ Cheese cheddar1 = new Cheese("cheddar", 1);
+ Cheese stilton2 = new Cheese("stilton", 2);
+ Cheese cheddar2 = new Cheese("cheddar", 2);
+ Cheese stilton3 = new Cheese("stilton", 3);
+ Cheese cheddar3 = new Cheese("cheddar", 3);
+
+ session.insert(stilton1);
+ session.insert(stilton2);
+ session.insert(stilton3);
+ session.insert(cheddar1);
+ session.insert(cheddar2);
+ session.insert(cheddar3);
+
+ QueryResults results = getQueryResults(session, "cheeses");
+ assertThat(results.getIdentifiers()).hasSize(2);
+
+ assertThat(results).hasSize(3);
+ assertThat(results)
+ .extracting(r->r.get("stilton"), r-> r.get("cheddar"))
+ .containsExactlyInAnyOrder(
+ tuple(stilton1, cheddar1),
+ tuple(stilton2, cheddar2),
+ tuple(stilton3, cheddar3));
+
+ FlatQueryResults flatResults = new FlatQueryResults(((StatefulKnowledgeSessionImpl) session).getQueryResults("cheeses"));
+
+ assertThat(flatResults)
+ .extracting(r->r.get("stilton"), r-> r.get("cheddar"))
+ .containsExactlyInAnyOrder(
+ tuple(stilton1, cheddar1),
+ tuple(stilton2, cheddar2),
+ tuple(stilton3, cheddar3));
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testTwoQueries(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ // @see JBRULES-410 More than one Query definition causes an incorrect
+ // Rete network to be built.
+
+ String drl = """
+ package org.drools.compiler.test;
+
+ import org.drools.mvel.compiler.Cheese;
+ import org.drools.mvel.compiler.Person;
+
+ query "find stinky cheeses"
+ Cheese(type == "stinky")
+ end
+
+ query "find pensioners"
+ Person(age > 65)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+
+ final Cheese stilton = new Cheese("stinky", 5);
+ session.insert(stilton);
+ final Person per1 = new Person("stinker", "smelly feet", 70);
+ final Person per2 = new Person("skunky", "smelly armpits", 40);
+ session.insert(per1);
+ session.insert(per2);
+
+ assertThat(getQueryResults(session, "find stinky cheeses")).hasSize(1);
+ assertThat(getQueryResults(session, "find pensioners")).hasSize(1);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testDoubleQueryWithExists(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.integrationtests;
+ import org.drools.mvel.compiler.Person;
+ query "2 persons with the same status"
+ p : Person($status : status, $age : age)
+ exists Person(status == $status, age > $age);
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+
+
+ final Person stilton20 = new Person("p1", "stilton", 20);
+ stilton20.setStatus("europe");
+ final FactHandle c1FactHandle = session.insert(stilton20);
+
+ final Person stilton30 = new Person("p2", "stilton", 30);
+ stilton30.setStatus("europe");
+ final FactHandle c2FactHandle = session.insert(stilton30);
+
+ final Person stilton40 = new Person("p3", "stilton", 40);
+ stilton40.setStatus("europe");
+ final FactHandle c3FactHandle = session.insert(stilton40);
+
+
+ QueryResults results = session.getQueryResults("2 persons with the same status");
+ assertThat(results).hasSize(2);
+
+ // europe=[ 1, 2 ], america=[ 3 ]
+ stilton40.setStatus("america");
+ session.update(c3FactHandle, stilton40);
+
+ results = session.getQueryResults( "2 persons with the same status");
+ assertThat(results).hasSize(1);
+
+ // europe=[ 1 ], america=[ 2, 3 ]
+ stilton30.setStatus("america");
+ session.update(c2FactHandle, stilton30);
+
+ results = session.getQueryResults("2 persons with the same status");
+ assertThat(results).hasSize(1);
+
+ // europe=[ ], america=[ 1, 2, 3 ]
+ stilton20.setStatus("america");
+ session.update(c1FactHandle, stilton20);
+
+ results = getQueryResults(session, "2 persons with the same status");
+ assertThat(results).hasSize(2);
+
+ // europe=[ 2 ], america=[ 1, 3 ]
+ stilton30.setStatus("europe");
+ session.update(c2FactHandle, stilton30);
+
+ results = getQueryResults(session, "2 persons with the same status");
+ assertThat(results).hasSize(1);
+
+ // europe=[ 1, 2 ], america=[ 3 ]
+ stilton20.setStatus("europe");
+ session.update(c1FactHandle, stilton20);
+
+ results = session.getQueryResults("2 persons with the same status");
+ assertThat(results).hasSize(1);
+
+ // europe=[ 1, 2, 3 ], america=[ ]
+ stilton40.setStatus("europe");
+ session.update(c3FactHandle, stilton40);
+
+ results = session.getQueryResults("2 persons with the same status");
+ assertThat(results).hasSize(2);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithCollect(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.compiler.integrationtests;
+
+ import org.drools.mvel.compiler.InsertedObject;
+ import java.util.ArrayList;
+
+ rule rule1
+ when
+ then
+ insert( new InsertedObject( "value1") );
+ insert( new InsertedObject( "value2") );
+ end
+
+ query "assertedobjquery"
+ assertedobj : InsertedObject( value=="value1" )
+ end
+
+ query "collect objects"
+ $list : ArrayList() from collect( InsertedObject() )
+ end
+ """;
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession session = kbase.newKieSession();
+ session.fireAllRules();
+
+ QueryResults results = getQueryResults(session, "collect objects");
+ assertThat(results).hasSize(1);
+
+ final QueryResultsRow row = results.iterator().next();
+ final List list = (List) row.get("$list");
+
+ assertThat(list).hasSize(2);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testDroolsQueryCleanup(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ String drl = """
+ package org.drools.mvel.compiler
+
+ query getWorker(String _id)
+ queryResult : Worker(id == _id)
+ end
+
+ query getWorkers()
+ queryResult : Worker()
+ end
+ """;
+
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+
+ KieSession ksession = kbase.newKieSession();
+
+ String workerId = "B1234";
+ Worker worker = new Worker();
+ worker.setId(workerId);
+
+ FactHandle handle = ksession.insert(worker);
+ ksession.fireAllRules();
+
+ assertThat(handle).isNotNull();
+
+ Object retractedWorker = null;
+ for (int i = 0; i < 100; i++) {
+ retractedWorker = ksession.getQueryResults("getWorker",
+ new Object[]{workerId});
+ }
+
+ assertThat(retractedWorker).isNotNull();
+
+ StatefulKnowledgeSessionImpl sessionImpl = (StatefulKnowledgeSessionImpl) ksession;
+
+ Collection<EntryPointNode> entryPointNodes = ((InternalRuleBase)kbase).getRete().getEntryPointNodes().values();
+
+ EntryPointNode defaultEntryPointNode = null;
+ for (EntryPointNode epNode : entryPointNodes) {
+ if (epNode.getEntryPoint().getEntryPointId().equals("DEFAULT")) {
+ defaultEntryPointNode = epNode;
+ break;
+ }
+ }
+ assertThat(defaultEntryPointNode).isNotNull();
+
+ Map<ObjectType, ObjectTypeNode> obnodes = defaultEntryPointNode.getObjectTypeNodes();
+
+ ObjectType key = new ClassObjectType(DroolsQuery.class);
+ ObjectTypeNode droolsQueryNode = obnodes.get(key);
+ Iterator<InternalFactHandle> it = droolsQueryNode.getFactHandlesIterator(sessionImpl);
+ assertThat(it).isExhausted();
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testStandardQueryListener(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
+ runQueryListenerTest(kieBaseTestConfiguration, QueryListenerOption.STANDARD);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testNonCloningQueryListener(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
+ runQueryListenerTest(kieBaseTestConfiguration, QueryListenerOption.LIGHTWEIGHT);
+ }
+
+ public void runQueryListenerTest(KieBaseTestConfiguration kieBaseTestConfiguration , QueryListenerOption option) throws IOException, ClassNotFoundException {
+ String drl = """
+ package org.drools.mvel.integrationtests;
+ import org.drools.mvel.compiler.Cheese;
+ query cheeses(String $type)
+ $cheese : Cheese(type == $type)
+ end
+
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ // insert some data into the session
+ for (int i = 0; i < 10000; i++) {
+ ksession.insert(new Cheese(i % 2 == 0 ? "stilton" : "brie"));
+ }
+
+ // query the session
+ for (int i = 0; i < 100; i++) {
+ QueryResults queryResults = ksession.getQueryResults("cheeses", "stilton");
+
+ assertThat(queryResults).extracting(row -> row.get("$cheese")).hasSize(5000);
+ }
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithEval(KieBaseTestConfiguration kieBaseTestConfiguration) throws IOException, ClassNotFoundException {
+ // [Regression in 5.2.0.M2]: NPE during rule evaluation on MVELPredicateExpression.evaluate(MVELPredicateExpression.java:82)
+
+ String drl = """
+ package org.drools.mvel.integrationtests
+ import org.drools.mvel.compiler.DomainObject;
+ query queryWithEval
+ $do: DomainObject()
+ not DomainObject(id == $do.id, eval(interval.isAfter($do.getInterval())))
+ end
+ """;
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ DomainObject do1 = new DomainObject();
+ do1.setId(1);
+ do1.setInterval(new Interval(10, 5));
+ DomainObject do2 = new DomainObject();
+ do2.setId(1);
+ do2.setInterval(new Interval(20, 5));
+ ksession.insert(do1);
+ ksession.insert(do2);
+
+ QueryResults results = ksession.getQueryResults("queryWithEval");
+ assertThat(results).hasSize(1);
+ assertThat(results.iterator().next().get("$do")).isEqualTo(do2);
+ }
+
+
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testGlobalsInQueries(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ String drl = """
+ package com.sample
+
+ global java.lang.String AString;
+ global java.util.List list;
+
+ declare AThing
+ name: String @key
+ end
+
+ rule init
+ when
+ then
+ insert(new AThing(AString));
+ insert(new AThing('Holla'));
+ end
+
+ query test(String $in)
+ AThing($in;)
+ end
+
+ rule spot
+ when
+ test("Hello";)
+ AThing("Hello";)
+ test(AString;)
+ AThing(AString;)
+ then
+ list.add(AString + " World");
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ks = kbase.newKieSession();
+
+ List<String> list = new ArrayList<>();
+ ks.setGlobal("AString", "Hello");
+ ks.setGlobal("list", list);
+ ks.fireAllRules();
+
+ assertThat(list).containsExactly("Hello World");
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithClassArg(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ //DROOLS-590
+ String drl = """
+ global java.util.List list;
+
+ declare Foo end
+
+ query bar(Class $c)
+ Class(this.getName() == $c.getName())
+ end
+
+ query bar2(Class $c)
+ Class(this == $c)
+ end
+
+ rule Init when then insert(Foo.class); end
+
+ rule React1
+ when
+ bar(Foo.class ;)
+ then
+ list.add('aa');
+ end
+
+ rule React2
+ when
+ bar2(Foo.class ;)
+ then
+ list.add('bb');
+ end
+ """;
+
+ List<String> list = new ArrayList<>();
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ks = kbase.newKieSession();
+ ks.setGlobal("list", list);
+ ks.fireAllRules();
+
+ assertThat(list).containsExactly("aa", "bb");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testPassGlobalToNestedQuery(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ // DROOLS-851
+ String drl = """
+ global java.util.List list;
+ global Integer number;
+
+ query findString(String $out)
+ findStringWithLength(number, $out;)
+ end
+
+ query findStringWithLength(int $in, String $out)
+ $out := String($in := length)
+ end
+
+ rule R when
+ findString($s;)
+ then
+ list.add($s);
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ks = kbase.newKieSession();
+
+ List<String> list = new ArrayList<>();
+ ks.setGlobal("list", list);
+ ks.setGlobal("number", 3);
+
+ ks.insert("Hi");
+ ks.insert("Bye");
+ ks.insert("Hello");
+ ks.fireAllRules();
+
+ assertThat(list).containsExactly("Bye");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithAccessorAsArgument(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ // DROOLS-414
+ String drl = """
+ import org.drools.mvel.compiler.Person
+ global java.util.List persons;
+ query contains(String $s, String $c)
+ $s := String(this.contains($c))
+ end
+ rule R when
+ $p : Person()
+ contains($p.name, "a";)
+ then
+ persons.add($p);
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ List<Person> personsWithA = new ArrayList<Person>();
+ ksession.setGlobal("persons", personsWithA);
+
+ ksession.insert("Mark");
+ ksession.insert("Edson");
+ ksession.insert("Mario");
+ ksession.insert(new Person("Mark"));
+ ksession.insert(new Person("Edson"));
+ ksession.insert(new Person("Mario"));
+ ksession.fireAllRules();
+
+ assertThat(personsWithA).hasSize(2);
+ assertThat(personsWithA).extracting(p -> p.getName()).containsExactlyInAnyOrder("Mark", "Mario");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithExpressionAsArgument(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception {
+ // DROOLS-414
+ String drl = """
+ import org.drools.mvel.compiler.Person;
+ global java.util.List persons;
+ query checkLength(String $s, int $l)
+ $s := String(length == $l)
+ end
+ rule R when
+ $i : Integer()
+ $p : Person()
+ checkLength($p.name, 1 + $i + $p.age;)
+ then
+ persons.add($p);
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ List<Person> list = new ArrayList<Person>();
+ ksession.setGlobal("persons", list);
+
+ ksession.insert(1);
+ ksession.insert("Mark");
+ ksession.insert("Edson");
+ ksession.insert("Mario");
+ ksession.insert(new Person("Mark", 2));
+ ksession.insert(new Person("Edson", 3));
+ ksession.insert(new Person("Mario", 4));
+ ksession.fireAllRules();
+
+ assertThat(list).hasSize(2);
+
+ assertThat(list).extracting(p -> p.getName()).containsExactlyInAnyOrder("Mark", "Edson");
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryInSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ // DROOLS-1386
+ String drl = """
+ query myquery(Integer $i)
+ $i := Integer()
+ end
+
+ rule R when
+ String()
+ accumulate (myquery($i;);
+ $result_count : count(1)
+ )
+ eval($result_count > 0)
+ then
+ end
+ """;
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ FactHandle iFH = ksession.insert(1);
+ FactHandle sFH = ksession.insert("");
+
+ ksession.fireAllRules();
+
+ ksession.update(iFH, 1);
+ ksession.delete(sFH);
+
+ ksession.fireAllRules();
+ }
+
+ public static class Question {}
+ public static class QuestionVisible {
+ private final Question question;
+ public QuestionVisible(Question question) {
+ this.question = question;
+ }
+ public Question getQuestion() {
+ return question;
+ }
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithOptionalOr(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ // DROOLS-1386
+ String drl = """
+ package org.test;
+ import org.drools.mvel.integrationtests.query.QueryTest.Question;
+ import org.drools.mvel.integrationtests.query.QueryTest.QuestionVisible;
+ query QuestionsKnowledge
+ $question: Question()
+ $visible: QuestionVisible(question == $question) or not QuestionVisible(question == $question)
+ end
+ """;
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+ Question question = new Question();
+ ksession.insert(question);
+ QueryResults results = ksession.getQueryResults("QuestionsKnowledge");
+ assertThat(results).hasSize(1);
+ QueryResultsRow row = results.iterator().next();
+ assertThat(row.get("$question")).isSameAs(question);
+
+ QuestionVisible questionVisible = new QuestionVisible(question);
+ ksession.insert(questionVisible);
+ results = ksession.getQueryResults("QuestionsKnowledge");
+ assertThat(results).hasSize(1);
+ row = results.iterator().next();
+ assertThat(row.get("$question")).isSameAs(question);
+ assertThat(row.get("$visible")).isSameAs(questionVisible);
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ String drl = """
+ import org.drools.mvel.compiler.oopath.model.Thing;
+ query isContainedIn(Thing $x, Thing $y)
+ $y := Thing() from $x.children
+ or
+ ($z := Thing() from $x.children and isContainedIn($z, $y;))
+ end
+ """;
+
+ Thing smartphone = new Thing("smartphone");
+ List<String> itemList = Arrays.asList("display", "keyboard", "processor");
+ itemList.stream().map(item -> new Thing(item)).forEach((thing) -> smartphone.addChild(thing));
+
+ KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, drl);
+ KieSession ksession = kbase.newKieSession();
+
+ ksession.insert(smartphone);
+
+ QueryResults queryResults = ksession.getQueryResults("isContainedIn", smartphone, Variable.v);
+ assertThat(queryResults).as("Query does not contain all items").extracting(row -> ((Thing) row.get("$y")).getName()).containsAll(itemList);
+ }
+}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryWithErrorsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryWithErrorsTest.java
new file mode 100644
index 0000000000..5cbcbfa8bd
--- /dev/null
+++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/query/QueryWithErrorsTest.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.mvel.integrationtests.query;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
+import org.drools.testcoverage.common.util.KieUtil;
+import org.drools.testcoverage.common.util.TestParametersUtil2;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.kie.api.builder.KieBuilder;
+import org.kie.api.builder.Message;
+
+public class QueryWithErrorsTest {
+
+ public static Stream<KieBaseTestConfiguration> parameters() {
+ return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream();
+ }
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithIncompatibleArgs(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ String drl ="""
+ global java.util.List list;
+
+ query
+ foo(String $s, String $s, String $s)
+ end
+
+ rule React
+ when
+ $i : Integer()
+ foo($i, $x, $i ;)
+ then
+ end
+ """;
+
+ KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
+ List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
+ assertThat(errors).hasSize(2);
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithSyntaxError(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ String drl = """
+ global java.util.List list;
+ query
+ foo(Integer $i)
+ end
+ rule React
+ when
+ $i : Integer()
+ foo($i) // missing ";" should result in 1 compilation error
+ then
+ end
+ """;
+
+ KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
+ List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
+ assertThat(errors).hasSize(1);
+ }
+
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testQueryWithWrongParamNumber(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ String drl = """
+ global java.util.List list;
+ query foo(Integer $i)
+
+ end
+ rule React
+ when
+ $i : Integer()
+ $j : Integer()
+ foo($i, $j ;)
+ then
+ end
+ """;
+
+ KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
+ List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
+ assertThat(errors).hasSize(1);
+ }
+
+
+ @ParameterizedTest(name = "KieBase type={0}")
+ @MethodSource("parameters")
+ public void testNotExistingDeclarationInQuery(KieBaseTestConfiguration kieBaseTestConfiguration) {
+ // DROOLS-414
+ String drl ="""
+ import org.drools.compiler.Person;
+ global java.util.List persons;
+
+ query checkLength(String $s, int $l)
+ $s := String(length == $l)
+ end
+
+ rule R when
+ $i : Integer()
+ $p : Person()
+ checkLength($p.name, 1 + $x + $p.age;)
+ then
+ persons.add($p);
+ end\n"
+ """;
+
+ KieBuilder kieBuilder = KieUtil.getKieBuilderFromDrls(kieBaseTestConfiguration, false, drl);
+ List<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
+ assertThat(errors).as("Should have an error").isNotEmpty();
+ }
+
+
+}
diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_QueryWithParams.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_QueryWithParams.drl
deleted file mode 100644
index 222fcb7e02..0000000000
--- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_QueryWithParams.drl
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.drools.integrationtests;
-
-import org.drools.mvel.compiler.InsertedObject;
-
-rule rule1
- when
- then
- insert( new InsertedObject( "value1") );
- insert( new InsertedObject( "value2") );
-end
-
-query "assertedobjquery" ( String $value )
- assertedobj : InsertedObject( value == $value )
-end
-
-
-query "assertedobjquery2" ( String $value1, String $value2 )
- assertedobj : InsertedObject( value == $value2 )
-end
-
\ No newline at end of file
diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_TwoQuerries.drl b/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_TwoQuerries.drl
deleted file mode 100644
index f9e0446330..0000000000
--- a/drools-test-coverage/test-compiler-integration/src/test/resources/org/drools/mvel/integrationtests/test_TwoQuerries.drl
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.drools.compiler.test;
-
-import org.drools.mvel.compiler.Cheese;
-import org.drools.mvel.compiler.Person;
-
-query "find stinky cheeses"
- Cheese(type == "stinky")
-end
-
-query "find pensioners"
- Person(age > 65)
-end
\ No newline at end of file
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@kie.apache.org
For additional commands, e-mail: commits-help@kie.apache.org