mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-19 23:02:24 +00:00
Refactor move tests from ebean-core to ebean-test
This commit is contained in:
1 parent
0b00a14fd3
commit
eab56d323b
1650 files changed
+185
-147
No files matched your search
@@ -0,0 +1,180 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.PagedList;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Ebean adds order by clause if none provided when using both first rows and max rows.
|
||||
*/
|
||||
public class TestAddOrderByWithFirstRowsMaxRows extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test_firstRows() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setFirstRow(3)
|
||||
.order().asc("id")
|
||||
.findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("order by t0.id");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_maxRows() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setMaxRows(10)
|
||||
.findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains("from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id limit 10");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_firstRowsMaxRows() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setFirstRow(3)
|
||||
.setMaxRows(10)
|
||||
.order().asc("id")
|
||||
.findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("order by t0.id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_maxRows1() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
// maxRows 1 with no first rows means Ebean does not automatically
|
||||
// add the order by id to the query
|
||||
DB.find(Order.class)
|
||||
.setMaxRows(1)
|
||||
.findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).doesNotContain("order by t0.id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pagingOne() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
PagedList<Order> pagedList =
|
||||
DB.find(Order.class)
|
||||
.setMaxRows(10)
|
||||
.findPagedList();
|
||||
|
||||
pagedList.getList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains("join o_customer t1 on t1.id = t0.kcustomer_id limit 10");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pagingTwo() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setFirstRow(10)
|
||||
.setMaxRows(10)
|
||||
.order("id")
|
||||
.findPagedList()
|
||||
.getList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains(" limit 10 offset 10");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_pagingAppendToExistingOrderBy() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.order().asc("orderDate")
|
||||
.setMaxRows(10)
|
||||
.findPagedList()
|
||||
.getList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("order by t0.order_date");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pagingExistingOrderByWithId() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.order().asc("orderDate")
|
||||
.order().desc("id")
|
||||
.setMaxRows(10)
|
||||
.findPagedList()
|
||||
.getList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("order by t0.order_date, t0.id desc");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.bean.ObjectGraphNode;
|
||||
import io.ebean.bean.ObjectGraphOrigin;
|
||||
import io.ebeaninternal.api.SpiQuery;
|
||||
import org.tests.model.basic.Address;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestAutofetchTuneWithJoin extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
runQuery();
|
||||
collectUsage();
|
||||
}
|
||||
|
||||
private void runQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q = DB.find(Order.class)
|
||||
.setAutoTune(true)
|
||||
//.fetch("customer")
|
||||
//.fetch("customer.contacts")
|
||||
.where().lt("id", 3).query();
|
||||
|
||||
List<Order> list = q.findList();
|
||||
|
||||
for (Order order : list) {
|
||||
order.getOrderDate();
|
||||
order.getShipDate();
|
||||
// order.setShipDate(new Date(System.currentTimeMillis()));
|
||||
Customer customer = order.getCustomer();
|
||||
customer.getName();
|
||||
Address shippingAddress = customer.getShippingAddress();
|
||||
if (shippingAddress != null) {
|
||||
shippingAddress.getLine1();
|
||||
shippingAddress.getCity();
|
||||
}
|
||||
// customer.getContacts()
|
||||
}
|
||||
|
||||
SpiQuery<?> sq = (SpiQuery<?>) q;
|
||||
ObjectGraphNode parentNode = sq.getParentNode();
|
||||
ObjectGraphOrigin origin = parentNode.getOriginQueryPoint();
|
||||
assertThat(origin).isNotNull();
|
||||
// MetaAutoFetchStatistic metaAutoFetchStatistic =
|
||||
// ((DefaultOrmQuery<?>)q).getMetaAutoFetchStatistic();
|
||||
// if (metaAutoFetchStatistic != null) {
|
||||
// List<NodeUsageStats> nodeUsageStats =
|
||||
// metaAutoFetchStatistic.getNodeUsageStats();
|
||||
// System.out.println(nodeUsageStats);
|
||||
// List<QueryStats> queryStats = metaAutoFetchStatistic.getQueryStats();
|
||||
// System.out.println(queryStats);
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
private static void collectUsage() {
|
||||
|
||||
DB.getDefault().autoTune().collectProfiling();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
public class TestConnectionCloseOnSqlerr extends BaseTestCase {
|
||||
|
||||
static boolean runManuallyNow = true;
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
if (runManuallyNow) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
try {
|
||||
Query<Customer> q0 = DB.find(Customer.class).where().icontains("namexxx", "Rob")
|
||||
.query();
|
||||
|
||||
q0.findList();
|
||||
} catch (Exception e) {
|
||||
if (e.getMessage().contains("Unsuccessfully waited")) {
|
||||
fail();
|
||||
} else {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTransactional() {
|
||||
|
||||
if (runManuallyNow) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
Query<Customer> q0 = DB.find(Customer.class).where().icontains("namexxx", "Rob")
|
||||
.query();
|
||||
|
||||
q0.findList();
|
||||
DB.commitTransaction();
|
||||
} catch (Exception e) {
|
||||
if (e.getMessage().contains("Unsuccessfully waited")) {
|
||||
fail("No connections found while only one thread is running. (after " + i + " queries)");
|
||||
} else {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} finally {
|
||||
if (DB.currentTransaction().isActive()) {
|
||||
DB.rollbackTransaction();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.BeanState;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.MyLobSize;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestDefaultFetchLazy extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testFetchTypeLazy() {
|
||||
|
||||
MyLobSize m = new MyLobSize();
|
||||
m.setName("aname");
|
||||
m.setMyCount(10);
|
||||
m.setMyLob("A big lob of data");
|
||||
|
||||
DB.save(m);
|
||||
|
||||
assertNotNull(m.getId());
|
||||
|
||||
MyLobSize myLobSize = DB.find(MyLobSize.class, m.getId());
|
||||
|
||||
BeanState beanState = DB.beanState(myLobSize);
|
||||
Set<String> loadedProps = beanState.loadedProps();
|
||||
|
||||
assertNotNull(loadedProps);
|
||||
assertTrue(loadedProps.contains("id"));
|
||||
assertTrue(loadedProps.contains("name"));
|
||||
|
||||
// FetchType.LAZY properties excluded
|
||||
assertFalse(loadedProps.contains("myLob"));
|
||||
assertFalse(loadedProps.contains("myCount"));
|
||||
|
||||
// the details is also tuned
|
||||
Query<MyLobSize> queryMany = DB.find(MyLobSize.class).fetch("details")// ,"+query")
|
||||
.where().gt("id", 0).query();
|
||||
|
||||
queryMany.findList();
|
||||
|
||||
String generatedSql = queryMany.getGeneratedSql();
|
||||
assertTrue(generatedSql.contains("t1.other"));
|
||||
assertFalse(generatedSql.contains("t1.something"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestExprNestedDisjunction extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
java.sql.Date onAfter = java.sql.Date.valueOf("2009-08-31");
|
||||
|
||||
Query<Customer> q = DB.find(Customer.class).where()
|
||||
.disjunction()
|
||||
.conjunction().startsWith("name", "r").eq("anniversary", onAfter).endJunction()
|
||||
.conjunction().eq("status", Customer.Status.ACTIVE).gt("id", 0).endJunction()
|
||||
.order().asc("name");
|
||||
|
||||
q.findList();
|
||||
String s = q.getGeneratedSql();
|
||||
|
||||
assertThat(s).contains("(t0.name like ");
|
||||
assertThat(s).contains(" and t0.anniversary = ?) or (t0.status = ? and t0.id > ?)");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_nested_and() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
java.sql.Date onAfter = java.sql.Date.valueOf("2009-08-31");
|
||||
|
||||
Query<Customer> q = DB.find(Customer.class)
|
||||
.where()
|
||||
.or()
|
||||
.and()
|
||||
.startsWith("name", "r").eq("anniversary", onAfter).endAnd()
|
||||
.and()
|
||||
.eq("status", Customer.Status.ACTIVE).gt("id", 0).endAnd()
|
||||
.order().asc("name");
|
||||
|
||||
q.findList();
|
||||
String s = q.getGeneratedSql();
|
||||
|
||||
assertThat(s).contains("(t0.name like ");
|
||||
assertThat(s).contains(" and t0.anniversary = ?) or (t0.status = ? and t0.id > ?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_not() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
java.sql.Date onAfter = java.sql.Date.valueOf("2009-08-31");
|
||||
|
||||
Query<Customer> q = DB.find(Customer.class)
|
||||
.where()
|
||||
.not()
|
||||
.gt("id", 1)
|
||||
.eq("anniversary", onAfter)
|
||||
.endNot()
|
||||
.order().asc("name");
|
||||
|
||||
q.findList();
|
||||
String s = q.getGeneratedSql();
|
||||
|
||||
assertThat(s).contains("where not (t0.id > ? and t0.anniversary = ?) order by t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_not_nested() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
java.sql.Date onAfter = java.sql.Date.valueOf("2009-08-31");
|
||||
|
||||
Query<Customer> q = DB.find(Customer.class)
|
||||
.where()
|
||||
.or()
|
||||
.eq("status", Customer.Status.ACTIVE)
|
||||
.not()
|
||||
.gt("id", 1)
|
||||
.eq("anniversary", onAfter)
|
||||
.order().asc("name");
|
||||
|
||||
q.findList();
|
||||
String s = q.getGeneratedSql();
|
||||
|
||||
assertThat(s).contains("where (t0.status = ? or not (t0.id > ? and t0.anniversary = ?))");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_not_nested_with_endNot() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
java.sql.Date onAfter = java.sql.Date.valueOf("2009-08-31");
|
||||
|
||||
Query<Customer> q = DB.find(Customer.class)
|
||||
.where()
|
||||
.or()
|
||||
.eq("status", Customer.Status.ACTIVE)
|
||||
.not()
|
||||
.gt("id", 1)
|
||||
.eq("anniversary", onAfter)
|
||||
.endNot()
|
||||
.endOr()
|
||||
.order().asc("name");
|
||||
|
||||
q.findList();
|
||||
String s = q.getGeneratedSql();
|
||||
|
||||
assertThat(s).contains("where (t0.status = ? or not (t0.id > ? and t0.anniversary = ?))");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestFindOneOrEmpty extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void empty() {
|
||||
|
||||
Optional<Customer> willBeEmpty = DB.find(Customer.class)
|
||||
.setId(Integer.MAX_VALUE)
|
||||
.findOneOrEmpty();
|
||||
|
||||
assertThat(willBeEmpty).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Optional<Customer> customer = DB.find(Customer.class)
|
||||
.setId(1)
|
||||
.findOneOrEmpty();
|
||||
|
||||
assertThat(customer.isPresent()).isTrue();
|
||||
|
||||
customer.ifPresent(customer1 -> {
|
||||
String name = customer1.getName();
|
||||
assertThat(name).isNotEmpty();
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.tests.query;
|
||||
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.RawSql;
|
||||
import io.ebean.RawSqlBuilder;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestIContains extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testIContains() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// case insensitive
|
||||
Query<Customer> query = DB.find(Customer.class).where().icontains("name", "Rob").query();
|
||||
|
||||
query.findList();
|
||||
String generatedSql = query.getGeneratedSql();
|
||||
|
||||
assertThat(generatedSql).contains("lower(t0.name)");
|
||||
|
||||
// case sensitive
|
||||
query = DB.find(Customer.class).where().contains("name", "Rob").query();
|
||||
|
||||
query.findList();
|
||||
generatedSql = query.getGeneratedSql();
|
||||
|
||||
assertThat(generatedSql).contains(" t0.name ");
|
||||
|
||||
DB.find(Customer.class).where().icontains("name", "Rob").findList();
|
||||
DB.find(Customer.class).where().icontains("name", "Rob").findList();
|
||||
DB.find(Customer.class).where().icontains("name", "Rob").findList();
|
||||
|
||||
String sql = "select id, status, name from o_customer where lower(name) like :name";
|
||||
RawSql parse = RawSqlBuilder.parse(sql).create();
|
||||
|
||||
DB.find(Customer.class).setRawSql(parse).setParameter("name", "Jim").findList();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestImplicitJoinOnParentRelationship extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id, name")
|
||||
.where().eq("orders.details.product.name", "Desk")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
if (isPostgres()) {
|
||||
String expectedSql = "select distinct on (t0.id) t0.id, t0.name from o_customer t0 join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 join o_product u3 on u3.id = u2.product_id where u3.name = ?";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
|
||||
} else {
|
||||
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 join o_product u3 on u3.id = u2.product_id where u3.name = ?";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
}
|
||||
|
||||
// select distinct t0.id c0, t0.name c1
|
||||
// from o_customer t0
|
||||
// join o_order u1 on u1.kcustomer_id = t0.id
|
||||
// join o_order_detail u2 on u2.order_id = u1.id
|
||||
// join o_product u3 on u3.id = u2.product_id
|
||||
// where u3.name = ?
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testWithDisjunction() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id, name")
|
||||
.where().disjunction().eq("orders.details.product.name", "Desk").eq("id", 4).endJunction()
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
if (isPostgres()) {
|
||||
String expectedSql = "select distinct on (t0.id) t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null left join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ?)";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
} else {
|
||||
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null left join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ?)";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithOr() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id, name")
|
||||
.where().or().eq("orders.details.product.name", "Desk").eq("id", 4).endJunction()
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
if (isPostgres()) {
|
||||
String expectedSql = "select distinct on (t0.id) t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null left join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ?)";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
|
||||
} else {
|
||||
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null left join o_order_detail u2 on u2.order_id = u1.id and u2.id > 0 left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ?)";
|
||||
assertThat(sqlOf(query, 1)).contains(expectedSql);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class TestInvalidFetchPath extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void invalidFetchPathAndProperties_expect_error() {
|
||||
assertThrows(PersistenceException.class, () ->
|
||||
DB.find(Customer.class)
|
||||
.fetch("notValidPath", "notHaveProps")
|
||||
.findList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidFetchPath_expect_error() {
|
||||
assertThrows(PersistenceException.class, () ->
|
||||
DB.find(Customer.class)
|
||||
.fetch("notValidPath")
|
||||
.findList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fetchWithInvalidPropertyName_expect_allowed() {
|
||||
DB.find(Customer.class)
|
||||
.fetch("billingAddress", "invalidPropertyName")
|
||||
.findList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.EOptOneA;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestJoinOptOneCascade extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
// the left join cascades to the join for c
|
||||
Query<EOptOneA> query = DB.find(EOptOneA.class).fetch("b").fetch("b.c");
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("left join eopt_one_b ");
|
||||
assertThat(sql).contains("left join eopt_one_c ");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_where() {
|
||||
|
||||
// the left join cascades to the join for c
|
||||
Query<EOptOneA> query = DB.find(EOptOneA.class)
|
||||
.where()
|
||||
.eq("b.c.nameForC", "foo")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("left join eopt_one_b ");
|
||||
assertThat(sql).contains("left join eopt_one_c ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestLimitAlterFetchMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// Due to the use of maxRows... we will convert
|
||||
// the fetch join to contacts over to a query join
|
||||
// ... otherwise we wouldn't be able to use the
|
||||
// limit offset clause
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
// this will automatically get converted to a
|
||||
// query join ... due to the maxRows
|
||||
.fetch("contacts").setMaxRows(5).order("id");
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
|
||||
System.out.println(list);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestLimitQuery extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testHasManyWithLimit() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> customers = DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
.setFirstRow(0)
|
||||
.setMaxRows(10)
|
||||
.where().like("name", "%A%")
|
||||
.findList();
|
||||
|
||||
// should at least find the "Cust NoAddress" customer
|
||||
assertTrue(!customers.isEmpty());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.Product;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestManyWhereJoin extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).select("id,status")
|
||||
// the where on a 'many' (like orders) requires an
|
||||
// additional join and distinct which is independent
|
||||
// of a fetch join (if there is a fetch join)
|
||||
.where().eq("orders.status", Order.Status.NEW)
|
||||
// .where().eq("orders.details.product.name", "Desk")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 1);
|
||||
|
||||
// select distinct t0.id c0, t0.status c1
|
||||
// from o_customer t0
|
||||
// join o_order u1 on u1.kcustomer_id = t0.id
|
||||
// where u1.status = ? ; --bind(NEW)
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.id) t0.id, ");
|
||||
} else {
|
||||
assertThat(sql).contains("select distinct t0.id");
|
||||
}
|
||||
assertThat(sql).contains("join o_order ");
|
||||
assertThat(sql).contains(".status = ?");
|
||||
assertThat(sql).contains("t0.id, t0.status from o_customer t0 join o_order u1 on u1.kcustomer_id = t0.id and u1.order_date is not null where u1.status = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithFetchJoinAndWhere() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).select("id,status")
|
||||
.fetch("orders")
|
||||
// the where on a 'many' (like orders) requires an
|
||||
// additional join and distinct which is independent
|
||||
// of a fetch join (if there is a fetch join)
|
||||
.where().eq("orders.status", Order.Status.NEW)
|
||||
// .where().eq("orders.details.product.name", "Desk")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 3);
|
||||
|
||||
// select distinct t0.id c0, t0.status c1,
|
||||
// t1.id c2, t1.status c3, t1.order_date c4, t1.ship_date c5, t2.name c6, t1.cretime c7, t1.updtime c8, t1.kcustomer_id c9, t0.id
|
||||
// from o_customer t0
|
||||
// left join o_order t1 on t1.kcustomer_id = t0.id
|
||||
// left join o_customer t2 on t2.id = t1.kcustomer_id
|
||||
// join o_order u1 on u1.kcustomer_id = t0.id
|
||||
// where t1.order_date is not null and u1.status = ?
|
||||
// order by t0.id; --bind(NEW)
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.id, t1.id) t0.id, t0.status,");
|
||||
} else {
|
||||
assertThat(sql).contains("select distinct t0.id, t0.status, t1.id, t1.status,");
|
||||
}
|
||||
assertThat(sql).contains("left join o_order t1 on ");
|
||||
assertThat(sql).contains("join o_order u1 on ");
|
||||
assertThat(sql).contains(" u1.status = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUsingForeignKey() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Long productId = 1L;
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().eq("details.product.id", productId)
|
||||
.order("cretime asc").query();
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 3);
|
||||
|
||||
// select distinct t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7, t0.cretime
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// join o_order_detail u1 on u1.order_id = t0.id
|
||||
// where u1.product_id = ?
|
||||
// order by t0.cretime; --bind(1)
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.cretime, t0.id) t0.id, t0.status,");
|
||||
} else {
|
||||
assertThat(sql).contains("select distinct t0.id, t0.status,");
|
||||
}
|
||||
assertThat(sql).contains(" join o_order_detail u1 on u1.order_id = t0.id");
|
||||
assertThat(sql).contains(" where u1.product_id = ?");
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as previous test but use a reference bean.
|
||||
*/
|
||||
@Test
|
||||
public void testUsingForeignKeyReferenceBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Product product = DB.reference(Product.class, 1L);
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
//.fetch("details")
|
||||
.where().eq("details.product", product)
|
||||
.order("cretime asc").query();
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 3);
|
||||
|
||||
// select distinct t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7, t0.cretime
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// join o_order_detail u1 on u1.order_id = t0.id
|
||||
// where u1.product_id = ?
|
||||
// order by t0.cretime
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.cretime, t0.id) t0.id, t0.status,");
|
||||
} else {
|
||||
assertThat(sql).contains("select distinct t0.id, t0.status,");
|
||||
}
|
||||
assertThat(sql).contains(" join o_order_detail u1 on u1.order_id = t0.id");
|
||||
assertThat(sql).contains(" where u1.product_id = ?");
|
||||
}
|
||||
|
||||
/**
|
||||
* Additionally add a fetch join.
|
||||
*/
|
||||
@Test
|
||||
public void testUsingForeignKeyAndFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Product product = DB.reference(Product.class, 1L);
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetch("details")
|
||||
.where().eq("details.product", product)
|
||||
.order("cretime asc").query();
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 3);
|
||||
|
||||
// select distinct t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t2.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7,
|
||||
// t1.id c8, t1.order_qty c9, t1.ship_qty c10, t1.unit_price c11, t1.cretime c12, t1.updtime c13, t1.order_id c14, t1.product_id c15, t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime
|
||||
// from o_order t0
|
||||
// join o_customer t2 on t2.id = t0.kcustomer_id
|
||||
// left join o_order_detail t1 on t1.order_id = t0.id
|
||||
// join o_order_detail u1 on u1.order_id = t0.id
|
||||
// where t1.id > 0 and u1.product_id = ?
|
||||
// order by t0.cretime, t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc; --bind(1)
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime) t0.id, t0.status,");
|
||||
} else {
|
||||
assertThat(sql).contains("select distinct t0.id, t0.status,");
|
||||
}
|
||||
assertThat(sql).contains(" join o_order_detail u1 on u1.order_id = t0.id");
|
||||
assertThat(sql).contains(" u1.product_id = ?");
|
||||
|
||||
// additional join for fetching the many details
|
||||
assertThat(sql).contains(" left join o_order_detail t1 on t1.order_id = t0.id");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.Transaction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.MRole;
|
||||
import org.tests.model.basic.MUser;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestManyWhereJoinM2M extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
try (Transaction txn = DB.beginTransaction()) {
|
||||
|
||||
MRole r1 = new MRole();
|
||||
r1.setRoleName("role1");
|
||||
DB.save(r1);
|
||||
|
||||
MRole r2 = new MRole();
|
||||
r2.setRoleName("role2special");
|
||||
DB.save(r2);
|
||||
|
||||
MRole r3 = new MRole();
|
||||
r3.setRoleName("role3");
|
||||
DB.save(r3);
|
||||
|
||||
MUser u0 = new MUser();
|
||||
u0.setUserName("user0");
|
||||
u0.addRole(r1);
|
||||
u0.addRole(r2);
|
||||
|
||||
DB.save(u0);
|
||||
|
||||
MUser u1 = new MUser();
|
||||
u1.setUserName("user1");
|
||||
u1.addRole(r1);
|
||||
|
||||
DB.save(u1);
|
||||
|
||||
MUser u2 = new MUser();
|
||||
u2.setUserName("user2");
|
||||
DB.save(u2);
|
||||
|
||||
txn.commit();
|
||||
}
|
||||
Query<MUser> query = DB.find(MUser.class).fetch("roles")
|
||||
// the where on a 'many' (like orders) requires an
|
||||
// additional join and distinct which is independent
|
||||
// of a fetch join (if there is a fetch join)
|
||||
.where().eq("roles.roleName", "role2special").query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
assertTrue(sql.contains("select distinct"));
|
||||
assertTrue(sql.contains("left join mrole "));
|
||||
assertTrue(sql.contains("join mrole "));
|
||||
assertTrue(sql.contains(".role_name = ?"));
|
||||
|
||||
isEmpty();
|
||||
isNotEmpty();
|
||||
}
|
||||
|
||||
private void isEmpty() {
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.where().isEmpty("roles")
|
||||
.query();
|
||||
|
||||
List<MUser> usersWithNoRoles = query.findList();
|
||||
|
||||
assertThat(sqlOf(query, 2)).contains("select t0.userid, t0.user_name, t0.user_type_id from muser t0 where not exists (select 1 from mrole_muser x where x.muser_userid = t0.userid)");
|
||||
assertThat(usersWithNoRoles).isNotEmpty();
|
||||
}
|
||||
|
||||
private void isNotEmpty() {
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.select("userName")
|
||||
.where().isNotEmpty("roles")
|
||||
.query();
|
||||
|
||||
List<MUser> usersWithRoles = query.findList();
|
||||
|
||||
assertThat(sqlOf(query, 1)).contains("select t0.userid, t0.user_name from muser t0 where exists (select 1 from mrole_muser x where x.muser_userid = t0.userid)");
|
||||
assertThat(usersWithRoles).isNotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.RawSql;
|
||||
import io.ebean.RawSqlBuilder;
|
||||
import org.tests.model.basic.MyAdHoc;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestMyAdHocSqlSelect extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select order_id, count(*) as detailCount from o_order_detail group by order_id";
|
||||
|
||||
RawSql rawSql = RawSqlBuilder
|
||||
.parse(sql)
|
||||
.columnMapping("order_id", "order.id")
|
||||
.create();
|
||||
|
||||
Query<MyAdHoc> query = DB.find(MyAdHoc.class)
|
||||
.setRawSql(rawSql)
|
||||
.where().gt("order_id", 0)
|
||||
.having().gt("detailCount", 0)
|
||||
.query();
|
||||
|
||||
assertNotNull(query.findList());
|
||||
assertSql(query).contains(" group by order_id having count(*) > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_explicitColumnMapping() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select order_id, count(*) as detail_count from o_order_detail group by order_id";
|
||||
|
||||
RawSql rawSql = RawSqlBuilder
|
||||
.parse(sql)
|
||||
.columnMapping("order_id", "order.id")
|
||||
.columnMapping("detail_count", "detailCount")
|
||||
.create();
|
||||
|
||||
Query<MyAdHoc> query = DB.find(MyAdHoc.class)
|
||||
.setRawSql(rawSql)
|
||||
.where().gt("order_id", 0)
|
||||
.having().gt("detailCount", 0)
|
||||
.query();
|
||||
|
||||
assertNotNull(query.findList());
|
||||
assertSql(query).contains(" group by order_id having count(*) > ?");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestOneToManyCorrectGrouping extends BaseTestCase {
|
||||
|
||||
public static final int EXPECTED_ITERATIONS = 2;
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
Query<Customer> customerQuery = DB.find(Customer.class)
|
||||
.fetch("orders")
|
||||
.where().le("id", 2)
|
||||
.query();
|
||||
|
||||
final AtomicInteger count = new AtomicInteger();
|
||||
|
||||
customerQuery.findEach(customer -> {
|
||||
for (Order order : customer.getOrders()) {
|
||||
order.getId();
|
||||
}
|
||||
count.incrementAndGet();
|
||||
});
|
||||
assertEquals(EXPECTED_ITERATIONS, count.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebeantest.LoggedSql;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests if outer joins are correctly used.
|
||||
*
|
||||
* @author Roland Praml, FOCONIS AG
|
||||
*
|
||||
*/
|
||||
public class TestOuterJoin extends BaseTestCase {
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
ResetBasicData.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOuterOnNullQuery() throws Exception {
|
||||
|
||||
LoggedSql.start();
|
||||
List<Customer> list = DB.find(Customer.class).where()
|
||||
.isNull("orders")
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" where not exists "); // perfored with not exists query
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
// use OR construct
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.or()
|
||||
.isNull("orders.details.product.name")
|
||||
.isNull("orders")
|
||||
.endOr()
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" left join o_order ")
|
||||
.contains(" left join o_order_detail ")
|
||||
.contains(" left join o_product ")
|
||||
.contains(" or not exists ");
|
||||
|
||||
assertThat(list).hasSize(4);
|
||||
|
||||
// use AND construct
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.and()
|
||||
.isNull("orders.details.product.name")
|
||||
.isNull("orders")
|
||||
.endAnd()
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" left join o_order ")
|
||||
.contains(" left join o_order_detail ")
|
||||
.contains(" left join o_product ")
|
||||
.contains(" and not exists ");
|
||||
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.isNull("orders.details.product.name")
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" left join o_order ")
|
||||
.contains(" left join o_order_detail ")
|
||||
.contains(" left join o_product ");
|
||||
assertThat(list).hasSize(4);
|
||||
LoggedSql.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInnerOnNonNullQuery() throws Exception {
|
||||
|
||||
LoggedSql.start();
|
||||
List<Customer> list = DB.find(Customer.class).where()
|
||||
.isNotNull("orders")
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" where exists "); // perfored with not exists query
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
// use OR construct
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.or()
|
||||
.isNotNull("orders.details.product.name")
|
||||
.isNotNull("orders")
|
||||
.endOr()
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" left join o_order ")
|
||||
.contains(" left join o_order_detail ")
|
||||
.contains(" left join o_product ")
|
||||
.contains(" or exists ");
|
||||
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
// use AND construct
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.and()
|
||||
.isNotNull("orders.details.product.name")
|
||||
.isNotNull("orders")
|
||||
.endAnd()
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.doesNotContain(" left join ")
|
||||
.contains(" and exists ");
|
||||
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
|
||||
LoggedSql.start();
|
||||
list = DB.find(Customer.class).where()
|
||||
.isNotNull("orders.details.product.name")
|
||||
.le("id", 4) // ignore others than basicData
|
||||
.findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.doesNotContain(" left join ");
|
||||
assertThat(list).hasSize(2);
|
||||
LoggedSql.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOuterOnFetch() {
|
||||
|
||||
LoggedSql.start();
|
||||
|
||||
List<Order> orders1 = DB.find(Order.class).order("id").findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" join o_customer") // ensure that we do not left join the customer
|
||||
.doesNotContain(" left join o_customer");
|
||||
|
||||
|
||||
// now fetch "details" bean, which may be optional
|
||||
LoggedSql.start();
|
||||
|
||||
List<Order> orders2 = DB.find(Order.class)
|
||||
.fetch("details", "id").order("id").findList();
|
||||
|
||||
assertThat(LoggedSql.collect().get(0))
|
||||
.contains(" left join o_order_detail ");
|
||||
|
||||
LoggedSql.stop();
|
||||
|
||||
assertThat(orders2).isEqualTo(orders1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.CKeyParent;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryAlias extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testExists() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<CKeyParent> sq = DB.createQuery(CKeyParent.class)
|
||||
.select("id.oneKey").alias("st0")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<CKeyParent> pq = DB.find(CKeyParent.class).alias("myt0").where().in("id.oneKey", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
// Without alias command is should be:
|
||||
// select t0.one_key c0, t0.two_key c1, t0.name c2, t0.version c3, t0.assoc_id c4 from ckey_parent t0 where (t0
|
||||
// .one_key) in (select t0.one_key from ckey_parent t0)
|
||||
// but with alias command SQL should look like this:
|
||||
// select myt0.one_key c0, myt0.two_key c1, myt0.name c2, myt0.version c3, myt0.assoc_id c4 from ckey_parent myt0
|
||||
// where (myt0.one_key) in (select st0.one_key from ckey_parent st0)
|
||||
|
||||
assertThat(sql).contains("ckey_parent myt0");
|
||||
assertThat(sql).contains("(myt0.one_key) in (select st0.one_key from ckey_parent st0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExistsWithConcat() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<CKeyParent> sq = DB.createQuery(CKeyParent.class)
|
||||
.select("concat(id.oneKey,id.twoKey)").alias("st0")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<CKeyParent> pq = DB.find(CKeyParent.class).alias("myt0").where().in("concat(id.oneKey,id.twoKey)", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("ckey_parent myt0");
|
||||
assertThat(sql).contains("(concat(myt0.one_key,myt0.two_key)) in (select concat(st0.one_key,st0.two_key) from ckey_parent st0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotExists() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<CKeyParent> sq = DB.createQuery(CKeyParent.class)
|
||||
.select("id.oneKey").alias("st0")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<CKeyParent> pq = DB.find(CKeyParent.class).alias("myt0").where().notIn("id.oneKey", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
// Without alias command is should be:
|
||||
// select t0.one_key c0, t0.two_key c1, t0.name c2, t0.version c3, t0.assoc_id c4 from ckey_parent t0 where (t0
|
||||
// .one_key) in (select t0.one_key from ckey_parent t0)
|
||||
// but with alias command SQL should look like this:
|
||||
// select myt0.one_key c0, myt0.two_key c1, myt0.name c2, myt0.version c3, myt0.assoc_id c4 from ckey_parent myt0
|
||||
// where (myt0.one_key) in (select st0.one_key from ckey_parent st0)
|
||||
|
||||
assertThat(sql).contains("ckey_parent myt0");
|
||||
assertThat(sql).contains("(myt0.one_key) not in (select st0.one_key from ckey_parent st0)");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.annotation.ForPlatform;
|
||||
import io.ebean.annotation.Platform;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryBaseTable extends BaseTestCase {
|
||||
|
||||
@ForPlatform({Platform.H2, Platform.POSTGRES})
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Customer one = DB.find(Customer.class)
|
||||
.setBaseTable("O_CUSTOMER")
|
||||
.where().startsWith("name", "Rob")
|
||||
.findOne();
|
||||
|
||||
Customer two = DB.find(Customer.class)
|
||||
.where().startsWith("name", "Rob")
|
||||
.findOne();
|
||||
|
||||
Customer three = DB.find(Customer.class)
|
||||
.setBaseTable("O_CUSTOMER")
|
||||
.where().startsWith("name", "Fiona")
|
||||
.findOne();
|
||||
|
||||
assertThat(one.getName()).isEqualTo(two.getName());
|
||||
assertThat(three.getName()).isEqualTo("Fiona");
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(sql).hasSize(3);
|
||||
assertSql(sql.get(0)).contains("from O_CUSTOMER");
|
||||
assertSql(sql.get(1)).contains("from o_customer");
|
||||
assertSql(sql.get(2)).contains("from O_CUSTOMER");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebeantest.LoggedSql;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryExists extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testExistsBoolean_basic() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().gt("id", 1)
|
||||
.query();
|
||||
|
||||
LoggedSql.start();
|
||||
boolean check = query.exists();
|
||||
String sql = LoggedSql.stop().get(0);
|
||||
assertThat(check).isTrue();
|
||||
|
||||
if (isH2() || isPostgres()) {
|
||||
assertThat(sql).contains("select t0.id from o_order t0 where t0.id > ? limit 1");
|
||||
}
|
||||
|
||||
assertThat(DB.find(Order.class).where().gt("id", 1).exists()).isTrue();
|
||||
assertThat(DB.find(Order.class).where().or().gt("id", 1).isNull("shipDate").exists()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExists_orders_onOneToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().raw("exists (select 1 from o_order_detail where order_id = t0.id)")
|
||||
.query();
|
||||
|
||||
List<Order> ordersThatHave = query.findList();
|
||||
|
||||
Query<Order> query2 = DB.find(Order.class)
|
||||
.where().raw("not exists (select 1 from o_order_detail where order_id = t0.id)")
|
||||
.query();
|
||||
|
||||
List<Order> ordersThatDontHave = query2.findList();
|
||||
|
||||
assertSql(query).contains(" exists (");
|
||||
assertThat(query2.getGeneratedSql()).contains(" not exists (");
|
||||
|
||||
assertThat(ordersThatHave).isNotEmpty();
|
||||
assertThat(ordersThatDontHave).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExists_onOneToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.where().raw("exists (select 1 from contact where customer_id = t0.id)")
|
||||
.query();
|
||||
|
||||
List<Customer> customersWithContacts = query.findList();
|
||||
|
||||
Query<Customer> query2 = DB.find(Customer.class)
|
||||
.where().raw("not exists (select 1 FROM contact where customer_id = t0.id)")
|
||||
.query();
|
||||
|
||||
query2.findList();
|
||||
|
||||
assertSql(query).contains(" exists (");
|
||||
assertThat(query2.getGeneratedSql()).contains(" not exists (");
|
||||
|
||||
assertThat(customersWithContacts).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExists() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> subQuery = DB.find(Order.class).alias("sq").select("id").where().raw("sq.kcustomer_id = qt.id").query();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).alias("qt").where().exists(subQuery).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("exists (select 1 from");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotExists() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> subQuery = DB.find(Order.class).alias("sq").where().raw("sq.kcustomer_id = qt.id").query();
|
||||
Query<Customer> query = DB.find(Customer.class).alias("qt").where().notExists(subQuery).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("not exists (select 1 from");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExistsNoWhere() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> subQuery = DB.find(Order.class).alias("sq").select("id");
|
||||
Query<Customer> query = DB.find(Customer.class).alias("qt").where().notExists(subQuery).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("not exists (select 1 from o_order sq)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestQueryFetchJoinWithOrder extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class)
|
||||
.fetchQuery("details")
|
||||
.order().asc("id")
|
||||
.order().desc("details.id").findList();
|
||||
|
||||
assertNotNull(list);
|
||||
|
||||
List<Order> list2 = DB.find(Order.class)
|
||||
.fetchQuery("customer")
|
||||
.fetch("customer.contacts")
|
||||
.order().asc("id")
|
||||
.order().asc("customer.contacts.lastName")
|
||||
.findList();
|
||||
|
||||
assertNotNull(list2);
|
||||
|
||||
List<Customer> list3 = DB.find(Customer.class)
|
||||
.fetch("orders")
|
||||
.filterMany("orders").eq("status", Order.Status.NEW)
|
||||
.order().desc("orders.id")
|
||||
.findList();
|
||||
|
||||
assertNotNull(list3);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.OrderShipment;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryFetchManyTwoDeep extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testFetchOneToManyWithChildOneToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// test that join to order.details is not included in the initial query (included in query join)
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
.fetch("orders")
|
||||
.fetch("orders.details");
|
||||
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertTrue(!list.isEmpty());
|
||||
String mainSql = sqlOf(query);
|
||||
assertThat(mainSql).contains("from o_customer t0 ");
|
||||
assertThat(mainSql).contains("left join o_order t1 on t1.kcustomer_id = t0.id");
|
||||
assertThat(mainSql).contains("left join o_customer t2 on t2.id = t1.kcustomer_id");
|
||||
assertThat(mainSql).doesNotContain("join or_order_ship");
|
||||
|
||||
//select t0.id c0, t0.status c1, t0.name c2, t0.smallnote c3, t0.anniversary c4, t0.cretime c5, t0.updtime c6, t0.billing_address_id c7, t0.shipping_address_id c8, t1.id c9, t1.status c10, t1.order_date c11, t1.ship_date c12,
|
||||
// t2.name c13, t1.cretime c14, t1.updtime c15, t1.kcustomer_id c16
|
||||
// from o_customer t0
|
||||
// left join o_order t1 on t1.kcustomer_id = t0.id
|
||||
// left join o_customer t2 on t2.id = t1.kcustomer_id
|
||||
// where t1.order_date is not null order by t0.id; --bind()
|
||||
|
||||
|
||||
//List<SpiQuery<?>> secondaryQueries = spiQuery.getLoggedSecondaryQueries();
|
||||
//Assert.assertNotNull(secondaryQueries);
|
||||
assertEquals(2, sql.size());
|
||||
|
||||
//SpiQuery<?> secondaryQuery = secondaryQueries.get(0);
|
||||
String secondarySql = sql.get(1);
|
||||
assertThat(secondarySql).contains("from o_order_detail t0 where t0.id > 0 and (t0.order_id) ");
|
||||
platformAssertIn(secondarySql, "(t0.order_id)");
|
||||
|
||||
// select t0.order_id c0, t0.id c1, t0.order_qty c2, t0.ship_qty c3, t0.unit_price c4, t0.cretime c5, t0.updtime c6, t0.order_id c7, t0.product_id c8
|
||||
// from o_order_detail t0
|
||||
// where (t0.order_id) in (?,?,?,?,?)
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFetchOptionalManyToOneThenDownToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// test that join to order.details is not included
|
||||
Query<OrderShipment> shipQuery = DB.find(OrderShipment.class)
|
||||
.setAutoTune(false)
|
||||
.fetch("order")
|
||||
.fetch("order.details");
|
||||
|
||||
List<OrderShipment> shipList = shipQuery.findList();
|
||||
assertTrue(!shipList.isEmpty());
|
||||
|
||||
String generatedSql = shipQuery.getGeneratedSql();
|
||||
|
||||
// select ...
|
||||
// from or_order_ship t0
|
||||
// left join o_order t1 on t1.id = t0.order_id
|
||||
// left join o_customer t3 on t3.id = t1.kcustomer_id
|
||||
// left join o_order_detail t2 on t2.order_id = t1.id
|
||||
// where t2.id > 0 ; --bind()
|
||||
|
||||
assertTrue(generatedSql.contains("from or_order_ship t0"));
|
||||
// Relationship from OrderShipment to Order is optional so outer join here
|
||||
assertTrue(generatedSql.contains("left join o_order t1 on t1.id = t0.order_id"));
|
||||
assertTrue(generatedSql.contains("left join o_customer t3 on t3.id = t1.kcustomer_id"));
|
||||
assertTrue(generatedSql.contains("left join o_order_detail t2 on t2.order_id = t1.id"));
|
||||
|
||||
|
||||
// If OrderShipment to Order is not optional you get inner joins up to o_order_detail (which is a many)
|
||||
|
||||
// select ...
|
||||
// from or_order_ship t0
|
||||
// join o_order t1 on t1.id = t0.order_id
|
||||
// join o_customer t3 on t3.id = t1.kcustomer_id
|
||||
// left join o_order_detail t2 on t2.order_id = t1.id
|
||||
// where t2.id > 0 ; --bind()
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testFetchMandatoryManyToOneThenDownToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// test that join to order.details is not included
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setAutoTune(false)
|
||||
.fetch("customer")
|
||||
.fetch("customer.orders");
|
||||
|
||||
List<Contact> shipList = query.findList();
|
||||
assertTrue(!shipList.isEmpty());
|
||||
|
||||
String generatedSql = query.getGeneratedSql();
|
||||
|
||||
// select ...
|
||||
// from contact t0
|
||||
// join o_customer t1 on t1.id = t0.customer_id
|
||||
// left join o_order t2 on t2.kcustomer_id = t1.id
|
||||
// left join o_customer t3 on t3.id = t2.kcustomer_id
|
||||
// where t2.order_date is not null ; --bind()
|
||||
|
||||
assertThat(generatedSql).contains("from contact t0 ");
|
||||
// Relationship from Contact to Customer is mandatory so inner join here
|
||||
assertThat(generatedSql).contains("join o_customer t1 on t1.id = t0.customer_id");
|
||||
// outer join on many relationship 'orders'
|
||||
assertThat(generatedSql).contains("left join o_order t2 on t2.kcustomer_id = t1.id");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFetchMandatoryManyToOneWithPredicate() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// test that join to order.details is not included
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setAutoTune(false)
|
||||
.fetch("customer")
|
||||
.where().ilike("customer.name", "Rob%")
|
||||
.query();
|
||||
|
||||
List<Contact> list = query.findList();
|
||||
assertTrue(!list.isEmpty());
|
||||
|
||||
String generatedSql = query.getGeneratedSql();
|
||||
|
||||
// select ...
|
||||
// from contact t0
|
||||
// join o_customer t1 on t1.id = t0.customer_id
|
||||
// where lower(t1.name) like ? ; --bind(rob%)
|
||||
|
||||
assertThat(generatedSql).contains("from contact t0 ");
|
||||
assertThat(generatedSql).contains("join o_customer t1 on t1.id = t0.customer_id");
|
||||
assertThat(generatedSql).contains("where lower(t1.name) like ");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.ContactNote;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestQueryFetchSkipPath extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class)
|
||||
|
||||
// .setAutoTune(true)
|
||||
.setAutoTune(false).select("status")
|
||||
// .fetch("customer","id")
|
||||
// .fetch("customer.contacts","id")
|
||||
.fetch("customer.contacts.notes", "title").findList();
|
||||
|
||||
for (Order order : list) {
|
||||
order.getStatus();
|
||||
Customer customer = order.getCustomer();
|
||||
List<Contact> contacts = customer.getContacts();
|
||||
for (Contact contact : contacts) {
|
||||
List<ContactNote> notes = contact.getNotes();
|
||||
for (ContactNote contactNote : notes) {
|
||||
contactNote.getTitle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryFilterCaseInsensitive extends BaseTestCase {
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
ResetBasicData.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEq() {
|
||||
|
||||
// Note: this test uses only customer#1..#4
|
||||
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.eq("name", "ROB") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).isEmpty();
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.ieq("name", "ROB") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNe() {
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.ne("name", "ROB") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).hasSize(4);
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.ine("name", "ROB") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(3);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLike() {
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.like("name", "%O%") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).isEmpty();
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.ilike("name", "%O%") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(4); // Rob / Fiona / Cust No address / NocCust
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContains() {
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.contains("name", "O") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).isEmpty();
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.icontains("name", "O") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(4); // Rob / Fiona / Cust No address / NocCust
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartsWith() {
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.startsWith("name", "RO") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).isEmpty();
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.istartsWith("name", "RO") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEndsWith() {
|
||||
List<Customer> customers = DB.find(Customer.class).where()
|
||||
.endsWith("name", "OB") // case match
|
||||
.le("id", 4).findList();
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(customers).isEmpty();
|
||||
} else {
|
||||
assertThat(customers).isNotEmpty();
|
||||
}
|
||||
|
||||
customers = DB.find(Customer.class).where()
|
||||
.iendsWith("name", "OB") // case insensitive match
|
||||
.le("id", 4).findList();
|
||||
|
||||
assertThat(customers).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.ExpressionList;
|
||||
import io.ebean.Query;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestQueryFilterMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Customer customer = DB.find(Customer.class)
|
||||
.fetchLazy("orders")
|
||||
.filterMany("orders").eq("status", Order.Status.NEW)
|
||||
.where().ieq("name", "Rob")
|
||||
.order().asc("id").setMaxRows(1)
|
||||
.findList().get(0);
|
||||
|
||||
final int size = customer.getOrders().size();
|
||||
assertThat(size).isGreaterThan(0);
|
||||
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(2, sqlList.size());
|
||||
assertThat(sqlList.get(1)).contains("status = ?");
|
||||
|
||||
// Currently this does not include the query filter
|
||||
DB.refreshMany(customer, "orders");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterMany_firstMaxRows_fluidStyle() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
final Query<Customer> query = DB.find(Customer.class)
|
||||
.where().ieq("name", "Rob")
|
||||
// fluid style adding maxRows/firstRow to filterMany
|
||||
.filterMany("orders").eq("status", Order.Status.NEW).order("id desc").setMaxRows(100).setFirstRow(3)
|
||||
.order().asc("id").setMaxRows(5);
|
||||
|
||||
final List<Customer> customers = query.findList();
|
||||
assertThat(customers).isNotEmpty();
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(2, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("lower(t0.name) = ?");
|
||||
assertThat(sqlList.get(1)).contains("status = ?");
|
||||
|
||||
if (isH2() || isPostgres()) {
|
||||
assertThat(sqlList.get(0)).doesNotContain("offset");
|
||||
assertThat(sqlList.get(0)).contains(" limit 5");
|
||||
assertThat(sqlList.get(1)).contains(" offset 3");
|
||||
assertThat(sqlList.get(1)).contains(" limit 100");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_firstMaxRows() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
final Query<Customer> query = DB.find(Customer.class)
|
||||
.where().ieq("name", "Rob")
|
||||
.order().asc("id").setMaxRows(5);
|
||||
|
||||
// non-fluid style adding maxRows/firstRow
|
||||
final ExpressionList<Customer> filterMany = query.filterMany("orders").order("id desc").eq("status", Order.Status.NEW);
|
||||
filterMany.setMaxRows(100);
|
||||
filterMany.setFirstRow(3);
|
||||
|
||||
final List<Customer> customers = query.findList();
|
||||
assertThat(customers).isNotEmpty();
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(2, sqlList.size());
|
||||
|
||||
assertThat(sqlList.get(0)).contains("lower(t0.name) = ?");
|
||||
assertThat(sqlList.get(1)).contains("status = ?");
|
||||
|
||||
if (isH2() || isPostgres()) {
|
||||
assertThat(sqlList.get(0)).doesNotContain("offset");
|
||||
assertThat(sqlList.get(0)).contains(" limit 5");
|
||||
assertThat(sqlList.get(1)).contains(" offset 3");
|
||||
assertThat(sqlList.get(1)).contains(" limit 100");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterMany_firstMaxRows_expressionFluidStyle() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
final Query<Customer> query = DB.find(Customer.class)
|
||||
.where().ieq("name", "Rob")
|
||||
// use expression + fluid style adding maxRows/firstRow to filterMany
|
||||
.filterMany("orders", "status = ?", Order.Status.NEW)
|
||||
.setMaxRows(100).setFirstRow(3).order("orderDate desc, id")
|
||||
.order().asc("id").setMaxRows(5);
|
||||
|
||||
final List<Customer> customers = query.findList();
|
||||
assertThat(customers).isNotEmpty();
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(2, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("lower(t0.name) = ?");
|
||||
assertThat(sqlList.get(1)).contains("status = ?");
|
||||
|
||||
if (isH2() || isPostgres()) {
|
||||
assertThat(sqlList.get(0)).doesNotContain("offset");
|
||||
assertThat(sqlList.get(0)).contains(" limit 5");
|
||||
assertThat(sqlList.get(1)).contains(" order by t0.order_date desc, t0.id limit 100 offset 3");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_with_findOne() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Customer customer = DB.find(Customer.class)
|
||||
.setMaxRows(1)
|
||||
.order().asc("id")
|
||||
.fetch("orders")
|
||||
.filterMany("orders").raw("1 = 0")
|
||||
.findOne();
|
||||
|
||||
assertThat(customer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_with_findOneOrEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Optional<Customer> customer = DB.find(Customer.class)
|
||||
.setMaxRows(1)
|
||||
.order().asc("id")
|
||||
.fetch("orders")
|
||||
.filterMany("orders").raw("1 = 0")
|
||||
.findOneOrEmpty();
|
||||
|
||||
assertThat(customer).isPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_filterMany_with_isNotEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.filterMany("orders").raw("1=0")
|
||||
.where().isNotEmpty("orders")
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
for (Customer customer : list) {
|
||||
assertThat(customer.getOrders()).isEmpty();
|
||||
}
|
||||
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("from o_customer t0 left join o_order t1 on t1.kcustomer_id = t0.id and t1.order_date is not null left join o_customer t2 on t2.id = t1.kcustomer_id where exists (select 1 from o_order x where x.kcustomer_id = t0.id and x.order_date is not null) and 1=0 order by t0.id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_filterMany_in_findCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetch("orders")
|
||||
.filterMany("orders").in("status", Order.Status.NEW)
|
||||
.order().asc("id");
|
||||
|
||||
query.findCount();
|
||||
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("select count(*) from o_customer");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_filterMany_copy_findList() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetch("orders")
|
||||
.filterMany("orders").in("status", Order.Status.NEW)
|
||||
.order().asc("id");
|
||||
|
||||
query.copy().findList();
|
||||
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("from o_customer t0 left join o_order t1 on t1.kcustomer_id = t0.id and t1.order_date is not null left join o_customer t2 on t2.id = t1.kcustomer_id where t1.status ");
|
||||
if (isPostgres()) {
|
||||
assertThat(sqlList.get(0)).contains("where t1.status = any(?) order by t0.id");
|
||||
} else {
|
||||
assertThat(sqlList.get(0)).contains("where t1.status in (?) order by t0.id");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_filterMany_fetchQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetchQuery("orders") // explicitly fetch orders separately
|
||||
.filterMany("orders").in("status", Order.Status.NEW)
|
||||
.order().asc("id");
|
||||
|
||||
query.findList();
|
||||
|
||||
List<String> sqlList = LoggedSqlCollector.stop();
|
||||
assertEquals(2, sqlList.size());
|
||||
assertThat(sqlList.get(0)).contains("from o_customer t0");
|
||||
if (isPostgres()) {
|
||||
assertThat(sqlList.get(1)).contains("from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id where t0.order_date is not null and (t0.kcustomer_id) = any(?)");
|
||||
assertThat(sqlList.get(1)).contains(" and t0.status = any(?)");
|
||||
} else {
|
||||
assertThat(sqlList.get(1)).contains("from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id where t0.order_date is not null and (t0.kcustomer_id) in ");
|
||||
assertThat(sqlList.get(1)).contains(" and t0.status in ");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisjunction() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.filterMany("orders")
|
||||
.or()
|
||||
.eq("status", Order.Status.NEW)
|
||||
.eq("orderDate", LocalDate.now())
|
||||
.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains(" from o_customer t0 left join o_order t1 on t1.kcustomer_id = t0.id and t1.order_date is not null left join o_customer t2 on t2.id = t1.kcustomer_id where (t1.status = ? or t1.order_date = ?) order by t0.id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNestedFilterMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
LoggedSqlCollector.start();
|
||||
DB.find(Customer.class)
|
||||
.filterMany("contacts").isNotNull("firstName")
|
||||
.filterMany("contacts.notes").istartsWith("title", "foo")
|
||||
.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(sql).hasSize(2);
|
||||
assertSql(sql.get(0)).contains(" from o_customer t0 left join contact t1 on t1.customer_id = t0.id where t1.first_name is not null order by t0.id; --bind()");
|
||||
platformAssertIn(sql.get(1), " from contact_note t0 where (t0.contact_id)");
|
||||
assertSql(sql.get(1)).contains(" and lower(t0.title) like");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterManyUsingExpression() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.where()
|
||||
.filterMany("contacts", "firstName isNotNull and email istartsWith ?", "rob")
|
||||
.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(sql).hasSize(1);
|
||||
if (isSqlServer()) {
|
||||
assertSql(sql.get(0)).contains(" from o_customer t0 left join contact t1 on t1.customer_id = t0.id where (t1.first_name is not null and lower(t1.email) like ? ) order by t0.id; --bind(rob%)");
|
||||
} else {
|
||||
assertSql(sql.get(0)).contains(" from o_customer t0 left join contact t1 on t1.customer_id = t0.id where (t1.first_name is not null and lower(t1.email) like ? escape'|' ) order by t0.id; --bind(rob%)");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.MUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestQueryFilterManyOnM2M extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
DB.find(MUser.class).fetch("roles").filterMany("roles").ilike("roleName", "Jim%").findList();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.Product;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryFilterManyOnSecondary extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testFilterManyWithSimplePredicate() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetchQuery("orders")
|
||||
.where().ilike("name", "Rob%").gt("id", 0)
|
||||
.filterMany("orders").eq("status", Order.Status.NEW)
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
for (Customer customer : list) {
|
||||
List<Order> orders = customer.getOrders();
|
||||
for (Order order : orders) {
|
||||
assertEquals(Order.Status.NEW, order.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testFilterManyWithPathPredicate() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetchQuery("details")
|
||||
.fetch("details.product", "name")
|
||||
.filterMany("details").ilike("product.name", "c%")
|
||||
.query();
|
||||
|
||||
List<Order> orders = query.findList();
|
||||
for (Order order : orders) {
|
||||
List<OrderDetail> details = order.getDetails();
|
||||
for (OrderDetail orderDetail : details) {
|
||||
Product product = orderDetail.getProduct();
|
||||
String name = product.getName();
|
||||
assertTrue(name.startsWith("C"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.util.List;
|
||||
|
||||
public class TestQueryFilterManySimple extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// not really last week :)
|
||||
Date lastWeek = Date.valueOf("2010-01-01");
|
||||
|
||||
List<Customer> list = DB.find(Customer.class)
|
||||
// .join("orders", new JoinConfig().lazy())
|
||||
// .join("orders", new JoinConfig().query())
|
||||
.fetch("orders").fetchQuery("contacts").where().ilike("name", "rob%")
|
||||
.filterMany("orders").eq("status", Order.Status.NEW).gt("orderDate", lastWeek)
|
||||
.filterMany("contacts").isNotNull("firstName").findList();
|
||||
|
||||
// invoke lazy loading
|
||||
list.get(0).getOrders().size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.Transaction;
|
||||
import io.ebean.annotation.Transactional;
|
||||
import io.ebean.bean.PersistenceContext;
|
||||
import io.ebeaninternal.api.SpiTransaction;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.EBasicLog;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.o2m.OmBasicChild;
|
||||
import org.tests.o2m.OmBasicParent;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryFindEach extends BaseTestCase {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TestQueryFindEach.class);
|
||||
private final Random random = new Random();
|
||||
private final AtomicInteger batchCount = new AtomicInteger();
|
||||
private final AtomicInteger rowCount = new AtomicInteger();
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetchQuery("contacts")
|
||||
.where().gt("id", 0).order("id")
|
||||
.setMaxRows(2).query();
|
||||
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
query.findEach(customer -> {
|
||||
counter.incrementAndGet();
|
||||
assertNotNull(customer.getName());
|
||||
});
|
||||
|
||||
assertEquals(2, counter.get());
|
||||
}
|
||||
|
||||
private void resetFindEachCounts() {
|
||||
batchCount.set(0);
|
||||
rowCount.set(0);
|
||||
}
|
||||
|
||||
private void seedData() {
|
||||
for (int i = 0; i < 15; i++) {
|
||||
EBasicLog log = new EBasicLog("findEachBatch " + i);
|
||||
DB.save(log);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findEachBatch() {
|
||||
seedData();
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(5);
|
||||
assertThat(batchCount.get()).isEqualTo(3);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(10);
|
||||
assertThat(batchCount.get()).isEqualTo(2);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(14);
|
||||
assertThat(batchCount.get()).isEqualTo(2);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(15);
|
||||
assertThat(batchCount.get()).isEqualTo(1);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(16);
|
||||
assertThat(batchCount.get()).isEqualTo(1);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
|
||||
resetFindEachCounts();
|
||||
findEachWithBatch(20);
|
||||
assertThat(batchCount.get()).isEqualTo(1);
|
||||
assertThat(rowCount.get()).isEqualTo(15);
|
||||
}
|
||||
|
||||
private void findEachWithBatch(int batchSize) {
|
||||
DB.find(EBasicLog.class)
|
||||
.where().startsWith("name", "findEachBatch")
|
||||
.findEach(batchSize, batch -> {
|
||||
int batchId = batchCount.incrementAndGet();
|
||||
int rows = rowCount.addAndGet(batch.size());
|
||||
log.info("batch id:{} size:{} total rows:{}", batchId, batch.size(), rows);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistenceContext_scope() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class);
|
||||
|
||||
try (final Transaction transaction = DB.beginTransaction()) {
|
||||
// effectively loads customers into persistence context
|
||||
final List<Customer> customerList = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.findList();
|
||||
|
||||
SpiTransaction spiTxn = (SpiTransaction) transaction;
|
||||
PersistenceContext pc = spiTxn.getPersistenceContext();
|
||||
assertThat(pc.size(Customer.class)).isEqualTo(customerList.size());
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
query.findEach(contact -> {
|
||||
// use customer from persistence context (otherwise would invoke lazy loading)
|
||||
assertNotNull(contact.getCustomer().getName());
|
||||
});
|
||||
|
||||
final List<String> sql = LoggedSqlCollector.stop();
|
||||
assertThat(sql).hasSize(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the behaviour when an exception is thrown inside the findVisit().
|
||||
*/
|
||||
@Test
|
||||
public void testVisitThrowingException() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetchQuery("contacts")
|
||||
.where().gt("id", 0).order("id")
|
||||
.setMaxRows(2).query();
|
||||
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
query.findEach(customer -> {
|
||||
counter.incrementAndGet();
|
||||
if (counter.intValue() > 0) {
|
||||
throw new IllegalStateException("cause a failure");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void iterateResetLimit() {
|
||||
|
||||
DB.find(OmBasicChild.class).delete();
|
||||
DB.find(OmBasicParent.class).delete();
|
||||
insertData();
|
||||
|
||||
test_setLazyLoadBatchSize_withFetchLazy();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(OmBasicChild.class)
|
||||
.setLazyLoadBatchSize(100)
|
||||
.findEach(child -> {
|
||||
assertNotNull(child.getParent().getName());
|
||||
});
|
||||
|
||||
final List<String> sql = LoggedSqlCollector.stop();
|
||||
assertThat(sql.size()).isLessThan(50);
|
||||
}
|
||||
|
||||
private void test_setLazyLoadBatchSize_withFetchLazy() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(OmBasicParent.class)
|
||||
.setLazyLoadBatchSize(5)
|
||||
.fetchLazy("children")
|
||||
.setMaxRows(50)
|
||||
.findEach(it -> {
|
||||
it.getChildren().size();
|
||||
});
|
||||
|
||||
final List<String> sql = LoggedSqlCollector.stop();
|
||||
assertThat(sql).hasSize(11);
|
||||
assertThat(sql.get(0)).contains(" from om_basic_parent ");
|
||||
for (int i = 1; i < 11; i++) {
|
||||
assertThat(sql.get(i)).contains(" --bind(Array[5]");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(batchSize = 40)
|
||||
private void insertData() {
|
||||
for (int i = 0; i < 150; i++) {
|
||||
insertData2(i);
|
||||
}
|
||||
}
|
||||
|
||||
private void insertData2(int i) {
|
||||
OmBasicParent p = new OmBasicParent("bl_" + i);
|
||||
DB.save(p);
|
||||
|
||||
int children = 20 + random.nextInt(10);
|
||||
for (int j = 0; j < children; j++) {
|
||||
OmBasicChild c = new OmBasicChild("bl_" + i + "_" + j, p);
|
||||
DB.save(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryFindEachWhile extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query
|
||||
= DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
.fetchQuery("contacts").where().gt("id", 0).order("id")
|
||||
.setMaxRows(2).query();
|
||||
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
query.findEachWhile(customer -> {
|
||||
counter.incrementAndGet();
|
||||
assertNotNull(customer.getName());
|
||||
return true;
|
||||
});
|
||||
|
||||
assertEquals(2, counter.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the behaviour when an exception is thrown inside the findVisit().
|
||||
*/
|
||||
@Test
|
||||
public void testVisitThrowingException() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).setAutoTune(false)
|
||||
.fetchQuery("contacts").where().gt("id", 0).order("id")
|
||||
.setMaxRows(2).query();
|
||||
|
||||
final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> {
|
||||
query.findEachWhile(customer -> {
|
||||
counter.incrementAndGet();
|
||||
if (counter.intValue() > 0) {
|
||||
throw new IllegalStateException("cause a failure");
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FutureList;
|
||||
import io.ebean.Transaction;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestQueryFindFutureList extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test_cancel() throws InterruptedException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// warm the connection pool
|
||||
Transaction t0 = DB.createTransaction();
|
||||
Transaction t1 = DB.createTransaction();
|
||||
Transaction t2 = DB.createTransaction();
|
||||
t0.end();
|
||||
t1.end();
|
||||
t2.end();
|
||||
|
||||
FutureList<Order> futureList = DB.find(Order.class).findFutureList();
|
||||
|
||||
Thread.sleep(10);
|
||||
futureList.cancel(true);
|
||||
// calling again is ignored
|
||||
futureList.cancel(true);
|
||||
|
||||
// don't shutdown immediately
|
||||
Thread.sleep(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findFutureList() throws InterruptedException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
FutureList<Order> futureList = DB.find(Order.class).findFutureList();
|
||||
|
||||
// wait for it to complete
|
||||
List<Order> orders = futureList.getUnchecked();
|
||||
|
||||
assertEquals(DB.find(Order.class).findCount(), orders.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findFutureListWithTimeout() throws InterruptedException, TimeoutException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
FutureList<Order> futureList = DB.find(Order.class).findFutureList();
|
||||
|
||||
// wait for it to complete
|
||||
List<Order> orders = futureList.getUnchecked(1, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(DB.find(Order.class).findCount(), orders.size());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.QueryIterator;
|
||||
import io.ebean.annotation.ForPlatform;
|
||||
import io.ebean.annotation.Platform;
|
||||
import io.ebean.datasource.DataSourcePool;
|
||||
import io.ebean.plugin.SpiServer;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderShipment;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryFindIterate extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setMaxRows(2);
|
||||
|
||||
final AtomicInteger count = new AtomicInteger();
|
||||
|
||||
try (QueryIterator<Customer> it = query.findIterate()) {
|
||||
while (it.hasNext()) {
|
||||
Customer customer = it.next();
|
||||
customer.getName();
|
||||
count.incrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(2, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_hasNext_hasNext() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
QueryIterator<Customer> queryIterator = DB.find(Customer.class)
|
||||
.where()
|
||||
.isNotNull("name")
|
||||
.setMaxRows(3)
|
||||
.order().asc("id")
|
||||
.findIterate();
|
||||
|
||||
try {
|
||||
// check that hasNext does not move to the next bean
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertTrue(queryIterator.hasNext());
|
||||
|
||||
Customer first = queryIterator.next();
|
||||
logger.info("first: {}", queryIterator.next());
|
||||
assertEquals(first.getId(), Integer.valueOf(1));
|
||||
|
||||
while (queryIterator.hasNext()) {
|
||||
logger.info("next: {}", queryIterator.next());
|
||||
}
|
||||
|
||||
} finally {
|
||||
queryIterator.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findEach() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
//.fetch("contacts", new FetchConfig().query(2)).where().gt("id", 0).orderBy("id")
|
||||
.setMaxRows(2);
|
||||
|
||||
final AtomicInteger count = new AtomicInteger();
|
||||
|
||||
query.findEach(bean -> count.incrementAndGet());
|
||||
|
||||
assertEquals(2, count.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithLazyLoading() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(Order.class)
|
||||
//.select("orderDate")
|
||||
.where().gt("id", 0).le("id", 10)
|
||||
.findEach(order -> {
|
||||
Customer customer = order.getCustomer();
|
||||
// invoke lazy loading on customer, order details and order shipments
|
||||
order.getId();
|
||||
customer.getName();
|
||||
order.getDetails().size();
|
||||
order.getShipments().size();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithLazyBatchSize() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setLazyLoadBatchSize(10)
|
||||
.select("status, orderDate")
|
||||
.fetch("customer", "name")
|
||||
.where().gt("id", 0).le("id", 10)
|
||||
.setUseCache(false)
|
||||
.findEach(order -> {
|
||||
Customer customer = order.getCustomer();
|
||||
customer.getName();
|
||||
order.getDetails().size();
|
||||
order.getShipments().size();
|
||||
});
|
||||
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(3, loggedSql.size());
|
||||
assertTrue(trimSql(loggedSql.get(0), 7).contains("select t0.id, t0.status, t0.order_date, t1.id, t1.name from o_order t0 join o_customer t1"));
|
||||
assertTrue(trimSql(loggedSql.get(1), 7).contains("select t0.order_id, t0.id, t0.order_qty, t0.ship_qty, t0.unit_price"));
|
||||
assertTrue(trimSql(loggedSql.get(2), 7).contains("select t0.order_id, t0.id, t0.ship_time, t0.cretime, t0.updtime, t0.version, t0.order_id from or_order_ship"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithTwoJoins() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
// make sure we don't hit the L2 cache for order shipments
|
||||
DB.cacheManager().clear(Order.class);
|
||||
DB.cacheManager().clear(OrderShipment.class);
|
||||
|
||||
DB.find(Order.class)
|
||||
.setLazyLoadBatchSize(10)
|
||||
.setUseCache(false)
|
||||
.select("status, orderDate")
|
||||
.fetch("customer", "name")
|
||||
.fetch("details")
|
||||
.where().gt("id", 0).le("id", 10)
|
||||
.order().asc("id")
|
||||
.findEach(order -> {
|
||||
Customer customer = order.getCustomer();
|
||||
order.getId();
|
||||
customer.getName();
|
||||
order.getDetails().size();
|
||||
order.getShipments().size();
|
||||
});
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(2, loggedSql.size());
|
||||
assertThat(trimSql(loggedSql.get(0), 7).contains("select t0.id, t0.status, t0.order_date, t1.id, t1.name, t2.id, t2.order_qty, t2.ship_qty"));
|
||||
assertThat(trimSql(loggedSql.get(1), 7).contains("select t0.order_id, t0.id, t0.ship_time, t0.cretime, t0.updtime, t0.version, t0.order_id from or_order_ship"));
|
||||
}
|
||||
|
||||
@ForPlatform(Platform.H2)
|
||||
@Test
|
||||
public void testWithExceptionInQuery() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
// intentionally a query with incorrect type binding
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
.where().gt("id", "JUNK_NOT_A_LONG")
|
||||
.setMaxRows(2).query();
|
||||
|
||||
// this throws an exception immediately
|
||||
assertThrows(PersistenceException.class, () -> query.findEach(bean -> { }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithExceptionInLoop() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setAutoTune(false)
|
||||
.where().gt("id", 0)
|
||||
.setMaxRows(2).query();
|
||||
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
query.findEach(customer -> {
|
||||
if (customer != null) {
|
||||
throw new IllegalStateException("cause an exception");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseConnection_findIterate() {
|
||||
findIterateCloseConnection(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseConnection_findIterate_withBatchLoad() {
|
||||
findIterateCloseConnection(true);
|
||||
}
|
||||
|
||||
public void findIterateCloseConnection(boolean withLoadBatch) {
|
||||
ResetBasicData.reset();
|
||||
|
||||
SpiServer pluginApi = server().pluginApi();
|
||||
DataSourcePool dsPool = (DataSourcePool) pluginApi.config().getReadOnlyDataSource();
|
||||
if (dsPool == null) {
|
||||
dsPool = (DataSourcePool) server().dataSource();
|
||||
}
|
||||
|
||||
int startConns = dsPool.getStatus(false).getBusy();
|
||||
final Query<Customer> query = server().find(Customer.class)
|
||||
.where()
|
||||
.isNotNull("name")
|
||||
.setMaxRows(3)
|
||||
.order().asc("id");
|
||||
|
||||
if (withLoadBatch) {
|
||||
query.setLazyLoadBatchSize(1);
|
||||
}
|
||||
|
||||
QueryIterator<Customer> queryIterator = query.findIterate();
|
||||
|
||||
assertThat(dsPool.getStatus(false).getBusy()).isEqualTo(startConns + 1);
|
||||
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertThat(queryIterator.next()).isNotNull();
|
||||
assertThat(dsPool.getStatus(false).getBusy()).isEqualTo(startConns + 1);
|
||||
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertThat(queryIterator.next()).isNotNull();
|
||||
assertThat(dsPool.getStatus(false).getBusy()).isEqualTo(startConns + 1);
|
||||
|
||||
assertTrue(queryIterator.hasNext());
|
||||
assertThat(queryIterator.next()).isNotNull();
|
||||
assertThat(dsPool.getStatus(false).getBusy()).isEqualTo(startConns + 1);
|
||||
|
||||
assertFalse(queryIterator.hasNext());
|
||||
assertThat(dsPool.getStatus(false).getBusy()).isEqualTo(startConns);
|
||||
try {
|
||||
queryIterator.next();
|
||||
fail("noSuchElementException expected");
|
||||
} catch (NoSuchElementException e) {
|
||||
logger.debug("Expected NoSuchElementException");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.Product;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestQueryFindMapTypedKey extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Map<String, Product> productsBySku = DB.find(Product.class)
|
||||
.setMapKey("sku")
|
||||
.findMap();
|
||||
|
||||
assertThat(productsBySku).isNotEmpty();
|
||||
|
||||
Product desk = productsBySku.get("DSK1");
|
||||
assertNotNull(desk);
|
||||
|
||||
Map<String, Customer> map = DB.find(Customer.class)
|
||||
.select("id, name")
|
||||
.setMapKey("name")
|
||||
.findMap();
|
||||
|
||||
assertNotNull(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_manyToOneId() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Map<Object, Order> orderMap = DB.find(Order.class)
|
||||
.where().eq("status", Order.Status.NEW)
|
||||
.setMapKey("customer.id")
|
||||
.findMap();
|
||||
|
||||
assertThat(orderMap).isNotEmpty();
|
||||
assertThat(orderMap.keySet()).contains(1, 2);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import io.ebean.PagedList;
|
||||
import org.assertj.core.util.Lists;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryFindNative extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test_in_bindCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
String sql = "select id,first_name from contact where id in(:ids)";
|
||||
DB.findNative(Contact.class, sql).setParameter("ids", Lists.newArrayList(1, 2, 3)).findList();
|
||||
DB.findNative(Contact.class, sql).setParameter("ids", Lists.newArrayList(1, 2)).findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains("(?,?,?)");
|
||||
assertThat(loggedSql.get(1)).contains("(?,?)");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
String sql = "select n.id from contact n where n.first_name like ?";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
int rowCount = server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter("J%")
|
||||
.findCount();
|
||||
|
||||
List<Integer> nativeIds =
|
||||
server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter(1, "J%")
|
||||
.findIds();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(nativeIds).hasSize(rowCount);
|
||||
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
assertThat(loggedSql.get(0)).contains("select count(*) from ( select n.id from contact n where n.first_name like ?)");
|
||||
assertThat(loggedSql.get(1)).startsWith("select n.id from contact n where n.first_name like ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findPagedList() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
String sql = "select n.id, n.first_name from contact n where n.first_name like ?";
|
||||
|
||||
PagedList<Contact> pagedList = server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter("J%")
|
||||
.setMaxRows(100)
|
||||
.findPagedList();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
int listSize = pagedList.getList().size();
|
||||
int totalCount = pagedList.getTotalCount();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(listSize).isEqualTo(totalCount);
|
||||
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
assertThat(loggedSql.get(0)).startsWith("select n.id, n.first_name from contact n where n.first_name like ?");
|
||||
assertThat(loggedSql.get(1)).contains("select count(*) from ( select n.id, n.first_name from contact n where n.first_name like ?)");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void findPagedList_withColumnAlias() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
String sql = "select n.id, 'SillyName' first_name from contact n where n.id < ? ";
|
||||
|
||||
PagedList<Contact> pagedList = server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter(100)
|
||||
.setMaxRows(100)
|
||||
.findPagedList();
|
||||
|
||||
int listSize = pagedList.getList().size();
|
||||
int totalCount = pagedList.getTotalCount();
|
||||
|
||||
assertThat(listSize).isEqualTo(totalCount);
|
||||
|
||||
for (Contact contact : pagedList.getList()) {
|
||||
assertThat(contact.getFirstName()).isEqualTo("SillyName");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void findIds() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select c.id from contact c where c.first_name like ? ";
|
||||
|
||||
List<Integer> ids = DB.sqlQuery(sql)
|
||||
.setParameter(1, "J%")
|
||||
.mapToScalar(Integer.class).findList();
|
||||
|
||||
List<Integer> idsScalar =
|
||||
server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter(1, "J%")
|
||||
.findSingleAttributeList();
|
||||
|
||||
List<Integer> nativeIds =
|
||||
server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter(1, "J%")
|
||||
.findIds();
|
||||
|
||||
|
||||
assertThat(nativeIds).isNotEmpty();
|
||||
assertThat(nativeIds).containsAll(ids);
|
||||
assertThat(idsScalar).containsAll(ids);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void joinFromManyToOne() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql =
|
||||
"select c.id, c.first_name, c.last_name, t.id, t.name " +
|
||||
" from contact c " +
|
||||
" join o_customer t on t.id = c.customer_id " +
|
||||
" where t.name like ? " +
|
||||
" order by c.first_name, c.last_name";
|
||||
|
||||
List<Contact> contacts =
|
||||
server()
|
||||
.findNative(Contact.class, sql)
|
||||
.setParameter("Rob")
|
||||
.findList();
|
||||
|
||||
|
||||
assertThat(contacts).isNotEmpty();
|
||||
|
||||
Customer customer = contacts.get(0).getCustomer();
|
||||
assertThat(customer).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void joinFromOneToMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql =
|
||||
"select cu.id, cu.name, ct.id, ct.first_name " +
|
||||
" from o_customer cu " +
|
||||
" left join contact ct on cu.id = ct.customer_id " +
|
||||
" where cu.name like ? " +
|
||||
" order by name";
|
||||
|
||||
List<Customer> customers =
|
||||
server()
|
||||
.findNative(Customer.class, sql)
|
||||
.setParameter(1, "Rob")
|
||||
.findList();
|
||||
|
||||
assertThat(customers).isNotEmpty();
|
||||
|
||||
List<Contact> contacts = customers.get(0).getContacts();
|
||||
assertThat(contacts).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bind_positionedParams_InSelect() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select id, name, " +
|
||||
"case when anniversary >= ? then 1 when anniversary < ? then 2 end as order_column_1 " +
|
||||
"from o_customer " +
|
||||
"order by order_column_1";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
.setParameter(LocalDate.now())
|
||||
.setParameter(LocalDate.now())
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(10)
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer order by order_column_1 limit 10 offset 1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bind_namedParams_InSelect() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select id, name, " +
|
||||
"case when anniversary >= :date then 1 when anniversary < :date then 2 end as order_column_1 " +
|
||||
"from o_customer " +
|
||||
"order by order_column_1";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
.setParameter("date", LocalDate.now())
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(10)
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer order by order_column_1 limit 10 offset 1");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void findNativeWithOneFetchQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select * from o_customer";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
.fetchQuery("contacts")
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer");
|
||||
assertThat(loggedSql.get(1)).contains("from contact");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNativeWithOneFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select * from o_customer";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
.fetch("contacts", "firstName, lastName")
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer");
|
||||
assertThat(loggedSql.get(1)).contains("select t0.customer_id, t0.id, t0.first_name, t0.last_name from contact t0 where");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNativeWithMultipleFetchQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select * from o_customer";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
.fetchQuery("orders")
|
||||
.fetchQuery("contacts")
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql).hasSize(3);
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer");
|
||||
assertThat(loggedSql).anyMatch(s -> s.contains("from o_order"));
|
||||
assertThat(loggedSql).anyMatch(s -> s.contains("from contact"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNativeWithMultipleFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select * from o_customer";
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> result = DB.findNative(Customer.class, sql)
|
||||
// with nativeSql fetch (default) are converted to fetchQuery()
|
||||
.fetch("orders")
|
||||
.fetch("contacts", FetchConfig.ofDefault())
|
||||
.findList();
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
if (isH2()) {
|
||||
assertThat(loggedSql).hasSize(3);
|
||||
assertThat(loggedSql.get(0)).contains("from o_customer");
|
||||
assertThat(loggedSql).anyMatch(s -> s.contains("from o_order"));
|
||||
assertThat(loggedSql).anyMatch(s -> s.contains("from contact"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.PagedList;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryFindPagedList extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void empty() {
|
||||
PagedList<Customer> empty = PagedList.emptyList();
|
||||
|
||||
assertThat(empty.getList()).isEmpty();
|
||||
assertThat(empty.getTotalPageCount()).isEqualTo(0);
|
||||
assertThat(empty.getTotalCount()).isEqualTo(0);
|
||||
assertThat(empty.getPageIndex()).isEqualTo(0);
|
||||
assertThat(empty.getPageSize()).isEqualTo(0);
|
||||
assertThat(empty.hasNext()).isFalse();
|
||||
assertThat(empty.hasPrev()).isFalse();
|
||||
assertThat(empty.getDisplayXtoYofZ("a", "b")).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_noMaxRows() {
|
||||
assertThrows(PersistenceException.class, () ->
|
||||
DB.find(Order.class).findPagedList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_maxRows_NoCount() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class)
|
||||
.setMaxRows(4)
|
||||
.findPagedList();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Order> orders = pagedList.getList();
|
||||
|
||||
assertTrue(!orders.isEmpty());
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(1, loggedSql.size());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_maxRows_countInBackground() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class)
|
||||
.setMaxRows(3)
|
||||
.findPagedList();
|
||||
|
||||
Future<Integer> rowCount = pagedList.getFutureCount();
|
||||
List<Order> orders = pagedList.getList();
|
||||
|
||||
// these are each getting the total row count
|
||||
int totalRowCount = pagedList.getTotalCount();
|
||||
Integer totalRowCountWithTimeout = rowCount.get(30, TimeUnit.SECONDS);
|
||||
Integer totalRowCountViaFuture = rowCount.get();
|
||||
|
||||
assertTrue(orders.size() < totalRowCount);
|
||||
assertEquals(Integer.valueOf(totalRowCount), totalRowCountViaFuture);
|
||||
assertEquals(Integer.valueOf(totalRowCount), totalRowCountWithTimeout);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_maxRows_countInBackground_withLoadRowCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// fetch less that total orders (page size 3)
|
||||
PagedList<Order> pagedList = DB.find(Order.class)
|
||||
.setMaxRows(3)
|
||||
.findPagedList();
|
||||
|
||||
pagedList.loadCount();
|
||||
List<Order> orders = pagedList.getList();
|
||||
int totalRowCount = pagedList.getTotalCount();
|
||||
|
||||
assertThat(orders.size()).isLessThan(totalRowCount);
|
||||
assertTrue(pagedList.hasNext());
|
||||
assertFalse(pagedList.hasPrev());
|
||||
|
||||
|
||||
// fetch less that total orders (page size 3)
|
||||
PagedList<Order> pagedList2 = DB.find(Order.class)
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(3)
|
||||
.order("id")
|
||||
.findPagedList();
|
||||
|
||||
pagedList2.loadCount();
|
||||
List<Order> orders2 = pagedList2.getList();
|
||||
int totalRowCount2 = pagedList2.getTotalCount();
|
||||
assertTrue(pagedList2.hasNext());
|
||||
assertTrue(pagedList2.hasPrev());
|
||||
|
||||
assertThat(totalRowCount).isEqualTo(totalRowCount2);
|
||||
assertThat(orders2.size()).isLessThan(totalRowCount);
|
||||
|
||||
|
||||
PagedList<Order> pagedList3 = DB.find(Order.class)
|
||||
.setFirstRow(2)
|
||||
.setMaxRows(150)
|
||||
.order("id")
|
||||
.findPagedList();
|
||||
|
||||
assertFalse(pagedList3.hasNext());
|
||||
assertTrue(pagedList3.hasPrev());
|
||||
|
||||
List<Order> list3 = pagedList3.getList();
|
||||
String xtoYofZ = pagedList3.getDisplayXtoYofZ(" to ", " of ");
|
||||
assertThat(xtoYofZ).isEqualTo("3 to " + totalRowCount + " of " + totalRowCount);
|
||||
assertThat(list3.size()).isEqualTo(totalRowCount - 2);
|
||||
|
||||
PagedList<Order> pagedList4 = DB.find(Order.class)
|
||||
.setFirstRow(0)
|
||||
.setMaxRows(totalRowCount)
|
||||
.findPagedList();
|
||||
|
||||
assertFalse(pagedList4.hasNext());
|
||||
assertFalse(pagedList4.hasPrev());
|
||||
assertThat(pagedList4.getDisplayXtoYofZ(" to ", " of ")).isEqualTo("1 to " + totalRowCount + " of " + totalRowCount);
|
||||
|
||||
PagedList<Order> pagedList5 = DB.find(Order.class)
|
||||
.setFirstRow(0)
|
||||
.setMaxRows(totalRowCount - 1)
|
||||
.findPagedList();
|
||||
|
||||
assertTrue(pagedList5.hasNext());
|
||||
assertFalse(pagedList5.hasPrev());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_noCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class).setMaxRows(4).findPagedList();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Order> orders = pagedList.getList();
|
||||
|
||||
assertTrue(!orders.isEmpty());
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(1, loggedSql.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_countInBackground() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class).setMaxRows(3).findPagedList();
|
||||
|
||||
Future<Integer> rowCount = pagedList.getFutureCount();
|
||||
List<Order> orders = pagedList.getList();
|
||||
|
||||
// these are each getting the total row count
|
||||
int totalRowCount = pagedList.getTotalCount();
|
||||
Integer totalRowCountWithTimeout = rowCount.get(30, TimeUnit.SECONDS);
|
||||
Integer totalRowCountViaFuture = rowCount.get();
|
||||
|
||||
assertTrue(orders.size() < totalRowCount);
|
||||
assertEquals(Integer.valueOf(totalRowCount), totalRowCountViaFuture);
|
||||
assertEquals(Integer.valueOf(totalRowCount), totalRowCountWithTimeout);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_countInBackground_withLoadRowCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// fetch less that total orders (page size 3)
|
||||
PagedList<Order> pagedList = DB.find(Order.class).setMaxRows(3).findPagedList();
|
||||
|
||||
pagedList.loadCount();
|
||||
List<Order> orders = pagedList.getList();
|
||||
int totalRowCount = pagedList.getTotalCount();
|
||||
|
||||
assertThat(orders.size()).isLessThan(totalRowCount);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_countUsingForegound() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class).setMaxRows(3).findPagedList();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
// kinda not normal but just wrap in a transaction to assert
|
||||
// the background fetch does not occur (which explicitly creates
|
||||
// its own transaction) ... so a bit naughty with the test here
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
|
||||
List<Order> orders = pagedList.getList();
|
||||
int totalRowCount = pagedList.getTotalCount();
|
||||
|
||||
// invoke it again but cached...
|
||||
int totalRowCountAgain = pagedList.getTotalCount();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertTrue(orders.size() < totalRowCount);
|
||||
assertEquals(2, loggedSql.size());
|
||||
assertEquals(totalRowCount, totalRowCountAgain);
|
||||
|
||||
String firstTxn = loggedSql.get(0).substring(0, 10);
|
||||
String secTxn = loggedSql.get(1).substring(0, 10);
|
||||
|
||||
assertEquals(firstTxn, secTxn);
|
||||
|
||||
} finally {
|
||||
DB.endTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_usingAlias() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
PagedList<Order> pagedList = DB.find(Order.class)
|
||||
.alias("b")
|
||||
.where().raw("b.id > 0")
|
||||
.setMaxRows(6)
|
||||
.findPagedList();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
pagedList.getTotalCount();
|
||||
pagedList.getList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(2, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains("select count(*) from o_order b where b.id > 0");
|
||||
assertThat(trimSql(loggedSql.get(1), 3)).contains(" b.id, b.status, b.order_date");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.CacheMode;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Article;
|
||||
import org.tests.model.basic.Section;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryFindReadOnly extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
Section s0 = new Section("some content");
|
||||
Article a0 = new Article("art1", "auth1");
|
||||
a0.addSection(s0);
|
||||
|
||||
DB.save(a0);
|
||||
|
||||
Article ar1 = DB.find(Article.class).setReadOnly(true).setId(a0.getId()).findOne();
|
||||
|
||||
assertNotNull(ar1);
|
||||
assertTrue(DB.beanState(ar1).isReadOnly());
|
||||
|
||||
List<Section> ar1sections = ar1.getSections();
|
||||
assertEquals(1, ar1sections.size());
|
||||
|
||||
Section s2 = ar1sections.get(0);
|
||||
assertTrue(DB.beanState(s2).isReadOnly());
|
||||
|
||||
DB.find(Article.class).setBeanCacheMode(CacheMode.PUT).findList();
|
||||
|
||||
Article ar0 = DB.find(Article.class, a0.getId());
|
||||
|
||||
assertNotNull(ar0);
|
||||
assertFalse(DB.beanState(ar0).isReadOnly());
|
||||
|
||||
List<Section> ar0sections = ar0.getSections();
|
||||
Section s1 = ar0sections.get(0);
|
||||
assertFalse(DB.beanState(s1).isReadOnly());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryFindStream extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void findStream_basic() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
try (Stream<Customer> stream = DB.find(Customer.class)
|
||||
.findStream()) {
|
||||
|
||||
// bad example, don't use a stream like this when we can
|
||||
// use findSingleAttributeList() instead
|
||||
final List<String> namesStream = stream
|
||||
.map(Customer::getName)
|
||||
.collect(toList());
|
||||
|
||||
final List<String> namesQuery = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(namesStream).hasSize(namesQuery.size());
|
||||
assertThat(namesStream).containsAll(namesQuery);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findLargeStream_basic() {
|
||||
ResetBasicData.reset();
|
||||
try (Stream<Customer> stream = DB.find(Customer.class)
|
||||
.findLargeStream()) {
|
||||
|
||||
// bad example, don't use a stream like this when we can
|
||||
// use findSingleAttributeList() instead
|
||||
final List<String> namesStream = stream
|
||||
.map(Customer::getName)
|
||||
.collect(toList());
|
||||
|
||||
final List<String> namesQuery = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(namesStream).hasSize(namesQuery.size());
|
||||
assertThat(namesStream).containsAll(namesQuery);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void manualTest_findSteam_when_closeWithResources() {
|
||||
// confirm manually the stream is closed via try with resources block
|
||||
try (Stream<Customer> stream = DB.find(Customer.class).findStream()) {
|
||||
// silly assert
|
||||
assertThat(stream.hashCode()).isNotZero();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void manualTest_findSteam_when_streamNotClosed_connectionLeak() {
|
||||
Stream<Customer> stream = DB.find(Customer.class).findStream();
|
||||
// remember a steam MUST be closed or we leak resources
|
||||
// comment out the close(); below to leak a connection
|
||||
stream.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryInAssocOne extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).where().lt("id", 200).findList();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().in("customer", list).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("join o_customer t1 on t1.id = t0.kcustomer_id");
|
||||
platformAssertIn(sql, "where t0.kcustomer_id");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_isIn() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).where().lt("id", 300).findList();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isIn("customer", list).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("join o_customer t1 on t1.id = t0.kcustomer_id");
|
||||
platformAssertIn(sql, "t0.kcustomer_id");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_notIn() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).where().lt("id", 200).findList();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().notIn("customer", list).query();
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertThat(sql).contains("join o_customer t1 on t1.id = t0.kcustomer_id");
|
||||
platformAssertNotIn(sql, "t0.kcustomer_id");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryInIdTypeConversion extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).where().idIn("1", "2").findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_emptyList() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).where().idIn().findList();
|
||||
assertThat(list).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_emptyList_idIn() {
|
||||
List<Customer> list = DB.find(Customer.class).where().idIn(new Object[] {}).findList();
|
||||
assertThat(list).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.model.m2m.Role;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryIsNull extends BaseTestCase {
|
||||
|
||||
|
||||
@Test
|
||||
public void queryShouldContainIsNullOnColumn() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isNull("customerName").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("name is null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotNull_when_OneToMany_expect_existsSubquery() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isNotNull("details").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains(" where exists (select 1 from o_order_detail x where x.order_id = t0.id and x.id > 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEmpty_when_OneToMany_expect_existsSubquery() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isNotEmpty("details").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains(" where exists (select 1 from o_order_detail x where x.order_id = t0.id and x.id > 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNull_when_OneToMany_expect_notExistsSubquery() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isNull("details").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains(" where not exists (select 1 from o_order_detail x where x.order_id = t0.id and x.id > 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEmpty_when_OneToMany_expect_notExistsSubquery() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().isEmpty("details").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains(" where not exists (select 1 from o_order_detail x where x.order_id = t0.id and x.id > 0)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isEmpty_when_ManyToMany_expect_notExistsSubqueryAndNoJoin() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Role> query = DB.find(Role.class).where().isEmpty("permissions").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from mt_role t0 where not exists (select 1 from mt_role_permission x where x.mt_role_id = t0.id)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNull_when_ManyToMany_expect_notExistsSubqueryAndNoJoin() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Role> query = DB.find(Role.class).where().isNull("permissions").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from mt_role t0 where not exists (select 1 from mt_role_permission x where x.mt_role_id = t0.id)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotEmpty_when_ManyToMany_expect_existsSubqueryAndNoJoin() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Role> query = DB.find(Role.class).where().isNotEmpty("permissions").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from mt_role t0 where exists (select 1 from mt_role_permission x where x.mt_role_id = t0.id)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isNotNull_when_ManyToMany_expect_existsSubqueryAndNoJoin() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Role> query = DB.find(Role.class).where().isNotNull("permissions").query();
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from mt_role t0 where exists (select 1 from mt_role_permission x where x.mt_role_id = t0.id)");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestQueryJoinBatchSize extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class)
|
||||
.fetch("customer")
|
||||
//.fetch("orders.details", new FetchConfig().query())
|
||||
//.fetch("orders.shipments", new FetchConfig().query())
|
||||
.findList();
|
||||
|
||||
for (Order order : list) {
|
||||
Customer customer = order.getCustomer();
|
||||
customer.getName();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void test() {
|
||||
//
|
||||
// ResetBasicData.reset();
|
||||
//
|
||||
// DB.find(Customer.class)
|
||||
// .fetch("orders", new FetchConfig().query(3).lazy(2))
|
||||
// //.fetch("orders.details", new FetchConfig().query())
|
||||
// //.fetch("orders.shipments", new FetchConfig().query())
|
||||
// .findList();
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestQueryJoinMulipleMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class).fetch("customer").fetch("customer.contacts").where()
|
||||
.gt("id", 0).findList();
|
||||
|
||||
assertNotNull(list);
|
||||
|
||||
for (Order order : list) {
|
||||
List<Contact> contacts = order.getCustomer().getContacts();
|
||||
contacts.size();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryMultiManyOrder extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q = DB.find(Order.class).fetch("shipments").fetch("details")
|
||||
.fetch("details.product").fetch("customer").where().gt("id", 0).query();
|
||||
|
||||
List<Order> list = q.findList();
|
||||
String sql = q.getGeneratedSql();
|
||||
|
||||
assertTrue(!list.isEmpty());
|
||||
assertTrue(sql.contains("join o_customer "));
|
||||
|
||||
assertFalse(sql.contains("left join contact "));
|
||||
assertFalse(sql.contains("left join o_order_detail "));
|
||||
assertFalse(sql.contains("left join o_product "));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryNullAssocOne extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q0 = DB.find(Order.class).where().eq("customer", null).query();
|
||||
|
||||
List<Order> orders = q0.findList();
|
||||
assertNotNull(orders);
|
||||
assertTrue(q0.getGeneratedSql().contains("where t0.kcustomer_id is null"));
|
||||
|
||||
Query<Order> q1 = DB.find(Order.class).where().eq("customer.id", null).query();
|
||||
|
||||
List<Order> o1 = q1.findList();
|
||||
assertTrue(o1.size() == orders.size());
|
||||
assertTrue(q1.getGeneratedSql().contains("where t0.kcustomer_id is null"));
|
||||
|
||||
Query<Order> q2 = DB.find(Order.class).where().isNull("customer").query();
|
||||
|
||||
List<Order> o2 = q2.findList();
|
||||
assertTrue(o2.size() == orders.size());
|
||||
assertTrue(q2.getGeneratedSql().contains("where t0.kcustomer_id is null"));
|
||||
|
||||
Query<Order> q3 = DB.find(Order.class).where().isNull("customer").query();
|
||||
|
||||
List<Order> o3 = q3.findList();
|
||||
assertTrue(o3.size() == orders.size());
|
||||
assertTrue(q3.getGeneratedSql().contains("where t0.kcustomer_id is null"));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryOrderById extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void orderById_default_expectNotOrderById() {
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id,name")
|
||||
.order("id")
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(5);
|
||||
|
||||
query.findList();
|
||||
if (isSqlServer()) {
|
||||
assertSql(query).isEqualTo("select t0.id, t0.name from o_customer t0 order by t0.id offset 1 rows fetch next 5 rows only");
|
||||
} else if (!isOracle()) {
|
||||
assertSql(query).isEqualTo("select t0.id, t0.name from o_customer t0 order by t0.id limit 5 offset 1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderById_whenTrue_expectOrderById() {
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id,name")
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(5)
|
||||
.orderById(true);
|
||||
|
||||
query.findList();
|
||||
if (isSqlServer()) {
|
||||
assertSql(query).isEqualTo("select t0.id, t0.name from o_customer t0 order by t0.id offset 1 rows fetch next 5 rows only");
|
||||
} else if (!isOracle()) {
|
||||
assertSql(query).isEqualTo("select t0.id, t0.name from o_customer t0 order by t0.id limit 5 offset 1");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestQueryPathJoinAndOrder extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class).select("id,name, status").fetch("contacts")
|
||||
.order().asc("id").order().desc("contacts.firstName").setMaxRows(3).findList();
|
||||
|
||||
assertNotNull(list);
|
||||
|
||||
// can't really assert that the contacts are batch loaded
|
||||
// via a secondary query join
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
public class TestQueryPlanCacheRowCount extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).where().eq("status", Order.Status.NEW).ge("id", 1)
|
||||
.order().desc("id");
|
||||
|
||||
int rc0 = query.findCount();
|
||||
|
||||
List<Integer> ids = query.findIds();
|
||||
assertEquals(rc0, ids.size());
|
||||
|
||||
List<Order> list0 = query.findList();
|
||||
assertEquals(rc0, list0.size());
|
||||
|
||||
int rc1 = query.findCount();
|
||||
assertEquals(rc0, rc1);
|
||||
|
||||
List<Integer> ids1 = query.findIds();
|
||||
assertEquals(rc0, ids1.size());
|
||||
|
||||
List<Order> list1 = query.findList();
|
||||
assertEquals(rc0, list1.size());
|
||||
|
||||
int idGt = 5;
|
||||
if (!ids1.isEmpty()) {
|
||||
Object id = ids.get(0);
|
||||
idGt = Integer.valueOf("" + id);
|
||||
}
|
||||
|
||||
// should still hit query plan cache
|
||||
Query<Order> query2 = DB.find(Order.class).where().eq("status", Order.Status.NEW)
|
||||
.ge("id", idGt).order().desc("id");
|
||||
|
||||
int rc2 = query2.findCount();
|
||||
|
||||
System.out.println("Expection Not same " + rc0 + " != " + rc2);
|
||||
assertNotSame(rc0, rc2);
|
||||
|
||||
List<Integer> ids2 = query2.findIds();
|
||||
assertEquals(rc2, ids2.size());
|
||||
|
||||
List<Order> list2 = query2.findList();
|
||||
assertEquals(rc2, list2.size());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestRefToLazyLoadMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> custList = DB.find(Customer.class).select("id").findList();
|
||||
|
||||
Customer c = custList.get(0);
|
||||
|
||||
List<Contact> contacts2 = c.getContacts();
|
||||
assertEquals(3, DB.beanState(c).loadedProps().size());
|
||||
|
||||
// now lazy load the contacts
|
||||
contacts2.size();
|
||||
|
||||
Customer c2 = DB.reference(Customer.class, c.getId());
|
||||
|
||||
// we only "loaded" the contacts BeanList and not all of c2
|
||||
List<Contact> contacts = c2.getContacts();
|
||||
// Set<String> loadedProps = DB.beanState(c2).getLoadedProps();
|
||||
// assertEquals(1, loadedProps.size());
|
||||
|
||||
// now lazy load the contacts
|
||||
contacts.size();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestRowCount extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetch("details")
|
||||
.where()
|
||||
.gt("id", 1)
|
||||
.gt("details.id", 1)
|
||||
.order("id desc").query();
|
||||
|
||||
int rc = query.findCount();
|
||||
|
||||
List<Object> ids = query.findIds();
|
||||
|
||||
List<Order> list = query.findList();
|
||||
System.out.println(list);
|
||||
for (Order order : list) {
|
||||
order.getStatus();
|
||||
}
|
||||
|
||||
assertEquals(rc, ids.size());
|
||||
assertEquals(rc, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void find_count_distinct_singleProperty() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("anniversary")
|
||||
.where().eq("status", Customer.Status.NEW)
|
||||
.query();
|
||||
|
||||
int count = query.findCount();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select count(distinct t0.anniversary) from o_customer t0 where t0.status = ?");
|
||||
assertThat(count).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void find_count_distinct_multipleProperties() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("anniversary, status");
|
||||
|
||||
int count = query.findCount();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select count(*) from ( select distinct t0.anniversary, t0.status from o_customer t0)");
|
||||
assertThat(count).isGreaterThan(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestSubQuery extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testId() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Integer> productIds = new ArrayList<>();
|
||||
productIds.add(3);
|
||||
productIds.add(4);
|
||||
productIds.add(5);
|
||||
|
||||
Query<Order> sq = DB.find(Order.class).select("id").where()
|
||||
.in("details.product.id", productIds).query();
|
||||
|
||||
DB.find(Order.class).where().in("id", sq).findList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_IsIn() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Integer> productIds = new ArrayList<>();
|
||||
productIds.add(3);
|
||||
|
||||
Query<Order> sq = DB.createQuery(Order.class).select("id").where()
|
||||
.isIn("details.product.id", productIds).query();
|
||||
|
||||
assertThat(DB.find(Order.class).where().isIn("id", sq).findList()).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_IsInNoWhere() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> sq = DB.createQuery(Order.class).select("id");
|
||||
int expectedSize = DB.find(Order.class).findCount(); // expect everything
|
||||
|
||||
assertThat(DB.find(Order.class).where().isIn("id", sq).findList()).hasSize(expectedSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Testcase, that discovered, that DefaultOrmQuery.setDefaultSelectClause is set on subQueries with fetch path.
|
||||
* Also checks, that SqlTreeBuilder does not read id on Many2One props.
|
||||
*/
|
||||
@Test
|
||||
public void test_IsInWithFetchSubQuery1() {
|
||||
|
||||
List<Integer> productIds = new ArrayList<>();
|
||||
productIds.add(3);
|
||||
|
||||
Query<OrderDetail> sq = DB.createQuery(OrderDetail.class).fetch("order", "id").where()
|
||||
.isIn("product.id", productIds).query();
|
||||
|
||||
// execute the subQuery as copy (generatedSQL must be part of original query)
|
||||
Query<OrderDetail> debugSq = sq.copy();
|
||||
debugSq.findSingleAttribute();
|
||||
if (isPostgres()) {
|
||||
assertThat(debugSq.getGeneratedSql()).isEqualTo("select t1.id from o_order_detail t0 join o_order t1 on t1.id = t0.order_id where t0.product_id = any(?)");
|
||||
} else {
|
||||
assertThat(debugSq.getGeneratedSql()).isEqualTo("select t1.id from o_order_detail t0 join o_order t1 on t1.id = t0.order_id where t0.product_id in (?)");
|
||||
}
|
||||
|
||||
Query<Order> query = DB.find(Order.class).select("shipDate").where().isIn("id", sq).query();
|
||||
query.findSingleAttribute();
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(query.getGeneratedSql()).isEqualTo("select t0.ship_date from o_order t0 where (t0.id) in (" + debugSq.getGeneratedSql() + ")");
|
||||
} else {
|
||||
assertThat(query.getGeneratedSql()).isEqualTo("select t0.ship_date from o_order t0 where (t0.id) in (" + debugSq.getGeneratedSql() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test checks, that DefaultOrmQuery.markQueryJoins handles subQuery correct.
|
||||
*/
|
||||
@Test
|
||||
public void test_IsInWithFetchSubQuery2() {
|
||||
|
||||
Query<OrderDetail> sq = DB.createQuery(OrderDetail.class).fetch("order.customer", "anniversary").where()
|
||||
.eq("order.customer.name", "Roland")
|
||||
.query().setDistinct(true);
|
||||
|
||||
// execute the subQuery as copy (generatedSQL must be part of original query)
|
||||
Query<OrderDetail> debugSq = sq.copy();
|
||||
debugSq.findSingleAttribute();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).select("status").where().isIn("shipDate", sq).query();
|
||||
query.findSingleAttribute();
|
||||
assertThat(query.getGeneratedSql())
|
||||
.isEqualTo("select t0.status from o_order t0 where (t0.ship_date) in (" + debugSq.getGeneratedSql() + ")");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks, that SqlTreeBuilder does not read id on One2Many props.
|
||||
*/
|
||||
@Test
|
||||
public void test_IsInWithFetchSubQuery3() {
|
||||
|
||||
List<Integer> productIds = new ArrayList<>();
|
||||
productIds.add(3);
|
||||
|
||||
Query<OrderDetail> sq = DB.createQuery(OrderDetail.class).fetch("order.shipments", "id").where()
|
||||
.isIn("product.id", productIds).query();
|
||||
|
||||
// execute the subQuery as copy (generatedSQL must be part of original query)
|
||||
Query<OrderDetail> debugSq = sq.copy();
|
||||
debugSq.findSingleAttribute();
|
||||
assertThat(debugSq.getGeneratedSql()).contains("select t2.id from o_order_detail t0 join o_order t1 on t1.id = t0.order_id left join or_order_ship t2");
|
||||
|
||||
Query<OrderShipment> query = DB.find(OrderShipment.class).select("shipTime").where().isIn("id", sq).query();
|
||||
query.findSingleAttribute();
|
||||
|
||||
assertThat(query.getGeneratedSql())
|
||||
.isEqualTo("select t0.ship_time from or_order_ship t0 where (t0.id) in (" + debugSq.getGeneratedSql() + ")");
|
||||
}
|
||||
|
||||
public void testCompositeKey() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<CKeyParent> sq = DB.createQuery(CKeyParent.class).select("id.oneKey")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<CKeyParent> pq = DB.find(CKeyParent.class).where().in("id.oneKey", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
String golden = "(t0.one_key) in (select t0.one_key from ckey_parent t0) ";
|
||||
|
||||
assertThat(sql).contains(golden);
|
||||
}
|
||||
|
||||
/**
|
||||
* show that ebean is not using the correct table name in the subquery (sq)
|
||||
*
|
||||
* public void testInheritance1() { ResetBasicData.reset();
|
||||
*
|
||||
* Query<Vehicle> sq = DB.createQuery(Vehicle.class) .select("id")
|
||||
* .setAutoTune(false) .where() .query();
|
||||
*
|
||||
* Query<VehicleDriver> pq = DB.find(VehicleDriver.class)
|
||||
* .where().in("vehicle.id", sq) .query();
|
||||
*
|
||||
* pq.findList();
|
||||
*
|
||||
* String sql = pq.getGeneratedSql(); System.err.println(sql);
|
||||
*
|
||||
* String golden = "(t0.vehicle_id) in (select t0.id from t0.vehicle t0)"; if
|
||||
* (sql.indexOf(golden) < 0) { System.out.println("failed sql:"+sql);
|
||||
* fail("golden string not found"); }
|
||||
*
|
||||
* }
|
||||
*/
|
||||
|
||||
/**
|
||||
* show that ebean is adding the discriminator to the list of columns in the
|
||||
* subquery
|
||||
*/
|
||||
public void testInheritance2() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<VehicleDriver> sq = DB.createQuery(VehicleDriver.class).select("vehicle")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<Vehicle> pq = DB.find(Vehicle.class).where().in("id", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
// TODO: If, after bugfixing, the system still join against vehicle I do not
|
||||
// know now, in our case, it is not necessary if not
|
||||
// using it in the where clause
|
||||
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left join vehicle t1 on t1.id = t0.vehicle_id )";
|
||||
assertThat(sql).contains(golden);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* show that ebean is adding the discriminator to the list of columns in the
|
||||
* subquery. Second test to make sure that joining is still possible after
|
||||
* bugfixing testInheritance2.
|
||||
*/
|
||||
public void testInheritance3() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<VehicleDriver> sq = DB.createQuery(VehicleDriver.class).select("vehicle")
|
||||
.setAutoTune(false).where().eq("vehicle.licenseNumber", "abc").query();
|
||||
|
||||
Query<Vehicle> pq = DB.find(Vehicle.class).where().in("id", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left join vehicle t1 on t1.id = t0.vehicle_id where t1.license_number = ? )";
|
||||
assertThat(sql).contains(golden);
|
||||
}
|
||||
|
||||
/**
|
||||
* show that ebean is using the wrong column (from the vehicle_driver table
|
||||
* instead of vehicle) for the selected column in the subquery. In contrast to
|
||||
* testInheritance2+3 this test forces ebean to "drill down" to the key of the
|
||||
* relation.
|
||||
*/
|
||||
public void testInheritance4() {
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<VehicleDriver> sq = DB.createQuery(VehicleDriver.class).select("vehicle.id")
|
||||
.setAutoTune(false).where().query();
|
||||
|
||||
Query<Vehicle> pq = DB.find(Vehicle.class).where().in("id", sq).query();
|
||||
|
||||
pq.findList();
|
||||
|
||||
String sql = pq.getGeneratedSql();
|
||||
|
||||
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left join vehicle t1 on t1.id = t0.vehicle_id )";
|
||||
assertThat(sql).contains(golden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.FetchConfig;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestThreeLevelQueryJoin extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(Customer.class).fetchQuery("orders")
|
||||
.fetchQuery("orders.details")
|
||||
.fetchQuery("orders.shipments")
|
||||
.fetchQuery("shippingAddress")
|
||||
.fetchQuery("billingAddress").findList();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Country;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class TestWhereIn extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testInVarchar() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().in("code", "NZ", "AU")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
platformAssertIn(sqlOf(query), "where t0.code");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotInVarchar() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().notIn("code", "NZ", "SA", "US")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
platformAssertNotIn(sqlOf(query), "where t0.code");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInOrEmpty_expect_noJoinWhenEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.select("id")
|
||||
.where().inOrEmpty("customer.billingAddress.id", new ArrayList<>()).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).isEqualTo("select t0.id from o_order t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInOrEmpty_expect_joinWhenNotEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.select("id")
|
||||
.where().inOrEmpty("customer.billingAddress.id", Arrays.asList(1)).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).contains("select t0.id from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id where t1.billing_address_id ");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testInOrEmpty_when_null() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().inOrEmpty("code", null).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).isEqualTo("select t0.code, t0.name from o_country t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInOrEmpty_when_empty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().inOrEmpty("code", new ArrayList<>()).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).isEqualTo("select t0.code, t0.name from o_country t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIn_when_empty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().in("code", new ArrayList<>()).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).contains("where 1=0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIn_when_null() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().in("code", (Collection)null).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).contains("where 1=0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotIn_when_empty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().notIn("code", new ArrayList<>()).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).contains("where 1=1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotIn_when_null() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Country> query = DB.find(Country.class)
|
||||
.where().notIn("code", (Collection)null).query();
|
||||
|
||||
query.findList();
|
||||
assertThat(sqlOf(query)).contains("where 1=1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package org.tests.query;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Expr;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.annotation.ForPlatform;
|
||||
import io.ebean.annotation.Platform;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestWhereRawClause extends BaseTestCase {
|
||||
|
||||
|
||||
@Test
|
||||
public void testRawClauseWithJunction() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where()
|
||||
.raw("(status = ? or (orderDate < ? and shipDate is null) or customer.name like ?)",
|
||||
Order.Status.APPROVED, new Timestamp(System.currentTimeMillis()), "Rob")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
assertSql(query).contains(" where (t0.status = ? or (t0.order_date < ? and t0.ship_date is null) or t1.name like ?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRawClause() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(OrderDetail.class)
|
||||
.where()
|
||||
.not(Expr.eq("id", 1))
|
||||
.raw("orderQty < shipQty")
|
||||
.findList();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRaw_bindExpansion_subquery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.where()
|
||||
.raw("id in (select c.id from o_customer c where c.name in (?1))", asList("Rob", "Fiona", "Jack"))
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(sqlOf(query)).contains(" t0.id in (select c.id from o_customer c where c.name in (?,?,?))");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRawOrEmpty_when_notEmpty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<String> vals = asList("Rob", "Fiona", "Jack");
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.where()
|
||||
.rawOrEmpty("id in (select c.id from o_customer c where c.name in (?1))", vals)
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(sqlOf(query)).contains(" t0.id in (select c.id from o_customer c where c.name in (?,?,?))");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRawOrEmpty_when_null() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.where()
|
||||
.rawOrEmpty("id in (select c.id from o_customer c where c.name in (?1))", null)
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(sqlOf(query)).isEqualTo("select t0.id, t0.name from o_customer t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRawOrEmpty_when_empty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.where()
|
||||
.rawOrEmpty("id in (select c.id from o_customer c where c.name in (?1))", Collections.emptySet())
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(sqlOf(query)).isEqualTo("select t0.id, t0.name from o_customer t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRaw_bindExpansion() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.where()
|
||||
.raw("name in (?1)", asList("Rob", "Fiona", "Jack"))
|
||||
.query();
|
||||
|
||||
List<Customer> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
assertThat(sqlOf(query)).contains(" t0.name in (?,?,?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ForPlatform(Platform.POSTGRES)
|
||||
public void testRawPostgresArray() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = DB.find(Customer.class)
|
||||
.where()
|
||||
.raw("name = any(?)", asList("Rob", "Fiona", "Jack"))
|
||||
.findList();
|
||||
|
||||
assertThat(list).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@ForPlatform(Platform.POSTGRES)
|
||||
public void testRawOrEmpty_PostgresArray() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.select("name").where().rawOrEmpty("name = any(?)", asList("Rob", "Fiona", "Jack"))
|
||||
.findList();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.select("name").where().rawOrEmpty("name = any(?)", asList())
|
||||
.findList();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.select("name").where().rawOrEmpty("name = any(?)", null)
|
||||
.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(sql.get(0)).contains("select t0.id, t0.name from o_customer t0 where t0.name = any(?);");
|
||||
assertThat(sql.get(1)).contains("select t0.id, t0.name from o_customer t0; --bind()");
|
||||
assertThat(sql.get(2)).contains("select t0.id, t0.name from o_customer t0; --bind()");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRawWithBindParams() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(OrderDetail.class)
|
||||
.where()
|
||||
.ne("id", 42)
|
||||
.raw("orderQty < ?", 100)
|
||||
.gt("id", 1)
|
||||
.raw("unitPrice > ? and product.id > ?", 2, 3)
|
||||
.findList();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
package org.tests.query.aggregation;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebeantest.LoggedSql;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.model.tevent.TEventMany;
|
||||
import org.tests.model.tevent.TEventOne;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestAggregationCount extends BaseTestCase {
|
||||
|
||||
@BeforeAll
|
||||
public static void setup() {
|
||||
TEventOne one = new TEventOne("first", TEventOne.Status.AA);
|
||||
one.getLogs().add(new TEventMany("all", 1, 10));
|
||||
one.getLogs().add(new TEventMany("be", 2, 12.2));
|
||||
one.getLogs().add(new TEventMany("add", 3, 13));
|
||||
DB.save(one);
|
||||
|
||||
TEventOne two = new TEventOne("second", TEventOne.Status.AA);
|
||||
two.getLogs().add(new TEventMany("at", 10, 10));
|
||||
two.getLogs().add(new TEventMany("add", 30, 13));
|
||||
two.getLogs().add(new TEventMany("alf", 30, 13));
|
||||
DB.save(two);
|
||||
|
||||
TEventOne three = new TEventOne("thrird", TEventOne.Status.BB);
|
||||
DB.save(three);
|
||||
three.setName("third");
|
||||
DB.save(three);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBaseSelect() {
|
||||
|
||||
Query<TEventOne> query = DB.find(TEventOne.class);
|
||||
List<TEventOne> list = query.findList();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, t0.status, t0.version, t0.event_id from tevent_one t0");
|
||||
|
||||
for (TEventOne eventOne : list) {
|
||||
// lazy loading on Aggregation properties
|
||||
// is not expected to work at this stage
|
||||
Double totalAmount = eventOne.getTotalAmount();
|
||||
assertThat(totalAmount).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void example_count() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
int count =
|
||||
DB.find(TEventOne.class)
|
||||
.where().isNotNull("name")
|
||||
.findCount();
|
||||
|
||||
assertThat(count).isGreaterThan(1);
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select count(*) from tevent_one t0 where t0.name is not null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonAggregationLazyLoading() {
|
||||
|
||||
Query<TEventOne> query = DB.find(TEventOne.class).select("id");
|
||||
List<TEventOne> list = query.findList();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select t0.id from tevent_one t0");
|
||||
|
||||
for (TEventOne eventOne : list) {
|
||||
String name = eventOne.getName();
|
||||
assertThat(name).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findCount_withHaving() {
|
||||
Query<TEventOne> query = DB.find(TEventOne.class)
|
||||
//.select("id, totalUnits")
|
||||
.having()
|
||||
.ge("totalUnits", 1)
|
||||
.query();
|
||||
|
||||
LoggedSql.start();
|
||||
int count = query.findCount();
|
||||
List<String> sql = LoggedSql.stop();
|
||||
assertThat(sql).hasSize(1);
|
||||
assertThat(sql.get(0)).contains("group by t0.id");
|
||||
assertThat(count).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFull() {
|
||||
|
||||
Query<TEventOne> query2 = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits, totalAmount")
|
||||
.where()
|
||||
.startsWith("logs.description", "a")
|
||||
.having()
|
||||
.ge("count", 1)
|
||||
.order().asc("name");
|
||||
|
||||
List<TEventOne> list = query2.findList();
|
||||
for (TEventOne eventOne : list) {
|
||||
System.out.println(eventOne.getId() + " " + eventOne.getName() + " count:" + eventOne.getCount() + " units:" + eventOne.getTotalUnits() + " amount:" + eventOne.getTotalAmount());
|
||||
}
|
||||
|
||||
assertThat(list).isNotEmpty();
|
||||
|
||||
String sql = sqlOf(query2, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, count(u1.id), sum(u1.my_units), sum(u1.my_units * u1.amount) from tevent_one t0");
|
||||
assertThat(sql).contains("from tevent_one t0 join tevent_many u1 on u1.event_id = t0.id ");
|
||||
assertThat(sql).contains("where u1.description like ");
|
||||
assertThat(sql).contains(" group by t0.id, t0.name having count(u1.id) >= ? order by t0.name");
|
||||
|
||||
// invoke lazy loading
|
||||
Long version = list.get(0).getVersion();
|
||||
assertThat(version).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOrderByTotal() {
|
||||
|
||||
Query<TEventOne> query = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits, totalAmount")
|
||||
.order().asc("totalUnits").order().asc("name");
|
||||
|
||||
List<TEventOne> list = query.findList();
|
||||
assertThat(list).isNotEmpty();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
if (isH2()) {
|
||||
assertThat(sql).contains("select distinct t0.id, t0.name, count(u1.id), sum(u1.my_units), sum(u1.my_units * u1.amount), sum(u1.my_units), t0.name from tevent_one t0 ");
|
||||
} else if (isPostgres()) {
|
||||
assertThat(sql).contains("t0.name, count(u1.id), sum(u1.my_units), sum(u1.my_units * u1.amount), sum(u1.my_units), t0.name from tevent_one t0 ");
|
||||
}
|
||||
assertThat(sql).contains("from tevent_one t0 join tevent_many u1 on u1.event_id = t0.id ");
|
||||
assertThat(sql).contains(" group by t0.id, t0.name ");
|
||||
assertThat(sql).contains(" order by sum(u1.my_units), t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectSome() {
|
||||
|
||||
Query<TEventOne> query0 = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits");
|
||||
|
||||
query0.findList();
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, count(u1.id), sum(u1.my_units) from tevent_one t0");
|
||||
assertThat(sql).contains("group by t0.id, t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectOnly() {
|
||||
|
||||
Query<TEventOne> query0 = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits, totalAmount");
|
||||
|
||||
query0.findList();
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, count(u1.id), sum(u1.my_units), sum(u1.my_units * u1.amount) from tevent_one t0");
|
||||
assertThat(sql).contains("group by t0.id, t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectWhere() {
|
||||
|
||||
Query<TEventOne> query0 = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits, totalAmount")
|
||||
.where().gt("logs.description", "a").query();
|
||||
|
||||
query0.findList();
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, count(u1.id), sum(u1.my_units), sum(u1.my_units * u1.amount) from tevent_one t0");
|
||||
assertThat(sql).contains("group by t0.id, t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectHavingOrderBy() {
|
||||
|
||||
Query<TEventOne> query1 = DB.find(TEventOne.class)
|
||||
.select("name, count, totalUnits, totalAmount")
|
||||
.having().ge("count", 1)
|
||||
.order().asc("name");
|
||||
|
||||
query1.findList();
|
||||
assertThat(query1.getGeneratedSql()).contains("having count(u1.id) >= ? order by t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectWithFetch() {
|
||||
|
||||
Query<TEventOne> query0 = DB.find(TEventOne.class)
|
||||
.select("name, count")
|
||||
.fetch("event", "name");
|
||||
|
||||
query0.findList();
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select t0.id, t0.name, count(u1.id), t1.id, t1.name from tevent_one t0 left join tevent t1 on t1.id = t0.event_id join tevent_many u1 on u1.event_id = t0.id ");
|
||||
assertThat(sql).contains("group by t0.id, t0.name, t1.id, t1.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTopLevelAggregation() {
|
||||
|
||||
Query<TEventOne> query0 = DB.find(TEventOne.class)
|
||||
.select("status, maxVersion")
|
||||
.where().isNotNull("name")
|
||||
.having().ge("maxVersion", 1)
|
||||
.query();
|
||||
|
||||
List<TEventOne> list = query0.findList();
|
||||
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select t0.status, max(t0.version) from tevent_one t0");
|
||||
assertThat(sql).contains("where t0.name is not null");
|
||||
assertThat(sql).contains("group by t0.status");
|
||||
assertThat(sql).contains("having max(t0.version) >= ?");
|
||||
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
for (TEventOne eventOne : list) {
|
||||
assertThat(eventOne.getStatus()).isNotNull();
|
||||
assertThat(eventOne.getMaxVersion()).isNotNull();
|
||||
|
||||
// bean has no Id, so it is not in Persistence Context, nor Load context
|
||||
assertThat(eventOne.getId()).isNull();
|
||||
// ... and it will not invoke lazy loading
|
||||
assertThat(eventOne.getName()).isNull();
|
||||
}
|
||||
|
||||
List<String> lazyLoadSql = LoggedSqlCollector.stop();
|
||||
assertThat(lazyLoadSql).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query0 = DB.find(Order.class)
|
||||
.select("max(updtime)")
|
||||
.where().eq("status", Order.Status.NEW)
|
||||
.query();
|
||||
|
||||
Timestamp maxUpdateTime = query0.findSingleAttribute();
|
||||
assertThat(maxUpdateTime).isNotNull();
|
||||
|
||||
String sql = sqlOf(query0, 5);
|
||||
assertThat(sql).contains("select max(t0.updtime) from o_order t0");
|
||||
|
||||
Timestamp maxNotNew = DB.find(Order.class)
|
||||
.select("max(updtime)")
|
||||
.where().ne("status", Order.Status.NEW)
|
||||
.findSingleAttribute();
|
||||
|
||||
assertThat(maxNotNew).isNotNull();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_maxInteger() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<OrderDetail> query = DB.find(OrderDetail.class)
|
||||
.select("max(orderQty)");
|
||||
|
||||
Integer maxOrderQty = query.findSingleAttribute();
|
||||
assertThat(maxOrderQty).isGreaterThan(20);
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select max(t0.order_qty) from o_order_detail t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_minInteger() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<OrderDetail> query = DB.find(OrderDetail.class)
|
||||
.select("min(orderQty)");
|
||||
|
||||
Integer minOrderQty = query.findSingleAttribute();
|
||||
assertThat(minOrderQty).isLessThan(10);
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select min(t0.order_qty) from o_order_detail t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_maxString() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.select("max(lastName)");
|
||||
|
||||
String maxName = query.findSingleAttribute();
|
||||
assertThat(maxName).isNotNull();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select max(t0.last_name) from contact t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_minString() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.select("min(firstName)");
|
||||
|
||||
String minName = query.findSingleAttribute();
|
||||
assertThat(minName).isNotNull();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select min(t0.first_name) from contact t0");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_count() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.select("count(lastName)");
|
||||
|
||||
Long count = query.findSingleAttribute();
|
||||
assertThat(count).isNotNull();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select count(t0.last_name) from contact t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDynamicSingleAttributeAggregation_countDistinct() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.select("count(distinct lastName)");
|
||||
|
||||
Long count = query.findSingleAttribute();
|
||||
assertThat(count).isNotNull();
|
||||
|
||||
String sql = sqlOf(query, 5);
|
||||
assertThat(sql).contains("select count(distinct t0.last_name) from contact t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void example() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
String maxLastName =
|
||||
DB.find(Contact.class)
|
||||
.select("max(lastName)")
|
||||
.where().isNull("phone")
|
||||
.findSingleAttribute();
|
||||
|
||||
assertThat(maxLastName).isNotNull();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select max(t0.last_name) from contact t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void example_countDistinct() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Long count =
|
||||
DB.find(Contact.class)
|
||||
.select("count(distinct lastName)")
|
||||
.where().isEmpty("notes")
|
||||
.findSingleAttribute();
|
||||
|
||||
assertThat(count).isNotNull();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select count(distinct t0.last_name) from contact t0 where not exists (select 1 from contact_note x where x.contact_id = t0.id)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void example_nonAggregateFormula() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<String> names =
|
||||
|
||||
DB.find(Contact.class)
|
||||
.select(concat("lastName",", ","firstName"))
|
||||
.where().isNull("phone")
|
||||
.order().asc("lastName")
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(names).isNotEmpty();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select " + concat("t0.last_name",", ","t0.first_name") + " from contact t0 where t0.phone is null order by t0.last_name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void concat_expectString() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<String> names =
|
||||
|
||||
DB.find(Contact.class)
|
||||
.select(concat("updtime",", ","firstName")+"::String")
|
||||
.where().isNull("phone")
|
||||
.order().asc("lastName")
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(names).isNotEmpty();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select " + concat("t0.updtime",", ","t0.first_name") + " from contact t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void explicitCast() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Instant instant =
|
||||
|
||||
DB.find(Contact.class)
|
||||
.select("max(updtime)::Instant")
|
||||
.where().isNull("phone")
|
||||
.findSingleAttribute();
|
||||
|
||||
assertThat(instant).isNotNull();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select max(t0.updtime) from contact t0 where t0.phone is null");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void formula_mapToProperty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Contact> contacts =
|
||||
|
||||
DB.find(Contact.class)
|
||||
.select("email, " + concat("lastName",", ","firstName") + " as lastName")
|
||||
.where().isNull("phone")
|
||||
.order().asc("lastName")
|
||||
.findList();
|
||||
|
||||
assertThat(contacts).isNotEmpty();
|
||||
|
||||
for (Contact name : contacts) {
|
||||
String lastName = name.getLastName();
|
||||
assertThat(lastName).contains(", ");
|
||||
}
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("select t0.id, t0.email, " + concat("t0.last_name",", ","t0.first_name") + " lastName from contact t0 where t0.phone is null order by t0.last_name; --bind()");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package org.tests.query.autotune;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.ProfileLocation;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Address;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class TestAutoTuneProfiling extends BaseTestCase {
|
||||
|
||||
@Disabled
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
execute();
|
||||
}
|
||||
collectUsage();
|
||||
|
||||
sortOfBusy();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
execute();
|
||||
}
|
||||
collectUsage();
|
||||
|
||||
sortOfBusy();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
execute();
|
||||
}
|
||||
}
|
||||
|
||||
private void sortOfBusy() {
|
||||
|
||||
for (int i = 0; i < 90000000; i++) {
|
||||
new Random().nextLong();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void execute() {
|
||||
// useOrderDate();
|
||||
// useOrderDateCustomerName();
|
||||
// useLots();
|
||||
useLotUntuned();
|
||||
}
|
||||
|
||||
private static final ProfileLocation loc0 = ProfileLocation.create();
|
||||
|
||||
private Order findById(long id) {
|
||||
|
||||
return DB.find(Order.class)
|
||||
.setProfileLocation(loc0)
|
||||
.select("status, orderDate, shipDate")
|
||||
.setId(id)
|
||||
.setUseCache(false)
|
||||
.findOne();
|
||||
}
|
||||
|
||||
private void useOrderDate() {
|
||||
Order order = findById(3);
|
||||
order.getStatus();
|
||||
order.getShipDate();
|
||||
}
|
||||
|
||||
private void useOrderDateCustomerName() {
|
||||
Order order = findById(3);
|
||||
order.getOrderDate();
|
||||
order.getCustomer().getName();
|
||||
}
|
||||
|
||||
private void useLots() {
|
||||
|
||||
Order order = findById(3);
|
||||
order.getOrderDate();
|
||||
order.getShipDate();
|
||||
// order.setShipDate(new Date(System.currentTimeMillis()));
|
||||
Customer customer = order.getCustomer();
|
||||
customer.getName();
|
||||
Address shippingAddress = customer.getShippingAddress();
|
||||
if (shippingAddress != null) {
|
||||
shippingAddress.getLine1();
|
||||
shippingAddress.getCity();
|
||||
}
|
||||
}
|
||||
|
||||
private void useLotUntuned() {
|
||||
Order order = findById(3);
|
||||
List<OrderDetail> details = order.getDetails();
|
||||
for (OrderDetail detail : details) {
|
||||
detail.getProduct().getName();
|
||||
detail.getOrderQty();
|
||||
detail.getShipQty();
|
||||
detail.getUnitPrice();
|
||||
}
|
||||
|
||||
// Customer customer = order.getCustomer();
|
||||
// customer.getName();
|
||||
// Address billingAddress = customer.getBillingAddress();
|
||||
// if (billingAddress != null) {
|
||||
// billingAddress.getCity();
|
||||
// billingAddress.getLine1();
|
||||
// billingAddress.getLine2();
|
||||
// }
|
||||
}
|
||||
|
||||
private static void collectUsage() {
|
||||
|
||||
DB.getDefault().autoTune().collectProfiling();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Acl {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
protected Long id;
|
||||
|
||||
String name;
|
||||
|
||||
public Acl(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Entity
|
||||
public class AclContainerRelation {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
protected Long id;
|
||||
|
||||
@ManyToOne(cascade = {}, fetch = FetchType.LAZY)
|
||||
@NotNull
|
||||
private Contract container;
|
||||
|
||||
@ManyToOne(cascade = {}, fetch = FetchType.LAZY)
|
||||
@NotNull
|
||||
private Acl aclEntry;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Contract getContainer() {
|
||||
return container;
|
||||
}
|
||||
|
||||
public void setContainer(final Contract container) {
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
public Acl getAclEntry() {
|
||||
return aclEntry;
|
||||
}
|
||||
|
||||
public void setAclEntry(final Acl aclEntry) {
|
||||
this.aclEntry = aclEntry;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Contract {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
protected Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(cascade = CascadeType.ALL, mappedBy = "contract")
|
||||
private List<Position> positions;
|
||||
|
||||
@OneToMany(cascade = CascadeType.ALL, mappedBy = "container", fetch = FetchType.LAZY)
|
||||
@Nonnull
|
||||
private List<AclContainerRelation> aclEntries = new ArrayList<>();
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Position> getPositions() {
|
||||
return positions;
|
||||
}
|
||||
|
||||
public void setPositions(final List<Position> positions) {
|
||||
this.positions = positions;
|
||||
}
|
||||
|
||||
public List<AclContainerRelation> getAclEntries() {
|
||||
return aclEntries;
|
||||
}
|
||||
|
||||
public void setAclEntries(final List<AclContainerRelation> aclEntries) {
|
||||
this.aclEntries = aclEntries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Entity
|
||||
public class ContractCosts {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
protected Long id;
|
||||
|
||||
String status;
|
||||
|
||||
@NotNull
|
||||
@ManyToOne(cascade = {}, optional = false)
|
||||
private Position position;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Position getPosition() {
|
||||
return position;
|
||||
}
|
||||
|
||||
public void setPosition(final Position position) {
|
||||
this.position = position;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
|
||||
public class Main1 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
TestDistinct test = new TestDistinct();
|
||||
test.testMissingUnique();
|
||||
// executed query:
|
||||
// select t0.id, t0.position_id from contract_costs t0
|
||||
// join position t1 on t1.id = t0.position_id
|
||||
// join contract t2 on t2.id = t1.contract_id
|
||||
// left join acl_container_relation t3 on t3.container_id = t2.id
|
||||
// where t3.acl_entry_id in (?, ? ) ; --bind(Array[2]={1,2})
|
||||
|
||||
// Test will fail:
|
||||
// Expected size:<1> but was:<2> in:
|
||||
// <[org.tests.query.cache.ContractCosts@1, org.tests.query.cache.ContractCosts@1]>
|
||||
// at org.tests.query.cache.TestDistinct.testMissingUnique(TestDistinct.java:49)
|
||||
// at org.tests.query.cache.Main1.main(Main1.java:7)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import io.ebean.DB;
|
||||
|
||||
public class Main2 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
TestDistinct test = new TestDistinct();
|
||||
DB.find(ContractCosts.class).where()
|
||||
.in("position.contract.aclEntries.aclEntry.id",1L, 2L, 3L).findList(); // <-- will fix some cache issue?
|
||||
test.testMissingUnique();
|
||||
|
||||
// executed query:
|
||||
// select distinct t0.id, t0.position_id from contract_costs t0
|
||||
// join position u1 on u1.id = t0.position_id
|
||||
// join contract u2 on u2.id = u1.contract_id
|
||||
// join acl_container_relation u3 on u3.container_id = u2.id
|
||||
// where u3.acl_entry_id in (?, ? ) ; --bind(Array[2]={1,2})
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "e_position")
|
||||
public class Position {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
protected Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne(cascade = {}, optional = false)
|
||||
private Contract contract;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Contract getContract() {
|
||||
return contract;
|
||||
}
|
||||
|
||||
public void setContract(final Contract contract) {
|
||||
this.contract = contract;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.tests.query.cache;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.ExpressionList;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestDistinct extends BaseTestCase {
|
||||
/**
|
||||
* The call of {@link #positionsQuery} {@link ExpressionList#findList()} causes the following use of {@link #costsQuery(UUID...)} to not
|
||||
* use distinct and return the wrong number of results.
|
||||
*/
|
||||
@Test
|
||||
public void testMissingUnique() {
|
||||
Acl acl = new Acl("1");
|
||||
DB.save(acl);
|
||||
Acl acl2 = new Acl("2");
|
||||
DB.save(acl2);
|
||||
Contract contract = new Contract();
|
||||
AclContainerRelation rel1 = new AclContainerRelation();
|
||||
rel1.setAclEntry(acl);
|
||||
rel1.setContainer(contract);
|
||||
AclContainerRelation rel2 = new AclContainerRelation();
|
||||
rel2.setAclEntry(acl2);
|
||||
rel2.setContainer(contract);
|
||||
contract.getAclEntries().add(rel1);
|
||||
contract.getAclEntries().add(rel2);
|
||||
Position pos = new Position();
|
||||
pos.setContract(contract);
|
||||
contract.getPositions().add(pos);
|
||||
DB.save(contract);
|
||||
ContractCosts cost = new ContractCosts();
|
||||
cost.setPosition(pos);
|
||||
DB.save(cost);
|
||||
|
||||
//costsQuery(acl.getId(), acl2.getId()).findCount();
|
||||
|
||||
// the between causes the error
|
||||
List<Position> positions = positionsQuery(acl.getId()).findList();
|
||||
// the between causes the error
|
||||
|
||||
System.out.println("The error, query without distinct:");
|
||||
List<ContractCosts> costs = costsQuery(acl.getId(), acl2.getId()).findList();
|
||||
assertThat(costs).hasSize(1);
|
||||
}
|
||||
|
||||
public ExpressionList<Position> positionsQuery(final Long aclId) {
|
||||
return DB.find(Position.class).where().eq("contract.aclEntries.aclEntry.id", aclId);
|
||||
}
|
||||
|
||||
public ExpressionList<ContractCosts> costsQuery(final Long... aclId) {
|
||||
return DB.find(ContractCosts.class).where().in("position.contract.aclEntries.aclEntry.id", aclId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.tests.query.cancel;
|
||||
|
||||
import org.tests.model.basic.EBasic.Status;
|
||||
|
||||
/**
|
||||
* DTO for Ebasic Queries.
|
||||
*/
|
||||
public class EBasicDto {
|
||||
private Integer id;
|
||||
|
||||
private Status status;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Status getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Status status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.tests.query.cancel;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.h2.api.Trigger;
|
||||
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Transaction;
|
||||
|
||||
/**
|
||||
* Class to artificially slow down selects on 'e_basic' table
|
||||
*/
|
||||
public class SlowDownEBasic implements Trigger {
|
||||
|
||||
private static int wait;
|
||||
|
||||
private static boolean triggerInstalled;
|
||||
|
||||
@Override
|
||||
public void init(final Connection conn, final String schemaName, final String triggerName, final String tableName,
|
||||
final boolean before, final int type) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fire(final Connection conn, final Object[] oldRow, final Object[] newRow) {
|
||||
try {
|
||||
Thread.sleep(wait);
|
||||
} catch (InterruptedException e) {
|
||||
// nop
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
}
|
||||
|
||||
|
||||
public static void setSelectWaitMillis(final int wait) throws SQLException {
|
||||
SlowDownEBasic.wait = wait;
|
||||
if (triggerInstalled) {
|
||||
return;
|
||||
}
|
||||
triggerInstalled = true;
|
||||
try (Transaction txn = DB.beginTransaction(); Statement stmt = txn.connection().createStatement()) {
|
||||
|
||||
stmt.execute("CREATE TRIGGER SLOW_DOWN_E_BASIC BEFORE SELECT ON e_basic " + "CALL \""
|
||||
+ SlowDownEBasic.class.getName() + "\"");
|
||||
txn.commit();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package org.tests.query.cancel;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.EBasic;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.DtoQuery;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.QueryIterator;
|
||||
import io.ebean.SqlQuery;
|
||||
import io.ebean.annotation.ForPlatform;
|
||||
import io.ebean.annotation.Platform;
|
||||
|
||||
/**
|
||||
* Tests, if all kind of queries are cancelable. There are two ways how to
|
||||
* cancel a query: <br/>
|
||||
* <b>At begin:</b>
|
||||
*
|
||||
* <pre>
|
||||
* query = DB.find(...)
|
||||
* query.cancel();
|
||||
* query.findList();
|
||||
* </pre>
|
||||
* <p>
|
||||
* The query was caneled before executing. In this case we do hit the DB driver
|
||||
* <br/>
|
||||
* <br/>
|
||||
* <b>During run:</b>
|
||||
*
|
||||
* <pre>
|
||||
* // Thread 1: Thread 2
|
||||
* query = DB.find(...)
|
||||
* query.findList();
|
||||
* ...finding
|
||||
* ...finding query.cancel();
|
||||
* ...JDBC-Exception
|
||||
* </pre>
|
||||
* <p>
|
||||
* The test tries to simulate a slow query by installing the
|
||||
* {@link SlowDownEBasic} 'SELECT' trigger. The trigger can be configured to
|
||||
* wait 3 * <code>timing</code> ms and a second thread will cancel the query in
|
||||
* <code>timing</code> ms.
|
||||
* <p>
|
||||
* in this case, we expect a JDBC exception from the driver. <br/>
|
||||
* <br/>
|
||||
* NOTE:<br/>
|
||||
* H2 checks the cancel flag in org.h2.command.Prepared::setCurrentRowNumber
|
||||
* only every 128th row. So we need at least 128 models and we cannot check
|
||||
* queries like findCount or findOne, because they only return one row.
|
||||
*
|
||||
* @author Roland Praml, FOCONIS AG
|
||||
*/
|
||||
public class SqlQueryCancelTest extends BaseTestCase {
|
||||
|
||||
private final int timing = 20;
|
||||
|
||||
@BeforeAll
|
||||
public static void setupTestData() throws SQLException {
|
||||
for (int i = 0; i < 128; i++) {
|
||||
EBasic model = new EBasic("Basic " + i);
|
||||
DB.save(model);
|
||||
}
|
||||
if (Platform.H2.equals(DB.getDefault().platform())) {
|
||||
SlowDownEBasic.setSelectWaitMillis(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelSqlQueryAtBegin() throws SQLException {
|
||||
doCancelSqlAtBegin(SqlQuery::findList);
|
||||
doCancelSqlAtBegin(SqlQuery::findOne);
|
||||
doCancelSqlAtBegin(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelSqlAtBegin(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@ForPlatform(Platform.H2)
|
||||
@Test
|
||||
public void cancelSqlDuringRun() throws SQLException {
|
||||
|
||||
doCancelSqlDuringRun(SqlQuery::findList);
|
||||
// doCancelSqlDuringRun(q -> q.setMaxRows(1).findOne());
|
||||
// findOne cannot be tested, as H2 does the cancel check every 128 rows only
|
||||
doCancelSqlDuringRun(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelSqlDuringRun(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void cancelOrmQueryAtBegin() throws SQLException {
|
||||
doCancelOrmAtBegin(Query::findCount);
|
||||
doCancelOrmAtBegin(Query::findFutureCount);
|
||||
// We cannot test 'findCount' due H2 restrictions
|
||||
doCancelOrmAtBegin(Query::findFutureIds);
|
||||
doCancelOrmAtBegin(Query::findFutureList);
|
||||
doCancelOrmAtBegin(Query::findIds);
|
||||
doCancelOrmAtBegin(Query::findIterate);
|
||||
doCancelOrmAtBegin(Query::findList);
|
||||
doCancelOrmAtBegin(Query::findMap);
|
||||
doCancelOrmAtBegin(Query::findOne);
|
||||
doCancelOrmAtBegin(q -> q.setMaxRows(1000).findPagedList().getList()); // untested
|
||||
doCancelOrmAtBegin(Query::findSet);
|
||||
doCancelOrmAtBegin(q -> q.select("name").findSingleAttribute());
|
||||
doCancelOrmAtBegin(q -> q.select("name").findSingleAttributeList());
|
||||
doCancelOrmAtBegin(Query::findStream);
|
||||
// testDuringRun(Query::findVersions);
|
||||
// EBasic has no history support, but it should work if @History is added
|
||||
doCancelOrmAtBegin(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelOrmAtBegin(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@ForPlatform(Platform.H2)
|
||||
@Test
|
||||
public void cancelOrmDuringRun() throws Throwable {
|
||||
// doCancelOrmDuringRun(Query::findCount);
|
||||
// testDuringRunFuture(Query::findFutureCount);
|
||||
// We cannot test 'findCount' due H2 restrictions
|
||||
doCancelOrmFutureDuringRun(Query::findFutureIds);
|
||||
doCancelOrmFutureDuringRun(Query::findFutureList);
|
||||
doCancelOrmDuringRun(Query::findIds);
|
||||
doCancelOrmDuringRun(Query::findIterate);
|
||||
doCancelOrmDuringRun(Query::findList);
|
||||
doCancelOrmDuringRun(Query::findMap);
|
||||
// doCancelOrmDuringRun(q -> q.setMaxRows(1).findOne());
|
||||
// findOne cannot be tested, as H2 does the cancel check every 128 rows only
|
||||
doCancelOrmDuringRun(q -> q.setMaxRows(1000).findPagedList().getList()); // untested
|
||||
doCancelOrmDuringRun(Query::findSet);
|
||||
doCancelOrmDuringRun(q -> q.select("name").findSingleAttribute());
|
||||
doCancelOrmDuringRun(q -> q.select("name").findSingleAttributeList());
|
||||
doCancelOrmDuringRun(Query::findStream);
|
||||
// testDuringRun(Query::findVersions);
|
||||
// EBasic has no history support, but it should work if @History is added
|
||||
doCancelOrmDuringRun(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelOrmDuringRun(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelOrmDuringIterate() throws SQLException {
|
||||
|
||||
Query<EBasic> query = DB.find(EBasic.class);
|
||||
|
||||
QueryIterator<EBasic> iter = query.findIterate();
|
||||
assertThat(iter.hasNext()).isTrue();
|
||||
query.cancel();
|
||||
assertThat(iter.next()).isNotNull();
|
||||
|
||||
// We might have 100 entities in a buffer. So we must iterate through all.
|
||||
assertThatThrownBy(() -> {
|
||||
while (iter.hasNext()) iter.next();
|
||||
})
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelOrmDtoQueryAtBegin() throws SQLException {
|
||||
|
||||
doCancelOrmDtoAtBegin(DtoQuery::findIterate);
|
||||
doCancelOrmDtoAtBegin(DtoQuery::findList);
|
||||
doCancelOrmDtoAtBegin(DtoQuery::findOne);
|
||||
doCancelOrmDtoAtBegin(DtoQuery::findStream);
|
||||
doCancelOrmDtoAtBegin(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelOrmDtoAtBegin(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@ForPlatform(Platform.H2)
|
||||
@Test
|
||||
public void cancelOrmDtoDuringRun() throws SQLException {
|
||||
|
||||
doCancelOrmDtoDuringRun(DtoQuery::findIterate);
|
||||
doCancelOrmDtoDuringRun(DtoQuery::findList);
|
||||
// doCancelOrmDtoDuringRun(q -> q.setMaxRows(1).findOne());
|
||||
// findOne cannot be tested, as H2 does the cancel check every 128 rows only
|
||||
doCancelOrmDtoDuringRun(DtoQuery::findStream);
|
||||
doCancelOrmDtoDuringRun(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelOrmDtoDuringRun(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelOrmDtoDuringIterate() {
|
||||
DtoQuery<EBasicDto> query = DB.find(EBasic.class).select("id,status").asDto(EBasicDto.class);
|
||||
|
||||
QueryIterator<EBasicDto> iter = query.findIterate();
|
||||
assertThat(iter.hasNext()).isTrue();
|
||||
query.cancel();
|
||||
if (isMariaDB()) {
|
||||
assertThrows(PersistenceException.class, iter::next);
|
||||
} else {
|
||||
assertThat(iter.next()).isNotNull();
|
||||
}
|
||||
|
||||
// We might have 100 entities in a buffer. So we must iterate through all.
|
||||
assertThatThrownBy(() -> {
|
||||
while (iter.hasNext()) iter.next();
|
||||
})
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelSqlDtoQueryAtBegin() throws SQLException {
|
||||
|
||||
doCancelSqlDtoAtBegin(DtoQuery::findIterate);
|
||||
doCancelSqlDtoAtBegin(DtoQuery::findList);
|
||||
doCancelSqlDtoAtBegin(DtoQuery::findOne);
|
||||
doCancelSqlDtoAtBegin(DtoQuery::findStream);
|
||||
doCancelSqlDtoAtBegin(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelSqlDtoAtBegin(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@ForPlatform(Platform.H2)
|
||||
@Test
|
||||
public void cancelSqlDtoDuringRun() throws SQLException {
|
||||
|
||||
//doCancelSqlDtoDuringRun(DtoQuery::findIterate);
|
||||
doCancelSqlDtoDuringRun(DtoQuery::findList);
|
||||
// doCancelSqlDtoDuringRun(q -> q.setMaxRows(1).findOne());
|
||||
// findOne cannot be tested, as H2 does the cancel check every 128 rows only
|
||||
doCancelSqlDtoDuringRun(DtoQuery::findStream);
|
||||
doCancelSqlDtoDuringRun(q -> q.findEach(e -> {
|
||||
}));
|
||||
doCancelSqlDtoDuringRun(q -> q.findEachWhile(e -> true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cancelSqlDtoDuringIterate() throws SQLException {
|
||||
|
||||
DtoQuery<EBasicDto> query = DB.findDto(EBasicDto.class, "select id, status from e_basic");
|
||||
|
||||
QueryIterator<EBasicDto> iter = query.findIterate();
|
||||
assertThat(iter.hasNext()).isTrue();
|
||||
query.cancel();
|
||||
assertThat(iter.next()).isNotNull();
|
||||
|
||||
// We might have 100 entities in a buffer. So we must iterate through all.
|
||||
assertThatThrownBy(() -> {
|
||||
while (iter.hasNext()) iter.next();
|
||||
})
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
private void doCancelSqlAtBegin(Consumer<SqlQuery> test) throws SQLException {
|
||||
SqlQuery query = DB.sqlQuery("select * from e_basic");
|
||||
query.cancel();
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
private void doCancelSqlDuringRun(Consumer<SqlQuery> test) throws SQLException {
|
||||
SqlQuery warmup = DB.sqlQuery("select * from e_basic");
|
||||
test.accept(warmup);
|
||||
SqlQuery query = DB.sqlQuery("select * from e_basic");
|
||||
executeDelayed(query::cancel);
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasCauseInstanceOf(org.h2.jdbc.JdbcSQLTimeoutException.class);
|
||||
}
|
||||
|
||||
private void doCancelOrmAtBegin(Consumer<Query<EBasic>> test) throws SQLException {
|
||||
Query<EBasic> query = DB.find(EBasic.class);
|
||||
query.cancel();
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
private void doCancelOrmDuringRun(Consumer<Query<EBasic>> test) throws SQLException {
|
||||
Query<EBasic> warmup = DB.find(EBasic.class);
|
||||
test.accept(warmup);
|
||||
Query<EBasic> warmup2 = DB.find(EBasic.class);
|
||||
test.accept(warmup2);
|
||||
Query<EBasic> query = DB.find(EBasic.class);
|
||||
executeDelayed(query::cancel);
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasCauseInstanceOf(org.h2.jdbc.JdbcSQLTimeoutException.class);
|
||||
}
|
||||
|
||||
private void doCancelOrmFutureDuringRun(Function<Query<EBasic>, Future<?>> test) throws SQLException, InterruptedException, ExecutionException {
|
||||
Query<EBasic> warmup = DB.find(EBasic.class);
|
||||
test.apply(warmup).get();
|
||||
|
||||
Query<EBasic> query = DB.find(EBasic.class);
|
||||
executeDelayed(query::cancel);
|
||||
assertThatThrownBy(() -> {
|
||||
try {
|
||||
test.apply(query).get();
|
||||
} catch (ExecutionException ee) {
|
||||
throw ee.getCause();
|
||||
}
|
||||
})
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasCauseInstanceOf(org.h2.jdbc.JdbcSQLTimeoutException.class);
|
||||
}
|
||||
|
||||
private void doCancelOrmDtoAtBegin(Consumer<DtoQuery<EBasicDto>> test) throws SQLException {
|
||||
DtoQuery<EBasicDto> query = DB.find(EBasic.class).select("id,status").asDto(EBasicDto.class);
|
||||
query.cancel();
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
private void doCancelOrmDtoDuringRun(Consumer<DtoQuery<EBasicDto>> test) throws SQLException {
|
||||
DtoQuery<EBasicDto> warmup = DB.find(EBasic.class).select("id,status").asDto(EBasicDto.class);
|
||||
test.accept(warmup);
|
||||
|
||||
DtoQuery<EBasicDto> query = DB.find(EBasic.class).select("id,status").asDto(EBasicDto.class);
|
||||
executeDelayed(query::cancel);
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasCauseInstanceOf(org.h2.jdbc.JdbcSQLTimeoutException.class);
|
||||
}
|
||||
|
||||
private void doCancelSqlDtoAtBegin(Consumer<DtoQuery<EBasicDto>> test) throws SQLException {
|
||||
DtoQuery<EBasicDto> query = DB.findDto(EBasicDto.class, "select id, status from e_basic");
|
||||
query.cancel();
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasMessageContaining("Query was cancelled");
|
||||
}
|
||||
|
||||
private void doCancelSqlDtoDuringRun(Consumer<DtoQuery<EBasicDto>> test) throws SQLException {
|
||||
DtoQuery<EBasicDto> warmup = DB.findDto(EBasicDto.class, "select id, status from e_basic");
|
||||
test.accept(warmup);
|
||||
|
||||
DtoQuery<EBasicDto> query = DB.findDto(EBasicDto.class, "select id, status from e_basic");
|
||||
executeDelayed(query::cancel);
|
||||
assertThatThrownBy(() -> test.accept(query))
|
||||
.isInstanceOf(PersistenceException.class)
|
||||
.hasCauseInstanceOf(org.h2.jdbc.JdbcSQLTimeoutException.class);
|
||||
}
|
||||
|
||||
private void executeDelayed(Runnable r) throws SQLException {
|
||||
// We modify the DB here. Otherwise we may hit an internal H2 cache, if the
|
||||
// same query is performed. Queries from the cache cannot be canceled.
|
||||
EBasic makeDbDirty = new EBasic("Basic " + UUID.randomUUID());
|
||||
DB.save(makeDbDirty);
|
||||
SlowDownEBasic.setSelectWaitMillis(timing * 3);
|
||||
new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(timing);
|
||||
r.run();
|
||||
SlowDownEBasic.setSelectWaitMillis(0);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package org.tests.query.embedded;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.ExpressionList;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.embedded.EEmbDatePeriod;
|
||||
import org.tests.model.embedded.EEmbInner;
|
||||
import org.tests.model.embedded.EEmbOuter;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Test that selecting A and filtering on 'B.C=some_value' will correctly create join on table for B.
|
||||
* Model:
|
||||
* - Bean A has relation to bean B
|
||||
* - Bean B has an embedded property C
|
||||
*/
|
||||
public class TestFilteringByEmbeddedInJoinedTable extends BaseTestCase {
|
||||
|
||||
private EEmbOuter createOuter(String nomeOuter, Date date1, Date date2) {
|
||||
EEmbOuter outer1 = new EEmbOuter();
|
||||
outer1.setNomeOuter(nomeOuter);
|
||||
|
||||
EEmbDatePeriod eEmbDatePeriod = new EEmbDatePeriod();
|
||||
eEmbDatePeriod.setDate1(date1);
|
||||
eEmbDatePeriod.setDate2(date2);
|
||||
outer1.setDatePeriod(eEmbDatePeriod);
|
||||
|
||||
DB.save(outer1);
|
||||
return outer1;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOuterTableJoined() {
|
||||
|
||||
EEmbOuter outer1 = createOuter("outer1", new Date(11111), new Date(12222));
|
||||
// Unused outer2 just to populate the DB
|
||||
EEmbOuter outer2 = createOuter("outer2", new Date(21111), new Date(22222));
|
||||
assertThat(outer2).isNotNull();
|
||||
|
||||
EEmbOuter outer3 = createOuter("outer3", new Date(31111), new Date(32222));
|
||||
|
||||
|
||||
EEmbInner inner1 = new EEmbInner();
|
||||
inner1.setOuter(outer1);
|
||||
inner1.setNomeInner("inner1-1");
|
||||
DB.save(inner1);
|
||||
|
||||
EEmbInner inner2 = new EEmbInner();
|
||||
// Setting outer1 also here
|
||||
inner2.setOuter(outer1);
|
||||
inner2.setNomeInner("inner2-1");
|
||||
DB.save(inner2);
|
||||
|
||||
EEmbInner inner3 = new EEmbInner();
|
||||
inner3.setOuter(outer3);
|
||||
inner3.setNomeInner("inner3-3");
|
||||
DB.save(inner3);
|
||||
|
||||
ExpressionList<EEmbInner> el = DB.find(EEmbInner.class).where()
|
||||
.eq("outer.datePeriod.date1", new Date(11111));
|
||||
List<EEmbInner> list = el.findList();
|
||||
|
||||
assertThat(list).hasSize(2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package org.tests.query.embedded;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Database;
|
||||
import io.ebean.cache.ServerCache;
|
||||
import io.ebean.cache.ServerCacheManager;
|
||||
import io.ebean.cache.ServerCacheStatistics;
|
||||
import org.tests.model.embedded.EAddress;
|
||||
import org.tests.model.embedded.EInvoice;
|
||||
import org.tests.model.embedded.EInvoice.State;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestMultipleEmbeddedLoading extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testSimpleCase() {
|
||||
|
||||
// prepare test
|
||||
EAddress ship = new EAddress();
|
||||
ship.setStreet("1 Banana St");
|
||||
ship.setSuburb("Suburb");
|
||||
ship.setCity("Auckland");
|
||||
|
||||
EAddress bill = new EAddress();
|
||||
bill.setStreet("2 Apple St");
|
||||
bill.setSuburb("Suburb");
|
||||
bill.setCity("Auckland");
|
||||
|
||||
EInvoice invoice = new EInvoice();
|
||||
invoice.setInvoiceDate(new Date(System.currentTimeMillis()));
|
||||
invoice.setState(State.New);
|
||||
invoice.setShipAddress(ship);
|
||||
invoice.setBillAddress(bill);
|
||||
|
||||
// act: save and fetch
|
||||
DB.save(invoice);
|
||||
|
||||
EInvoice invoice2 = DB.find(EInvoice.class, invoice.getId());
|
||||
|
||||
// assert fetched bean populated as expected
|
||||
assertEquals(invoice.getId(), invoice2.getId());
|
||||
assertEquals(invoice.getState(), invoice2.getState());
|
||||
assertThat(invoice2.getInvoiceDate()).isEqualToIgnoringMillis(invoice.getInvoiceDate());
|
||||
assertEquals("2 Apple St", invoice.getBillAddress().getStreet());
|
||||
assertEquals("2 Apple St", invoice2.getBillAddress().getStreet());
|
||||
|
||||
// act: only update one of the embedded fields
|
||||
invoice2.getBillAddress().setStreet("3 Pineapple St");
|
||||
// bean should be dirty
|
||||
DB.save(invoice2);
|
||||
|
||||
awaitL2Cache();
|
||||
|
||||
EInvoice invoice3 = DB.find(EInvoice.class, invoice.getId());
|
||||
|
||||
// assert field has updated value
|
||||
assertEquals("3 Pineapple St", invoice3.getBillAddress().getStreet());
|
||||
|
||||
|
||||
// fetch a partial
|
||||
EInvoice invoicePartial = DB.find(EInvoice.class)
|
||||
.select("state, date")
|
||||
.where().idEq(invoice.getId())
|
||||
.findOne();
|
||||
|
||||
// lazy load of embedded bean
|
||||
EAddress billAddress = invoicePartial.getBillAddress();
|
||||
|
||||
assertNotNull(billAddress);
|
||||
assertEquals("3 Pineapple St", billAddress.getStreet());
|
||||
|
||||
Database server = DB.getDefault();
|
||||
ServerCacheManager serverCacheManager = server.cacheManager();
|
||||
|
||||
// get cache, clear the cache and statistics
|
||||
ServerCache beanCache = serverCacheManager.beanCache(EInvoice.class);
|
||||
beanCache.clear();
|
||||
beanCache.statistics(true);
|
||||
|
||||
// fetch and load the cache
|
||||
EInvoice invoice4 = DB.find(EInvoice.class, invoice.getId());
|
||||
assertNotNull(invoice4);
|
||||
|
||||
ServerCacheStatistics statistics = beanCache.statistics(false);
|
||||
|
||||
assertEquals(1, statistics.getSize());
|
||||
assertEquals(0, statistics.getHitCount());
|
||||
|
||||
// fetch out of the cache this time
|
||||
EInvoice invoice5 = DB.find(EInvoice.class, invoice.getId());
|
||||
assertNotNull(invoice5);
|
||||
|
||||
statistics = beanCache.statistics(false);
|
||||
assertEquals(1, statistics.getSize());
|
||||
assertEquals(1, statistics.getHitCount());
|
||||
|
||||
billAddress = invoice5.getBillAddress();
|
||||
|
||||
assertNotNull(billAddress);
|
||||
assertEquals("3 Pineapple St", billAddress.getStreet());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package org.tests.query.finder;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Transaction;
|
||||
import io.ebean.meta.MetaQueryMetric;
|
||||
import io.ebean.meta.MetaQueryPlan;
|
||||
import io.ebean.meta.MetaTimedMetric;
|
||||
import io.ebean.meta.QueryPlanInit;
|
||||
import io.ebean.meta.QueryPlanRequest;
|
||||
import io.ebean.meta.ServerMetrics;
|
||||
import io.ebean.meta.SortMetric;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.EBasic;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestCustomerFinder extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void a_runFirst_metricsAsJson_sqlInInitialCollectionOnly() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
runQueries();
|
||||
|
||||
StringBuilder buffer0 = new StringBuilder();
|
||||
DB.getDefault().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHeader(false)
|
||||
.write(buffer0);
|
||||
|
||||
String json0 = buffer0.toString();
|
||||
System.out.println(json0);
|
||||
assertThat(json0).contains("\"name\":\"txn.main\"");
|
||||
assertThat(json0).contains("\"name\":\"orm.Customer.findList\"");
|
||||
//assertThat(json0).contains("\"sql\":\"select t0.id, t0.status, t0.name");
|
||||
|
||||
runQueries();
|
||||
|
||||
StringBuilder buffer1 = new StringBuilder();
|
||||
DB.getDefault().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHeader(false)
|
||||
.write(buffer1);
|
||||
|
||||
String json1 = buffer1.toString();
|
||||
System.out.println(json1);
|
||||
assertThat(json1).contains("\"name\":\"txn.main\"");
|
||||
assertThat(json1).contains("\"name\":\"orm.Customer.findList\"");
|
||||
assertThat(json1).doesNotContain("\"sql\":\"select t0.id, t0.status, t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ref() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Customer customer = Customer.find.ref(1);
|
||||
assertThat(customer.getId()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_all_byId_byName() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> all = Customer.find.all();
|
||||
List<Customer> list = DB.find(Customer.class).findList();
|
||||
|
||||
assertThat(all.size()).isEqualTo(list.size());
|
||||
|
||||
Customer customer = all.get(0);
|
||||
|
||||
Customer customer1 = Customer.find.byId(customer.getId());
|
||||
|
||||
assertThat(customer.getId()).isEqualTo(customer1.getId());
|
||||
assertThat(customer.getName()).isEqualTo(customer1.getName());
|
||||
|
||||
assertThat(Customer.find.db().name()).isEqualTo(DB.getDefault().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void currentTransaction() {
|
||||
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
Transaction t1 = DB.currentTransaction();
|
||||
Transaction t2 = Customer.find.currentTransaction();
|
||||
assertThat(t2).isSameAs(t1);
|
||||
|
||||
} finally {
|
||||
DB.endTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flush() {
|
||||
|
||||
Transaction transaction = DB.beginTransaction();
|
||||
try {
|
||||
Customer.find.currentTransaction().setBatchMode(true);
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
EBasic b = new EBasic("junk");
|
||||
DB.save(b);
|
||||
|
||||
assertTrue(LoggedSqlCollector.current().isEmpty());
|
||||
Customer.find.flush();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertSql(sql.get(0)).contains("insert into e_basic");
|
||||
} finally {
|
||||
transaction.end();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_byName_deleteById() {
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setName("Newbie-879879897");
|
||||
|
||||
DB.save(customer);
|
||||
assertThat(customer.getId()).isNotNull();
|
||||
|
||||
Customer customer2 = Customer.find.byName(customer.getName());
|
||||
assertThat(customer.getId()).isEqualTo(customer2.getId());
|
||||
assertThat(customer.getName()).isEqualTo(customer2.getName());
|
||||
|
||||
Customer.find.deleteById(customer.getId());
|
||||
awaitL2Cache();
|
||||
|
||||
Customer notThere = Customer.find.byId(customer.getId());
|
||||
assertThat(notThere).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_update() {
|
||||
|
||||
int rowsUpdated = Customer.find.updateToInactive("Frankie Who");
|
||||
logger.debug("updated {}", rowsUpdated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ormQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> customers =
|
||||
Customer.find.byNameStatus("R", Customer.Status.NEW);
|
||||
|
||||
assertThat(customers).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_nativeSingleAttribute() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<String> names = Customer.find.namesStartingWith("F");
|
||||
assertThat(names).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_finders_queryPlans() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
// change default collect query plan threshold to 200 micros
|
||||
QueryPlanInit init0 = new QueryPlanInit();
|
||||
init0.setAll(true);
|
||||
init0.thresholdMicros(2);
|
||||
final List<MetaQueryPlan> plans = server().metaInfo().queryPlanInit(init0);
|
||||
assertThat(plans.size()).isGreaterThan(1);
|
||||
|
||||
// the server has some plans
|
||||
runQueries();
|
||||
|
||||
// change query plan threshold to 100 micros
|
||||
QueryPlanInit init = new QueryPlanInit();
|
||||
init.setAll(true);
|
||||
init.thresholdMicros(1);
|
||||
final List<MetaQueryPlan> appliedToPlans = server().metaInfo().queryPlanInit(init);
|
||||
assertThat(appliedToPlans.size()).isGreaterThan(4);
|
||||
|
||||
// run queries again
|
||||
runQueries();
|
||||
|
||||
ServerMetrics metrics = DB.getDefault().metaInfo().collectMetrics();
|
||||
|
||||
List<MetaQueryMetric> planStats = metrics.queryMetrics();
|
||||
assertThat(planStats.size()).isGreaterThan(4);
|
||||
|
||||
for (MetaQueryMetric planStat : planStats) {
|
||||
System.out.println(planStat);
|
||||
}
|
||||
|
||||
for (MetaTimedMetric txnTimed : metrics.timedMetrics()) {
|
||||
System.out.println(txnTimed);
|
||||
}
|
||||
|
||||
// obtains db query plans ...
|
||||
QueryPlanRequest request = new QueryPlanRequest();
|
||||
// collect max 1000 plans (use something more like 10)
|
||||
request.maxCount(1_000);
|
||||
// don't collect any more plans if used 10 secs
|
||||
request.maxTimeMillis(10_000);
|
||||
List<MetaQueryPlan> plans0 = server().metaInfo().queryPlanCollectNow(request);
|
||||
assertThat(plans0).isNotEmpty();
|
||||
|
||||
for (MetaQueryPlan plan : plans) {
|
||||
logger.info("queryPlan label:{}, queryTimeMicros:{} loc:{} sql:{} bind:{} plan:{}",
|
||||
plan.label(), plan.queryTimeMicros(), plan.profileLocation(),
|
||||
plan.sql(), plan.bind(), plan.plan());
|
||||
System.out.println(plan);
|
||||
}
|
||||
|
||||
//DB.getBackgroundExecutor().scheduleWithFixedDelay(...)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_metricsAsJson_withAll() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
runQueries();
|
||||
|
||||
String metricsJson = server().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHash(true)
|
||||
.withExtraAttributes(true)
|
||||
.withNewLine(true)
|
||||
.withSort(SortMetric.TOTAL)
|
||||
.json();
|
||||
|
||||
assertThat(metricsJson).contains("\"name\":\"txn.main\"");
|
||||
assertThat(metricsJson).contains("\"name\":\"orm.Customer.findList\"");
|
||||
assertThat(metricsJson).contains("\"loc\":\"org.tests.model.basic.finder.CustomerFinder.byNameStatus\"");
|
||||
if (isH2() || isPostgres()) {
|
||||
assertThat(metricsJson).contains("\"hash\":\"de3affa5b4bff07e19c1c012590dcde6\"");
|
||||
assertThat(metricsJson).contains("\"sql\":\"select t0.id, t0.status,");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_metricsAsJson_minimal() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
runQueries();
|
||||
|
||||
String metricsJson = server().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHash(false)
|
||||
.withExtraAttributes(false)
|
||||
.withNewLine(false)
|
||||
.withSort(null)
|
||||
.json();
|
||||
|
||||
assertThat(metricsJson).contains("\"name\":\"txn.main\"");
|
||||
assertThat(metricsJson).contains("\"name\":\"orm.Customer.findList\"");
|
||||
assertThat(metricsJson).doesNotContain("\"loc\":");
|
||||
assertThat(metricsJson).doesNotContain("\"sqlHash\":");
|
||||
assertThat(metricsJson).doesNotContain("\"sql\":");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_metricsAsJson_write() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
runQueries();
|
||||
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
server().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHeader(false)
|
||||
.write(buffer);
|
||||
|
||||
String metricsJson = buffer.toString();
|
||||
assertThat(metricsJson).contains("\"name\":\"txn.main\"");
|
||||
assertThat(metricsJson).contains("\"name\":\"orm.Customer.findList\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_metricsAsJson_writeWithHeader() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
runQueries();
|
||||
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
server().metaInfo()
|
||||
.collectMetricsAsJson()
|
||||
.withHeader(true)
|
||||
.write(buffer);
|
||||
|
||||
String metricsJson = buffer.toString();
|
||||
assertThat(metricsJson).contains(" \"metrics\":[");
|
||||
assertThat(metricsJson).contains("\"name\":\"txn.main\"");
|
||||
assertThat(metricsJson).contains("\"name\":\"orm.Customer.findList\"");
|
||||
}
|
||||
|
||||
private void runQueries() {
|
||||
resetAllMetrics();
|
||||
|
||||
List<Customer> customers = Customer.find.all();
|
||||
assertThat(customers).isNotEmpty();
|
||||
|
||||
Customer customer = Customer.find.byId(1);
|
||||
assertThat(customer).isNotNull();
|
||||
Customer.find.byId(2);
|
||||
|
||||
Customer.find.namesStartingWith("F");
|
||||
Customer.find.byNameStatus("Rob", Customer.Status.ACTIVE);
|
||||
Customer.find.totalCount();
|
||||
Customer.find.updateNames("Junk", 2000);
|
||||
Customer.find.byId(3);
|
||||
DB.find(Customer.class)
|
||||
.setLabel("someDeleteQuery")
|
||||
.where().eq("name", "JunkNotExists")
|
||||
.delete();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Expr;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.basic.one2one.Wheel;
|
||||
import org.tests.model.basic.MRole;
|
||||
import org.tests.model.basic.MUser;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestDisjunctWhereOuterJoin extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
|
||||
MRole r1 = new MRole();
|
||||
r1.setRoleName("role1B");
|
||||
DB.save(r1);
|
||||
|
||||
MRole r2 = new MRole();
|
||||
r2.setRoleName("role2specialB");
|
||||
DB.save(r2);
|
||||
|
||||
MRole r3 = new MRole();
|
||||
r3.setRoleName("role3B");
|
||||
DB.save(r3);
|
||||
|
||||
MUser u0 = new MUser();
|
||||
u0.setUserName("user0B");
|
||||
u0.addRole(r1);
|
||||
u0.addRole(r2);
|
||||
|
||||
DB.save(u0);
|
||||
|
||||
MUser u1 = new MUser();
|
||||
u1.setUserName("user1B");
|
||||
u1.addRole(r1);
|
||||
|
||||
DB.save(u1);
|
||||
|
||||
queryOrExpression(r2.getRoleid());
|
||||
|
||||
queryDisjunction(r2.getRoleid());
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.where().disjunction()
|
||||
.eq("roles.roleName", "role2specialB") // user0
|
||||
.eq("roles.roleName", "role3B") // nobody
|
||||
.endJunction().query();
|
||||
|
||||
List<MUser> list = query.findList();
|
||||
assertThat(list).hasSize(1); // list should contain user0
|
||||
|
||||
String sql = sqlOf(query);
|
||||
assertSqlOuterJoins(sql);
|
||||
assertThat(sql).contains(".role_name = ?");
|
||||
|
||||
} finally {
|
||||
DB.rollbackTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
private void queryDisjunction(Integer roleid) {
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.where().or()
|
||||
.eq("userName", "user0B")
|
||||
.eq("roles.roleid", roleid)
|
||||
.endOr().query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = sqlOf(query);
|
||||
assertSqlOuterJoins(sql);
|
||||
assertThat(sql).contains("where (t0.user_name = ? or u1.roleid = ?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectOneToOneDisjunction() {
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
Query<Wheel> query = DB.find(Wheel.class)
|
||||
.select("id")
|
||||
.where().or()
|
||||
.ge("tire.id", 100)
|
||||
.lt("tire.id", 100)
|
||||
.endOr().query();
|
||||
query.findList();
|
||||
String sql = sqlOf(query);
|
||||
assertThat(sql).contains("join");
|
||||
} finally {
|
||||
DB.rollbackTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
private void queryOrExpression(Integer roleid) {
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.where().or(
|
||||
Expr.eq("userName", "user0B"),
|
||||
Expr.eq("roles.roleid", roleid)
|
||||
)
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = sqlOf(query);
|
||||
assertSqlOuterJoins(sql);
|
||||
assertThat(sql).contains("where (t0.user_name = ? or u1.roleid = ?)");
|
||||
}
|
||||
|
||||
private void assertSqlOuterJoins(String sql) {
|
||||
assertThat(sql).contains("select distinct");
|
||||
assertThat(sql).contains("left join mrole_muser u1z_ on u1z_.muser_userid = t0.userid");
|
||||
assertThat(sql).contains("left join mrole u1 on u1.roleid = u1z_.mrole_roleid");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.UUOne;
|
||||
import org.tests.model.basic.UUTwo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestDisjunctWhereOuterOnMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
DB.deleteAll(DB.find(UUTwo.class).select("id").findList());
|
||||
DB.deleteAll(DB.find(UUOne.class).select("id").findList());
|
||||
|
||||
// setup
|
||||
UUOne master1 = new UUOne();
|
||||
master1.setName("testDisjOuter_1_name");
|
||||
|
||||
UUTwo detail1 = new UUTwo();
|
||||
detail1.setMaster(master1);
|
||||
detail1.setName("testDisjOuter_CHILD_1");
|
||||
|
||||
UUOne master2 = new UUOne();
|
||||
master2.setName("testDisjOuter_2_name");
|
||||
|
||||
DB.save(master1);
|
||||
DB.save(detail1);
|
||||
DB.save(master2);
|
||||
|
||||
|
||||
// Have outer join so that "testDisjOuter_2_name" is found
|
||||
Query<UUOne> query = DB.find(UUOne.class)
|
||||
.where().disjunction()
|
||||
.eq("name", "testDisjOuter_2_name")
|
||||
.eq("comments.name", "testDisjOuter_CHILD_1")
|
||||
.endJunction()
|
||||
.query();
|
||||
|
||||
List<UUOne> list = query.findList();
|
||||
int rowCount = query.findCount();
|
||||
|
||||
// select distinct t0.id c0, t0.name c1
|
||||
// from uuone t0
|
||||
// join uutwo u1 on u1.master_id = t0.id
|
||||
// left join uutwo t1 on t1.master_id = t0.id
|
||||
// where (t0.name = ? or u1.name = ? ) ;
|
||||
// --bind(testDisjOuter_2_name,testDisjOuter_CHILD_1)
|
||||
|
||||
assertEquals(2, list.size());
|
||||
assertEquals(2, rowCount);
|
||||
|
||||
if (isPostgres()) {
|
||||
String expectedSql = "select distinct on (t0.id) t0.id, t0.name, t0.description, t0.version from uuone t0 left join uutwo u1 on u1.master_id = t0.id where (t0.name = ? or u1.name = ?)";
|
||||
assertSql(query).contains(expectedSql);
|
||||
|
||||
} else {
|
||||
String expectedSql = "select distinct t0.id, t0.name, t0.description, t0.version from uuone t0 left join uutwo u1 on u1.master_id = t0.id where (t0.name = ? or u1.name = ?)";
|
||||
assertSql(query).contains(expectedSql);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryJoinManyNonRoot extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test_manyPredicate() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Order> orders = DB.find(Order.class)
|
||||
.select("id, status, orderDate")
|
||||
.where().gt("details.orderQty", 0)
|
||||
.findList();
|
||||
|
||||
assertTrue(!orders.isEmpty());
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertTrue(loggedSql.get(0).contains("select distinct "));
|
||||
assertTrue(loggedSql.get(0).contains(" from o_order t0 join o_order_detail u1 on u1.order_id = t0.id "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_manyNonRoot() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q = DB.find(Order.class)
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.where().gt("id", 0).query();
|
||||
|
||||
List<Order> list = q.findList();
|
||||
String sql = q.getGeneratedSql();
|
||||
|
||||
assertTrue(!list.isEmpty());
|
||||
assertTrue(sql.contains("join o_customer t1 on t1.id "));
|
||||
assertTrue(sql.contains("left join contact t2 on"));
|
||||
|
||||
Map<Integer, Order> ordersById = DB.find(Order.class).setMapKey("id").where().gt("id", 0).query().findMap();
|
||||
for (Order o: list) {
|
||||
int withoutFetch = ordersById.get(o.getId()).getCustomer().getContacts().size();
|
||||
int withFetch = o.getCustomer().getContacts().size();
|
||||
assertEquals(withoutFetch, withFetch);
|
||||
}
|
||||
|
||||
|
||||
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6,
|
||||
// t1.id c7, t1.status c8, t1.name c9, t1.smallnote c10, t1.anniversary c11, t1.cretime c12, t1.updtime c13, t1.billing_address_id c14, t1.shipping_address_id c15,
|
||||
// t2.id c16, t2.first_name c17, t2.last_name c18, t2.phone c19, t2.mobile c20, t2.email c21, t2.cretime c22, t2.updtime c23, t2.customer_id c24, t2.group_id c25
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// left join contact t2 on t2.customer_id = t1.id
|
||||
// where t0.id > ? ; --bind(0)
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_manyRootQueryJoinOrderDetailsFirst() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q = DB.find(Order.class)
|
||||
.fetch("details")
|
||||
.fetch("details.product")
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.where().gt("id", 0).query();
|
||||
|
||||
List<Order> list = q.findList();
|
||||
String sql = q.getGeneratedSql();
|
||||
|
||||
assertTrue(!list.isEmpty());
|
||||
assertTrue(sql.contains("join o_customer t1 on t1.id "));
|
||||
assertTrue(sql.contains("left join o_order_detail "));
|
||||
assertTrue(sql.contains("left join o_product "));
|
||||
|
||||
assertFalse(sql.contains("left join contact"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_manyRootQueryJoinCustomerContactsFirst() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> q = DB.find(Order.class)
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.fetchQuery("details")
|
||||
.fetch("details.product")
|
||||
.where().gt("id", 0).query();
|
||||
|
||||
List<Order> list = q.findList();
|
||||
String sql = q.getGeneratedSql();
|
||||
|
||||
for (Order order : list) {
|
||||
order.getCustomer().getContacts().size();
|
||||
}
|
||||
|
||||
assertTrue(!list.isEmpty());
|
||||
assertTrue(sql.contains("join o_customer t1 on t1.id "));
|
||||
assertTrue(sql.contains("left join contact "));
|
||||
|
||||
assertFalse(sql.contains("left join o_order_detail "));
|
||||
assertFalse(sql.contains("left join o_product "));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.model.family.ChildPerson;
|
||||
import org.tests.model.family.ParentPerson;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestQueryJoinOnFormula extends BaseTestCase {
|
||||
|
||||
@BeforeEach
|
||||
public void init() {
|
||||
ResetBasicData.reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindIds() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Integer> orderIds = DB.find(Order.class)
|
||||
.where().eq("totalItems", 3)
|
||||
.findIds();
|
||||
assertThat(orderIds).hasSize(2);
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains(" left join (select order_id, count(*) as total_items,");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindList() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Order> orders = DB.find(Order.class)
|
||||
.where().eq("totalItems", 3)
|
||||
.findList();
|
||||
assertThat(orders).hasSize(2);
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains(" left join (select order_id, count(*) as total_items,");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindCount() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
int orders = DB.find(Order.class)
|
||||
.where().eq("totalItems", 3)
|
||||
.findCount();
|
||||
assertThat(orders).isEqualTo(2);
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("join (select order_id, count(*) as total_items,");
|
||||
assertSql(sql.get(0)).contains("select count(*) from ( select t0.id from o_order t0 left join (select order_id,");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindCount_multiFormula() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
int orders = DB.find(Order.class)
|
||||
.where()
|
||||
.eq("totalItems", 3)
|
||||
.gt("totalAmount", 10)
|
||||
.findCount();
|
||||
|
||||
assertThat(orders).isEqualTo(2);
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("select count(*) from ( select t0.id from o_order t0 left join (select order_id,");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindSingleAttributeList() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Date> orderDates = DB.find(Order.class)
|
||||
.select("orderDate")
|
||||
.where().eq("totalItems", 3)
|
||||
.findSingleAttributeList();
|
||||
assertThat(orderDates).hasSize(2);
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains(" left join (select order_id, count(*) as total_items,");
|
||||
assertSql(sql.get(0)).contains("select t0.order_date from o_order t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_OrderFindOne() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Order order = DB.find(Order.class)
|
||||
.select("totalItems")
|
||||
.where().eq("totalItems", 3)
|
||||
.setMaxRows(1)
|
||||
.orderById(true)
|
||||
.findOne();
|
||||
|
||||
assertThat(order.getTotalItems()).isEqualTo(3);
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("join (select order_id, count(*) as total_items,");
|
||||
if (isSqlServer()) {
|
||||
assertSql(sql.get(0)).contains("select top 1 t0.id, z_bt0.total_items from o_order t0 join (select");
|
||||
} else {
|
||||
assertSql(sql.get(0)).contains("select t0.id, z_bt0.total_items from o_order t0 join (select order_id");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ParentPersonFindIds() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<ParentPerson> orderIds = DB.find(ParentPerson.class)
|
||||
.where().eq("totalAge", 3)
|
||||
.findIds();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains("where coalesce(f2.child_age, 0) = ?; --bind(3)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ParentPersonFindList() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ParentPerson.class)
|
||||
.select("identifier")
|
||||
//.where().eq("totalAge", 3)
|
||||
.where().eq("familyName", "foo")
|
||||
.findList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("select t0.identifier from parent_person t0 where t0.family_name = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ParentPersonFindCount() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ParentPerson.class)
|
||||
.where().eq("totalAge", 3)
|
||||
.findCount();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("where coalesce(f2.child_age, 0) = ?)");
|
||||
assertSql(sql.get(0)).contains("select count(*) from ( select t0.identifier from parent_person t0 left join (select i2.parent_identifier, count(*) as child_count");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ParentPersonFindSingleAttributeList() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ParentPerson.class)
|
||||
.select("address")
|
||||
.where().eq("totalAge", 3)
|
||||
.findSingleAttributeList();
|
||||
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, sql.size());
|
||||
assertSql(sql.get(0)).contains("select t0.address from parent_person t0 left join (select i2.parent_identifier");
|
||||
assertSql(sql.get(0)).contains("where coalesce(f2.child_age, 0) = ?; --bind(3)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ParentPersonFindOne() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ParentPerson.class)
|
||||
.where().eq("totalAge", 3)
|
||||
.setMaxRows(1)
|
||||
.orderById(true)
|
||||
.findOne();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains("where coalesce(f2.child_age, 0) = ? order by t0.identifier");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ChildPersonParentFindIds() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ChildPerson.class)
|
||||
.where().eq("parent.totalAge", 3)
|
||||
.findIds();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains("select t0.identifier from child_person t0 left join (select i2.parent_identifier");
|
||||
assertThat(loggedSql.get(0)).contains("where coalesce(f2.child_age, 0) = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_ChildPersonParentFindCount() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(ChildPerson.class)
|
||||
.where().eq("parent.totalAge", 3)
|
||||
.findCount();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
assertThat(loggedSql.get(0)).contains("select count(*) from ( select t0.identifier");
|
||||
assertThat(loggedSql.get(0)).contains("where coalesce(f2.child_age, 0) = ?");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.el.ElPropertyValue;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryJoinQueryNonRoot extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
SpiEbeanServer server = (SpiEbeanServer) DB.getDefault();
|
||||
BeanDescriptor<Order> d = server.descriptor(Order.class);
|
||||
ElPropertyValue elGetValue = d.elGetValue("customer.contacts");
|
||||
|
||||
assertTrue(elGetValue.containsMany());
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class)
|
||||
.fetch("customer")
|
||||
.fetchQuery("customer.contacts", "firstName")
|
||||
.fetch("customer.contacts.group")
|
||||
.where().lt("id", 3).findList();
|
||||
|
||||
assertNotNull(list);
|
||||
assertTrue(!list.isEmpty());
|
||||
|
||||
for (Order order : list) {
|
||||
List<Contact> contacts = order.getCustomer().getContacts();
|
||||
for (Contact contact : contacts) {
|
||||
contact.getFirstName();
|
||||
}
|
||||
}
|
||||
|
||||
// String oq =
|
||||
// "find order join customer join customer.contacts join details (+query(4),+lazy(5))";
|
||||
// Query<Order> q = DB.createQuery(Order.class, oq);
|
||||
// q.setAutoTune(false);
|
||||
// List<Order> list2 = q.findList();
|
||||
//
|
||||
// assertTrue(list2.size() > 0);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package org.tests.query.joins;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestQueryManyToOneWhereClauseJoin extends BaseTestCase {
|
||||
|
||||
|
||||
/**
|
||||
* Testing 'where join' created for a ManyToOne relationship.
|
||||
*/
|
||||
@Test
|
||||
public void testJoin() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().ilike("customer.name", "rob%")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
//select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7
|
||||
String expectedSql = "from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id where lower(t1.name) like ";
|
||||
assertTrue(query.getGeneratedSql().contains(expectedSql));
|
||||
|
||||
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// where lower(t1.name) like ? ; --bind(rob%)
|
||||
}
|
||||
|
||||
/**
|
||||
* Although this is a disjunction it is on a ManyToOne so the 'default' join type is still fine.
|
||||
*/
|
||||
@Test
|
||||
public void testDisjunctionOnManyToOneJoin() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().disjunction().ilike("customer.name", "rob%").gt("id", 1).endJunction()
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
//select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7
|
||||
String expectedSql = "from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id where (lower(t1.name) like ";
|
||||
assertTrue(query.getGeneratedSql().contains(expectedSql));
|
||||
|
||||
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// where (lower(t1.name) like ? or t0.id > ? ) ; --bind(rob%,1)
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Testing ManyToOne relationship with predicate and fetch.
|
||||
*/
|
||||
@Test
|
||||
public void testWhereAndFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.where().ilike("customer.name", "rob%")
|
||||
.query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String generatedSql = query.getGeneratedSql();
|
||||
assertTrue(generatedSql.contains("from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id"));
|
||||
assertTrue(generatedSql.contains("left join contact t2 on t2.customer_id = t1.id"));
|
||||
assertTrue(generatedSql.contains("where lower(t1.name) like "));
|
||||
|
||||
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6,
|
||||
// t1.id c7, t1.status c8, t1.name c9, t1.smallnote c10, t1.anniversary c11, t1.cretime c12, t1.updtime c13, t1.billing_address_id c14, t1.shipping_address_id c15,
|
||||
// t2.id c16, t2.first_name c17, t2.last_name c18, t2.phone c19, t2.mobile c20, t2.email c21, t2.cretime c22, t2.updtime c23, t2.customer_id c24, t2.group_id c25
|
||||
// from o_order t0
|
||||
// join o_customer t1 on t1.id = t0.kcustomer_id
|
||||
// left join contact t2 on t2.customer_id = t1.id
|
||||
// where lower(t1.name) like ? ; --bind(rob%)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package org.tests.query.lazy;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.ProfileLocation;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.Product;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestQueryDefaultBatchSize extends BaseTestCase {
|
||||
|
||||
private static final ProfileLocation loc0 = ProfileLocation.create();
|
||||
private static final ProfileLocation loc1 = ProfileLocation.create();
|
||||
private static final ProfileLocation loc2 = ProfileLocation.create();
|
||||
private static final ProfileLocation loc3 = ProfileLocation.create();
|
||||
|
||||
@Test
|
||||
public void test_findEach() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setProfileLocation(loc0)
|
||||
.setLazyLoadBatchSize(2)
|
||||
.findEach(bean -> doStuff(bean));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findEach_withFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.find(Order.class)
|
||||
.setProfileLocation(loc1)
|
||||
.fetch("details", "id")
|
||||
.fetch("details.product", "sku")
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.setLazyLoadBatchSize(2)
|
||||
.findEach(bean -> doStuff(bean));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findList() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> orders =
|
||||
DB.find(Order.class)
|
||||
.setProfileLocation(loc2)
|
||||
.setLazyLoadBatchSize(2)
|
||||
.findList();
|
||||
|
||||
for (Order order : orders) {
|
||||
doStuff(order);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findList_withFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> orders =
|
||||
DB.find(Order.class)
|
||||
.setProfileLocation(loc3)
|
||||
.fetch("details", "id")
|
||||
.fetch("details.product", "sku")
|
||||
.fetch("customer")
|
||||
.fetch("customer.contacts")
|
||||
.setLazyLoadBatchSize(2)
|
||||
.findList();
|
||||
|
||||
for (Order order : orders) {
|
||||
doStuff(order);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_findList_lazyMany() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> orders = DB.find(Order.class)
|
||||
.setLazyLoadBatchSize(100)
|
||||
.findList();
|
||||
|
||||
for (Order order : orders) {
|
||||
List<OrderDetail> details = order.getDetails();
|
||||
details.size();
|
||||
for (OrderDetail detail : details) {
|
||||
Product product = detail.getProduct();
|
||||
product.getSku();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void doStuff(Order order) {
|
||||
// invoke lazy loading
|
||||
Customer customer = order.getCustomer();
|
||||
order.getId();
|
||||
customer.getName();
|
||||
customer.getContacts().size();
|
||||
order.getDetails().size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.OrderBy;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestOrderByClear extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.order().asc("orderDate");
|
||||
|
||||
|
||||
OrderBy<Order> orderBy = query.order();
|
||||
assertTrue(orderBy.containsProperty("orderDate"));
|
||||
|
||||
orderBy.clear();
|
||||
assertFalse(orderBy.containsProperty("orderDate"));
|
||||
|
||||
orderBy.asc("shipDate");
|
||||
assertTrue(orderBy.containsProperty("shipDate"));
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertTrue(sql.contains("order by t0.ship_date"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestOrderByOnComplex extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class).order().desc("customer");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
assertTrue(sql.contains("order by t0.kcustomer_id desc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOrderByCase() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.order("case when status=3 then 10 when status=2 then 11 else 99 end");
|
||||
|
||||
List<Order> list = query.findList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t0.id, t0.status, t0.order_date, t0.ship_date, t1.name, t0.cretime, t0.updtime, t0.kcustomer_id from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id order by case when t0.status=3 then 10 when t0.status=2 then 11 else 99 end");
|
||||
assertThat(list).isNotEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.annotation.IgnorePlatform;
|
||||
import io.ebean.annotation.Platform;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.MRole;
|
||||
import org.tests.model.basic.MUser;
|
||||
import org.tests.model.basic.MUserType;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
public class TestOrderByWithDistinct extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testOrderByValidation() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.where()
|
||||
.eq("junk", "blah")
|
||||
.eq("name", "jim")
|
||||
.order("id desc,path.that.does.not.exist,contacts.group.name asc").query();
|
||||
|
||||
Set<String> unknownProperties = query.validate();
|
||||
assertThat(unknownProperties).isNotEmpty();
|
||||
assertThat(unknownProperties).hasSize(2);
|
||||
assertThat(unknownProperties).contains("junk", "path.that.does.not.exist");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@IgnorePlatform({Platform.MYSQL, Platform.MARIADB, Platform.SQLSERVER, Platform.NUODB}) // do not support nulls first/last
|
||||
public void testDistinctOn() {
|
||||
|
||||
MRole role = DB.reference(MRole.class, 1);
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.where()
|
||||
.eq("roles", role)
|
||||
.order("userName asc nulls first").query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = sqlOf(query);
|
||||
if (isPostgres()) {
|
||||
assertThat(sql).contains("select distinct on (t0.user_name, t0.userid) t0.userid,");
|
||||
} else if (isH2()) {
|
||||
assertThat(sql).contains("select distinct t0.userid, t0.user_name, t0.user_type_id from muser t0");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testOrderByWithDistinct() {
|
||||
Query<MUser> query = DB.find(MUser.class);
|
||||
query.findList();
|
||||
|
||||
assertSql(query).doesNotContain("order by");
|
||||
assertSql(query).doesNotContain("select distinct");
|
||||
|
||||
query.setMaxRows(1000);
|
||||
query.findList();
|
||||
if (isH2()) {
|
||||
assertSql(query).contains("from muser t0 limit 1000");
|
||||
}
|
||||
query = DB.find(MUser.class)
|
||||
.where()
|
||||
.eq("roles.roleName", "A")
|
||||
.query();
|
||||
query.findList();
|
||||
assertSql(query).doesNotContain("order by");
|
||||
assertSql(query).contains("select distinct");
|
||||
|
||||
query.setMaxRows(1000);
|
||||
query.findList();
|
||||
if (isH2()) {
|
||||
assertSql(query).contains("where u1.role_name = ? limit 1000");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
/*
|
||||
* Original conversation:
|
||||
* https://groups.google.com/forum/?fromgroups=#!topic/ebean/uuvi1btdCDQ%5B1-25-false%5D
|
||||
*
|
||||
* This test exposes what may be a general problem with columns required by the order by phrase being omitted from the select.
|
||||
* I'm not sure this exposes all causes of the problem.
|
||||
*/
|
||||
|
||||
MUserType ut = new MUserType("md");
|
||||
DB.save(ut);
|
||||
MUser user1 = new MUser("one");
|
||||
user1.setUserType(ut);
|
||||
DB.save(user1);
|
||||
MUser user2 = new MUser("two");
|
||||
user2.setUserType(ut);
|
||||
DB.save(user2);
|
||||
|
||||
MRole roleA = new MRole("A");
|
||||
DB.save(roleA);
|
||||
MRole roleB = new MRole("B");
|
||||
DB.save(roleB);
|
||||
|
||||
user1.addRole(roleA);
|
||||
DB.save(user1);
|
||||
user2.addRole(roleB);
|
||||
DB.save(user2);
|
||||
|
||||
Query<MUser> query = DB.find(MUser.class)
|
||||
.fetch("userType", "name")
|
||||
.where()
|
||||
.eq("roles.roleName", "A")
|
||||
.order("userType.name, userName").query();
|
||||
List<MUser> list = query.findList();
|
||||
|
||||
// select distinct t0.userid c0, t0.user_name c1, t1.id c2, t1.name c3
|
||||
// from muser t0
|
||||
// left join muser_type t1 on t1.id = t0.user_type_id
|
||||
// join mrole_muser u1z_ on u1z_.muser_userid = t0.userid
|
||||
// join mrole u1 on u1.roleid = u1z_.mrole_roleid
|
||||
// where u1.role_name = ?
|
||||
// order by t1.name, t0.user_name; --bind(A)
|
||||
|
||||
assertEquals(1, list.size());
|
||||
assertEquals(user1, list.get(0));
|
||||
String generatedSql = query.getGeneratedSql();
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t1.name, t0.user_name, t0.userid) t0.userid"); // using distinct
|
||||
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.userid"); // using distinct
|
||||
}
|
||||
assertThat(generatedSql).contains("order by t1.name,"); // name in order by
|
||||
assertThat(generatedSql).contains("t1.name");// name in select
|
||||
|
||||
|
||||
// repeat with slight variation, not sure this really produces a different execution path
|
||||
// this problem also manifests when autofetch eliminates properties from the select that aren't used in the objects
|
||||
// still need them to be present for purpose of order by
|
||||
// so here I'm "simulating" a scenario where autofetch has dropped userType.name
|
||||
query = DB.find(MUser.class)
|
||||
.setAutoTune(false)
|
||||
.select("userName")
|
||||
.fetch("userType", "name")
|
||||
.where()
|
||||
.eq("roles.roleName", "A")
|
||||
.order("userType.name").query();
|
||||
list = query.findList();
|
||||
|
||||
assertEquals(1, list.size());
|
||||
assertEquals(user1, list.get(0));
|
||||
|
||||
// select distinct t0.userid c0, t0.user_name c1, t1.id c2, t1.name c3
|
||||
// from muser t0
|
||||
// left join muser_type t1 on t1.id = t0.user_type_id
|
||||
// join mrole_muser u1z_ on u1z_.muser_userid = t0.userid
|
||||
// join mrole u1 on u1.roleid = u1z_.mrole_roleid
|
||||
// where u1.role_name = ?
|
||||
// order by t1.name; --bind(A)
|
||||
|
||||
generatedSql = query.getGeneratedSql();
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t1.name, t0.userid) t0.userid"); // using distinct
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.userid"); // using distinct
|
||||
}
|
||||
assertThat(generatedSql).contains("order by t1.name"); // name in order by
|
||||
assertThat(generatedSql).contains("t1.name");// name in select
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestOrderByWithDistinctTake2 extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testRegex() {
|
||||
String test = "helloasc asc ASC desc DESC boodesc desc ASC";
|
||||
|
||||
test = test.replaceAll("(?i)\\b asc\\b|\\b desc\\b", "");
|
||||
assertEquals("helloasc boodesc", test);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id, name")
|
||||
.where().ilike("contacts.firstName", "R%")
|
||||
.order("name desc").query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String generatedSql = sqlOf(query);
|
||||
|
||||
// select distinct t0.id c0, t0.name
|
||||
// from o_customer t0 join contact u1 on u1.customer_id = t0.id
|
||||
// where lower(u1.first_name) like ?
|
||||
// order by t0.name; --bind(r%)
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t0.name, t0.id) t0.id, t0.name");
|
||||
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.id, t0.name");
|
||||
}
|
||||
assertThat(generatedSql).contains("order by t0.name desc");
|
||||
assertThat(generatedSql).contains("from o_customer t0 join contact u1 on u1.customer_id = t0.id");
|
||||
assertThat(generatedSql).contains("where lower(u1.first_name) like ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithAscAndDesc() {
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id")
|
||||
.where().ilike("contacts.firstName", "R%")
|
||||
.order("name asc,id desc").query();
|
||||
|
||||
query.findList();
|
||||
|
||||
String generatedSql = sqlOf(query);
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t0.name, t0.id) t0.id, t0.name, t0.id");
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.id, t0.name, t0.id");
|
||||
}
|
||||
assertThat(generatedSql).contains("order by t0.name, t0.id desc");
|
||||
assertThat(generatedSql).contains("from o_customer t0 join contact u1 on u1.customer_id = t0.id");
|
||||
assertThat(generatedSql).contains("where lower(u1.first_name) like ");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestOrderByWithFunction extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testWithFunction() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
String length = "length";
|
||||
if (isSqlServer()) {
|
||||
length = "len";
|
||||
}
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).order(length + "(name),name");
|
||||
|
||||
query.findList();
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertTrue(sql.contains("order by " + length + "(t0.name)"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package org.tests.query.orderby;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestOrderByWithMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
checkWithLazyLoadingOnBuiltInMany();
|
||||
checkWithBuiltInManyBasic();
|
||||
checkWithBuiltInMany();
|
||||
checkAppendId();
|
||||
checkNone();
|
||||
checkBoth();
|
||||
checkPrepend();
|
||||
checkAlreadyIncluded();
|
||||
checkAlreadyIncluded2();
|
||||
}
|
||||
|
||||
private void checkWithLazyLoadingOnBuiltInMany() {
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Query<Order> query = DB.find(Order.class);
|
||||
|
||||
// a query that ensures we are going to lazy load on the details
|
||||
List<Order> orders = query.findList();
|
||||
|
||||
for (Order order : orders) {
|
||||
// invoke lazy loading
|
||||
List<OrderDetail> details = order.getDetails();
|
||||
details.size();
|
||||
}
|
||||
|
||||
// first one is the main query and others are lazy loading queries
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertTrue(loggedSql.size() > 1);
|
||||
|
||||
String lazyLoadSql = loggedSql.get(1);
|
||||
// contains the foreign key back to the parent bean (t0.order_id)
|
||||
assertTrue(trimSql(lazyLoadSql, 2).contains("select t0.order_id, t0.id"));
|
||||
assertTrue(lazyLoadSql.contains("order by t0.order_id, t0.id, t0.order_qty, t0.cretime desc"));
|
||||
|
||||
}
|
||||
|
||||
private void checkWithBuiltInManyBasic() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("details");
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
assertTrue(sql.contains("order by t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc"));
|
||||
}
|
||||
|
||||
private void checkWithBuiltInMany() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("details").order().desc("customer.name");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
// t0.id inserted into the middle of the order by
|
||||
assertTrue(sql.contains("order by t1.name desc, t0.id, t2.id asc"));
|
||||
assertTrue(sql.contains("t2.id asc, t2.order_qty asc, t2.cretime desc"));
|
||||
}
|
||||
|
||||
private void checkAppendId() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("shipments").order().desc("customer.name");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
// append the id to ensure ordering of root level objects
|
||||
assertTrue(sql.contains("order by t1.name desc, t0.id"));
|
||||
}
|
||||
|
||||
private void checkNone() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).order().desc("customer.name");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
|
||||
// no need to append id to order by as there is no 'many' included in the
|
||||
// query
|
||||
assertTrue(sql.contains("order by t1.name desc"));
|
||||
assertTrue(!sql.contains("order by t1.name desc,"));
|
||||
}
|
||||
|
||||
private void checkBoth() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("shipments").order()
|
||||
.desc("customer.name, shipments.shipTime");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
// insert id into the middle of the order by
|
||||
assertTrue(sql.contains("order by t1.name, t0.id, t2.ship_time desc"));
|
||||
}
|
||||
|
||||
private void checkPrepend() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("shipments").order()
|
||||
.desc("shipments.shipTime");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
// prepend id in order by
|
||||
assertTrue(sql.contains("order by t0.id, t1.ship_time desc"));
|
||||
}
|
||||
|
||||
private void checkAlreadyIncluded() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("shipments").order()
|
||||
.desc("id, shipments.shipTime");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
// prepend id in order by
|
||||
assertTrue(sql.contains("order by t0.id, t1.ship_time desc"));
|
||||
}
|
||||
|
||||
private void checkAlreadyIncluded2() {
|
||||
|
||||
Query<Order> query = DB.find(Order.class).fetch("shipments").order()
|
||||
.desc("orderDate, id, shipments.shipTime");
|
||||
|
||||
query.findList();
|
||||
|
||||
String sql = query.getGeneratedSql();
|
||||
// prepend id in order by
|
||||
assertTrue(sql.contains("order by t0.order_date, t0.id, t1.ship_time desc"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.converstation.Conversation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestFetchPreference extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void fetchPreference_overrideOrder() {
|
||||
|
||||
Query<Conversation> query = DB.find(Conversation.class)
|
||||
// FetchPreference overrides so participants is joined and messages query joined
|
||||
.fetch("messages")
|
||||
.fetch("participants");
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 1);
|
||||
assertThat(sql).contains(" from c_conversation t0 left join c_participation t1 ");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void fetchPreference_sr() {
|
||||
|
||||
Query<Conversation> query = DB.find(Conversation.class)
|
||||
// without FetchPreference this ToMany would be our first ToMany join
|
||||
// and participants would be query joined
|
||||
.fetch("group.users")
|
||||
.fetch("messages")
|
||||
.fetch("participants");
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 1);
|
||||
|
||||
// join to group (the ToOne part only) and participants (our preferred ToMany path)
|
||||
assertThat(sql).contains(" from c_conversation t0 left join c_group t1 on t1.id = t0.group_id left join c_participation t2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fetchPreference_inOrder() {
|
||||
|
||||
Query<Conversation> query = DB.find(Conversation.class)
|
||||
.fetch("participants")
|
||||
.fetch("messages");
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 1);
|
||||
assertThat(sql).contains(" from c_conversation t0 left join c_participation t1 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fetchQuery_onlyOneJoinCandidate() {
|
||||
|
||||
Query<Conversation> query = DB.find(Conversation.class)
|
||||
.fetch("messages")
|
||||
.fetchQuery("participants");
|
||||
|
||||
query.findList();
|
||||
String sql = sqlOf(query, 1);
|
||||
|
||||
// participants is explicitly a "query join" so we can join to message
|
||||
assertThat(sql).contains(" from c_conversation t0 left join c_message t1 ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Truck;
|
||||
import org.tests.model.basic.Vehicle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestFindIdsWithInheritance extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testQuery() {
|
||||
|
||||
Truck truck = new Truck();
|
||||
truck.setLicenseNumber("TK123");
|
||||
|
||||
DB.save(truck);
|
||||
|
||||
List<Integer> ids = DB.find(Vehicle.class).findIds();
|
||||
assertNotNull(ids);
|
||||
|
||||
DB.delete(truck);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Database;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.tests.model.basic.EBasic;
|
||||
import com.sun.management.HotSpotDiagnosticMXBean;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.management.MBeanServer;
|
||||
import java.io.File;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@SuppressWarnings("restriction")
|
||||
public class TestFindIterateHeapDump extends BaseTestCase {
|
||||
|
||||
// All that heap dumping code from :
|
||||
// https://blogs.oracle.com/sundararajan/entry/programmatically_dumping_heap_from_java
|
||||
private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";
|
||||
|
||||
/**
|
||||
* field to store the hotspot diagnostic MBean
|
||||
*/
|
||||
private static volatile HotSpotDiagnosticMXBean hotspotMBean;
|
||||
|
||||
/**
|
||||
* Ignore this test generally - run it manually against MySQL specifically for Issue #56.
|
||||
*/
|
||||
@Disabled
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
Database server = DB.getDefault();
|
||||
|
||||
// Transaction transaction = server.beginTransaction();
|
||||
// try {
|
||||
// transaction.setBatchMode(true);
|
||||
// transaction.setBatchSize(20);
|
||||
// for (int i = 0; i < 20000; i++) {
|
||||
// EBasic dumbModel = new EBasic();
|
||||
// dumbModel.setName("Goodbye now");
|
||||
// server.save(dumbModel);
|
||||
// }
|
||||
// transaction.commit();
|
||||
//
|
||||
// } finally {
|
||||
// transaction.end();
|
||||
// }
|
||||
//
|
||||
// if (true) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// Intentionally not iterating through the iterator to
|
||||
|
||||
final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
server.find(EBasic.class)
|
||||
.findEach(bean -> {
|
||||
|
||||
int count = counter.incrementAndGet();
|
||||
if (count == 1) {
|
||||
dumpHeap("heap-dump13-initial.snapshot", true);
|
||||
}
|
||||
});
|
||||
|
||||
// try {
|
||||
// while (iterate.hasNext()) {
|
||||
// EBasic eBasic = iterate.next();
|
||||
// eBasic.getDescription();
|
||||
// }
|
||||
// } finally {
|
||||
// iterate.close();
|
||||
// }
|
||||
|
||||
String fileName = "heap-dump13.snapshot";
|
||||
|
||||
File file = new File(fileName);
|
||||
if (file.exists())
|
||||
file.delete();
|
||||
|
||||
dumpHeap(fileName, true);
|
||||
}
|
||||
|
||||
static void dumpHeap(String fileName, boolean live) {
|
||||
// initialize hotspot diagnostic MBean
|
||||
initHotspotMBean();
|
||||
try {
|
||||
hotspotMBean.dumpHeap(fileName, live);
|
||||
} catch (RuntimeException re) {
|
||||
throw re;
|
||||
} catch (Exception exp) {
|
||||
throw new RuntimeException(exp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* initialize the hotspot diagnostic MBean field
|
||||
*/
|
||||
private static void initHotspotMBean() {
|
||||
if (hotspotMBean == null) {
|
||||
synchronized (TestFindIterateHeapDump.class) {
|
||||
if (hotspotMBean == null) {
|
||||
hotspotMBean = getHotspotMBean();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get the hotspot diagnostic MBean from the ManagementFactory.
|
||||
*/
|
||||
private static HotSpotDiagnosticMXBean getHotspotMBean() {
|
||||
try {
|
||||
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
|
||||
return ManagementFactory.newPlatformMXBeanProxy(server, HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
|
||||
} catch (RuntimeException re) {
|
||||
throw re;
|
||||
} catch (Exception exp) {
|
||||
throw new RuntimeException(exp);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.BeanState;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestFindPartialWithConstructorSetFields extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> list = DB.find(Order.class)
|
||||
.setLazyLoadBatchSize(100)
|
||||
.setUseCache(false)
|
||||
.select("shipDate")
|
||||
.findList();
|
||||
|
||||
assertTrue(list.size() > 2);
|
||||
|
||||
// assert first bean is partially loaded
|
||||
Order order0 = list.get(0);
|
||||
BeanState beanState = DB.beanState(order0);
|
||||
Set<String> loadedProps = beanState.loadedProps();
|
||||
assertTrue(loadedProps.contains("shipDate"));
|
||||
assertFalse(loadedProps.contains("status"));
|
||||
assertFalse(loadedProps.contains("orderDate"));
|
||||
|
||||
// invoke lazy loading
|
||||
order0.getStatus();
|
||||
order0.getOrderDate();
|
||||
|
||||
// assert that these beans are fully loaded
|
||||
for (int i = 1; i < list.size(); i++) {
|
||||
Order order1 = list.get(1);
|
||||
beanState = DB.beanState(order1);
|
||||
loadedProps = beanState.loadedProps();
|
||||
assertNull(loadedProps);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.DB;
|
||||
import io.ebean.TransactionalTestCase;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.MNonEnum;
|
||||
import org.tests.model.basic.MNonUpdPropEntity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestFindWhereUsingEnumerated extends TransactionalTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
MNonUpdPropEntity e = new MNonUpdPropEntity();
|
||||
e.setNonEnum(MNonEnum.END);
|
||||
e.setName("TheNonEnumIsEnd");
|
||||
e.setNote("note");
|
||||
|
||||
DB.save(e);
|
||||
|
||||
MNonUpdPropEntity unique = DB.find(MNonUpdPropEntity.class).where()
|
||||
.eq("nonEnum", MNonEnum.END)
|
||||
.eq("name", "TheNonEnumIsEnd")
|
||||
.findOne();
|
||||
|
||||
assertThat(unique).isNotNull();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Database;
|
||||
import io.ebean.ExpressionList;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestFormulaWithFindCount extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testFindCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Database server = DB.getDefault();
|
||||
|
||||
|
||||
ExpressionList<Order> ex = server.find(Order.class).select("id, status ,totalAmount").where().gt("totalAmount", 1d);
|
||||
List<Order> list = ex.findList();
|
||||
|
||||
for (Order order : list) {
|
||||
Double amount = order.getTotalAmount();
|
||||
assertNotNull(amount);
|
||||
}
|
||||
|
||||
ExpressionList<Order> expressionList = server.find(Order.class).where().gt("totalAmount", 1d);
|
||||
int rowCount = expressionList.findCount();
|
||||
assertEquals(list.size(), rowCount);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.DB;
|
||||
import io.ebean.TransactionalTestCase;
|
||||
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestLikeEscaping extends TransactionalTestCase {
|
||||
|
||||
|
||||
@Test
|
||||
public void testLikeEscaping() {
|
||||
// Mysql, PgSql, H2 special chars: "_" "%"
|
||||
// MsSql special chars: "_" "%" "[" AND different Quoting!
|
||||
DB.save(ResetBasicData.createCustomer("Paul % Percentage", "*Star", "[none]", 0, null));
|
||||
DB.save(ResetBasicData.createCustomer("(none)", "More * Star", "[none]", 0, null));
|
||||
|
||||
DB.save(ResetBasicData.createCustomer("Paul %% Doublepercentage", "|Pipeway", "[other]", 1, null));
|
||||
DB.save(ResetBasicData.createCustomer("_Udo Underscore", "|Pipeway", "[other]", 1, null));
|
||||
|
||||
DB.save(ResetBasicData.createCustomer("Bodo \\ backslash", "\\BS", "[other]", 1, null));
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().contains("name", "Paul %%").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().contains("name", "o \\ b").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().contains("name", "o \\\\ b").findCount()
|
||||
).isEqualTo(0);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("name", "_").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("name", "_u").findCount()
|
||||
).isEqualTo(0);
|
||||
}
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().istartsWith("name", "_U").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
if (isPlatformCaseSensitive()) {
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("shippingAddress.line1", "|p").findCount()
|
||||
).isEqualTo(0);
|
||||
}
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("shippingAddress.line1", "|P").findCount()
|
||||
).isEqualTo(2);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("shippingAddress.line1", "\\B").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().endsWith("billingAddress.line1", "]").findCount()
|
||||
).isEqualTo(5);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().endsWith("billingAddress.line1", "[none]").findCount()
|
||||
).isEqualTo(2);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("billingAddress.line1", "[none]").findCount()
|
||||
).isEqualTo(2);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().contains("billingAddress.line1", "[none]").findCount()
|
||||
).isEqualTo(2);
|
||||
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().contains("shippingAddress.line1", "*").findCount()
|
||||
).isEqualTo(2);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().startsWith("shippingAddress.line1", "*").findCount()
|
||||
).isEqualTo(1);
|
||||
|
||||
assertThat(DB.find(Customer.class)
|
||||
.where().endsWith("shippingAddress.line1", "*").findCount()
|
||||
).isEqualTo(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.api.SpiQuery;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocMany;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestManyLazyLoadingQuery extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
SpiEbeanServer server = (SpiEbeanServer) DB.getDefault();
|
||||
|
||||
BeanDescriptor<Order> descOrder = server.descriptor(Order.class);
|
||||
BeanPropertyAssocMany<?> beanProperty = (BeanPropertyAssocMany<?>) descOrder.beanProperty("details");
|
||||
|
||||
List<Object> parentIds = new ArrayList<>();
|
||||
parentIds.add(1);
|
||||
|
||||
|
||||
List<Order> orders =
|
||||
DB.find(Order.class)
|
||||
.where().lt("id", 4)
|
||||
.findList();
|
||||
|
||||
for (Order order : orders) {
|
||||
List<OrderDetail> details = order.getDetails();
|
||||
System.out.println(details.size());
|
||||
}
|
||||
|
||||
|
||||
// start transaction to keep PC going to lazy query
|
||||
DB.beginTransaction();
|
||||
try {
|
||||
DB.find(Order.class, 1);
|
||||
|
||||
SpiQuery<?> query0 = (SpiQuery<?>) DB.find(OrderDetail.class);
|
||||
|
||||
query0.setLazyLoadForParents(beanProperty);
|
||||
|
||||
beanProperty.addWhereParentIdIn(query0, parentIds, false);
|
||||
|
||||
query0.findList();
|
||||
assertThat(query0.getGeneratedSql()).contains(" from o_order_detail t0 where (t0.order_id) ");
|
||||
platformAssertIn(query0.getGeneratedSql(), "where (t0.order_id)");
|
||||
|
||||
} finally {
|
||||
DB.endTransaction();
|
||||
}
|
||||
|
||||
List<OrderDetail> details = DB.find(OrderDetail.class)
|
||||
.where().eq("order.id", 1)
|
||||
.findList();
|
||||
|
||||
for (OrderDetail orderDetail : details) {
|
||||
System.out.println(orderDetail);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.basic.MRole;
|
||||
import org.tests.model.basic.MUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestManyToManyLazyLoading extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
createData();
|
||||
|
||||
List<MUser> users = DB.find(MUser.class).findList();
|
||||
|
||||
for (MUser user : users) {
|
||||
List<MRole> roles = user.getRoles();
|
||||
roles.size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void createData() {
|
||||
MRole r0 = new MRole("r0");
|
||||
MRole r1 = new MRole("r1");
|
||||
|
||||
DB.save(r0);
|
||||
DB.save(r1);
|
||||
|
||||
MUser u0 = new MUser("usr0");
|
||||
u0.addRole(r0);
|
||||
u0.addRole(r1);
|
||||
|
||||
DB.save(u0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.map.MpRole;
|
||||
import org.tests.model.map.MpUser;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
public class TestOneToManyAsMap extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
MpUser u = new MpUser();
|
||||
DB.save(u);
|
||||
|
||||
MpUser u2 = DB.find(MpUser.class, u.getId());
|
||||
assertNotNull(u2);
|
||||
|
||||
u2.setName("Charlie Brown");
|
||||
MpRole ourl = new MpRole();
|
||||
ourl.setOrganizationId(47L);
|
||||
u2.getRoles().put("one", ourl);
|
||||
DB.save(u2);
|
||||
|
||||
MpUser u3 = DB.find(MpUser.class, u.getId());
|
||||
assertEquals("Charlie Brown", u3.getName());
|
||||
|
||||
Map<String, MpRole> listMap = u3.getRoles();
|
||||
assertEquals(1, listMap.size());
|
||||
|
||||
MpRole mpRole = listMap.get("one");
|
||||
assertNotNull(mpRole);
|
||||
assertEquals(Long.valueOf(47L), mpRole.getOrganizationId());
|
||||
assertEquals("one", mpRole.getCode());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void json() {
|
||||
|
||||
Map<String,MpRole> roles = new LinkedHashMap<>();
|
||||
roles.put("r1", newRole(1L, "r1"));
|
||||
roles.put("r2", newRole(2L, "r2"));
|
||||
|
||||
MpUser u = new MpUser();
|
||||
u.setName("myName");
|
||||
u.setRoles(roles);
|
||||
|
||||
final String asJson = DB.json().toJson(u);
|
||||
|
||||
assertThat(asJson).isEqualTo("{\"name\":\"myName\",\"roles\":[{\"id\":1,\"code\":\"r1\"},{\"id\":2,\"code\":\"r2\"}]}");
|
||||
|
||||
final MpUser bean = DB.json().toBean(MpUser.class, asJson);
|
||||
assertThat(bean.getName()).isEqualTo("myName");
|
||||
final Map<String, MpRole> beanRoles = bean.getRoles();
|
||||
assertThat(beanRoles.get("r1").getId()).isEqualTo(1L);
|
||||
assertThat(beanRoles.get("r1").getCode()).isEqualTo("r1");
|
||||
assertThat(beanRoles.get("r2").getId()).isEqualTo(2L);
|
||||
assertThat(beanRoles.get("r2").getCode()).isEqualTo("r2");
|
||||
}
|
||||
|
||||
private MpRole newRole(Long id, String code) {
|
||||
MpRole role = new MpRole();
|
||||
role.setId(id);
|
||||
role.setCode(code);
|
||||
return role;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.converstation.Conversation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestQueryConversationRowCount extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
//"find conversation where club = :clubId and ( ( isPublic = :false and participants.user.id = :userId ) or isPublic = :true ) order by createdAt desc ";
|
||||
//"find conversation where groupId = :groupId and ( ( open = :false and participants.user.id = :userId ) or open = :true ) order by whenCreated desc ";
|
||||
|
||||
Long groupId = 1L;
|
||||
Long userId = 1L;
|
||||
|
||||
Query<Conversation> query = DB.find(Conversation.class)
|
||||
.where().eq("group.id", groupId)
|
||||
.disjunction()
|
||||
.conjunction()
|
||||
.eq("open", false).eq("participants.user.id", userId)
|
||||
.endJunction()
|
||||
.eq("open", true)
|
||||
.endJunction()
|
||||
.order("whenCreated desc").query();
|
||||
|
||||
query.findList();
|
||||
String generatedSql = sqlOf(query, 1);
|
||||
|
||||
// select distinct t0.id c0, t0.title c1, t0.open c2, t0.version c3, t0.when_created c4, t0.when_updated c5, t0.group_id c6, t0.when_created
|
||||
// from c_conversation t0
|
||||
// left join c_participation u1 on u1.conversation_id = t0.id
|
||||
// where t0.group_id = ? and ((t0.open = ? and u1.user_id = ? ) or t0.open = ? )
|
||||
// order by t0.when_created desc;
|
||||
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t0.when_created, t0.id) t0.id, t0.title, t0.isopen");
|
||||
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.id, t0.title, t0.isopen");
|
||||
}
|
||||
assertThat(generatedSql).contains("left join c_participation u1 on u1.conversation_id = t0.id");
|
||||
assertThat(generatedSql).contains("where t0.group_id = ? and ((t0.isopen = ? and u1.user_id = ?) or t0.isopen = ?)");
|
||||
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
query.findCount();
|
||||
|
||||
// select count(*) from (
|
||||
// select distinct t0.id c0
|
||||
// from c_conversation t0
|
||||
// left join c_participation u1 on u1.conversation_id = t0.id
|
||||
// where t0.group_id = ? and ((t0.open = ? and u1.user_id = ? ) or t0.open = ? )
|
||||
// ); --bind(1,true,1,true)
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertEquals(1, loggedSql.size());
|
||||
|
||||
String countSql = trimSql(loggedSql.get(0), 0);
|
||||
assertThat(countSql).contains("select count(*) from ( select distinct t0.id from c_conversation t0 left join c_participation u1 on u1.conversation_id = t0.id where t0.group_id = ? and ((t0.isopen = ? and u1.user_id = ?) or t0.isopen = ?))");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebean.bean.EntityBeanIntercept;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestQueryDistinct extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("name");
|
||||
|
||||
List<Customer> customers = query.findList();
|
||||
|
||||
String generatedSql = sqlOf(query);
|
||||
assertThat(generatedSql).contains("select distinct t0.name from o_customer t0");
|
||||
|
||||
for (Customer customer : customers) {
|
||||
|
||||
EntityBeanIntercept ebi = ((EntityBean) customer)._ebean_getIntercept();
|
||||
assertTrue(ebi.isDisableLazyLoad());
|
||||
assertNull(ebi.getPersistenceContext());
|
||||
|
||||
// lazy loading disabled
|
||||
assertNull(customer.getId());
|
||||
assertNull(customer.getAnniversary());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_onWhere() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.where().setDistinct(true)
|
||||
.select("name");
|
||||
|
||||
query.findList();
|
||||
|
||||
String generatedSql = sqlOf(query);
|
||||
assertThat(generatedSql).contains("select distinct t0.name from o_customer t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDistinctStatus() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("status")
|
||||
.where().isNotNull("status").query();
|
||||
|
||||
List<Customer> customers = query.findList();
|
||||
|
||||
String generatedSql = sqlOf(query);
|
||||
assertThat(generatedSql).contains("select distinct t0.status from o_customer t0");
|
||||
|
||||
for (Customer customer : customers) {
|
||||
|
||||
assertNotNull(customer.getStatus());
|
||||
|
||||
// lazy loading disabled
|
||||
assertNull(customer.getId());
|
||||
assertNull(customer.getAnniversary());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPagingQuery_expect_doesNotAddOrderBy() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setMaxRows(10)
|
||||
.setDistinct(true)
|
||||
.select("name");
|
||||
|
||||
query.findList();
|
||||
|
||||
if (isH2() || isPostgres()) {
|
||||
String generatedSql = sqlOf(query);
|
||||
assertThat(generatedSql).contains("select distinct t0.name from o_customer t0 limit 10");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQueryRawExpressionMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Integer quantity = 1;
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.where().raw("details.orderQty = ?", quantity)
|
||||
.query();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
query.findCount();
|
||||
List<String> sql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(trimSql(sql.get(0), 1)).contains("select count(*) from ( select distinct t0.id from o_order t0 left join o_order_detail t1 on t1.order_id = t0.id and t1.id > 0 where t1.order_qty = ?)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestQueryRowCountWithMany extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Long productId = 1L;
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetch("details")
|
||||
.where().eq("details.product.id", productId)
|
||||
.order("cretime asc").query();
|
||||
|
||||
List<Order> list = query.findList();
|
||||
|
||||
// select distinct t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t2.name c4, t0.cretime c5, t0.updtime c6, t0.kcustomer_id c7,
|
||||
// t1.id c8, t1.order_qty c9, t1.ship_qty c10, t1.unit_price c11, t1.cretime c12, t1.updtime c13, t1.order_id c14, t1.product_id c15, t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime
|
||||
// from o_order t0
|
||||
// join o_customer t2 on t2.id = t0.kcustomer_id
|
||||
// left join o_order_detail t1 on t1.order_id = t0.id
|
||||
// join o_order_detail u1 on u1.order_id = t0.id
|
||||
// where t1.id > 0 and u1.product_id = ?
|
||||
// order by t0.cretime, t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc; --bind(1)
|
||||
|
||||
String generatedSql = sqlOf(query, 1);
|
||||
if (isPostgres()) {
|
||||
assertThat(generatedSql).contains("select distinct on (t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime) t0.id, t0.status,"); // need the distinct
|
||||
|
||||
} else {
|
||||
assertThat(generatedSql).contains("select distinct t0.id, t0.status,"); // need the distinct
|
||||
}
|
||||
assertThat(generatedSql).contains("left join o_order_detail t1 on t1.order_id = t0.id"); //fetch join
|
||||
assertThat(generatedSql).contains("join o_order_detail u1 on u1.order_id = t0.id"); //predicate join
|
||||
assertThat(generatedSql).contains(" u1.product_id = ?"); // u1 as predicate alias
|
||||
assertThat(generatedSql).contains(" order by t0.cretime");
|
||||
|
||||
|
||||
int rowCount = query.findCount();
|
||||
|
||||
// select count(*) from o_order t0
|
||||
// left join o_order_detail t1 on t1.order_id = t0.id
|
||||
// where t1.product_id = ? ; --bind(1)
|
||||
|
||||
// select count(*) from (
|
||||
// select distinct t0.id c0 from o_order t0 join o_order_detail u1 on u1.order_id = t0.id where
|
||||
// u1.product_id = ?
|
||||
// ); --bind(1)
|
||||
|
||||
List<String> sqlLogged = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(list.size(), rowCount);
|
||||
assertEquals(2, sqlLogged.size());
|
||||
assertThat(trimSql(sqlLogged.get(1), 1)).contains(
|
||||
"select count(*) from ( select distinct t0.id from o_order t0 join o_order_detail u1 on u1.order_id = t0.id and u1.id > 0 where u1.product_id = ?)");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testWithFirstRowsMaxRows() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Long productId = 1L;
|
||||
|
||||
Query<Order> query = DB.find(Order.class)
|
||||
.fetch("details")
|
||||
.where().eq("details.product.id", productId)
|
||||
.setFirstRow(2)
|
||||
.setMaxRows(20)
|
||||
.orderBy("cretime asc")
|
||||
.query();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
query.findCount();
|
||||
|
||||
List<String> sqlLogged = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(1, sqlLogged.size());
|
||||
assertThat(trimSql(sqlLogged.get(0), 1)).contains("select count(*) from ( select distinct t0.id from o_order t0 join o_order_detail u1 on u1.order_id = t0.id and u1.id > 0 where u1.product_id = ?)");
|
||||
|
||||
query.findList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.CountDistinctOrder;
|
||||
import io.ebean.CountedValue;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Query;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.inherit.ChildA;
|
||||
import org.tests.inherit.Data;
|
||||
import org.tests.inherit.EUncle;
|
||||
import org.tests.lazyforeignkeys.MainEntity;
|
||||
import org.tests.lazyforeignkeys.MainEntityRelation;
|
||||
import org.tests.model.basic.Contact;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.model.basic.VwCustomer;
|
||||
import org.tests.o2m.OmBasicParent;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestQuerySingleAttribute extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesTwoToMany() {
|
||||
ResetBasicData.reset();
|
||||
// Query without ors with equals causing joins, only one Customer with name Rob exists
|
||||
Query<Customer> query0 = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where()
|
||||
.eq("name", "Rob")
|
||||
.query();
|
||||
|
||||
CountedValue<String> robs0 = (CountedValue<String>) query0.findSingleAttributeList().get(0);
|
||||
assertThat(robs0.getValue()).isEqualTo("Rob");
|
||||
assertThat(robs0.getCount()).isEqualTo(1);
|
||||
|
||||
// Query with or with equals causing joins
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where()
|
||||
.eq("name", "Rob")
|
||||
.or()
|
||||
.eq("orders.status", Order.Status.NEW)
|
||||
.eq("contacts.firstName", "Fred1")
|
||||
.endOr()
|
||||
.query();
|
||||
|
||||
CountedValue<String> robs = (CountedValue<String>) query.findSingleAttributeList().get(0);
|
||||
assertThat(robs.getValue()).isEqualTo("Rob");
|
||||
// only one Customer named rob exists, but 7 is returned for the amount of Customers named Rob
|
||||
assertThat(robs.getCount()).isEqualTo(1);
|
||||
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*) " +
|
||||
"from (select distinct t0.id, t0.name as attribute_ " +
|
||||
"from o_customer t0 left join contact u1 on u1.customer_id = t0.id left join o_order u2 on u2.kcustomer_id = t0.id and u2.order_date is not null " +
|
||||
"where t0.name = ? and (u2.status = ? or u1.first_name = ?)) r1 " +
|
||||
"group by r1.attribute_ " +
|
||||
"order by count(*) desc, r1.attribute_");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exampleUsage() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<String> names =
|
||||
DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("name")
|
||||
.where().eq("status", Customer.Status.NEW).startsWith("name", "R")
|
||||
.order().asc("name")
|
||||
.setMaxRows(100)
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(names).isNotNull();
|
||||
for (String name : names) {
|
||||
assertThat(name).startsWith("R");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exampleUsage_otherType() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Date> dates =
|
||||
DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("anniversary")
|
||||
.where().isNotNull("anniversary")
|
||||
.order().asc("anniversary")
|
||||
.findSingleAttributeList();
|
||||
|
||||
assertThat(dates).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withOrderBy() {
|
||||
|
||||
Query<Customer> query =
|
||||
DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("name")
|
||||
.where().eq("status", Customer.Status.NEW)
|
||||
.orderBy().asc("name");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.name from o_customer t0 where t0.status = ? order by t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basic() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).select("name");
|
||||
|
||||
List<String> names = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t0.name from o_customer t0");
|
||||
assertThat(names).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttribute() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.where().eq("id", 1).query();
|
||||
|
||||
String name = query.findSingleAttribute();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t0.name from o_customer t0");
|
||||
assertThat(name).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributeList_with_join_column() {
|
||||
ResetBasicData.reset();
|
||||
Query<MainEntityRelation> query = DB.find(MainEntityRelation.class)
|
||||
.fetch("entity1", "attr1")
|
||||
.setDistinct(true)
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
|
||||
List<CountedValue<String>> attr1list = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select distinct t0.id, t0.id1, t1.attr1 as attribute_ from main_entity_relation t0 left join main_entity t1 on t1.id = t0.id1) r1"
|
||||
+ " group by r1.attribute_"
|
||||
+ " order by count(*) desc, r1.attribute_"); // sub-query select clause includes t0.id1
|
||||
assertThat(attr1list).isNotNull();
|
||||
assertThat(attr1list).hasSize(2);
|
||||
assertThat(attr1list.get(0).getValue()).isEqualTo("a1");
|
||||
assertThat(attr1list.get(0).getCount()).isEqualTo(2l);
|
||||
assertThat(attr1list.get(1).getValue()).isEqualTo("a2");
|
||||
assertThat(attr1list.get(1).getCount()).isEqualTo(1l);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesVariousSelection1() {
|
||||
Query<MainEntityRelation> query = DB.find(MainEntityRelation.class)
|
||||
.fetch("entity1", "attr1")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select t0.id1, t1.attr1 as attribute_ from main_entity_relation t0 left join main_entity t1 on t1.id = t0.id1) r1"
|
||||
+ " group by r1.attribute_"
|
||||
+ " order by count(*) desc, r1.attribute_"); // sub-query select clause includes t0.id1
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesVariousSelection2() {
|
||||
Query<MainEntityRelation> query = DB.find(MainEntityRelation.class)
|
||||
.select("attr1")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select t0.attr1 as attribute_ from main_entity_relation t0) r1"
|
||||
+ " group by r1.attribute_"
|
||||
+ " order by count(*) desc, r1.attribute_");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesVariousSelection3() {
|
||||
Query<MainEntityRelation> query = DB.find(MainEntityRelation.class)
|
||||
.select("id")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select t0.id as attribute_ from main_entity_relation t0) r1"
|
||||
+ " group by r1.attribute_"
|
||||
+ " order by count(*) desc, r1.attribute_");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesVariousSelection4() {
|
||||
Query<MainEntityRelation> query = DB.find(MainEntityRelation.class)
|
||||
.fetch("entity1", "id")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select t0.id1, t1.id as attribute_ from main_entity_relation t0 left join main_entity t1 on t1.id = t0.id1) r1"
|
||||
+ " group by r1.attribute_"
|
||||
+ " order by count(*) desc, r1.attribute_"); // sub-query select clause includes t0.id1,
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttributesVariousSelection5() {
|
||||
Query<OmBasicParent> query = DB.find(OmBasicParent.class)
|
||||
.fetch("children", "name")
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.where().query();
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*)"
|
||||
+ " from (select t1.name as attribute_ from om_basic_parent t0 left join om_basic_child t1 on t1.parent_id = t0.id) r1 "
|
||||
+ "group by r1.attribute_ order by count(*) desc, r1.attribute_"); // sub-query select clause includes t1.id,
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttribute_with_aggregate() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("max(name)")
|
||||
.where().gt("id", 1).query();
|
||||
|
||||
String name = query.findSingleAttribute();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select max(t0.name) from o_customer t0");
|
||||
assertThat(name).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleAttribute_viaExpression() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String name = DB.find(Customer.class)
|
||||
.select("name")
|
||||
.where().eq("id", 1)
|
||||
.findSingleAttribute();
|
||||
|
||||
assertThat(name).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctAndWhere() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("name")
|
||||
.where().eq("status", Customer.Status.NEW)
|
||||
.query();
|
||||
|
||||
List<String> names = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.name from o_customer t0 where t0.status = ?");
|
||||
assertThat(names).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWhereWithJoin() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("name")
|
||||
.where().eq("status", Customer.Status.NEW)
|
||||
.istartsWith("billingAddress.city", "auck")
|
||||
.query();
|
||||
|
||||
List<String> names = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.name from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and lower(t1.city) like ");
|
||||
assertThat(names).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void queryPlan_expect_differentPlans() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class).select("name");
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select t0.name from o_customer t0");
|
||||
|
||||
Query<Customer> query2 = DB.find(Customer.class).select("name");
|
||||
query2.findList();
|
||||
assertThat(sqlOf(query2, 1)).contains("select t0.id, t0.name from o_customer t0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctOnIdProperty() {
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.select("id")
|
||||
.setMaxRows(100);
|
||||
|
||||
List<String> ids = query.findSingleAttributeList();
|
||||
if (isSqlServer()) {
|
||||
assertThat(sqlOf(query)).contains("select distinct top 100 t0.id from o_customer t0");
|
||||
} else if (isOracle()) {
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.id from o_customer t0 fetch next 100 rows only");
|
||||
} else {
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.id from o_customer t0 limit 100");
|
||||
}
|
||||
assertThat(ids).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.setDistinct(true)
|
||||
.fetch("billingAddress", "city");
|
||||
|
||||
List<String> cities = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.city from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id");
|
||||
assertThat(cities).contains("Auckland").containsNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer.billingAddress", "city");
|
||||
|
||||
List<String> cities = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t2.city from contact t0 join o_customer t1 on t1.id = t0.customer_id left join o_address t2 on t2.id = t1.billing_address_id");
|
||||
assertThat(cities).contains("Auckland").containsNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctSelectOnInheritedBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<ChildA> query = DB.find(ChildA.class)
|
||||
.setDistinct(true)
|
||||
.select("more");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.more from rawinherit_parent t0 where t0.type = 'A'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctFetchManyToOneInheritedBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<EUncle> query = DB.find(EUncle.class)
|
||||
.setDistinct(true)
|
||||
.fetch("parent", "more");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.more from rawinherit_uncle t0 join rawinherit_parent t1 on t1.id = t0.parent_id");
|
||||
|
||||
}
|
||||
|
||||
// hmm - same problem when not using distinct
|
||||
@Test
|
||||
public void findSingleOnIdProperty() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.select("id")
|
||||
.setMaxRows(100);
|
||||
|
||||
List<String> ids = query.findSingleAttributeList();
|
||||
if (isSqlServer()) {
|
||||
assertThat(sqlOf(query)).contains("select top 100 t0.id from o_customer t0");
|
||||
} else if (isOracle()) {
|
||||
assertThat(sqlOf(query)).contains("fetch next 100 rows only");
|
||||
} else {
|
||||
assertThat(sqlOf(query)).contains("select t0.id from o_customer t0 limit 100");
|
||||
}
|
||||
assertThat(ids).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleWithFetch() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = DB.find(Customer.class)
|
||||
.fetch("billingAddress", "city");
|
||||
|
||||
List<String> cities = query.findSingleAttributeList();
|
||||
|
||||
assertThat(cities).contains("Auckland").containsNull();
|
||||
assertThat(sqlOf(query)).contains("select t1.city from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleWithFetchOnView() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<VwCustomer> query = DB.find(VwCustomer.class)
|
||||
.fetch("billingAddress", "city");
|
||||
|
||||
List<String> cities = query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t1.city from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id");
|
||||
assertThat(cities).contains("Auckland").containsNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleSelectOnInheritedBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<ChildA> query = DB.find(ChildA.class)
|
||||
.select("more");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select t0.more from rawinherit_parent t0 where t0.type = 'A'");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleFetchManyToOneInheritedBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<EUncle> query = DB.find(EUncle.class)
|
||||
.fetch("parent", "more");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t1.more from rawinherit_uncle t0 join rawinherit_parent t1 on t1.id = t0.parent_id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findSingleFetchManyToOneInheritedBean_viaEbeanServer() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<EUncle> query = DB.find(EUncle.class)
|
||||
.fetch("parent", "more");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select t1.more from rawinherit_uncle t0 join rawinherit_parent t1 on t1.id = t0.parent_id");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled //don't know if ebean can handle this on many to many, as this means that the cartesian product is generated
|
||||
public void distinctFetchManyToManyInheritedBean() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Data> query = DB.find(Data.class)
|
||||
.setDistinct(true)
|
||||
.fetch("parents", "more")
|
||||
.setMaxRows(100);
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.more from rawinherit_data t0 "
|
||||
+ "join rawinherit_parent_rawinherit_data t1 on t0.id = t1.rawinherit_data_id "
|
||||
+ "join parent t2 on t1.rawinherit_parent_id = t2.id");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithOrderByPk() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.select("customer")
|
||||
.order().desc("customer");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.customer_id from contact t0 order by t0.customer_id desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithOrderByPkWithId() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.select("customer.id")
|
||||
.order().desc("customer.id");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t0.customer_id from contact t0 order by t0.customer_id desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetchOrderByPk() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer", "billingAddress")
|
||||
.order().desc("customer.billingAddress");
|
||||
|
||||
query.findSingleAttributeList();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.billing_address_id from contact t0 join o_customer t1 on t1.id = t0.customer_id order by t1.billing_address_id desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithOrderByPkAndQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer", "billingAddress")
|
||||
.where().eq("customer.billingAddress.city", "Auckland")
|
||||
.order().desc("customer.billingAddress.id");
|
||||
|
||||
List<Integer> ids = query.findSingleAttributeList();
|
||||
assertThat(ids).isNotEmpty();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.billing_address_id from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.billing_address_id "
|
||||
+ "where t2.city = ? "
|
||||
+ "order by t1.billing_address_id desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetchOrderByPkAndQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer", "billingAddress")
|
||||
.where().eq("customer.billingAddress.city", "Auckland")
|
||||
.order().desc("customer.billingAddress.id");
|
||||
|
||||
List<Short> ids = query.findSingleAttributeList();
|
||||
assertThat(ids).isNotEmpty();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.billing_address_id from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.billing_address_id "
|
||||
+ "where t2.city = ? "
|
||||
+ "order by t1.billing_address_id desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetchOrderByPkAndQuery3() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer", "billingAddress")
|
||||
.where().eq("customer.billingAddress.city", "Auckland")
|
||||
.order().desc("customer.billingAddress.id");
|
||||
|
||||
List<Integer> ids = query.findSingleAttributeList();
|
||||
assertThat(ids).isNotEmpty();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.billing_address_id from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.billing_address_id "
|
||||
+ "where t2.city = ? "
|
||||
+ "order by t1.billing_address");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetchOrderByPkAndQuery2() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.setDistinct(true)
|
||||
.fetch("customer", "billingAddress")
|
||||
.where().eq("customer.shippingAddress.city", "Auckland") // query on shippingAddress
|
||||
.order().desc("customer.billingAddress.id");
|
||||
|
||||
List<Short> ids = query.findSingleAttributeList();
|
||||
assertThat(ids).isNotEmpty();
|
||||
|
||||
assertThat(sqlOf(query)).contains("select distinct t1.billing_address_id from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.shipping_address_id "
|
||||
+ "where t2.city = ? "
|
||||
+ "order by t1.billing_address_id desc");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctWithCascadedFetchCount() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
|
||||
int count = DB.find(Contact.class).findCount();
|
||||
assertThat(count).isGreaterThanOrEqualTo(12);
|
||||
|
||||
Query<Contact> query = DB.find(Contact.class)
|
||||
.select("firstName");
|
||||
|
||||
List<CountedValue<Object>> list1 = query
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_ASC)
|
||||
|
||||
.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*) from ("
|
||||
+ "select t0.first_name as attribute_ from contact t0"
|
||||
+ ") r1 group by r1.attribute_ order by r1.attribute_");
|
||||
assertThat(list1.get(0)).isInstanceOf(CountedValue.class);
|
||||
// FIXME: These asserts will fail, because other tests will interfere. see #1298
|
||||
//assertThat(list1.toString()).isEqualTo("[3: Bugs1, 1: Fiona, 3: Fred1, 1: Jack, 3: Jim1, 1: Tracy]");
|
||||
|
||||
|
||||
query = DB.find(Contact.class).select("firstName");
|
||||
list1 = query
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_DESC)
|
||||
.findSingleAttributeList();
|
||||
assertThat(list1.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list1.toString()).isEqualTo("[1: Tracy, 3: Jim1, 1: Jack, 3: Fred1, 1: Fiona, 3: Bugs1]");
|
||||
|
||||
query = DB.find(Contact.class).select("firstName");
|
||||
list1 = query
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_ASC_ATTR_DESC)
|
||||
.findSingleAttributeList();
|
||||
assertThat(list1.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list1.toString()).isEqualTo("[1: Tracy, 1: Jack, 1: Fiona, 3: Jim1, 3: Fred1, 3: Bugs1]");
|
||||
|
||||
query = DB.find(Contact.class).fetch("customer.shippingAddress", "line1");//("firstName")
|
||||
List<CountedValue<Object>> list2 = query
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_ASC)
|
||||
.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*) from ("
|
||||
+ "select t2.line_1 as attribute_ "
|
||||
+ "from contact t0 join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.shipping_address_id"
|
||||
+ ") r1 group by r1.attribute_ order by r1.attribute_");
|
||||
assertThat(list2.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list2.toString()).isEqualTo("[1: null, 3: 1 Banana St, 5: 12 Apple St, 3: 15 Kumera Way]");
|
||||
|
||||
|
||||
query = DB.find(Contact.class).select("firstName")
|
||||
.where().eq("customer.shippingAddress.line1", "12 Apple St").query();
|
||||
List<CountedValue<Object>> list3 = query
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_ASC)
|
||||
.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*) from ("
|
||||
+ "select t0.first_name as attribute_ from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.shipping_address_id where t2.line_1 = ?"
|
||||
+ ") r1 group by r1.attribute_ order by r1.attribute_");
|
||||
assertThat(list3.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list3.toString()).isEqualTo("[1: Bugs1, 1: Fiona, 1: Fred1, 1: Jim1, 1: Tracy]");
|
||||
|
||||
|
||||
query = DB.find(Contact.class).fetch("customer.billingAddress", "line1")
|
||||
.where().or()
|
||||
.ne("customer.shippingAddress.line1", "12 Apple St")
|
||||
.isNull("customer.shippingAddress.line1")
|
||||
.endOr().query();
|
||||
List<CountedValue<Object>> list4 = query
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_ASC)
|
||||
.findSingleAttributeList();
|
||||
assertThat(sqlOf(query)).contains("select r1.attribute_, count(*) from ("
|
||||
+ "select t2.line_1 as attribute_ "
|
||||
+ "from contact t0 join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.billing_address_id "
|
||||
+ "left join o_address t3 on t3.id = t1.shipping_address_id "
|
||||
+ "where (t3.line_1 <> ? or t3.line_1 is null)"
|
||||
+ ") r1 group by r1.attribute_ order by r1.attribute_");
|
||||
assertThat(list4.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list4.toString()).isEqualTo("[1: null, 3: Bos town, 3: P.O.Box 1234]");
|
||||
|
||||
|
||||
// Test Limiter for MSSQL
|
||||
query = DB.find(Contact.class).fetch("customer.billingAddress", "line1").setFirstRow(1).setMaxRows(2);
|
||||
List<CountedValue<Object>> list5 = query
|
||||
.where().isNotNull("customer.billingAddress.line1").query()
|
||||
.setCountDistinct(CountDistinctOrder.ATTR_DESC)
|
||||
.findSingleAttributeList();
|
||||
|
||||
if (isOracle()) {
|
||||
assertSql(query).contains("select r1.attribute_, count(*) from (select t2.line_1 as attribute_ from contact t0 join o_customer t1 on t1.id = t0.customer_id left join o_address t2 on t2.id = t1.billing_address_id where t2.line_1 is not null) r1 group by r1.attribute_ order by r1.attribute_ desc offset 1 rows fetch next 2 rows only");
|
||||
} else {
|
||||
assertSql(query).contains("select r1.attribute_, count(*) from ("
|
||||
+ "select t2.line_1 as attribute_ from contact t0 "
|
||||
+ "join o_customer t1 on t1.id = t0.customer_id "
|
||||
+ "left join o_address t2 on t2.id = t1.billing_address_id "
|
||||
+ "where t2.line_1 is not null"
|
||||
+ ") r1 group by r1.attribute_ order by r1.attribute_ desc ");
|
||||
}
|
||||
if (isSqlServer()) {
|
||||
assertThat(sqlOf(query)).endsWith(" fetch next 2 rows only");
|
||||
} else if (isDb2()) {
|
||||
assertSql(query).endsWith("FETCH FIRST 2 ROWS ONLY");
|
||||
} else if (isOracle()) {
|
||||
assertSql(query).contains(" offset 1 rows fetch next 2 rows only");
|
||||
} else {
|
||||
assertThat(sqlOf(query)).endsWith(" limit 2 offset 1");
|
||||
}
|
||||
assertThat(list5.get(0)).isInstanceOf(CountedValue.class);
|
||||
//assertThat(list5.toString()).isEqualTo("[3: P.O.Box 1234, 3: Bos town]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void example() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<CountedValue<Order.Status>> orderStatusCount =
|
||||
|
||||
DB.find(Order.class)
|
||||
.select("status")
|
||||
.where()
|
||||
.gt("orderDate", LocalDate.now().minusMonths(3))
|
||||
.setCountDistinct(CountDistinctOrder.COUNT_DESC_ATTR_ASC)
|
||||
.findSingleAttributeList();
|
||||
|
||||
for (CountedValue<Order.Status> entry : orderStatusCount) {
|
||||
System.out.println(" count:" + entry.getCount()+" orderStatus:" + entry.getValue() );
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MainEntity e1 = new MainEntity();
|
||||
e1.setId("1");
|
||||
e1.setAttr1("a1");
|
||||
DB.save(e1);
|
||||
|
||||
MainEntity e2 = new MainEntity();
|
||||
e2.setId("2");
|
||||
e2.setAttr1("a2");
|
||||
DB.save(e2);
|
||||
|
||||
MainEntity e3 = new MainEntity();
|
||||
e3.setId("3");
|
||||
e3.setAttr1("a1");
|
||||
DB.save(e3);
|
||||
|
||||
MainEntityRelation rel = new MainEntityRelation();
|
||||
rel.setEntity1(e1);
|
||||
rel.setEntity2(e1);
|
||||
DB.save(rel);
|
||||
|
||||
rel = new MainEntityRelation();
|
||||
rel.setEntity1(e2);
|
||||
rel.setEntity2(e2);
|
||||
DB.save(rel);
|
||||
|
||||
rel = new MainEntityRelation();
|
||||
rel.setEntity1(e3);
|
||||
rel.setEntity2(e3);
|
||||
DB.save(rel);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void cleanup() {
|
||||
DB.find(MainEntityRelation.class).delete();
|
||||
DB.find(MainEntity.class).delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.tests.model.selfref.SelfParent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestSelfParent extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
if (DB.find(SelfParent.class).findCount() > 0) {
|
||||
// only run once
|
||||
return;
|
||||
}
|
||||
|
||||
SelfParent root = new SelfParent("root", null);
|
||||
SelfParent child1 = new SelfParent("child1", root);
|
||||
SelfParent child11 = new SelfParent("child11", child1);
|
||||
SelfParent child111 = new SelfParent("child111", child11);
|
||||
SelfParent child12 = new SelfParent("child12", child1);
|
||||
|
||||
SelfParent child2 = new SelfParent("child2", root);
|
||||
SelfParent child21 = new SelfParent("child21", child2);
|
||||
SelfParent child22 = new SelfParent("child22", child2);
|
||||
|
||||
DB.save(root);
|
||||
DB.save(child1);
|
||||
DB.save(child11);
|
||||
DB.save(child111);
|
||||
DB.save(child12);
|
||||
DB.save(child2);
|
||||
DB.save(child21);
|
||||
DB.save(child22);
|
||||
|
||||
List<SelfParent> roots = DB.find(SelfParent.class).where().eq("parent", null).findList();
|
||||
|
||||
assertEquals(1, roots.size());
|
||||
|
||||
printNode(roots.get(0));
|
||||
}
|
||||
|
||||
public static void printNode(SelfParent o) {
|
||||
//System.out.println(o.getName());
|
||||
for (SelfParent c : o.getChildren()) {
|
||||
printNode(c);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import io.ebean.Database;
|
||||
import io.ebean.Expression;
|
||||
import io.ebean.Query;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TestSubQueryBinding extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
Database server = DB.getDefault();
|
||||
|
||||
Query<Customer> someCustomerIds = server.find(Customer.class).select("id").where().lt("id", 5).query();
|
||||
|
||||
Expression someCustIdsExpression = server.expressionFactory().in("id", someCustomerIds);
|
||||
|
||||
Query<Customer> query = server.find(Customer.class).where().like("name", "Rob%").not(someCustIdsExpression).query();
|
||||
|
||||
query.findList();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.tests.query.other;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.DB;
|
||||
import org.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class TestWhereAnnotation extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void fetchEager_inFirstQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
DB.find(Customer.class)
|
||||
.fetch("orders")
|
||||
.findList();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertEquals(1, loggedSql.size());
|
||||
|
||||
String sql = loggedSql.get(0);
|
||||
assertTrue(sql.contains("t1.order_date is not null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fetchLazy_inLazyLoadQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
DB.cacheManager().clearAll();
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
List<Customer> customers = DB.find(Customer.class)
|
||||
.order().asc("id")
|
||||
.findList();
|
||||
|
||||
List<Order> orders = customers.get(0).getOrders();
|
||||
assertThat(orders.size()).isGreaterThan(0);
|
||||
orders.get(0).getStatus();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
|
||||
assertThat(loggedSql).hasSize(2);
|
||||
assertThat(loggedSql.get(1)).contains("t0.order_date is not null");
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 1650 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user