mirror of
https://github.com/ebean-orm/ebean.git
synced 2024-04-21 10:51:47 +00:00
#919 - io.ebean package initial
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import org.tests.model.basic.Country;
|
||||
import org.avaje.agentloader.AgentLoader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Types;
|
||||
|
||||
public class BaseTestCase {
|
||||
|
||||
protected static Logger logger = LoggerFactory.getLogger(BaseTestCase.class);
|
||||
|
||||
static {
|
||||
logger.debug("... preStart");
|
||||
if (!AgentLoader.loadAgentFromClasspath("ebean-agent", "debug=1;packages=com.avaje.tests,org.avaje.test")) {
|
||||
logger.info("avaje-ebeanorm-agent not found in classpath - not dynamically loaded");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the generated sql trimming column alias if required.
|
||||
*/
|
||||
protected String sqlOf(Query<?> query) {
|
||||
return trimSql(query.getGeneratedSql(), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the generated sql trimming column alias if required.
|
||||
*/
|
||||
protected String sqlOf(Query<?> query, int columns) {
|
||||
return trimSql(query.getGeneratedSql(), columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim out column alias if required from the generated sql.
|
||||
*/
|
||||
protected String trimSql(String sql, int columns) {
|
||||
for (int i = 0; i <= columns; i++) {
|
||||
sql = sql.replace(" c" + i + ",", ",");
|
||||
}
|
||||
for (int i = 0; i <= columns; i++) {
|
||||
sql = sql.replace(" c" + i + " ", " ");
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* MS SQL Server does not allow setting explicit values on identity columns
|
||||
* so tests that do this need to be skipped for SQL Server.
|
||||
*/
|
||||
public boolean isMsSqlServer() {
|
||||
return platformName().startsWith("sqlserver");
|
||||
}
|
||||
|
||||
public boolean isH2() {
|
||||
return platformName().equals("h2");
|
||||
}
|
||||
|
||||
public boolean isPostgres() {
|
||||
return platformName().equals("postgres");
|
||||
}
|
||||
|
||||
public boolean isMySql() {
|
||||
return platformName().equals("mysql");
|
||||
}
|
||||
|
||||
public boolean isPlatformBooleanNative() {
|
||||
return Types.BOOLEAN == spiEbeanServer().getDatabasePlatform().getBooleanDbType();
|
||||
}
|
||||
|
||||
public boolean isPlatformOrderNullsSupport() {
|
||||
return isH2() || isPostgres();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the L2 cache to propagate changes post-commit.
|
||||
*/
|
||||
protected void awaitL2Cache() {
|
||||
// do nothing, used to thread sleep
|
||||
}
|
||||
|
||||
protected <T> BeanDescriptor<T> getBeanDescriptor(Class<T> cls) {
|
||||
return spiEbeanServer().getBeanDescriptor(cls);
|
||||
}
|
||||
|
||||
protected String platformName() {
|
||||
return spiEbeanServer().getDatabasePlatform().getName();
|
||||
}
|
||||
|
||||
protected SpiEbeanServer spiEbeanServer() {
|
||||
return (SpiEbeanServer) Ebean.getDefaultServer();
|
||||
}
|
||||
|
||||
protected EbeanServer server() {
|
||||
return Ebean.getDefaultServer();
|
||||
}
|
||||
|
||||
protected void loadCountryCache() {
|
||||
|
||||
Ebean.find(Country.class)
|
||||
.setLoadBeanCache(true)
|
||||
.findList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.RawSql;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class ColumnMappingTest {
|
||||
|
||||
RawSql.ColumnMapping.Column col(int indexPos, String dbColumn, String dbAlias) {
|
||||
return new RawSql.ColumnMapping.Column(indexPos, dbColumn, dbAlias);
|
||||
}
|
||||
|
||||
RawSql.ColumnMapping mapping(RawSql.ColumnMapping.Column... cols) {
|
||||
return new RawSql.ColumnMapping(Arrays.asList(cols));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_same() {
|
||||
|
||||
RawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
|
||||
RawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "name", null));
|
||||
|
||||
assertSame(mapping1, mapping2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_diffPropertyName() {
|
||||
|
||||
RawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
|
||||
RawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "diff", null));
|
||||
|
||||
assertDifferent(mapping1, mapping2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_moreColumns() {
|
||||
|
||||
RawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
|
||||
RawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "name", null), col(2, "diff", null));
|
||||
|
||||
assertDifferent(mapping1, mapping2);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void equals_lessColumns() {
|
||||
|
||||
RawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
|
||||
RawSql.ColumnMapping mapping2 = mapping(col(1, "id", null));
|
||||
|
||||
assertDifferent(mapping1, mapping2);
|
||||
}
|
||||
|
||||
private void assertSame(Object key, Object key1) {
|
||||
assertThat(key).isEqualTo(key1);
|
||||
assertThat(key.hashCode()).isEqualTo(key1.hashCode());
|
||||
}
|
||||
|
||||
private void assertDifferent(Object key, Object key1) {
|
||||
assertThat(key).isNotEqualTo(key1);
|
||||
assertThat(key.hashCode()).isNotEqualTo(key1.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package io.ebean;
|
||||
|
||||
|
||||
import io.ebean.RawSql;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class ColumnTest {
|
||||
|
||||
RawSql.ColumnMapping.Column col(int indexPos, String dbColumn, String dbAlias) {
|
||||
return new RawSql.ColumnMapping.Column(indexPos, dbColumn, dbAlias);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_same() {
|
||||
assertSame(col(1, "name", null), col(1, "name", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_same_withAlias() {
|
||||
assertSame(col(1, "t0.name", "t0"), col(1, "t0.name", "t0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffIndex() {
|
||||
assertDifferent(col(1, "name", null), col(2, "name", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffProperty() {
|
||||
assertDifferent(col(1, "name", null), col(1, "diffName", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffAlias() {
|
||||
assertDifferent(col(1, "t1.name", "t1"), col(1, "t1.name", "t0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffAliasNullLast() {
|
||||
assertDifferent(col(1, "t1.name", "t1"), col(1, "t1.name", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffAliasNullFirst() {
|
||||
assertDifferent(col(1, "t1.name", null), col(1, "t1.name", "t1"));
|
||||
}
|
||||
|
||||
|
||||
private void assertSame(Object key, Object key1) {
|
||||
assertThat(key).isEqualTo(key1);
|
||||
assertThat(key.hashCode()).isEqualTo(key1.hashCode());
|
||||
}
|
||||
|
||||
private void assertDifferent(Object key, Object key1) {
|
||||
assertThat(key).isNotEqualTo(key1);
|
||||
assertThat(key.hashCode()).isNotEqualTo(key1.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.CurrentTenantProvider;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.TenantDataSourceProvider;
|
||||
import io.ebean.config.TenantMode;
|
||||
import io.ebean.config.TenantSchemaProvider;
|
||||
import io.ebean.config.dbplatform.mysql.MySqlPlatform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
public class EbeanServerFactory_MultiTenancy_Test {
|
||||
|
||||
/**
|
||||
* Tests using multi tenancy per database
|
||||
*/
|
||||
@Test
|
||||
public void create_new_server_with_multi_tenancy_db() {
|
||||
|
||||
String tenant = "customer";
|
||||
CurrentTenantProvider tenantProvider = Mockito.mock(CurrentTenantProvider.class);
|
||||
Mockito.doReturn(tenant).when(tenantProvider).currentId();
|
||||
|
||||
DataSource mockedDataSource = Mockito.mock(DataSource.class);
|
||||
TenantDataSourceProvider dataSourceProvider = Mockito.mock(TenantDataSourceProvider.class);
|
||||
Mockito.doReturn(mockedDataSource).when(dataSourceProvider).dataSource(tenant);
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("multiTenantDb");
|
||||
config.loadFromProperties();
|
||||
config.loadTestProperties();
|
||||
config.setRegister(false);
|
||||
config.setDefaultServer(false);
|
||||
|
||||
config.setTenantMode(TenantMode.DB);
|
||||
config.setCurrentTenantProvider(tenantProvider);
|
||||
config.setTenantDataSourceProvider(dataSourceProvider);
|
||||
|
||||
// When TenantMode.DB we don't really want to run DDL
|
||||
// and we want to explicitly specify the Database platform
|
||||
//config.setDdlGenerate(false);
|
||||
//config.setDdlRun(false);
|
||||
config.setDatabasePlatform(new PostgresPlatform());
|
||||
|
||||
EbeanServerFactory.create(config);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Tests using multi tenancy per schema
|
||||
*/
|
||||
@Test
|
||||
public void create_new_server_with_multi_tenancy_schema() {
|
||||
|
||||
String tenant = "customer";
|
||||
CurrentTenantProvider tenantProvider = Mockito.mock(CurrentTenantProvider.class);
|
||||
Mockito.doReturn(tenant).when(tenantProvider).currentId();
|
||||
|
||||
TenantSchemaProvider schemaProvider = Mockito.mock(TenantSchemaProvider.class);
|
||||
Mockito.doReturn("tenant_schema").when(schemaProvider).schema(tenant);
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("h2");
|
||||
config.loadFromProperties();
|
||||
config.loadTestProperties();
|
||||
config.setRegister(false);
|
||||
config.setDefaultServer(false);
|
||||
|
||||
config.setTenantMode(TenantMode.SCHEMA);
|
||||
config.setCurrentTenantProvider(tenantProvider);
|
||||
config.setTenantSchemaProvider(schemaProvider);
|
||||
|
||||
config.setDdlRun(false);
|
||||
config.setDatabasePlatform(new MySqlPlatform());
|
||||
|
||||
EbeanServerFactory.create(config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.event.ServerConfigStartup;
|
||||
import org.tests.model.basic.UTDetail;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EbeanServerFactory_ServerConfigStart_Test {
|
||||
|
||||
@Test
|
||||
public void test() throws InterruptedException {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("h2");
|
||||
config.loadFromProperties();
|
||||
config.setName("h2other");
|
||||
config.setH2ProductionMode(true);
|
||||
config.setDdlGenerate(false);
|
||||
config.setDdlRun(false);
|
||||
config.setDefaultServer(false);
|
||||
config.setRegister(false);
|
||||
|
||||
config.addClass(UTDetail.class);
|
||||
config.addClass(OnStartupViaClass.class);
|
||||
|
||||
// act - register an instance
|
||||
OnStartup onStartup = new OnStartup();
|
||||
config.addServerConfigStartup(onStartup);
|
||||
|
||||
EbeanServer ebeanServer = EbeanServerFactory.create(config);
|
||||
|
||||
assertThat(onStartup.calledWithConfig).isSameAs(config);
|
||||
assertThat(OnStartupViaClass.calledWithConfig).isSameAs(config);
|
||||
|
||||
assertThat(ebeanServer).isNotNull();
|
||||
|
||||
// test server shutdown and restart using the same ServerConfig
|
||||
ebeanServer.shutdown(true, false);
|
||||
|
||||
EbeanServer restartedServer = EbeanServerFactory.create(config);
|
||||
restartedServer.shutdown(true, false);
|
||||
}
|
||||
|
||||
public static class OnStartup implements ServerConfigStartup {
|
||||
|
||||
ServerConfig calledWithConfig;
|
||||
|
||||
@Override
|
||||
public void onStart(ServerConfig serverConfig) {
|
||||
calledWithConfig = serverConfig;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class OnStartupViaClass implements ServerConfigStartup {
|
||||
|
||||
static ServerConfig calledWithConfig;
|
||||
|
||||
@Override
|
||||
public void onStart(ServerConfig serverConfig) {
|
||||
calledWithConfig = serverConfig;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.Transaction;
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.avaje.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class EbeanServer_deleteAllByIdTest {
|
||||
|
||||
@Test
|
||||
public void deleteAllById() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
|
||||
Ebean.saveAll(someBeans);
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
ids.add(someBean.getId());
|
||||
}
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.deleteAll(EBasicVer.class, ids);
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id in (?,?,?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteAllById_withTransaction() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
|
||||
Ebean.saveAll(someBeans);
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
ids.add(someBean.getId());
|
||||
}
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.deleteAll(EBasicVer.class, ids, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id in (?,?,?)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteAllPermanentById() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
|
||||
Ebean.saveAll(someBeans);
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
ids.add(someBean.getId());
|
||||
}
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
|
||||
Ebean.deleteAllPermanent(EBasicVer.class, ids);
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id in (?,?,?)");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void deleteAllPermanentById_withTransaction() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
|
||||
Ebean.saveAll(someBeans);
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
ids.add(someBean.getId());
|
||||
}
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.deleteAllPermanent(EBasicVer.class, ids, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id in (?,?,?)");
|
||||
}
|
||||
|
||||
private List<EBasicVer> beans(int count) {
|
||||
List<EBasicVer> beans = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
beans.add(bean("foo" + i));
|
||||
}
|
||||
return beans;
|
||||
}
|
||||
|
||||
private EBasicVer bean(String name) {
|
||||
return new EBasicVer(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.Transaction;
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.avaje.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class EbeanServer_deleteByIdTest {
|
||||
|
||||
@Test
|
||||
public void deleteById() {
|
||||
|
||||
EBasicVer someBean = bean("foo1");
|
||||
Ebean.save(someBean);
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.delete(EBasicVer.class, someBean.getId());
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletePermanentById() {
|
||||
|
||||
EBasicVer someBean = bean("foo1");
|
||||
Ebean.save(someBean);
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.deletePermanent(EBasicVer.class, someBean.getId());
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id = ?");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void deleteById_withTransaction() {
|
||||
|
||||
EBasicVer someBean = bean("foo1");
|
||||
Ebean.save(someBean);
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.delete(EBasicVer.class, someBean.getId(), txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id = ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletePermanentById_withTransaction() {
|
||||
|
||||
EBasicVer someBean = bean("foo2");
|
||||
Ebean.save(someBean);
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.deletePermanent(EBasicVer.class, someBean.getId(), txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id = ?");
|
||||
}
|
||||
|
||||
private EBasicVer bean(String name) {
|
||||
return new EBasicVer(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.Transaction;
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.avaje.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class EbeanServer_deleteTest {
|
||||
|
||||
@Test
|
||||
public void delete() {
|
||||
|
||||
EBasicVer someBean = bean("foo1");
|
||||
Ebean.save(someBean);
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.delete(someBean);
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id=? and ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delete_withTransaction() {
|
||||
|
||||
EBasicVer someBean = bean("foo1");
|
||||
Ebean.save(someBean);
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.delete(someBean, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).contains("delete from e_basicver where id=? and ");
|
||||
}
|
||||
|
||||
private EBasicVer bean(String name) {
|
||||
return new EBasicVer(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package io.ebean;
|
||||
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EbeanServer_eqlTest extends BaseTestCase {
|
||||
|
||||
|
||||
@Test
|
||||
public void basic() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = server().createQuery(Customer.class, "order by id limit 10");
|
||||
query.setMaxRows(100);
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("order by t0.id ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basic_via_Ebean_defaultServer() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = Ebean.createQuery(Customer.class, "order by id limit 10");
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("order by t0.id ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderBy_override() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = server().createQuery(Customer.class, "order by id");
|
||||
|
||||
// use clear() and then effectively override the orderBy clause
|
||||
query.orderBy().clear().asc("name");
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("order by t0.name");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void namedParams() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = server().createQuery(Customer.class, "where name startsWith :name order by name");
|
||||
query.setParameter("name", "Ro");
|
||||
query.findList();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("where t0.name like ? ");
|
||||
}
|
||||
|
||||
@Test(expected = PersistenceException.class)
|
||||
public void unboundNamedParams_expect_PersistenceException() {
|
||||
|
||||
Query<Customer> query = server().createQuery(Customer.class, "where name = :name");
|
||||
query.findUnique();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namedQuery() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> name = server().createNamedQuery(Customer.class, "name");
|
||||
name.findList();
|
||||
|
||||
assertThat(sqlOf(name, 1)).contains("select t0.id, t0.name from o_customer t0 order by t0.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namedQuery_withStatus() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> name = server().createNamedQuery(Customer.class, "withStatus");
|
||||
name.order().clear().asc("status");
|
||||
name.findList();
|
||||
|
||||
assertThat(sqlOf(name, 2)).contains("select t0.id, t0.name, t0.status from o_customer t0 order by t0.status");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namedQuery_withContacts() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = server()
|
||||
.createNamedQuery(Customer.class, "withContacts")
|
||||
.setParameter("id", 1);
|
||||
|
||||
query.setUseCache(false);
|
||||
query.findUnique();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left join contact t1 on t1.customer_id = t0.id ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namedQuery_fromXml() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Query<Customer> query = server()
|
||||
.createNamedQuery(Customer.class, "withContactsById")
|
||||
.setParameter("id", 1);
|
||||
|
||||
query.setUseCache(false);
|
||||
query.findUnique();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left join contact t1 on t1.customer_id = t0.id ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import org.tests.model.basic.EBasic;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class EbeanServer_refresh {
|
||||
|
||||
@Test
|
||||
public void basic() {
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
EBasic basic = new EBasic("basic refresh");
|
||||
basic.setStatus(EBasic.Status.NEW);
|
||||
server.save(basic);
|
||||
|
||||
int rows =
|
||||
server.update(EBasic.class)
|
||||
.set("status", EBasic.Status.ACTIVE)
|
||||
.where().idEq(basic.getId())
|
||||
.update();
|
||||
|
||||
assertEquals(rows, 1);
|
||||
|
||||
server.refresh(basic);
|
||||
assertEquals(basic.getStatus(), EBasic.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refresh_when_oneToManyLoaded() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Order order = Ebean.find(Order.class, 1);
|
||||
order.getCustomer().getName();
|
||||
order.getDetails().size();
|
||||
|
||||
Ebean.refresh(order);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refresh_when_oneToManyVanilla() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Order order = Ebean.find(Order.class, 1);
|
||||
order.getCustomer().getName();
|
||||
order.setDetails(new ArrayList<>());
|
||||
|
||||
Ebean.refresh(order);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refresh_when_oneToManyNull() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
Order order = Ebean.find(Order.class, 1);
|
||||
order.getCustomer().getName();
|
||||
order.setDetails(null);
|
||||
|
||||
Ebean.refresh(order);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package io.ebean;
|
||||
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.avaje.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class EbeanServer_saveAllTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void saveAll() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.saveAll(someBeans);
|
||||
|
||||
// assert
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
for (String insertSql : loggedSql) {
|
||||
assertThat(insertSql).contains("insert into e_basicver (");
|
||||
assertThat(insertSql).contains("name, description, other, last_update) values (");
|
||||
}
|
||||
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
someBean.setName(someBean.getName() + "-mod");
|
||||
}
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.updateAll(someBeans);
|
||||
|
||||
loggedSql = LoggedSqlCollector.stop();
|
||||
for (String updateSql : loggedSql) {
|
||||
assertThat(updateSql).contains("update e_basicver set name=?, last_update=? where id=? ");
|
||||
}
|
||||
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Ebean.deleteAll(someBeans);
|
||||
|
||||
loggedSql = LoggedSqlCollector.stop();
|
||||
for (String updateSql : loggedSql) {
|
||||
assertThat(updateSql).contains("delete from e_basicver where id=? ");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void saveAll_withTransaction() {
|
||||
|
||||
List<EBasicVer> someBeans = beans(3);
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
Transaction txn = server.beginTransaction();
|
||||
try {
|
||||
server.saveAll(someBeans, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
|
||||
// assert
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
for (String insertSql : loggedSql) {
|
||||
assertThat(insertSql).contains("insert into e_basicver (");
|
||||
assertThat(insertSql).contains("name, description, other, last_update) values (");
|
||||
}
|
||||
|
||||
for (EBasicVer someBean : someBeans) {
|
||||
someBean.setName(someBean.getName() + "-mod");
|
||||
}
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
txn = server.beginTransaction();
|
||||
try {
|
||||
server.updateAll(someBeans, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
loggedSql = LoggedSqlCollector.stop();
|
||||
for (String updateSql : loggedSql) {
|
||||
assertThat(updateSql).contains("update e_basicver set name=?, last_update=? where id=? ");
|
||||
}
|
||||
|
||||
|
||||
// act
|
||||
LoggedSqlCollector.start();
|
||||
txn = server.beginTransaction();
|
||||
try {
|
||||
server.deleteAll(someBeans, txn);
|
||||
txn.commit();
|
||||
} finally {
|
||||
txn.end();
|
||||
}
|
||||
loggedSql = LoggedSqlCollector.stop();
|
||||
for (String updateSql : loggedSql) {
|
||||
assertThat(updateSql).contains("delete from e_basicver where id=? ");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private List<EBasicVer> beans(int count) {
|
||||
List<EBasicVer> beans = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
beans.add(bean("foo" + i));
|
||||
}
|
||||
return beans;
|
||||
}
|
||||
|
||||
private EBasicVer bean(String name) {
|
||||
return new EBasicVer(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.FetchConfig;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class FetchConfigTest {
|
||||
|
||||
@Test
|
||||
public void testLazy() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().lazy();
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(0);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(-1);
|
||||
assertThat(config.isQueryAll()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazy_withParameter() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().lazy(50);
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(50);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(-1);
|
||||
assertThat(config.isQueryAll()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQuery() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().query();
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(-1);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(0);
|
||||
assertThat(config.isQueryAll()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQuery_withParameter() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().query(50);
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(-1);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(50);
|
||||
assertThat(config.isQueryAll()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryFirst() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().queryFirst(50);
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(-1);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(50);
|
||||
assertThat(config.isQueryAll()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryAndLazy_withParameters() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().query(50).lazy(10);
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(10);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(50);
|
||||
assertThat(config.isQueryAll()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQueryAndLazy() throws Exception {
|
||||
|
||||
FetchConfig config = new FetchConfig().query(50).lazy();
|
||||
|
||||
assertThat(config.getLazyBatchSize()).isEqualTo(0);
|
||||
assertThat(config.getQueryBatchSize()).isEqualTo(50);
|
||||
assertThat(config.isQueryAll()).isEqualTo(false);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testEquals_when_noOptions() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig(), new FetchConfig());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_query_50_lazy_40() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().query(50).lazy(40), new FetchConfig().query(50).lazy(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_query_50_lazy() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().query(50).lazy(), new FetchConfig().query(50).lazy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_query_50() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().query(50), new FetchConfig().query(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_queryFirst_50_lazy_40() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().queryFirst(50).lazy(40), new FetchConfig().queryFirst(50).lazy(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_queryFirst_50_lazy() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().queryFirst(50).lazy(), new FetchConfig().queryFirst(50).lazy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals_when_queryFirst_50() throws Exception {
|
||||
|
||||
assertSame(new FetchConfig().queryFirst(50), new FetchConfig().queryFirst(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_query_50() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().query(50), new FetchConfig().query(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_query_50_lazy() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().query(50), new FetchConfig().query(50).lazy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_query_50_lazy_40() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().query(50), new FetchConfig().query(50).lazy(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_queryFirst_50() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().queryFirst(50), new FetchConfig().queryFirst(40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_queryFirst_50_lazy() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().queryFirst(50), new FetchConfig().queryFirst(50).lazy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotEquals_when_queryFirst_50_lazy_40() throws Exception {
|
||||
|
||||
assertDifferent(new FetchConfig().queryFirst(50), new FetchConfig().queryFirst(50).lazy(40));
|
||||
}
|
||||
|
||||
void assertDifferent(FetchConfig v1, FetchConfig v2) {
|
||||
assertThat(v1).isNotEqualTo(v2);
|
||||
assertThat(v1.hashCode()).isNotEqualTo(v2.hashCode());
|
||||
}
|
||||
|
||||
|
||||
void assertSame(FetchConfig v1, FetchConfig v2) {
|
||||
assertThat(v1).isEqualTo(v2);
|
||||
assertThat(v1.hashCode()).isEqualTo(v2.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.config.CurrentUserProvider;
|
||||
|
||||
/**
|
||||
* Returns the current user typically from a Thread local or similar context.
|
||||
*/
|
||||
public class MyCurrentUserProvider implements CurrentUserProvider {
|
||||
|
||||
public static final String DEFAULT = "42789";
|
||||
|
||||
/**
|
||||
* Do not do this yourself - this is for testing purposes.
|
||||
*/
|
||||
private static String userId = DEFAULT;
|
||||
|
||||
|
||||
@Override
|
||||
public Object currentUser() {
|
||||
// just hardcoding here for testing
|
||||
return userId;
|
||||
}
|
||||
|
||||
public static void setUserId(String value) {
|
||||
userId = value;
|
||||
}
|
||||
|
||||
public static void resetToDefault() {
|
||||
userId = DEFAULT;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.PrimaryServer;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrimaryServerTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testIsSkipPrimaryServer() throws Exception {
|
||||
PrimaryServer.setSkip(true);
|
||||
assertTrue(PrimaryServer.isSkip());
|
||||
PrimaryServer.setSkip(false);
|
||||
assertFalse(PrimaryServer.isSkip());
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testGetPrimaryServerName() throws Exception {
|
||||
|
||||
String primaryServerName = PrimaryServer.getDefaultServerName();
|
||||
assertEquals("h2", primaryServerName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoadProperties() throws Exception {
|
||||
|
||||
Properties properties = PrimaryServer.getProperties();
|
||||
assertTrue(!properties.isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.OrderBy;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class PropertyTest {
|
||||
|
||||
@Test
|
||||
public void equals() throws Exception {
|
||||
|
||||
assertEquals(prop("foo", true), prop("foo", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diff_basic() throws Exception {
|
||||
|
||||
assertNotEquals(prop("foo", true), prop("bar", true));
|
||||
assertNotEquals(prop("foo", true), prop("foo", false));
|
||||
assertNotEquals(prop("foo", false), prop("foo", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diff_nulls() throws Exception {
|
||||
|
||||
assertEquals(prop("foo", true, "nulls", "high"), prop("foo", true, "nulls", "high"));
|
||||
assertEquals(prop("foo", true, "nulls", "low"), prop("foo", true, "nulls", "low"));
|
||||
|
||||
assertNotEquals(prop("foo", true), prop("foo", true, "nulls", "high"));
|
||||
assertNotEquals(prop("foo", true, "nulls", "high"), prop("foo", true));
|
||||
assertNotEquals(prop("foo", true, "nulls", "high"), prop("foo", true, "nulls", "low"));
|
||||
assertNotEquals(prop("foo", true, "nulls", "low"), prop("foo", true, "nulls", "high"));
|
||||
}
|
||||
|
||||
private OrderBy.Property prop(String name, boolean asc) {
|
||||
return new OrderBy.Property(name, asc, null, null);
|
||||
}
|
||||
|
||||
private OrderBy.Property prop(String name, boolean asc, String nulls, String highLow) {
|
||||
return new OrderBy.Property(name, asc, nulls, highLow);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package io.ebean;
|
||||
|
||||
|
||||
import io.ebean.RawSql;
|
||||
import io.ebean.RawSqlBuilder;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class RawSqlKeyTest {
|
||||
|
||||
@Test
|
||||
public void equals_when_sameParsedSql() {
|
||||
|
||||
RawSql.Key key = RawSqlBuilder.parse("select id from customer").create().getKey();
|
||||
RawSql.Key key1 = RawSqlBuilder.parse("select id from customer").create().getKey();
|
||||
|
||||
assertSame(key, key1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffParsedSql() {
|
||||
|
||||
RawSql.Key key = RawSqlBuilder.parse("select id from customer").create().getKey();
|
||||
RawSql.Key key1 = RawSqlBuilder.parse("select name from customer").create().getKey();
|
||||
|
||||
assertDifferent(key, key1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_sameColumnMapping() {
|
||||
|
||||
RawSql.Key key = RawSqlBuilder.parse("select id from customer").columnMapping("id", "b").create().getKey();
|
||||
RawSql.Key key1 = RawSqlBuilder.parse("select id from customer").columnMapping("id", "b").create().getKey();
|
||||
|
||||
assertSame(key, key1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_diffColumnMapping() {
|
||||
|
||||
RawSql.Key key = RawSqlBuilder.parse("select a from customer").columnMapping("a", "b").create().getKey();
|
||||
RawSql.Key key1 = RawSqlBuilder.parse("select a from customer").columnMapping("a", "c").create().getKey();
|
||||
|
||||
assertDifferent(key, key1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_when_parseToUnpased() {
|
||||
|
||||
RawSql.Key key = RawSqlBuilder.parse("select a from customer").columnMapping("a", "b").create().getKey();
|
||||
RawSql.Key key1 = RawSqlBuilder.unparsed("select a from customer").columnMapping("a", "c").create().getKey();
|
||||
|
||||
assertDifferent(key, key1);
|
||||
}
|
||||
|
||||
private void assertSame(RawSql.Key key, RawSql.Key key1) {
|
||||
assertThat(key).isEqualTo(key1);
|
||||
assertThat(key.hashCode()).isEqualTo(key1.hashCode());
|
||||
}
|
||||
|
||||
private void assertDifferent(RawSql.Key key, RawSql.Key key1) {
|
||||
assertThat(key).isNotEqualTo(key1);
|
||||
assertThat(key.hashCode()).isNotEqualTo(key1.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.SqlQuery;
|
||||
import io.ebean.SqlRow;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class SqlRowBooleanTest {
|
||||
|
||||
@Test
|
||||
public void getBoolean() {
|
||||
|
||||
SqlQuery sqlQuery = Ebean.createSqlQuery("SELECT 1 IS NOT NULL AS ISNT_NULL");
|
||||
SqlRow row = sqlQuery.findUnique();
|
||||
|
||||
Boolean value = row.getBoolean("ISNT_NULL");
|
||||
|
||||
assertThat(value).isTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebean.bean.EntityBeanIntercept;
|
||||
import io.ebeaninternal.server.core.DefaultBeanState;
|
||||
import org.tests.model.embedded.EMain;
|
||||
import org.tests.model.embedded.Eembeddable;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class TestDirtyProperties extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testEmbeddedUpdateEmbeddedProperty() {
|
||||
|
||||
EMain emain = new EMain();
|
||||
|
||||
EntityBean eb = (EntityBean) emain;
|
||||
EntityBeanIntercept ebi = eb._ebean_getIntercept();
|
||||
|
||||
emain.setId(1);
|
||||
emain.setName("foo");
|
||||
Eembeddable embeddable = setEmbeddedBean(emain, "bar");
|
||||
setEmbeddedLoaded(embeddable);
|
||||
|
||||
// sets loaded state so follow setters are deemed as changes to the bean
|
||||
ebi.setLoaded();
|
||||
|
||||
emain.setName("changedFoo");
|
||||
|
||||
DefaultBeanState beanState = new DefaultBeanState(eb);
|
||||
|
||||
Set<String> changedProps = beanState.getChangedProps();
|
||||
Assert.assertEquals(1, changedProps.size());
|
||||
Assert.assertTrue(changedProps.contains("name"));
|
||||
|
||||
Map<String, ValuePair> dirtyValues = beanState.getDirtyValues();
|
||||
Assert.assertEquals(1, dirtyValues.size());
|
||||
Assert.assertTrue(dirtyValues.keySet().contains("name"));
|
||||
|
||||
ValuePair valuePair = dirtyValues.get("name");
|
||||
Assert.assertNotNull(valuePair);
|
||||
Assert.assertEquals("changedFoo", valuePair.getNewValue());
|
||||
Assert.assertEquals("foo", valuePair.getOldValue());
|
||||
|
||||
Eembeddable embeddableRead = emain.getEmbeddable();
|
||||
embeddableRead.setDescription("embChanged");
|
||||
|
||||
Set<String> changedProps2 = beanState.getChangedProps();
|
||||
Assert.assertEquals(2, changedProps2.size());
|
||||
Assert.assertTrue(changedProps2.contains("name"));
|
||||
Assert.assertTrue(changedProps2.contains("embeddable.description"));
|
||||
|
||||
Map<String, ValuePair> dirtyValues2 = beanState.getDirtyValues();
|
||||
Assert.assertEquals(2, dirtyValues2.size());
|
||||
Assert.assertTrue(dirtyValues2.keySet().contains("name"));
|
||||
Assert.assertTrue(dirtyValues2.keySet().contains("embeddable.description"));
|
||||
|
||||
ValuePair valuePair2 = dirtyValues2.get("embeddable.description");
|
||||
Assert.assertEquals("embChanged", valuePair2.getNewValue());
|
||||
Assert.assertEquals("bar", valuePair2.getOldValue());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testEmbeddedUpdateSetNewBean() {
|
||||
|
||||
EMain emain = new EMain();
|
||||
|
||||
EntityBean eb = (EntityBean) emain;
|
||||
EntityBeanIntercept ebi = eb._ebean_getIntercept();
|
||||
|
||||
emain.setId(1);
|
||||
emain.setName("foo");
|
||||
Eembeddable embeddable = setEmbeddedBean(emain, "bar");
|
||||
setEmbeddedLoaded(embeddable);
|
||||
|
||||
// sets loaded state so follow setters are deemed as changes to the bean
|
||||
ebi.setLoaded();
|
||||
|
||||
emain.setName("changedFoo");
|
||||
|
||||
Assert.assertSame(embeddable, emain.getEmbeddable());
|
||||
|
||||
Eembeddable embeddable2 = setEmbeddedBean(emain, "changeEmbeddedInstance");
|
||||
Assert.assertSame(embeddable2, emain.getEmbeddable());
|
||||
Assert.assertNotSame(embeddable, emain.getEmbeddable());
|
||||
|
||||
|
||||
DefaultBeanState beanState = new DefaultBeanState(eb);
|
||||
|
||||
Set<String> changedProps2 = beanState.getChangedProps();
|
||||
Assert.assertEquals(2, changedProps2.size());
|
||||
Assert.assertTrue(changedProps2.contains("name"));
|
||||
|
||||
Assert.assertTrue("The whole bean instance has changed", changedProps2.contains("embeddable"));
|
||||
|
||||
Map<String, ValuePair> dirtyValues2 = beanState.getDirtyValues();
|
||||
Assert.assertEquals(2, dirtyValues2.size());
|
||||
Assert.assertTrue(dirtyValues2.keySet().contains("name"));
|
||||
Assert.assertTrue(dirtyValues2.keySet().contains("embeddable"));
|
||||
|
||||
|
||||
ValuePair valuePair2 = dirtyValues2.get("embeddable");
|
||||
Assert.assertSame(embeddable2, valuePair2.getNewValue());
|
||||
Assert.assertSame(embeddable, valuePair2.getOldValue());
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void setEmbeddedLoaded(Eembeddable embeddable) {
|
||||
((EntityBean) embeddable)._ebean_getIntercept().setLoaded();
|
||||
}
|
||||
|
||||
|
||||
private Eembeddable setEmbeddedBean(EMain emain, String description) {
|
||||
|
||||
Eembeddable embeddable = new Eembeddable();
|
||||
embeddable.setDescription(description);
|
||||
|
||||
emain.setEmbeddable(embeddable);
|
||||
|
||||
EntityBean owner = (EntityBean) emain;
|
||||
EntityBeanIntercept ebi = owner._ebean_getIntercept();
|
||||
|
||||
// hooks the embeddable bean back to the owner
|
||||
int embeddablePropertyIndex = ebi.findProperty("embeddable");
|
||||
Assert.assertTrue(embeddablePropertyIndex > -1);
|
||||
((EntityBean) embeddable)._ebean_getIntercept().setEmbeddedOwner(owner, embeddablePropertyIndex);
|
||||
return embeddable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.ebean;
|
||||
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TestFilterWithEnum extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() throws InterruptedException {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> allOrders = Ebean.find(Order.class).findList();
|
||||
|
||||
Filter<Order> filter = Ebean.filter(Order.class);
|
||||
List<Order> newOrders = filter.eq("status", Order.Status.NEW).filter(allOrders);
|
||||
|
||||
Assert.assertNotNull(newOrders);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.ebean;
|
||||
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.beans.PropertyChangeEvent;
|
||||
import java.beans.PropertyChangeListener;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TestPropertyChangeListener extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = Ebean.find(Customer.class).findList();
|
||||
|
||||
Listener listener = new Listener();
|
||||
|
||||
Customer customer = list.get(0);
|
||||
Ebean.getBeanState(customer).addPropertyChangeListener(listener);
|
||||
|
||||
customer.setName("modName");
|
||||
customer.setSmallnote("modSmallNote");
|
||||
|
||||
Assert.assertEquals(2, listener.events.size());
|
||||
Assert.assertEquals("modName", listener.events.get(0).getNewValue());
|
||||
Assert.assertEquals("name", listener.events.get(0).getPropertyName());
|
||||
Assert.assertEquals("modSmallNote", listener.events.get(1).getNewValue());
|
||||
Assert.assertEquals("smallnote", listener.events.get(1).getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
class Listener implements PropertyChangeListener {
|
||||
|
||||
List<PropertyChangeEvent> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void propertyChange(PropertyChangeEvent evt) {
|
||||
events.add(evt);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.RawSql.Sql;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.tests.model.rawsql.ERawSqlAggBean;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class TestRawSqlBuilder extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testDeriveProperty() {
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName("item_total", "some_other")).isEqualTo("itemTotal");
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName(null, "some_other")).isEqualTo("someOther");
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName(null, "alias.some_other")).isEqualTo("someOther");
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName(null, "alias.someOther")).isEqualTo("someOther");
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName(null, "some")).isEqualTo("some");
|
||||
assertThat(RawSql.ColumnMapping.Column.derivePropertyName(null, "someOther")).isEqualTo("someOther");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimple() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder.parse("select id from t_cust");
|
||||
Sql sql = r.getSql();
|
||||
assertEquals("id", sql.getPreFrom());
|
||||
assertEquals("from t_cust", sql.getPreWhere());
|
||||
assertEquals("", sql.getPreHaving());
|
||||
assertNull(sql.getOrderBy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithNewLineCharacters() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder.parse("select\n id from\n o_customer");
|
||||
Sql sql = r.getSql();
|
||||
|
||||
assertEquals("id", sql.getPreFrom());
|
||||
assertEquals("from o_customer", sql.getPreWhere());
|
||||
assertEquals("", sql.getPreHaving());
|
||||
assertNull(sql.getOrderBy());
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
RawSql rawSql = r.create();
|
||||
|
||||
Ebean.find(Customer.class)
|
||||
.setRawSql(rawSql)
|
||||
.findList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithWhere() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder.parse("select id from t_cust where id > ?");
|
||||
Sql sql = r.getSql();
|
||||
assertEquals("id", sql.getPreFrom());
|
||||
assertEquals("from t_cust where id > ?", sql.getPreWhere());
|
||||
assertEquals("", sql.getPreHaving());
|
||||
assertNull(sql.getOrderBy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithOrder() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder.parse("select id from t_cust where id > ? order by id desc");
|
||||
Sql sql = r.getSql();
|
||||
assertEquals("id", sql.getPreFrom());
|
||||
assertEquals("from t_cust where id > ?", sql.getPreWhere());
|
||||
assertEquals("", sql.getPreHaving());
|
||||
assertEquals("order by", sql.getOrderByPrefix());
|
||||
assertEquals("id desc", sql.getOrderBy());
|
||||
|
||||
r = RawSqlBuilder.parse("select id from t_cust order by id desc");
|
||||
sql = r.getSql();
|
||||
assertEquals("id", sql.getPreFrom());
|
||||
assertEquals("from t_cust", sql.getPreWhere());
|
||||
assertEquals("", sql.getPreHaving());
|
||||
assertEquals("id desc", sql.getOrderBy());
|
||||
|
||||
r = RawSqlBuilder
|
||||
.parse("select id, sum(x) from t_cust where id > ? group by id order by id desc");
|
||||
sql = r.getSql();
|
||||
assertEquals("id, sum(x)", sql.getPreFrom());
|
||||
assertEquals("from t_cust where id > ?", sql.getPreWhere());
|
||||
assertEquals("group by id", sql.getPreHaving());
|
||||
assertEquals("id desc", sql.getOrderBy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithHaving() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder
|
||||
.parse("select id, sum(x) from t_cust where id > ? group by id having sum(x) > ? order by id desc");
|
||||
Sql sql = r.getSql();
|
||||
assertEquals("id, sum(x)", sql.getPreFrom());
|
||||
assertEquals("from t_cust where id > ?", sql.getPreWhere());
|
||||
assertEquals("group by id having sum(x) > ?", sql.getPreHaving());
|
||||
assertEquals("order by", sql.getOrderByPrefix());
|
||||
assertEquals("id desc", sql.getOrderBy());
|
||||
|
||||
// no where
|
||||
r = RawSqlBuilder
|
||||
.parse("select id, sum(x) from t_cust group by id having sum(x) > ? order by id desc");
|
||||
sql = r.getSql();
|
||||
assertEquals("id, sum(x)", sql.getPreFrom());
|
||||
assertEquals("from t_cust", sql.getPreWhere());
|
||||
assertEquals("group by id having sum(x) > ?", sql.getPreHaving());
|
||||
assertEquals("order by", sql.getOrderByPrefix());
|
||||
assertEquals("id desc", sql.getOrderBy());
|
||||
|
||||
// no where, no order by
|
||||
r = RawSqlBuilder.parse("select id, sum(x) from t_cust group by id having sum(x) > ?");
|
||||
sql = r.getSql();
|
||||
assertEquals("id, sum(x)", sql.getPreFrom());
|
||||
assertEquals("from t_cust", sql.getPreWhere());
|
||||
assertEquals("group by id having sum(x) > ?", sql.getPreHaving());
|
||||
assertNull(sql.getOrderBy());
|
||||
assertEquals("order by", sql.getOrderByPrefix());
|
||||
|
||||
// no order by
|
||||
r = RawSqlBuilder
|
||||
.parse("select id, sum(x) from t_cust where id > ? group by id having sum(x) > ?");
|
||||
sql = r.getSql();
|
||||
assertEquals("id, sum(x)", sql.getPreFrom());
|
||||
assertEquals("from t_cust where id > ?", sql.getPreWhere());
|
||||
assertEquals("group by id having sum(x) > ?", sql.getPreHaving());
|
||||
assertNull(sql.getOrderBy());
|
||||
assertEquals("order by", sql.getOrderByPrefix());
|
||||
}
|
||||
|
||||
/**
|
||||
* test support for order siblings by ... Oracle syntax.
|
||||
*/
|
||||
@Test
|
||||
public void testWithOrderSiblingsByName() {
|
||||
|
||||
String s = "SELECT ID, DESCRIPTION, NAME, PARENT_ID FROM SOME_TABLE WHERE lower(NAME) like :name START WITH ID = :parentId CONNECT BY PRIOR ID = PARENT_ID order siblings by NAME";
|
||||
|
||||
RawSql rawSql = RawSqlBuilder.parse(s).create();
|
||||
|
||||
Sql sql = rawSql.getSql();
|
||||
assertEquals("ID, DESCRIPTION, NAME, PARENT_ID", sql.getPreFrom());
|
||||
assertEquals("order siblings by", sql.getOrderByPrefix());
|
||||
assertEquals("NAME", sql.getOrderBy());
|
||||
assertEquals("FROM SOME_TABLE WHERE lower(NAME) like :name START WITH ID = :parentId CONNECT BY PRIOR ID = PARENT_ID", sql.getPreWhere());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testWithAlias() {
|
||||
|
||||
String rs = "select o.id, o.status, c.id, c.name, " +
|
||||
" d.id, d.order_qty, p.id, p.name " +
|
||||
"from o_order o join o_customer c on c.id = o.kcustomer_id " +
|
||||
"join o_order_detail d on d.order_id = o.id " +
|
||||
"join o_product p on p.id = d.product_id " +
|
||||
"where o.id <= :maxOrderId and p.id = :productId " +
|
||||
"order by o.id, d.id asc";
|
||||
|
||||
|
||||
RawSql rawSql = RawSqlBuilder.parse(rs)
|
||||
.tableAliasMapping("c", "customer")
|
||||
.tableAliasMapping("d", "details")
|
||||
.tableAliasMapping("p", "details.product")
|
||||
.create();
|
||||
|
||||
RawSql.ColumnMapping columnMapping = rawSql.getColumnMapping();
|
||||
assertEquals(0, columnMapping.getIndexPosition("id"));
|
||||
assertEquals(1, columnMapping.getIndexPosition("status"));
|
||||
assertEquals(2, columnMapping.getIndexPosition("customer.id"));
|
||||
assertEquals(3, columnMapping.getIndexPosition("customer.name"));
|
||||
assertEquals(4, columnMapping.getIndexPosition("details.id"));
|
||||
assertEquals(5, columnMapping.getIndexPosition("details.orderQty"));
|
||||
assertEquals(6, columnMapping.getIndexPosition("details.product.id"));
|
||||
assertEquals(7, columnMapping.getIndexPosition("details.product.name"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithCoalesceFunction() {
|
||||
|
||||
String rs = "select id, coalesce(status,'E') as status, " +
|
||||
" budgets.amount as budget," +
|
||||
" COALESCE(month_sums.sum,0.0) as transaction_sum, " +
|
||||
" COALESCE(month_balances.balance,0.0) as balance, " +
|
||||
" COALESCE(month_sums.end_date,date_trunc('month',budgets.month),month_balances.end_date) as data_month" +
|
||||
" from o_order order by id asc";
|
||||
|
||||
RawSqlBuilder builder = RawSqlBuilder.parse(rs);
|
||||
|
||||
RawSql rawSql = builder.create();
|
||||
RawSql.ColumnMapping columnMapping = rawSql.getColumnMapping();
|
||||
|
||||
assertEquals(0, columnMapping.getIndexPosition("id"));
|
||||
assertEquals(1, columnMapping.getIndexPosition("status"));
|
||||
assertEquals(2, columnMapping.getIndexPosition("budget"));
|
||||
assertEquals(3, columnMapping.getIndexPosition("transactionSum"));
|
||||
assertEquals(4, columnMapping.getIndexPosition("balance"));
|
||||
assertEquals(5, columnMapping.getIndexPosition("dataMonth"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postgres_parse_withDateTruncCaseHaving() {
|
||||
|
||||
if (!isPostgres()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
String sql = "select DATE_TRUNC('DAY', d.order_date) as day," +
|
||||
" count(*) as total," +
|
||||
" sum(case when d.status = 0 then 2 else 3 end) as scheduled," +
|
||||
" sum(case when d.status = 1 then 1 else 0 end) as completed" +
|
||||
" from o_order d" +
|
||||
" group by DATE_TRUNC('DAY', d.order_date)";
|
||||
|
||||
RawSql rawSql = RawSqlBuilder.parse(sql).create();
|
||||
|
||||
RawSql.ColumnMapping columnMapping = rawSql.getColumnMapping();
|
||||
|
||||
assertEquals(0, columnMapping.getIndexPosition("day"));
|
||||
assertEquals(1, columnMapping.getIndexPosition("total"));
|
||||
assertEquals(2, columnMapping.getIndexPosition("scheduled"));
|
||||
assertEquals(3, columnMapping.getIndexPosition("completed"));
|
||||
|
||||
Query<ERawSqlAggBean> query = Ebean.find(ERawSqlAggBean.class)
|
||||
.setRawSql(rawSql)
|
||||
.having().gt("total", 2)
|
||||
.query();
|
||||
|
||||
|
||||
query.findList();
|
||||
|
||||
String fullSql = query.getGeneratedSql();
|
||||
assertThat(fullSql).contains(" having count(*) > ?");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.RawSql.Sql;
|
||||
import io.ebean.RawSqlBuilder;
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.Assert;
|
||||
|
||||
public class TestRawSqlBuilderDistinct extends TestCase {
|
||||
|
||||
public void testDistinct() {
|
||||
|
||||
RawSqlBuilder r = RawSqlBuilder.parse("select distinct id, name from t_cust");
|
||||
Sql sql = r.getSql();
|
||||
Assert.assertEquals("id, name", sql.getPreFrom());
|
||||
Assert.assertEquals("from t_cust", sql.getPreWhere());
|
||||
Assert.assertEquals("", sql.getPreHaving());
|
||||
Assert.assertNull(sql.getOrderBy());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.DRawSqlColumnsParser;
|
||||
import io.ebean.RawSql.ColumnMapping;
|
||||
import io.ebean.RawSql.ColumnMapping.Column;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class TestRawSqlColumnParsing extends TestCase {
|
||||
|
||||
public void test_simple() {
|
||||
|
||||
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a,b,c");
|
||||
Map<String, Column> mapping = columnMapping.mapping();
|
||||
Column c = mapping.get("a");
|
||||
|
||||
assertEquals("a", c.getDbColumn());
|
||||
assertEquals(0, c.getIndexPos());
|
||||
assertEquals("a", c.getPropertyName());
|
||||
|
||||
c = mapping.get("b");
|
||||
assertEquals("b", c.getDbColumn());
|
||||
assertEquals(1, c.getIndexPos());
|
||||
assertEquals("b", c.getPropertyName());
|
||||
|
||||
c = mapping.get("c");
|
||||
assertEquals("c", c.getDbColumn());
|
||||
assertEquals(2, c.getIndexPos());
|
||||
assertEquals("c", c.getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
public void test_simpleWithSpacing() {
|
||||
|
||||
ColumnMapping columnMapping = DRawSqlColumnsParser.parse(" a , b , c ");
|
||||
Map<String, Column> mapping = columnMapping.mapping();
|
||||
Column c = mapping.get("a");
|
||||
|
||||
assertEquals("a", c.getDbColumn());
|
||||
assertEquals(0, c.getIndexPos());
|
||||
assertEquals("a", c.getPropertyName());
|
||||
|
||||
c = mapping.get("b");
|
||||
assertEquals("b", c.getDbColumn());
|
||||
assertEquals(1, c.getIndexPos());
|
||||
assertEquals("b", c.getPropertyName());
|
||||
|
||||
c = mapping.get("c");
|
||||
assertEquals("c", c.getDbColumn());
|
||||
assertEquals(2, c.getIndexPos());
|
||||
assertEquals("c", c.getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
public void test_withAlias() {
|
||||
|
||||
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, c c2 , d d3 , e e4 ");
|
||||
Map<String, Column> mapping = columnMapping.mapping();
|
||||
|
||||
assertEquals(5, mapping.size());
|
||||
|
||||
Column c = mapping.get("a0");
|
||||
|
||||
assertEquals("a", c.getDbColumn());
|
||||
assertEquals(0, c.getIndexPos());
|
||||
assertEquals("a0", c.getPropertyName());
|
||||
|
||||
c = mapping.get("b1");
|
||||
assertEquals("b", c.getDbColumn());
|
||||
assertEquals(1, c.getIndexPos());
|
||||
assertEquals("b1", c.getPropertyName());
|
||||
|
||||
c = mapping.get("c2");
|
||||
assertEquals("c", c.getDbColumn());
|
||||
assertEquals(2, c.getIndexPos());
|
||||
assertEquals("c2", c.getPropertyName());
|
||||
|
||||
c = mapping.get("d3");
|
||||
assertEquals("d", c.getDbColumn());
|
||||
assertEquals(3, c.getIndexPos());
|
||||
assertEquals("d3", c.getPropertyName());
|
||||
|
||||
|
||||
c = mapping.get("e4");
|
||||
assertEquals("e", c.getDbColumn());
|
||||
assertEquals(4, c.getIndexPos());
|
||||
assertEquals("e4", c.getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
public void test_withDatabaseFunction() {
|
||||
|
||||
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, MONTH(MAKEDATE(2015, 241)) m2 , d d3 , e e4 ");
|
||||
Map<String, Column> mapping = columnMapping.mapping();
|
||||
|
||||
assertEquals(5, mapping.size());
|
||||
|
||||
Column c = mapping.get("a0");
|
||||
|
||||
assertEquals("a", c.getDbColumn());
|
||||
assertEquals(0, c.getIndexPos());
|
||||
assertEquals("a0", c.getPropertyName());
|
||||
|
||||
c = mapping.get("b1");
|
||||
assertEquals("b", c.getDbColumn());
|
||||
assertEquals(1, c.getIndexPos());
|
||||
assertEquals("b1", c.getPropertyName());
|
||||
|
||||
c = mapping.get("m2");
|
||||
assertEquals("MONTH(MAKEDATE(2015, 241))", c.getDbColumn());
|
||||
assertEquals(2, c.getIndexPos());
|
||||
assertEquals("m2", c.getPropertyName());
|
||||
|
||||
c = mapping.get("d3");
|
||||
assertEquals("d", c.getDbColumn());
|
||||
assertEquals(3, c.getIndexPos());
|
||||
assertEquals("d3", c.getPropertyName());
|
||||
|
||||
|
||||
c = mapping.get("e4");
|
||||
assertEquals("e", c.getDbColumn());
|
||||
assertEquals(4, c.getIndexPos());
|
||||
assertEquals("e4", c.getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
public void test_withAsAlias() {
|
||||
|
||||
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a as a0,'b' b1, \"c(blah)\" as c2 , d as d3 , e as e4 ");
|
||||
Map<String, Column> mapping = columnMapping.mapping();
|
||||
|
||||
assertEquals(5, mapping.size());
|
||||
|
||||
Column c = mapping.get("a0");
|
||||
|
||||
assertEquals("a", c.getDbColumn());
|
||||
assertEquals(0, c.getIndexPos());
|
||||
assertEquals("a0", c.getPropertyName());
|
||||
|
||||
c = mapping.get("b1");
|
||||
assertEquals("'b'", c.getDbColumn());
|
||||
assertEquals(1, c.getIndexPos());
|
||||
assertEquals("b1", c.getPropertyName());
|
||||
|
||||
c = mapping.get("c2");
|
||||
assertEquals("\"c(blah)\"", c.getDbColumn());
|
||||
assertEquals(2, c.getIndexPos());
|
||||
assertEquals("c2", c.getPropertyName());
|
||||
|
||||
c = mapping.get("d3");
|
||||
assertEquals("d", c.getDbColumn());
|
||||
assertEquals(3, c.getIndexPos());
|
||||
assertEquals("d3", c.getPropertyName());
|
||||
|
||||
|
||||
c = mapping.get("e4");
|
||||
assertEquals("e", c.getDbColumn());
|
||||
assertEquals(4, c.getIndexPos());
|
||||
assertEquals("e4", c.getPropertyName());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.bean.EntityBean;
|
||||
import org.tests.model.converstation.User;
|
||||
import org.avaje.ebeantest.LoggedSqlCollector;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestUnsetLoadedProperties extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testUnsetPropertyLoadedState() {
|
||||
|
||||
// populate db with a user
|
||||
User seed = new User();
|
||||
seed.setName("someName");
|
||||
seed.setEmail("some@junk.com");
|
||||
seed.save();
|
||||
|
||||
|
||||
// our bean to perform stateless update
|
||||
User user = new User();
|
||||
user.setId(seed.getId());
|
||||
user.setName("name mod");
|
||||
user.setEmail("change@junk.com");
|
||||
|
||||
|
||||
BeanState beanState = Ebean.getBeanState(user);
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name", "email");
|
||||
|
||||
user.markPropertyUnset("email");
|
||||
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name");
|
||||
|
||||
LoggedSqlCollector.start();
|
||||
user.update();
|
||||
|
||||
List<String> loggedSql = LoggedSqlCollector.stop();
|
||||
assertThat(loggedSql).hasSize(1);
|
||||
assertThat(loggedSql.get(0)).doesNotContain("email");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnloadVia_EntityBeanIntercept_setPropertyLoaded() {
|
||||
|
||||
// our bean to perform stateless update
|
||||
User user = new User();
|
||||
user.setId(42L);
|
||||
user.setName("name mod");
|
||||
user.setEmail("change@junk.com");
|
||||
|
||||
BeanState beanState = Ebean.getBeanState(user);
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name", "email");
|
||||
|
||||
// unset the loaded state for email
|
||||
((EntityBean) user)._ebean_getIntercept().setPropertyLoaded("email", false);
|
||||
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnloadVia_Model_markPropertyUnset() {
|
||||
|
||||
// our bean to perform stateless update
|
||||
User user = new User();
|
||||
user.setId(42L);
|
||||
user.setName("name mod");
|
||||
user.setEmail("change@junk.com");
|
||||
|
||||
BeanState beanState = Ebean.getBeanState(user);
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name", "email");
|
||||
|
||||
|
||||
user.markPropertyUnset("email");
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnloadVia_BeanState_setPropertyLoaded() {
|
||||
|
||||
// our bean to perform stateless update
|
||||
User user = new User();
|
||||
user.setId(42L);
|
||||
user.setName("name mod");
|
||||
user.setEmail("change@junk.com");
|
||||
|
||||
BeanState beanState = Ebean.getBeanState(user);
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name", "email");
|
||||
|
||||
Ebean.getBeanState(user).setPropertyLoaded("email", false);
|
||||
assertThat(beanState.getLoadedProps()).containsExactly("id", "name");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package io.ebean;
|
||||
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.search.Match;
|
||||
import io.ebean.search.MultiMatch;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextExpressionListTest {
|
||||
|
||||
@Test
|
||||
public void syntax() {
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text().match("name", "rob");
|
||||
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text().should()
|
||||
.match("name", "rob")
|
||||
.match("note", "war and peace");
|
||||
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text()
|
||||
.should()
|
||||
.match("title", "war and peace")
|
||||
.match("author", "leo tolstoy")
|
||||
.should()
|
||||
.match("translator", "Constance Garnett")
|
||||
.match("translator", "Louise Maude");
|
||||
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text()
|
||||
.should()
|
||||
.match("title", "war and peace")
|
||||
.match("author", "leo tolstoy")
|
||||
.should()
|
||||
.match("translator", "Constance Garnett", new Match().opAnd().boost(2).minShouldMatch("75%"))
|
||||
.match("translator", "Louise Maude")
|
||||
.where()
|
||||
.gt("reviewDate", 12345);
|
||||
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text()
|
||||
.must()
|
||||
.match("title", "quick")
|
||||
.endJunction()
|
||||
.should()
|
||||
.match("title", "brown")
|
||||
.match("title", "dog")
|
||||
.endJunction()
|
||||
.mustNot()
|
||||
.match("title", "lazy")
|
||||
.endJunction()
|
||||
.where()
|
||||
.gt("reviewDate", 12345);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void syntax_multiMatch() {
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text()
|
||||
.multiMatch("Will Smith", "title", "*name");
|
||||
|
||||
MultiMatch match = MultiMatch.fields("title", "*name")
|
||||
.opAnd()
|
||||
.type(MultiMatch.Type.PHRASE_PREFIX);
|
||||
|
||||
Ebean.find(Order.class)
|
||||
.text()
|
||||
.multiMatch("Will Smith", match);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package io.ebean;
|
||||
|
||||
import io.ebean.PersistBatch;
|
||||
import io.ebean.TxScope;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class TxScopeTest {
|
||||
|
||||
@Test
|
||||
public void checkBatchMode_when_bothNull() throws Exception {
|
||||
|
||||
TxScope scope = new TxScope();
|
||||
scope.setBatchSize(100);
|
||||
|
||||
assertNull(scope.getBatch());
|
||||
assertNull(scope.getBatchOnCascade());
|
||||
|
||||
scope.checkBatchMode();
|
||||
assertEquals(scope.getBatch(), PersistBatch.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkBatchMode_when_bothInherit() throws Exception {
|
||||
|
||||
TxScope scope = new TxScope();
|
||||
scope.setBatchSize(100);
|
||||
scope.setBatch(PersistBatch.INHERIT);
|
||||
scope.setBatchOnCascade(PersistBatch.INHERIT);
|
||||
|
||||
scope.checkBatchMode();
|
||||
assertEquals(scope.getBatch(), PersistBatch.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkBatchMode_when_batchSizeZero_and_onCascadeInherit() throws Exception {
|
||||
|
||||
TxScope scope = new TxScope();
|
||||
scope.setBatchOnCascade(PersistBatch.INHERIT);
|
||||
|
||||
scope.checkBatchMode();
|
||||
assertNull(scope.getBatch());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkBatchMode_when_batchSizeZero_and_bothInherit() throws Exception {
|
||||
|
||||
TxScope scope = new TxScope();
|
||||
scope.setBatch(PersistBatch.INHERIT);
|
||||
scope.setBatchOnCascade(PersistBatch.INHERIT);
|
||||
|
||||
scope.checkBatchMode();
|
||||
assertEquals(scope.getBatch(), PersistBatch.INHERIT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkBatchMode_when_onCascadeSet() throws Exception {
|
||||
|
||||
TxScope scope = new TxScope();
|
||||
scope.setBatchSize(100);
|
||||
scope.setBatchOnCascade(PersistBatch.INSERT);
|
||||
|
||||
scope.checkBatchMode();
|
||||
assertNull(scope.getBatch());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package io.ebean;
|
||||
|
||||
import org.tests.model.basic.Country;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class UpdateQueryTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void basic() {
|
||||
|
||||
EbeanServer server = server();
|
||||
UpdateQuery<Customer> update = server.update(Customer.class);
|
||||
Query<Customer> query = update
|
||||
.set("status", Customer.Status.ACTIVE)
|
||||
.set("updtime", new Timestamp(System.currentTimeMillis()))
|
||||
.where()
|
||||
.eq("status", Customer.Status.NEW)
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
query.update();
|
||||
|
||||
assertThat(query.getGeneratedSql()).contains("update o_customer set status=?, updtime=? where status = ? and id > ?");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void withJoin() {
|
||||
|
||||
if (isMySql()) {
|
||||
return;
|
||||
}
|
||||
EbeanServer server = server();
|
||||
|
||||
Country nz = server.getReference(Country.class, "NZ");
|
||||
|
||||
UpdateQuery<Customer> update = server.update(Customer.class);
|
||||
Query<Customer> query = update
|
||||
.set("status", Customer.Status.ACTIVE)
|
||||
.set("updtime", new Timestamp(System.currentTimeMillis()))
|
||||
.where()
|
||||
.eq("status", Customer.Status.NEW)
|
||||
.eq("billingAddress.country", nz)
|
||||
//.isEmpty("contacts")
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
query.update();
|
||||
|
||||
assertThat(sqlOf(query)).contains("update o_customer set status=?, updtime=? where id in (select t0.id from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and t1.country_code = ? and t0.id > ? )");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whereIsEmpty() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
Query<Customer> updateQuery = server
|
||||
.update(Customer.class)
|
||||
.set("status", Customer.Status.ACTIVE)
|
||||
.where()
|
||||
.isEmpty("contacts")
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
updateQuery.update();
|
||||
|
||||
assertThat(updateQuery.getGeneratedSql()).contains("update o_customer set status=? where not exists (select 1 from contact where customer_id = id) and id > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setNull() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
Query<Customer> updateQuery = server
|
||||
.update(Customer.class)
|
||||
.setNull("status")
|
||||
.where()
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
updateQuery.update();
|
||||
|
||||
assertThat(updateQuery.getGeneratedSql()).contains("update o_customer set status=null where id > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void set_whenValueIsNull_expectNull() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
Query<Customer> updateQuery = server
|
||||
.update(Customer.class)
|
||||
.set("status", null)
|
||||
.where()
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
updateQuery.update();
|
||||
|
||||
assertThat(updateQuery.getGeneratedSql()).contains("update o_customer set status=null where id > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setExpression() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
Query<Customer> updateQuery = server
|
||||
.update(Customer.class)
|
||||
.setRaw("status = coalesce(status, 'A')")
|
||||
.where()
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
updateQuery.update();
|
||||
|
||||
assertThat(updateQuery.getGeneratedSql()).contains("update o_customer set status = coalesce(status, 'A') where id > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setExpression_withBind() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
Query<Customer> updateQuery = server
|
||||
.update(Customer.class)
|
||||
.setRaw("status = coalesce(status, ?)", Customer.Status.ACTIVE)
|
||||
.where()
|
||||
.gt("id", 1000)
|
||||
.query();
|
||||
|
||||
updateQuery.update();
|
||||
|
||||
assertThat(updateQuery.getGeneratedSql()).contains("update o_customer set status = coalesce(status, ?) where id > ?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fluidSyntax() {
|
||||
|
||||
EbeanServer server = server();
|
||||
|
||||
int rows = server
|
||||
.update(Customer.class)
|
||||
.setRaw("status = coalesce(status, ?)", Customer.Status.ACTIVE)
|
||||
.where()
|
||||
.gt("id", 10000)
|
||||
.update();
|
||||
|
||||
assertThat(rows).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void useViaEbean() {
|
||||
|
||||
int rows = Ebean.update(Customer.class)
|
||||
.setRaw("status = coalesce(status, ?)", Customer.Status.ACTIVE)
|
||||
.where()
|
||||
.gt("id", 10000)
|
||||
.update();
|
||||
|
||||
assertThat(rows).isEqualTo(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package io.ebean.bean;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.Ebean;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.EBasic;
|
||||
import org.tests.model.basic.ResetBasicData;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class EntityBeanInterceptTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testHasDirtyProperty() throws Exception {
|
||||
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Customer> list = Ebean.find(Customer.class).findList();
|
||||
|
||||
Set<String> propertyNames = new HashSet<>();
|
||||
propertyNames.add("name");
|
||||
propertyNames.add("status");
|
||||
|
||||
|
||||
Customer customer = list.get(0);
|
||||
EntityBeanIntercept ebi = ((EntityBean) customer)._ebean_getIntercept();
|
||||
|
||||
assertFalse(ebi.hasDirtyProperty(propertyNames));
|
||||
|
||||
customer.setAnniversary(new Date(System.currentTimeMillis()));
|
||||
assertFalse(ebi.hasDirtyProperty(propertyNames));
|
||||
|
||||
customer.setStatus(Customer.Status.ACTIVE);
|
||||
assertTrue(ebi.hasDirtyProperty(propertyNames));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isPartial_when_new() {
|
||||
|
||||
EBasic basic = new EBasic();
|
||||
EntityBeanIntercept ebi = ((EntityBean) basic)._ebean_getIntercept();
|
||||
assertThat(ebi.isPartial()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isPartial_when_partial() {
|
||||
|
||||
EBasic basic = new EBasic();
|
||||
basic.setId(42);
|
||||
basic.setName("some");
|
||||
EntityBeanIntercept ebi = ((EntityBean) basic)._ebean_getIntercept();
|
||||
assertThat(ebi.isPartial()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isPartial_when_full() {
|
||||
|
||||
EBasic basic = new EBasic();
|
||||
basic.setId(42);
|
||||
basic.setName("some");
|
||||
basic.setDescription("asd");
|
||||
basic.setSomeDate(null);
|
||||
basic.setStatus(EBasic.Status.ACTIVE);
|
||||
|
||||
EntityBeanIntercept ebi = ((EntityBean) basic)._ebean_getIntercept();
|
||||
assertThat(ebi.isPartial()).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package io.ebean.common;
|
||||
|
||||
import io.ebean.bean.BeanCollection;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class BeanListTest {
|
||||
|
||||
Object object1 = new Object();
|
||||
Object object2 = new Object();
|
||||
Object object3 = new Object();
|
||||
|
||||
@NotNull
|
||||
private List<Object> all() {
|
||||
List<Object> all = new ArrayList<>();
|
||||
all.add(object1);
|
||||
all.add(object2);
|
||||
all.add(object3);
|
||||
return all;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private List<Object> some() {
|
||||
List<Object> some = new ArrayList<>();
|
||||
some.add(object2);
|
||||
some.add(object3);
|
||||
return some;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.add(object1);
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
|
||||
list.add(object1);
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1);
|
||||
|
||||
list.add(object2);
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2);
|
||||
|
||||
list.remove(object1);
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object2);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAll_given_emptyStart() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.addAll(all());
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(some());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
assertThat(list.contains(object1)).isFalse();
|
||||
list.add(object1);
|
||||
assertThat(list.contains(object2)).isTrue();
|
||||
list.add(object2); // object2 added as List allows duplicates
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddSome_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(some());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.addAll(all());
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.addAll(all());
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
list.remove(object2);
|
||||
list.remove(object3);
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.addAll(all());
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
list.removeAll(some());
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(all());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.remove(object2);
|
||||
list.remove(object3);
|
||||
|
||||
// assert
|
||||
assertThat(list.getModifyAdditions()).isEmpty();
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(all());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.removeAll(some());
|
||||
|
||||
// assert
|
||||
assertThat(list.getModifyAdditions()).isEmpty();
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(all());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.clear();
|
||||
|
||||
//assert
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object1, object2, object3);
|
||||
assertThat(list.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear_given_someBeansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.add(object1);
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.add(object2);
|
||||
list.add(object3);
|
||||
|
||||
// act
|
||||
list.clear();
|
||||
|
||||
//assert
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object1);
|
||||
assertThat(list.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.addAll(all());
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
list.retainAll(some());
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object2, object3);
|
||||
assertThat(list.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_someBeansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
list.add(object1);
|
||||
list.add(object2);
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
list.add(object3);
|
||||
|
||||
// act
|
||||
list.retainAll(some());
|
||||
|
||||
assertThat(list.getModifyAdditions()).containsExactly(object3);
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_noBeansInAdditions() throws Exception {
|
||||
|
||||
BeanList<Object> list = new BeanList<>(all());
|
||||
list.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
list.retainAll(some());
|
||||
|
||||
assertThat(list.getModifyRemovals()).containsExactly(object1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void internalAddWithCheck_when_interestingEquals_usesInstanceEquality() {
|
||||
|
||||
BeanList<Object> list = new BeanList<>();
|
||||
assertThat(list).hasSize(0);
|
||||
|
||||
SomeBean a = new SomeBean("A");
|
||||
list.internalAddWithCheck(a);
|
||||
list.internalAddWithCheck(a);
|
||||
assertThat(list).hasSize(1);
|
||||
|
||||
// expect to ignore equals and add as it is a diff instance (aka don't use equals())
|
||||
list.internalAddWithCheck(new SomeBean("A"));
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
list.internalAddWithCheck(new SomeBean("B"));
|
||||
assertThat(list).hasSize(3);
|
||||
}
|
||||
|
||||
/**
|
||||
* A entity bean with interesting equals implementation.
|
||||
*/
|
||||
private static class SomeBean {
|
||||
|
||||
final String val;
|
||||
|
||||
SomeBean(String val) {
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return 42;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other instanceof SomeBean) {
|
||||
return this.val.equals(((SomeBean) other).val);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package io.ebean.common;
|
||||
|
||||
import io.ebean.bean.BeanCollection;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class BeanMapTest {
|
||||
|
||||
Object object1 = new Object();
|
||||
Object object2 = new Object();
|
||||
Object object3 = new Object();
|
||||
|
||||
@NotNull
|
||||
private Map<String, Object> all() {
|
||||
Map<String, Object> all = new LinkedHashMap<>();
|
||||
all.put("1", object1);
|
||||
all.put("2", object2);
|
||||
all.put("3", object3);
|
||||
return all;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private Map<String, Object> some() {
|
||||
Map<String, Object> all = new LinkedHashMap<>();
|
||||
all.put("2", object2);
|
||||
all.put("3", object3);
|
||||
return all;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>();
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
map.put("1", object1);
|
||||
map.put("4", null);
|
||||
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
|
||||
map.put("1", object1);
|
||||
map.put("4", null);
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
|
||||
map.put("2", object2);
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1, object2);
|
||||
|
||||
map.remove("1");
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object2);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAll_given_emptyStart() throws Exception {
|
||||
|
||||
BeanMap<String, Object> set = new BeanMap<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.putAll(all());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>(some());
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
assertThat(map.values().contains(object1)).isFalse();
|
||||
map.put("1", object1);
|
||||
assertThat(map.values().contains(object2)).isTrue();
|
||||
map.put("2", object2);
|
||||
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddSome_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>(some());
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
map.putAll(all());
|
||||
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>();
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
map.putAll(all());
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
map.remove("2");
|
||||
map.remove("3");
|
||||
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>();
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
map.putAll(all());
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
map.remove("2");
|
||||
map.remove("3");
|
||||
|
||||
assertThat(map.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(map.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>(all());
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
map.remove("2");
|
||||
map.remove("3");
|
||||
|
||||
// assert
|
||||
assertThat(map.getModifyAdditions()).isEmpty();
|
||||
assertThat(map.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>(all());
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
map.remove("2");
|
||||
map.remove("3");
|
||||
|
||||
// assert
|
||||
assertThat(map.getModifyAdditions()).isEmpty();
|
||||
assertThat(map.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>(all());
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
map.clear();
|
||||
|
||||
//assert
|
||||
assertThat(map.getModifyRemovals()).containsExactly(object1, object2, object3);
|
||||
assertThat(map.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear_given_someBeansInAdditions() throws Exception {
|
||||
|
||||
BeanMap<String, Object> map = new BeanMap<>();
|
||||
map.put("1", object1);
|
||||
map.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
map.put("2", object2);
|
||||
map.put("3", object3);
|
||||
|
||||
// act
|
||||
map.clear();
|
||||
|
||||
//assert
|
||||
assertThat(map.getModifyRemovals()).containsExactly(object1);
|
||||
assertThat(map.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package io.ebean.common;
|
||||
|
||||
import io.ebean.bean.BeanCollection;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class BeanSetTest {
|
||||
|
||||
Object object1 = new Object();
|
||||
Object object2 = new Object();
|
||||
Object object3 = new Object();
|
||||
|
||||
@NotNull
|
||||
private Set<Object> all() {
|
||||
Set<Object> all = new LinkedHashSet<>();
|
||||
all.add(object1);
|
||||
all.add(object2);
|
||||
all.add(object3);
|
||||
return all;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private Set<Object> some() {
|
||||
Set<Object> some = new LinkedHashSet<>();
|
||||
some.add(object2);
|
||||
some.add(object3);
|
||||
return some;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.add(object1);
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
|
||||
set.add(object1);
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
|
||||
set.add(object2);
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2);
|
||||
|
||||
set.remove(object1);
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object2);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAll_given_emptyStart() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.addAll(all());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(some());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
assertThat(set.contains(object1)).isFalse();
|
||||
set.add(object1);
|
||||
assertThat(set.contains(object2)).isTrue();
|
||||
set.add(object2);
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddSome_given_someAlreadyIn() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(some());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.addAll(all());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.addAll(all());
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
set.remove(object2);
|
||||
set.remove(object3);
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.addAll(all());
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
set.removeAll(some());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(all());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.remove(object2);
|
||||
set.remove(object3);
|
||||
|
||||
// assert
|
||||
assertThat(set.getModifyAdditions()).isEmpty();
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemoveAll_given_beansNotInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(all());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.removeAll(some());
|
||||
|
||||
// assert
|
||||
assertThat(set.getModifyAdditions()).isEmpty();
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object2, object3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(all());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.clear();
|
||||
|
||||
//assert
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object1, object2, object3);
|
||||
assertThat(set.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClear_given_someBeansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.add(object1);
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.add(object2);
|
||||
set.add(object3);
|
||||
|
||||
// act
|
||||
set.clear();
|
||||
|
||||
//assert
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object1);
|
||||
assertThat(set.getModifyAdditions()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_beansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.addAll(all());
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object1, object2, object3);
|
||||
|
||||
// act
|
||||
set.retainAll(some());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object2, object3);
|
||||
assertThat(set.getModifyRemovals()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_someBeansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>();
|
||||
set.add(object1);
|
||||
set.add(object2);
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
set.add(object3);
|
||||
|
||||
// act
|
||||
set.retainAll(some());
|
||||
|
||||
assertThat(set.getModifyAdditions()).containsExactly(object3);
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRetainAll_given_noBeansInAdditions() throws Exception {
|
||||
|
||||
BeanSet<Object> set = new BeanSet<>(all());
|
||||
set.setModifyListening(BeanCollection.ModifyListenMode.ALL);
|
||||
|
||||
// act
|
||||
set.retainAll(some());
|
||||
|
||||
assertThat(set.getModifyRemovals()).containsExactly(object1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DbConstraintNamingTest {
|
||||
|
||||
DbConstraintNaming naming = new DbConstraintNaming();
|
||||
|
||||
@Test
|
||||
public void testPrimaryKeyName() throws Exception {
|
||||
|
||||
assertThat(naming.primaryKeyName("[cat].[sce].[foo_bar]")).isEqualTo("pk_foo_bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUniqueConstraintName() throws Exception {
|
||||
|
||||
assertThat(naming.uniqueConstraintName("[foo_bar]", "[jim]")).isEqualTo("uq_foo_bar_jim");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCheckConstraintName() throws Exception {
|
||||
|
||||
assertThat(naming.checkConstraintName("[foo_bar]", "[jim]")).isEqualTo("ck_foo_bar_jim");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalise() throws Exception {
|
||||
|
||||
assertThat(naming.normaliseTable("cat.sch.foo_bar]")).isEqualTo("foo_bar");
|
||||
assertThat(naming.normaliseTable("sch.foo_bar]")).isEqualTo("foo_bar");
|
||||
assertThat(naming.normaliseTable("foo_bar]")).isEqualTo("foo_bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultToLower() throws Exception {
|
||||
assertThat(naming.normaliseTable("SCH.FOO_BAR]")).isEqualTo("foo_bar");
|
||||
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR")).isEqualTo("sch.foo_bar");
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR")).isEqualTo("sch.foo_bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoLowerCaseTable() throws Exception {
|
||||
|
||||
DbConstraintNaming naming = new DbConstraintNaming(false, true);
|
||||
assertThat(naming.normaliseTable("SCH.FOO_BAR]")).isEqualTo("FOO_BAR");
|
||||
assertThat(naming.normaliseColumn("SCH.FOO_BAR]")).isEqualTo("sch.foo_bar");
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
// table name not lowered
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR")).isEqualTo("SCH.FOO_BAR");
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR")).isEqualTo("sch.foo_bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoLowerCaseColumn() throws Exception {
|
||||
|
||||
DbConstraintNaming naming = new DbConstraintNaming(true, false);
|
||||
assertThat(naming.normaliseTable("SCH.FOO_BAR]")).isEqualTo("foo_bar");
|
||||
assertThat(naming.normaliseColumn("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR");
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
assertThat(naming.lowerTableName("SCH.FOO_BAR")).isEqualTo("sch.foo_bar");
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR]")).isEqualTo("SCH.FOO_BAR]");
|
||||
// column name not lowered
|
||||
assertThat(naming.lowerColumnName("SCH.FOO_BAR")).isEqualTo("SCH.FOO_BAR");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class DbMigrationConfigTest {
|
||||
|
||||
@Test
|
||||
public void testLoad() {
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("h2other");
|
||||
config.loadFromProperties();
|
||||
config.setDefaultServer(false);
|
||||
|
||||
DbMigrationConfig migrationConfig = config.getMigrationConfig();
|
||||
|
||||
assertThat(migrationConfig.getMigrationPath()).isEqualTo("dbmigration/myapp");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadProperties_migration() {
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("ebean.migration.dbusername", "banana");
|
||||
properties.setProperty("ebean.migration.dbpassword", "apple");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", "db", properties);
|
||||
|
||||
DbMigrationConfig migrationConfig = new DbMigrationConfig();
|
||||
migrationConfig.loadSettings(wrapper, "db");
|
||||
|
||||
assertEquals(migrationConfig.getDbUsername(),"banana");
|
||||
assertEquals(migrationConfig.getDbPassword(),"apple");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadProperties_datasource() {
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("datasource.db.username", "banana");
|
||||
properties.setProperty("datasource.db.password", "apple");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", "db", properties);
|
||||
|
||||
DbMigrationConfig migrationConfig = new DbMigrationConfig();
|
||||
migrationConfig.loadSettings(wrapper, "db");
|
||||
|
||||
assertEquals(migrationConfig.getDbUsername(),"banana");
|
||||
assertEquals(migrationConfig.getDbPassword(),"apple");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadProperties_datasource_adminusername() {
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("datasource.db.adminusername", "banana");
|
||||
properties.setProperty("datasource.db.adminpassword", "apple");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", "db", properties);
|
||||
|
||||
DbMigrationConfig migrationConfig = new DbMigrationConfig();
|
||||
migrationConfig.loadSettings(wrapper, "db");
|
||||
|
||||
assertEquals(migrationConfig.getDbUsername(),"banana");
|
||||
assertEquals(migrationConfig.getDbPassword(),"apple");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import io.ebean.annotation.DocStoreMode;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class DocStoreConfigTest {
|
||||
|
||||
@Test
|
||||
public void loadSettings() throws Exception {
|
||||
|
||||
DocStoreConfig config = new DocStoreConfig();
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("ebean.docstore.active", "true");
|
||||
properties.setProperty("ebean.docstore.bulkBatchSize", "99");
|
||||
properties.setProperty("ebean.docstore.url", "http://foo:9800");
|
||||
properties.setProperty("ebean.docstore.persist", "IGNORE");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", null, properties);
|
||||
|
||||
config.loadSettings(wrapper);
|
||||
|
||||
assertTrue(config.isActive());
|
||||
assertFalse(config.isGenerateMapping());
|
||||
assertFalse(config.isDropCreate());
|
||||
assertEquals("http://foo:9800", config.getUrl());
|
||||
assertEquals(DocStoreMode.IGNORE, config.getPersist());
|
||||
assertEquals(99, config.getBulkBatchSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadSettings_generateMapping_dropCreate() throws Exception {
|
||||
|
||||
DocStoreConfig config = new DocStoreConfig();
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("ebean.docstore.generateMapping", "true");
|
||||
properties.setProperty("ebean.docstore.dropCreate", "true");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", null, properties);
|
||||
config.loadSettings(wrapper);
|
||||
|
||||
assertTrue(config.isGenerateMapping());
|
||||
assertTrue(config.isDropCreate());
|
||||
assertFalse(config.isCreate());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadSettings_generateMapping_create() throws Exception {
|
||||
|
||||
DocStoreConfig config = new DocStoreConfig();
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("ebean.docstore.generateMapping", "true");
|
||||
properties.setProperty("ebean.docstore.create", "true");
|
||||
|
||||
PropertiesWrapper wrapper = new PropertiesWrapper("ebean", null, properties);
|
||||
config.loadSettings(wrapper);
|
||||
|
||||
assertTrue(config.isGenerateMapping());
|
||||
assertTrue(config.isCreate());
|
||||
assertFalse(config.isDropCreate());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class MatchingNamingConventionTest {
|
||||
|
||||
private MatchingNamingConvention namingConvention = new MatchingNamingConvention();
|
||||
|
||||
@Test
|
||||
public void getColumnFromProperty() throws Exception {
|
||||
|
||||
String fkCol = "bridgetab_userId";
|
||||
String col = namingConvention.getColumnFromProperty(null, fkCol);
|
||||
assertThat(col).isEqualTo(fkCol);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getForeignKey() {
|
||||
|
||||
String fk = namingConvention.getForeignKey("billingAddress", "id");
|
||||
assertThat(fk).isEqualTo("billingAddressId");
|
||||
|
||||
fk = namingConvention.getForeignKey("billingAddress", "remoteIdProperty");
|
||||
assertThat(fk).isEqualTo("billingAddressRemoteIdProperty");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import io.ebean.Platform;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class PropertiesWrapperTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testGetServerName() throws Exception {
|
||||
|
||||
PropertiesWrapper pw = new PropertiesWrapper(null, "myserver", new Properties());
|
||||
assertEquals("myserver", pw.getServerName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetEnum() {
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.put("platform", "postgres");
|
||||
|
||||
PropertiesWrapper pw = new PropertiesWrapper("pref", "myserver", properties);
|
||||
assertEquals(Platform.POSTGRES, pw.getEnum(Platform.class, "platform", Platform.H2));
|
||||
assertEquals(Platform.H2, pw.getEnum(Platform.class, "junk", Platform.H2));
|
||||
assertNull(pw.getEnum(Platform.class, "junk", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrimPropertyValues() {
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.put("someBasic", " hello ");
|
||||
properties.put("someInt", " 42 ");
|
||||
properties.put("noTrimReqr", "jim");
|
||||
properties.put("includeSpaces", " jim bob ");
|
||||
|
||||
PropertiesWrapper pw = new PropertiesWrapper("pref", "myserver", properties);
|
||||
assertEquals("hello", pw.get("someBasic"));
|
||||
assertEquals(42, pw.getInt("someInt", 1));
|
||||
assertNull(pw.get("doesNotExist", null));
|
||||
assertEquals("jim", pw.get("noTrimReqr"));
|
||||
assertEquals("jim bob", pw.get("includeSpaces"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProperties() throws Exception {
|
||||
|
||||
String home = System.getenv("HOME");
|
||||
String tmpDir = System.getProperty("java.io.tmpdir");
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.put("someBasic", "hello");
|
||||
properties.put("someInt", "42");
|
||||
properties.put("someDouble", "5.5");
|
||||
properties.put("somePath", "${HOME}/hello");
|
||||
properties.put("someSystemProp", "/aaa/${java.io.tmpdir}/bbb");
|
||||
|
||||
PropertiesWrapper pw = new PropertiesWrapper("pref", "myserver", properties);
|
||||
|
||||
assertEquals(42, pw.getInt("someInt", 99));
|
||||
assertEquals(Double.valueOf(5.5D), (Double.valueOf(pw.getDouble("someDouble", 99.9D))));
|
||||
assertEquals(home + "/hello", pw.get("somePath", null));
|
||||
assertEquals(tmpDir, "/aaa/" + tmpDir + "/bbb", pw.get("someSystemProp"));
|
||||
|
||||
Properties properties1 = pw.asPropertiesLowerCase();
|
||||
assertEquals("hello", properties1.getProperty("somebasic"));
|
||||
assertEquals("42", properties1.getProperty("someint"));
|
||||
assertEquals(home + "/hello", properties1.get("somepath"));
|
||||
assertEquals(tmpDir, "/aaa/" + tmpDir + "/bbb", properties1.get("somesystemprop"));
|
||||
|
||||
|
||||
pw = new PropertiesWrapper(properties);
|
||||
|
||||
assertEquals(42, pw.getInt("someInt", 99));
|
||||
assertEquals(Double.valueOf(5.5D), (Double.valueOf(pw.getDouble("someDouble", 99.9D))));
|
||||
assertEquals(home + "/hello", pw.get("somePath", null));
|
||||
assertEquals(tmpDir, "/aaa/" + tmpDir + "/bbb", pw.get("someSystemProp"));
|
||||
|
||||
properties1 = pw.asPropertiesLowerCase();
|
||||
assertEquals("hello", properties1.getProperty("somebasic"));
|
||||
assertEquals("42", properties1.getProperty("someint"));
|
||||
assertEquals(home + "/hello", properties1.get("somepath"));
|
||||
assertEquals(tmpDir, "/aaa/" + tmpDir + "/bbb", properties1.get("somesystemprop"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PropertyMapTest {
|
||||
|
||||
@Test
|
||||
public void testDefaultProperties() throws Exception {
|
||||
|
||||
PropertyMap.defaultProperties();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEval() throws Exception {
|
||||
|
||||
String home = System.getenv("HOME");
|
||||
PropertyMap map = new PropertyMap();
|
||||
assertEquals(home, map.eval("${HOME}"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import io.ebean.PersistBatch;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ServerConfigTest {
|
||||
|
||||
@Test
|
||||
public void testLoadFromEbeanProperties() {
|
||||
|
||||
ServerConfig serverConfig = new ServerConfig();
|
||||
serverConfig.loadFromProperties();
|
||||
|
||||
assertEquals(PersistBatch.NONE, serverConfig.getPersistBatch());
|
||||
assertNotNull(serverConfig.getProperties());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoadWithProperties() {
|
||||
|
||||
ServerConfig serverConfig = new ServerConfig();
|
||||
serverConfig.setPersistBatch(PersistBatch.NONE);
|
||||
serverConfig.setPersistBatchOnCascade(PersistBatch.NONE);
|
||||
|
||||
Properties props = new Properties();
|
||||
props.setProperty("persistBatch", "INSERT");
|
||||
props.setProperty("persistBatchOnCascade", "INSERT");
|
||||
props.setProperty("dbuuid", "binary");
|
||||
props.setProperty("jdbcFetchSizeFindEach", "42");
|
||||
props.setProperty("jdbcFetchSizeFindList", "43");
|
||||
props.setProperty("backgroundExecutorShutdownSecs", "98");
|
||||
props.setProperty("backgroundExecutorSchedulePoolSize", "4");
|
||||
props.setProperty("h2ProductionMode", "true");
|
||||
|
||||
serverConfig.loadFromProperties(props);
|
||||
|
||||
assertTrue(serverConfig.isH2ProductionMode());
|
||||
assertEquals(PersistBatch.INSERT, serverConfig.getPersistBatch());
|
||||
assertEquals(PersistBatch.INSERT, serverConfig.getPersistBatchOnCascade());
|
||||
assertEquals(ServerConfig.DbUuid.BINARY, serverConfig.getDbTypeConfig().getDbUuid());
|
||||
assertEquals(42, serverConfig.getJdbcFetchSizeFindEach());
|
||||
assertEquals(43, serverConfig.getJdbcFetchSizeFindList());
|
||||
assertEquals(4, serverConfig.getBackgroundExecutorSchedulePoolSize());
|
||||
assertEquals(98, serverConfig.getBackgroundExecutorShutdownSecs());
|
||||
|
||||
serverConfig.setPersistBatch(PersistBatch.NONE);
|
||||
serverConfig.setPersistBatchOnCascade(PersistBatch.NONE);
|
||||
|
||||
Properties props1 = new Properties();
|
||||
props1.setProperty("ebean.persistBatch", "ALL");
|
||||
props1.setProperty("ebean.persistBatchOnCascade", "ALL");
|
||||
|
||||
serverConfig.loadFromProperties(props1);
|
||||
serverConfig.loadTestProperties();
|
||||
|
||||
assertEquals(PersistBatch.ALL, serverConfig.getPersistBatch());
|
||||
assertEquals(PersistBatch.ALL, serverConfig.getPersistBatchOnCascade());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.ebean.config;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class UnderscoreNamingConventionTest {
|
||||
|
||||
private UnderscoreNamingConvention namingConvention = new UnderscoreNamingConvention();
|
||||
|
||||
@Test
|
||||
public void getColumnFromProperty() throws Exception {
|
||||
|
||||
String fkCol = "bridgetab_user_id";
|
||||
|
||||
String col = namingConvention.getColumnFromProperty(null, fkCol);
|
||||
assertThat(col).isEqualTo(fkCol);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getForeignKey() {
|
||||
|
||||
String fk = namingConvention.getForeignKey("billing_address", "id");
|
||||
assertThat(fk).isEqualTo("billing_address_id");
|
||||
|
||||
fk = namingConvention.getForeignKey("billing_address", "remoteIdProperty");
|
||||
assertThat(fk).isEqualTo("billing_address_remote_id_property");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BasicSqlLimitOffsetTest {
|
||||
|
||||
private BasicSqlLimitOffset limiter = new BasicSqlLimitOffset();
|
||||
|
||||
@Test
|
||||
public void limit_maxRows() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 0, 10);
|
||||
assertThat(sql).isEqualTo(query + " limit 10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limit_firstRowMaxRows() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 5, 10);
|
||||
assertThat(sql).isEqualTo(query + " limit 10 offset 5");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limit_zeros() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 0, 0);
|
||||
assertThat(sql).isEqualTo(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BasicSqlStandardLimiterTest {
|
||||
|
||||
private BasicSqlAnsiLimiter limiter = new BasicSqlAnsiLimiter();
|
||||
|
||||
@Test
|
||||
public void limit_maxRows() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 0, 10);
|
||||
assertThat(sql).isEqualTo(query + " fetch next 10 rows only");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limit_firstRowMaxRows() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 5, 10);
|
||||
assertThat(sql).isEqualTo(query + " offset 5 rows fetch next 10 rows only");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limit_zeros() throws Exception {
|
||||
|
||||
String query = "select * from mytab order by id";
|
||||
String sql = limiter.limit(query, 0, 0);
|
||||
assertThat(sql).isEqualTo(query);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.DbTypeConfig;
|
||||
import io.ebean.Platform;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DatabasePlatformTest {
|
||||
|
||||
@Test
|
||||
public void defaultTypesForDecimalAndVarchar() throws Exception {
|
||||
|
||||
DatabasePlatform dbPlatform = new DatabasePlatform();
|
||||
assertEquals(defaultDecimalDefn(dbPlatform), "decimal(38)");
|
||||
assertEquals(defaultDefn(DbType.VARCHAR, dbPlatform), "varchar(255)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configure_customType() throws Exception {
|
||||
|
||||
DbTypeConfig config = new DbTypeConfig();
|
||||
config.addCustomMapping(DbType.VARCHAR, "text", Platform.POSTGRES);
|
||||
config.addCustomMapping(DbType.DECIMAL, "decimal(24,4)");
|
||||
|
||||
// PG renders custom decimal and varchar
|
||||
PostgresPlatform pgPlatform = new PostgresPlatform();
|
||||
pgPlatform.configure(config);
|
||||
assertEquals(defaultDecimalDefn(pgPlatform), "decimal(24,4)");
|
||||
assertEquals(defaultDefn(DbType.VARCHAR, pgPlatform), "text");
|
||||
|
||||
// H2 only renders custom decimal
|
||||
H2Platform h2Platform = new H2Platform();
|
||||
h2Platform.configure(config);
|
||||
assertEquals(defaultDecimalDefn(h2Platform), "decimal(24,4)");
|
||||
assertEquals(defaultDefn(DbType.VARCHAR, h2Platform), "varchar(255)");
|
||||
}
|
||||
|
||||
private String defaultDecimalDefn(DatabasePlatform dbPlatform) {
|
||||
return defaultDefn(DbType.DECIMAL, dbPlatform);
|
||||
}
|
||||
|
||||
private String defaultDefn(DbType type, DatabasePlatform dbPlatform) {
|
||||
return dbPlatform.getDbTypeMap().get(type).renderType(0, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Types;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DbPlatformTypeLookupTest {
|
||||
|
||||
DbPlatformTypeLookup lookup = new DbPlatformTypeLookup();
|
||||
|
||||
@Test
|
||||
public void byName() throws Exception {
|
||||
|
||||
assertEquals(lookup.byName("DECIMAL"), DbType.DECIMAL);
|
||||
assertEquals(lookup.byName("Decimal"), DbType.DECIMAL);
|
||||
assertEquals(lookup.byName("decimal"), DbType.DECIMAL);
|
||||
|
||||
assertEquals(lookup.byName("varchar"), DbType.VARCHAR);
|
||||
assertEquals(lookup.byName("varchar2"), DbType.VARCHAR);
|
||||
|
||||
assertEquals(lookup.byName("float"), DbType.REAL);
|
||||
assertEquals(lookup.byName("real"), DbType.REAL);
|
||||
|
||||
assertEquals(lookup.byName("uuid"), DbType.UUID);
|
||||
assertEquals(lookup.byName("hstore"), DbType.HSTORE);
|
||||
|
||||
assertEquals(lookup.byName("json"), DbType.JSON);
|
||||
assertEquals(lookup.byName("jsonb"), DbType.JSONB);
|
||||
assertEquals(lookup.byName("jsonclob"), DbType.JSONCLOB);
|
||||
assertEquals(lookup.byName("jsonblob"), DbType.JSONBLOB);
|
||||
assertEquals(lookup.byName("jsonVarchar"), DbType.JSONVARCHAR);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void byId() throws Exception {
|
||||
|
||||
assertEquals(lookup.byId(Types.ARRAY), DbType.ARRAY);
|
||||
assertEquals(lookup.byId(Types.BIGINT), DbType.BIGINT);
|
||||
|
||||
assertEquals(lookup.byId(ExtraDbTypes.UUID), DbType.UUID);
|
||||
assertEquals(lookup.byId(ExtraDbTypes.HSTORE), DbType.HSTORE);
|
||||
|
||||
assertEquals(lookup.byId(ExtraDbTypes.JSON), DbType.JSON);
|
||||
assertEquals(lookup.byId(ExtraDbTypes.JSONB), DbType.JSONB);
|
||||
assertEquals(lookup.byId(ExtraDbTypes.JSONClob), DbType.JSONCLOB);
|
||||
assertEquals(lookup.byId(ExtraDbTypes.JSONBlob), DbType.JSONBLOB);
|
||||
assertEquals(lookup.byId(ExtraDbTypes.JSONVarchar), DbType.JSONVARCHAR);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DbPlatformTypeParserTest {
|
||||
|
||||
@Test
|
||||
public void parse_text() throws Exception {
|
||||
|
||||
DbPlatformType type = DbPlatformTypeParser.parse("text");
|
||||
|
||||
assertEquals(type.getName(), "text");
|
||||
assertEquals(type.getDefaultLength(), 0);
|
||||
assertEquals(type.getDefaultScale(), 0);
|
||||
|
||||
assertEquals(type.renderType(0, 0), "text");
|
||||
assertEquals(type.renderType(40, 0), "text");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parse_varchar20() throws Exception {
|
||||
|
||||
DbPlatformType type = DbPlatformTypeParser.parse("varchar(20)");
|
||||
|
||||
assertEquals(type.getName(), "varchar");
|
||||
assertEquals(type.getDefaultLength(), 20);
|
||||
assertEquals(type.getDefaultScale(), 0);
|
||||
|
||||
assertEquals(type.renderType(0, 0), "varchar(20)");
|
||||
assertEquals(type.renderType(40, 0), "varchar(40)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parse_decimal_18_6() throws Exception {
|
||||
|
||||
DbPlatformType type = DbPlatformTypeParser.parse("decimal(18,6)");
|
||||
|
||||
assertEquals(type.getName(), "decimal");
|
||||
assertEquals(type.getDefaultLength(), 18);
|
||||
assertEquals(type.getDefaultScale(), 6);
|
||||
assertEquals(type.renderType(0, 0), "decimal(18,6)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parse_something() throws Exception {
|
||||
|
||||
DbPlatformType type = DbPlatformTypeParser.parse("something(asd,6)");
|
||||
|
||||
assertEquals(type.getName(), "something(asd,6)");
|
||||
assertEquals(type.getDefaultLength(), 0);
|
||||
assertEquals(type.getDefaultScale(), 0);
|
||||
assertEquals(type.renderType(0, 0), "something(asd,6)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parse_invalid() throws Exception {
|
||||
|
||||
DbPlatformType type = DbPlatformTypeParser.parse("something(asd");
|
||||
|
||||
assertEquals(type.getName(), "something(asd");
|
||||
assertEquals(type.getDefaultLength(), 0);
|
||||
assertEquals(type.getDefaultScale(), 0);
|
||||
assertEquals(type.renderType(0, 0), "something(asd");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class DbTypeMapTest {
|
||||
|
||||
@Test
|
||||
public void testLookupRender_given_postgresPlatformType() throws Exception {
|
||||
|
||||
PostgresPlatform pg = new PostgresPlatform();
|
||||
DbPlatformTypeMapping dbTypeMap = pg.getDbTypeMap();
|
||||
|
||||
assertThat(dbTypeMap.lookup("clob", false).renderType(0, 0)).isEqualTo("text");
|
||||
assertThat(dbTypeMap.lookup("CLOB", false).renderType(0, 0)).isEqualTo("text");
|
||||
|
||||
assertThat(dbTypeMap.lookup("varchar", true).renderType(20, 0)).isEqualTo("varchar(20)");
|
||||
|
||||
assertThat(dbTypeMap.lookup("json", false).renderType(0, 0)).isEqualTo("json");
|
||||
assertThat(dbTypeMap.lookup("jsonb", false).renderType(0, 0)).isEqualTo("jsonb");
|
||||
assertThat(dbTypeMap.lookup("jsonclob", false).renderType(0, 0)).isEqualTo("text");
|
||||
assertThat(dbTypeMap.lookup("jsonblob", false).renderType(0, 0)).isEqualTo("bytea");
|
||||
assertThat(dbTypeMap.lookup("jsonvarchar", false).renderType(200, 0)).isEqualTo("varchar(200)");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPlatformTypes() {
|
||||
|
||||
DbPlatformTypeMapping dbTypeMap = DbPlatformTypeMapping.logicalTypes();
|
||||
DbPlatformType dbType = dbTypeMap.get(DbPlatformType.JSON);
|
||||
DbPlatformType json = dbTypeMap.lookup("json", false);
|
||||
|
||||
assertThat(dbType).isSameAs(json);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.PlatformDdl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class H2PlatformTest {
|
||||
|
||||
H2Platform mySqlPlatform = new H2Platform();
|
||||
|
||||
@Test
|
||||
public void testTypeConversion() {
|
||||
PlatformDdl ddl = mySqlPlatform.getPlatformDdl();
|
||||
assertThat(ddl.convert("clob", false)).isEqualTo("clob");
|
||||
assertThat(ddl.convert("json", false)).isEqualTo("clob");
|
||||
assertThat(ddl.convert("jsonb", false)).isEqualTo("clob");
|
||||
assertThat(ddl.convert("varchar(20)", false)).isEqualTo("varchar(20)");
|
||||
assertThat(ddl.convert("decimal(10)", false)).isEqualTo("decimal(10)");
|
||||
assertThat(ddl.convert("decimal(8,4)", false)).isEqualTo("decimal(8,4)");
|
||||
assertThat(ddl.convert("boolean", false)).isEqualTo("boolean");
|
||||
assertThat(ddl.convert("bit", false)).isEqualTo("bit");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
|
||||
import io.ebean.config.dbplatform.mysql.MySqlHistorySupport;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MySqlHistorySupportTest {
|
||||
|
||||
private MySqlHistorySupport support = new MySqlHistorySupport();
|
||||
|
||||
@Test
|
||||
public void getAsOfPredicate() {
|
||||
|
||||
String asOfPredicate = support.getAsOfPredicate("t0", "sys_period");
|
||||
assertEquals(asOfPredicate, "(t0.sys_period_start <= ? and (t0.sys_period_end is null or t0.sys_period_end > ?))");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLower() throws Exception {
|
||||
|
||||
String lower = support.getSysPeriodLower("t0", "sys_period");
|
||||
assertEquals(lower, "t0.sys_period_start");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getUpper() throws Exception {
|
||||
|
||||
String upper = support.getSysPeriodUpper("t0", "sys_period");
|
||||
assertEquals(upper, "t0.sys_period_end");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.DbTypeConfig;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.mysql.MySqlPlatform;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.PlatformDdl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MySqlPlatformTest {
|
||||
|
||||
MySqlPlatform mySqlPlatform = new MySqlPlatform();
|
||||
|
||||
@Test
|
||||
public void testTypeConversion() {
|
||||
PlatformDdl ddl = mySqlPlatform.getPlatformDdl();
|
||||
assertThat(ddl.convert("clob", false)).isEqualTo("longtext");
|
||||
assertThat(ddl.convert("json", false)).isEqualTo("longtext");
|
||||
assertThat(ddl.convert("jsonb", false)).isEqualTo("longtext");
|
||||
assertThat(ddl.convert("varchar(20)", false)).isEqualTo("varchar(20)");
|
||||
assertThat(ddl.convert("boolean", false)).isEqualTo("tinyint(1) default 0");
|
||||
assertThat(ddl.convert("bit", false)).isEqualTo("tinyint(1) default 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void uuid_default() {
|
||||
|
||||
MySqlPlatform platform = new MySqlPlatform();
|
||||
platform.configure(new DbTypeConfig());
|
||||
|
||||
DbPlatformType dbType = platform.getDbTypeMap().get(DbPlatformType.UUID);
|
||||
assertThat(dbType.renderType(0, 0)).isEqualTo("varchar(40)");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void uuid_as_binary() {
|
||||
|
||||
MySqlPlatform platform = new MySqlPlatform();
|
||||
DbTypeConfig config = new DbTypeConfig();
|
||||
config.setDbUuid(ServerConfig.DbUuid.AUTO_BINARY);
|
||||
platform.configure(config);
|
||||
|
||||
DbPlatformType dbType = platform.getDbTypeMap().get(DbPlatformType.UUID);
|
||||
assertThat(dbType.renderType(0, 0)).isEqualTo("binary(16)");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.DbTypeConfig;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.oracle.OraclePlatform;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.PlatformDdl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class OraclePlatformTest {
|
||||
|
||||
OraclePlatform platform = new OraclePlatform();
|
||||
|
||||
@Test
|
||||
public void testTypeConversion() {
|
||||
|
||||
PlatformDdl ddl = platform.getPlatformDdl();
|
||||
|
||||
assertThat(ddl.convert("clob", false)).isEqualTo("clob");
|
||||
assertThat(ddl.convert("blob", false)).isEqualTo("blob");
|
||||
assertThat(ddl.convert("json", false)).isEqualTo("clob");
|
||||
assertThat(ddl.convert("jsonb", false)).isEqualTo("clob");
|
||||
|
||||
assertThat(ddl.convert("double", false)).isEqualTo("number(19,4)");
|
||||
assertThat(ddl.convert("varchar(20)", false)).isEqualTo("varchar2(20)");
|
||||
assertThat(ddl.convert("decimal(10)", false)).isEqualTo("number(10)");
|
||||
assertThat(ddl.convert("decimal(8,4)", false)).isEqualTo("number(8,4)");
|
||||
assertThat(ddl.convert("boolean", false)).isEqualTo("number(1) default 0");
|
||||
assertThat(ddl.convert("bit", false)).isEqualTo("bit");
|
||||
assertThat(ddl.convert("tinyint", false)).isEqualTo("number(3)");
|
||||
assertThat(ddl.convert("binary(16)", false)).isEqualTo("raw(16)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void uuid_default() {
|
||||
|
||||
OraclePlatform platform = new OraclePlatform();
|
||||
platform.configure(new DbTypeConfig());
|
||||
DbPlatformType dbType = platform.getDbTypeMap().get(DbPlatformType.UUID);
|
||||
|
||||
assertThat(dbType.renderType(0, 0)).isEqualTo("varchar2(40)");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void uuid_as_binary() {
|
||||
|
||||
OraclePlatform platform = new OraclePlatform();
|
||||
DbTypeConfig config = new DbTypeConfig();
|
||||
config.setDbUuid(ServerConfig.DbUuid.AUTO_BINARY);
|
||||
|
||||
platform.configure(config);
|
||||
|
||||
DbPlatformType dbType = platform.getDbTypeMap().get(DbPlatformType.UUID);
|
||||
assertThat(dbType.renderType(0, 0)).isEqualTo("raw(16)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.dbplatform.postgres.PostgresHistorySupport;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PostgresHistorySupportTest {
|
||||
|
||||
private PostgresHistorySupport support = new PostgresHistorySupport();
|
||||
|
||||
@Test
|
||||
public void getBindCount() throws Exception {
|
||||
|
||||
assertEquals(support.getBindCount(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAsOfPredicate() throws Exception {
|
||||
|
||||
String asOfPredicate = support.getAsOfPredicate("t0", "sys_period");
|
||||
assertEquals(asOfPredicate, "t0.sys_period @> ?::timestamptz");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSysPeriodLower() throws Exception {
|
||||
|
||||
String lower = support.getSysPeriodLower("t0", "sys_period");
|
||||
assertEquals(lower, "lower(t0.sys_period)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSysPeriodUpper() throws Exception {
|
||||
|
||||
String upper = support.getSysPeriodUpper("t0", "sys_period");
|
||||
assertEquals(upper, "upper(t0.sys_period)");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.ebean.config.dbplatform;
|
||||
|
||||
import io.ebean.config.DbTypeConfig;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.PlatformDdl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PostgresPlatformTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testTypeConversion() {
|
||||
|
||||
PostgresPlatform platform = new PostgresPlatform();
|
||||
PlatformDdl ddl = platform.getPlatformDdl();
|
||||
|
||||
assertThat(ddl.convert("clob", false)).isEqualTo("text");
|
||||
assertThat(ddl.convert("blob", false)).isEqualTo("bytea");
|
||||
assertThat(ddl.convert("json", false)).isEqualTo("json");
|
||||
assertThat(ddl.convert("jsonb", false)).isEqualTo("jsonb");
|
||||
assertThat(ddl.convert("hstore", false)).isEqualTo("hstore");
|
||||
assertThat(ddl.convert("double", false)).isEqualTo("float");
|
||||
assertThat(ddl.convert("tinyint", false)).isEqualTo("smallint");
|
||||
assertThat(ddl.convert("double", false)).isEqualTo("float");
|
||||
assertThat(ddl.convert("varchar(20)", false)).isEqualTo("varchar(20)");
|
||||
assertThat(ddl.convert("decimal(10)", false)).isEqualTo("decimal(10)");
|
||||
assertThat(ddl.convert("decimal(8,4)", false)).isEqualTo("decimal(8,4)");
|
||||
assertThat(ddl.convert("boolean", false)).isEqualTo("boolean");
|
||||
assertThat(ddl.convert("bit", false)).isEqualTo("bit");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUuidType() {
|
||||
|
||||
PostgresPlatform platform = new PostgresPlatform();
|
||||
platform.configure(new DbTypeConfig());
|
||||
|
||||
DbPlatformType dbType = platform.getDbTypeMap().get(DbPlatformType.UUID);
|
||||
String columnDefn = dbType.renderType(0, 0);
|
||||
|
||||
assertThat(columnDefn).isEqualTo("uuid");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.ebean.dbmigration;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class DbMigrationTest extends BaseTestCase {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DbMigrationTest.class);
|
||||
|
||||
//@Ignore
|
||||
@Test
|
||||
public void writeCurrent() {
|
||||
|
||||
logger.info("start");
|
||||
|
||||
DbOffline.asH2();
|
||||
DbMigration migration = new DbMigration();
|
||||
DbOffline.reset();
|
||||
|
||||
//migration.writeCurrent();
|
||||
|
||||
assertThat(DbOffline.isSet()).isFalse();
|
||||
|
||||
logger.info("end");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package io.ebean.dbmigration.ddlgeneration;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import io.ebean.dbmigration.migration.ChangeSet;
|
||||
import io.ebean.dbmigration.model.CurrentModel;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
|
||||
ServerConfig serverConfig = new ServerConfig();
|
||||
|
||||
private DdlHandler h2Handler() {
|
||||
return new H2Platform().createDdlHandler(serverConfig);
|
||||
}
|
||||
|
||||
private DdlHandler postgresHandler() {
|
||||
return new PostgresPlatform().createDdlHandler(serverConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addColumn_nullable_noConstraint() throws Exception {
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
DdlHandler handler = h2Handler();
|
||||
handler.generate(write, Helper.getAddColumn());
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo("alter table foo add column added_to_foo varchar(20);\n\n");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void addColumn_withForeignKey() throws Exception {
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
DdlHandler handler = h2Handler();
|
||||
handler.generate(write, Helper.getAlterTableAddColumn());
|
||||
|
||||
String buffer = write.apply().getBuffer();
|
||||
assertThat(buffer).contains("alter table foo add column some_id integer;");
|
||||
|
||||
String fkBuffer = write.applyForeignKeys().getBuffer();
|
||||
assertThat(fkBuffer).contains("alter table foo add constraint fk_foo_some_id foreign key (some_id) references bar (id) on delete restrict on update restrict;");
|
||||
assertThat(fkBuffer).contains("create index idx_foo_some_id on foo (some_id);");
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropColumn() throws Exception {
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
DdlHandler handler = h2Handler();
|
||||
|
||||
handler.generate(write, Helper.getDropColumn());
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo("alter table foo drop column col2;\n\n");
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo("");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void createTable() throws Exception {
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
DdlHandler handler = h2Handler();
|
||||
|
||||
handler.generate(write, Helper.getCreateTable());
|
||||
|
||||
String createTableDDL = Helper.asText(this, "/assert/create-table.txt");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(createTableDDL);
|
||||
assertThat(write.dropAll().getBuffer().trim()).isEqualTo("drop table if exists foo;");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateChangeSet() throws Exception {
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
DdlHandler handler = h2Handler();
|
||||
|
||||
handler.generate(write, Helper.getChangeSet());
|
||||
|
||||
String apply = Helper.asText(this, "/assert/BaseDdlHandlerTest/baseApply.sql");
|
||||
String rollbackLast = Helper.asText(this, "/assert/BaseDdlHandlerTest/baseDropAll.sql");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void generateChangeSetFromModel() throws Exception {
|
||||
|
||||
SpiEbeanServer defaultServer = (SpiEbeanServer) Ebean.getDefaultServer();
|
||||
|
||||
ChangeSet createChangeSet = new CurrentModel(defaultServer).getChangeSet();
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
DdlHandler handler = h2Handler();
|
||||
handler.generate(write, createChangeSet);
|
||||
|
||||
String apply = Helper.asText(this, "/assert/changeset-apply.txt");
|
||||
String rollbackLast = Helper.asText(this, "/assert/changeset-dropAll.txt");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void generateChangeSetFromModel_given_postgresTypes() throws Exception {
|
||||
|
||||
SpiEbeanServer defaultServer = (SpiEbeanServer) Ebean.getDefaultServer();
|
||||
|
||||
ChangeSet createChangeSet = new CurrentModel(defaultServer).getChangeSet();
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
DdlHandler handler = postgresHandler();
|
||||
handler.generate(write, createChangeSet);
|
||||
|
||||
String apply = Helper.asText(this, "/assert/changeset-pg-apply.sql");
|
||||
String applyLast = Helper.asText(this, "/assert/changeset-pg-applyLast.sql");
|
||||
String rollbackFirst = Helper.asText(this, "/assert/changeset-pg-rollbackFirst.sql");
|
||||
String rollbackLast = Helper.asText(this, "/assert/changeset-pg-rollbackLast.sql");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.applyForeignKeys().getBuffer()).isEqualTo(applyLast);
|
||||
assertThat(write.dropAllForeignKeys().getBuffer()).isEqualTo(rollbackFirst);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package io.ebean.dbmigration.ddlgeneration;
|
||||
|
||||
import io.ebean.dbmigration.migration.AddColumn;
|
||||
import io.ebean.dbmigration.migration.ChangeSet;
|
||||
import io.ebean.dbmigration.migration.CreateTable;
|
||||
import io.ebean.dbmigration.migration.DropColumn;
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import io.ebean.dbmigration.migrationreader.MigrationXmlReader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.LineNumberReader;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Helper for testing to return some basic migration objects.
|
||||
*/
|
||||
public class Helper {
|
||||
|
||||
static Migration migration = MigrationXmlReader.read("/container/test-create-table.xml");
|
||||
|
||||
static Migration alterTableMigration = MigrationXmlReader.read("/container/test-alter-table.xml");
|
||||
|
||||
static ChangeSet changeSet;
|
||||
|
||||
static List<Object> changeSetChildren;
|
||||
|
||||
static ChangeSet alterTableChangeSet;
|
||||
|
||||
static List<Object> alterTableChangeSetChildren;
|
||||
|
||||
static {
|
||||
List<ChangeSet> changeSets = migration.getChangeSet();
|
||||
changeSet = changeSets.get(0);
|
||||
changeSetChildren = changeSet.getChangeSetChildren();
|
||||
|
||||
alterTableChangeSet = alterTableMigration.getChangeSet().get(0);
|
||||
alterTableChangeSetChildren = alterTableChangeSet.getChangeSetChildren();
|
||||
}
|
||||
|
||||
public static ChangeSet getChangeSet() {
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
public static CreateTable getCreateTable() {
|
||||
return (CreateTable) changeSetChildren.get(0);
|
||||
}
|
||||
|
||||
public static AddColumn getAddColumn() {
|
||||
return (AddColumn) changeSetChildren.get(1);
|
||||
}
|
||||
|
||||
public static AddColumn getAlterTableAddColumn() {
|
||||
return (AddColumn) alterTableChangeSetChildren.get(0);
|
||||
}
|
||||
|
||||
public static DropColumn getDropColumn() {
|
||||
return (DropColumn) changeSetChildren.get(2);
|
||||
}
|
||||
|
||||
public static String asText(Object instance, String relativePath) throws IOException {
|
||||
InputStream is = instance.getClass().getResourceAsStream(relativePath);
|
||||
if (is == null) {
|
||||
throw new IllegalArgumentException("resource " + relativePath + " not found");
|
||||
}
|
||||
return asText(is);
|
||||
}
|
||||
|
||||
public static String asText(InputStream in) throws IOException {
|
||||
|
||||
try {
|
||||
InputStreamReader reader = new InputStreamReader(in);
|
||||
|
||||
LineNumberReader lineNumberReader = new LineNumberReader(reader);
|
||||
|
||||
StringBuilder builder = new StringBuilder(400);
|
||||
String line;
|
||||
while ((line = lineNumberReader.readLine()) != null) {
|
||||
builder.append(line).append("\n");
|
||||
}
|
||||
return builder.toString();
|
||||
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.oracle.OraclePlatform;
|
||||
import io.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import io.ebean.dbmigration.ddlgeneration.Helper;
|
||||
import io.ebean.dbmigration.migration.AddTableComment;
|
||||
import io.ebean.dbmigration.migration.AlterColumn;
|
||||
import io.ebean.dbmigration.migration.Column;
|
||||
import io.ebean.dbmigration.migration.CreateTable;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class BaseTableDdlTest {
|
||||
|
||||
ServerConfig serverConfig = new ServerConfig();
|
||||
|
||||
@Test
|
||||
public void testAlterColumn() throws IOException {
|
||||
|
||||
BaseTableDdl ddlGen = new BaseTableDdl(serverConfig, new H2Platform().getPlatformDdl());
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName("mytab");
|
||||
alterColumn.setCheckConstraint("check (acol in ('A','B'))");
|
||||
alterColumn.setCheckConstraintName("ck_mytab_acol");
|
||||
|
||||
ddlGen.generate(write, alterColumn);
|
||||
|
||||
String ddl = write.apply().getBuffer();
|
||||
assertThat(ddl).contains("alter table mytab drop constraint ck_mytab_acol");
|
||||
assertThat(ddl).contains("alter table mytab add constraint ck_mytab_acol check (acol in ('A','B'))");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddColumn_withTypeConversion() throws IOException {
|
||||
|
||||
BaseTableDdl ddlGen = new BaseTableDdl(serverConfig, new OraclePlatform().getPlatformDdl());
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
Column column = new Column();
|
||||
column.setName("col_name");
|
||||
column.setType("varchar(20)");
|
||||
|
||||
ddlGen.alterTableAddColumn(write.apply(), "mytable", column, false);
|
||||
|
||||
String ddl = write.apply().getBuffer();
|
||||
assertThat(ddl).contains("alter table mytable add column col_name varchar2(20)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnComment() throws IOException {
|
||||
|
||||
BaseTableDdl ddlGen = new BaseTableDdl(serverConfig, new H2Platform().getPlatformDdl());
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName("mytab");
|
||||
alterColumn.setColumnName("acol");
|
||||
alterColumn.setComment("my comment");
|
||||
|
||||
ddlGen.generate(write, alterColumn);
|
||||
|
||||
String ddl = write.apply().getBuffer();
|
||||
assertThat(ddl).contains("comment on column mytab.acol is 'my comment'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddTableComment() throws IOException {
|
||||
|
||||
BaseTableDdl ddlGen = new BaseTableDdl(serverConfig, new H2Platform().getPlatformDdl());
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
AddTableComment addTableComment = new AddTableComment();
|
||||
addTableComment.setName("mytab");
|
||||
addTableComment.setComment("my comment");
|
||||
|
||||
ddlGen.generate(write, addTableComment);
|
||||
|
||||
String ddl = write.apply().getBuffer();
|
||||
assertThat(ddl).contains("comment on table mytab is 'my comment'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerate() throws Exception {
|
||||
|
||||
BaseTableDdl ddlGen = new BaseTableDdl(serverConfig, new H2Platform().getPlatformDdl());
|
||||
|
||||
DdlWrite write = new DdlWrite();
|
||||
|
||||
ddlGen.generate(write, createTable());
|
||||
String apply = write.apply().getBuffer();
|
||||
String applyLast = write.applyForeignKeys().getBuffer();
|
||||
|
||||
String rollbackFirst = write.dropAllForeignKeys().getBuffer();
|
||||
String rollbackLast = write.dropAll().getBuffer();
|
||||
|
||||
assertThat(apply).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-apply.txt"));
|
||||
assertThat(applyLast).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-applyLast.txt"));
|
||||
assertThat(rollbackFirst).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-rollbackFirst.txt"));
|
||||
assertThat(rollbackLast).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-rollback.txt"));
|
||||
}
|
||||
|
||||
private CreateTable createTable() {
|
||||
CreateTable createTable = new CreateTable();
|
||||
createTable.setName("mytable");
|
||||
createTable.setPkName("pk_mytable");
|
||||
List<Column> columns = createTable.getColumn();
|
||||
Column col = new Column();
|
||||
col.setName("id");
|
||||
col.setType("integer");
|
||||
col.setPrimaryKey(true);
|
||||
|
||||
columns.add(col);
|
||||
|
||||
Column col2 = new Column();
|
||||
col2.setName("status");
|
||||
col2.setType("varchar(1)");
|
||||
col2.setNotnull(true);
|
||||
col2.setCheckConstraint("check (status in ('A','B'))");
|
||||
col2.setCheckConstraintName("ck_mytable_status");
|
||||
|
||||
columns.add(col2);
|
||||
|
||||
Column col3 = new Column();
|
||||
col3.setName("order_id");
|
||||
col3.setType("integer");
|
||||
col3.setNotnull(true);
|
||||
col3.setReferences("orders.id");
|
||||
col3.setForeignKeyName("fk_mytable_order_id");
|
||||
col3.setForeignKeyIndex("ix_mytable_order_id");
|
||||
|
||||
columns.add(col3);
|
||||
|
||||
return createTable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.config.DbConstraintNormalise;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class DbNameNormaliseTest {
|
||||
|
||||
DbConstraintNormalise normalise = new DbConstraintNormalise();
|
||||
|
||||
@Test
|
||||
public void testNormalise() throws Exception {
|
||||
|
||||
assertThat(normalise.normaliseTable("cat.sch.foo_bar]")).isEqualTo("foo_bar");
|
||||
assertThat(normalise.normaliseTable("sch.foo_bar]")).isEqualTo("foo_bar");
|
||||
assertThat(normalise.normaliseTable("foo_bar]")).isEqualTo("foo_bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrimQuotes() throws Exception {
|
||||
|
||||
assertThat(normalise.trimQuotes("[foo]")).isEqualTo("foo");
|
||||
assertThat(normalise.trimQuotes("'foo'")).isEqualTo("foo");
|
||||
assertThat(normalise.trimQuotes("\"foo\"")).isEqualTo("foo");
|
||||
assertThat(normalise.trimQuotes("`foo`")).isEqualTo("foo");
|
||||
|
||||
assertThat(normalise.trimQuotes("`fo_o`")).isEqualTo("fo_o");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import io.ebean.dbmigration.model.CurrentModel;
|
||||
import io.ebean.dbmigration.model.MConfiguration;
|
||||
import io.ebean.dbmigration.model.ModelContainer;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
|
||||
public class H2HistoryDdlTest {
|
||||
|
||||
@Test
|
||||
public void testRegenerateHistoryTriggers() throws Exception {
|
||||
|
||||
SpiEbeanServer ebeanServer = (SpiEbeanServer) Ebean.getDefaultServer();
|
||||
|
||||
HistoryTableUpdate update = new HistoryTableUpdate("c_user");
|
||||
update.add(HistoryTableUpdate.Change.ADD, "one");
|
||||
update.add(HistoryTableUpdate.Change.DROP, "two");
|
||||
|
||||
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
ModelContainer modelContainer = currentModel.read();
|
||||
DdlWrite write = new DdlWrite(new MConfiguration(), modelContainer);
|
||||
|
||||
H2Platform h2Platform = new H2Platform();
|
||||
PlatformDdl h2Ddl = h2Platform.getPlatformDdl();
|
||||
h2Ddl.configure(ebeanServer.getServerConfig());
|
||||
h2Ddl.regenerateHistoryTriggers(write, update);
|
||||
|
||||
assertThat(write.applyHistory().isEmpty()).isFalse();
|
||||
assertThat(write.applyHistory().getBuffer()).contains("add one");
|
||||
assertThat(write.dropAll().isEmpty()).isTrue();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class HistoryTableUpdateTest {
|
||||
|
||||
@Test
|
||||
public void testDescription() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.ADD, "two");
|
||||
upd.add(HistoryTableUpdate.Change.DROP, "four");
|
||||
|
||||
assertThat(upd.description()).isEqualTo("[add two, drop four]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDescription_withIncludeExclude() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.ADD, "two");
|
||||
upd.add(HistoryTableUpdate.Change.INCLUDE, "five");
|
||||
upd.add(HistoryTableUpdate.Change.EXCLUDE, "six");
|
||||
upd.add(HistoryTableUpdate.Change.DROP, "four");
|
||||
|
||||
assertThat(upd.description()).isEqualTo("[add two, include five, exclude six, drop four]");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.util.IndexSet;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
||||
public class IndexSetTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
IndexSet set = new IndexSet();
|
||||
assertTrue(set.add(new String[]{"one_column"}));
|
||||
assertTrue(set.add(new String[]{"two_column"}));
|
||||
assertFalse(set.add(new String[]{"one_column"}));
|
||||
|
||||
assertTrue(set.add(new String[]{"a", "b"}));
|
||||
assertTrue(set.add(new String[]{"b", "c"}));
|
||||
assertTrue(set.add(new String[]{"a"}));
|
||||
assertFalse(set.add(new String[]{"a", "b"}));
|
||||
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.sqlserver.SqlServerPlatform;
|
||||
import io.ebean.config.dbplatform.mysql.MySqlPlatform;
|
||||
import io.ebean.config.dbplatform.oracle.OraclePlatform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import io.ebean.dbmigration.migration.AlterColumn;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class PlatformDdl_AlterColumnTest {
|
||||
|
||||
PlatformDdl h2Ddl = new H2Platform().getPlatformDdl();
|
||||
PlatformDdl pgDdl = new PostgresPlatform().getPlatformDdl();
|
||||
PlatformDdl mysqlDdl = new MySqlPlatform().getPlatformDdl();
|
||||
PlatformDdl oraDdl = new OraclePlatform().getPlatformDdl();
|
||||
PlatformDdl sqlServerDdl = new SqlServerPlatform().getPlatformDdl();
|
||||
|
||||
AlterColumn alterNotNull() {
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName("mytab");
|
||||
alterColumn.setColumnName("acol");
|
||||
alterColumn.setCurrentType("varchar(5)");
|
||||
alterColumn.setNotnull(Boolean.TRUE);
|
||||
|
||||
return alterColumn;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnBaseAttributes() throws Exception {
|
||||
|
||||
AlterColumn alterColumn = alterNotNull();
|
||||
assertNull(h2Ddl.alterColumnBaseAttributes(alterColumn));
|
||||
assertNull(pgDdl.alterColumnBaseAttributes(alterColumn));
|
||||
assertNull(oraDdl.alterColumnBaseAttributes(alterColumn));
|
||||
|
||||
String sql = mysqlDdl.alterColumnBaseAttributes(alterColumn);
|
||||
assertEquals("alter table mytab modify acol varchar(5) not null", sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnBaseAttributes(alterColumn);
|
||||
assertEquals("alter table mytab alter column acol varchar(5) not null", sql);
|
||||
|
||||
alterColumn.setNotnull(Boolean.FALSE);
|
||||
sql = mysqlDdl.alterColumnBaseAttributes(alterColumn);
|
||||
assertEquals("alter table mytab modify acol varchar(5)", sql);
|
||||
|
||||
alterColumn.setNotnull(null);
|
||||
alterColumn.setType("varchar(100)");
|
||||
|
||||
sql = mysqlDdl.alterColumnBaseAttributes(alterColumn);
|
||||
assertEquals("alter table mytab modify acol varchar(100)", sql);
|
||||
|
||||
alterColumn.setCurrentNotnull(Boolean.TRUE);
|
||||
sql = mysqlDdl.alterColumnBaseAttributes(alterColumn);
|
||||
assertEquals("alter table mytab modify acol varchar(100) not null", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnType() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterColumnType("mytab", "acol", "varchar(20)");
|
||||
assertEquals("alter table mytab alter column acol varchar(20)", sql);
|
||||
|
||||
sql = pgDdl.alterColumnType("mytab", "acol", "varchar(20)");
|
||||
assertEquals("alter table mytab alter column acol type varchar(20)", sql);
|
||||
|
||||
sql = oraDdl.alterColumnType("mytab", "acol", "varchar(20)");
|
||||
assertEquals("alter table mytab modify acol varchar(20)", sql);
|
||||
|
||||
sql = mysqlDdl.alterColumnType("mytab", "acol", "varchar(20)");
|
||||
assertNull(sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnType("mytab", "acol", "varchar(20)");
|
||||
assertNull(sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnNotnull() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterColumnNotnull("mytab", "acol", true);
|
||||
assertEquals("alter table mytab alter column acol set not null", sql);
|
||||
|
||||
sql = pgDdl.alterColumnNotnull("mytab", "acol", true);
|
||||
assertEquals("alter table mytab alter column acol set not null", sql);
|
||||
|
||||
sql = oraDdl.alterColumnNotnull("mytab", "acol", true);
|
||||
assertEquals("alter table mytab modify acol not null", sql);
|
||||
|
||||
sql = mysqlDdl.alterColumnNotnull("mytab", "acol", true);
|
||||
assertNull(sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnNotnull("mytab", "acol", true);
|
||||
assertNull(sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnNull() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterColumnNotnull("mytab", "acol", false);
|
||||
assertEquals("alter table mytab alter column acol set null", sql);
|
||||
|
||||
sql = pgDdl.alterColumnNotnull("mytab", "acol", false);
|
||||
assertEquals("alter table mytab alter column acol drop not null", sql);
|
||||
|
||||
sql = oraDdl.alterColumnNotnull("mytab", "acol", false);
|
||||
assertEquals("alter table mytab modify acol null", sql);
|
||||
|
||||
sql = mysqlDdl.alterColumnNotnull("mytab", "acol", false);
|
||||
assertNull(sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnNotnull("mytab", "acol", false);
|
||||
assertNull(sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnDefaultValue() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterColumnDefaultValue("mytab", "acol", "'hi'");
|
||||
assertEquals("alter table mytab alter column acol set default 'hi'", sql);
|
||||
|
||||
sql = pgDdl.alterColumnDefaultValue("mytab", "acol", "'hi'");
|
||||
assertEquals("alter table mytab alter column acol set default 'hi'", sql);
|
||||
|
||||
sql = oraDdl.alterColumnDefaultValue("mytab", "acol", "'hi'");
|
||||
assertEquals("alter table mytab modify acol default 'hi'", sql);
|
||||
|
||||
sql = mysqlDdl.alterColumnDefaultValue("mytab", "acol", "'hi'");
|
||||
assertEquals("alter table mytab alter acol set default 'hi'", sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnDefaultValue("mytab", "acol", "'hi'");
|
||||
assertEquals("alter table mytab add default 'hi' for acol", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAlterColumnDropDefault() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterColumnDefaultValue("mytab", "acol", "DROP DEFAULT");
|
||||
assertEquals("alter table mytab alter column acol drop default", sql);
|
||||
|
||||
sql = pgDdl.alterColumnDefaultValue("mytab", "acol", "DROP DEFAULT");
|
||||
assertEquals("alter table mytab alter column acol drop default", sql);
|
||||
|
||||
sql = oraDdl.alterColumnDefaultValue("mytab", "acol", "DROP DEFAULT");
|
||||
assertEquals("alter table mytab modify acol drop default", sql);
|
||||
|
||||
sql = mysqlDdl.alterColumnDefaultValue("mytab", "acol", "DROP DEFAULT");
|
||||
assertEquals("alter table mytab alter acol drop default", sql);
|
||||
|
||||
sql = sqlServerDdl.alterColumnDefaultValue("mytab", "acol", "DROP DEFAULT");
|
||||
assertTrue(sql, sql.startsWith("-- alter"));
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.sqlserver.SqlServerPlatform;
|
||||
import io.ebean.config.dbplatform.mysql.MySqlPlatform;
|
||||
import io.ebean.config.dbplatform.oracle.OraclePlatform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PlatformDdl_dropUniqueConstraintTest {
|
||||
|
||||
|
||||
PlatformDdl h2Ddl = new H2Platform().getPlatformDdl();
|
||||
PlatformDdl pgDdl = new PostgresPlatform().getPlatformDdl();
|
||||
PlatformDdl mysqlDdl = new MySqlPlatform().getPlatformDdl();
|
||||
PlatformDdl oraDdl = new OraclePlatform().getPlatformDdl();
|
||||
PlatformDdl sqlServerDdl = new SqlServerPlatform().getPlatformDdl();
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
|
||||
String sql = h2Ddl.alterTableDropUniqueConstraint("mytab", "uq_name");
|
||||
assertEquals("alter table mytab drop constraint uq_name", sql);
|
||||
sql = pgDdl.alterTableDropUniqueConstraint("mytab", "uq_name");
|
||||
assertEquals("alter table mytab drop constraint uq_name", sql);
|
||||
sql = oraDdl.alterTableDropUniqueConstraint("mytab", "uq_name");
|
||||
assertEquals("alter table mytab drop constraint uq_name", sql);
|
||||
sql = sqlServerDdl.alterTableDropUniqueConstraint("mytab", "uq_name");
|
||||
assertEquals("alter table mytab drop constraint uq_name", sql);
|
||||
|
||||
|
||||
sql = mysqlDdl.alterTableDropUniqueConstraint("mytab", "uq_name");
|
||||
assertEquals("alter table mytab drop index uq_name", sql);
|
||||
}
|
||||
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import io.ebean.config.dbplatform.DbPlatformTypeMapping;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.util.PlatformTypeConverter;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PlatformTypeConverterTest {
|
||||
|
||||
@Test
|
||||
public void convert_withSuffix_expect_suffix() {
|
||||
|
||||
PostgresPlatform pg = new PostgresPlatform();
|
||||
DbPlatformTypeMapping dbTypeMap = pg.getDbTypeMap();
|
||||
|
||||
PlatformTypeConverter converter = new PlatformTypeConverter(dbTypeMap);
|
||||
|
||||
assertThat(converter.convert("varchar(10)")).isEqualTo("varchar(10)");
|
||||
assertThat(converter.convert("VARCHAR(10) default 'en' not null")).isEqualTo("varchar(10) default 'en' not null");
|
||||
assertThat(converter.convert("DECIMAL(10,2) DEFAULT '0.00' NOT NULL")).isEqualTo("decimal(10,2) DEFAULT '0.00' NOT NULL");
|
||||
assertThat(converter.convert("CRAZY(12,0) suffix")).isEqualTo("CRAZY(12,0) suffix");
|
||||
assertThat(converter.convert("CRAZY(12) suffix")).isEqualTo("CRAZY(12) suffix");
|
||||
assertThat(converter.convert("CRAZY suffix")).isEqualTo("CRAZY suffix");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvert_given_postgres() throws Exception {
|
||||
|
||||
PostgresPlatform pg = new PostgresPlatform();
|
||||
DbPlatformTypeMapping dbTypeMap = pg.getDbTypeMap();
|
||||
|
||||
PlatformTypeConverter converter = new PlatformTypeConverter(dbTypeMap);
|
||||
|
||||
assertThat(converter.convert("varchar(10)")).isEqualTo("varchar(10)");
|
||||
assertThat(converter.convert("decimal(10,2)")).isEqualTo("decimal(10,2)");
|
||||
assertThat(converter.convert("clob")).isEqualTo("text");
|
||||
assertThat(converter.convert("blob")).isEqualTo("bytea");
|
||||
assertThat(converter.convert("tinyint")).isEqualTo("smallint");
|
||||
assertThat(converter.convert("funky")).isEqualTo("funky"); // unknown
|
||||
assertThat(converter.convert("integer(8)")).isEqualTo("integer"); // removes scale
|
||||
|
||||
assertThat(converter.convert("funky(")).isEqualTo("funky(");
|
||||
assertThat(converter.convert("funky()")).isEqualTo("funky()");
|
||||
assertThat(converter.convert("funky)")).isEqualTo("funky)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvert_given_h2() throws Exception {
|
||||
|
||||
|
||||
H2Platform platform = new H2Platform();
|
||||
DbPlatformTypeMapping dbTypeMap = platform.getDbTypeMap();
|
||||
|
||||
PlatformTypeConverter converter = new PlatformTypeConverter(dbTypeMap);
|
||||
|
||||
assertThat(converter.convert("varchar(10)")).isEqualTo("varchar(10)");
|
||||
assertThat(converter.convert("decimal(10,2)")).isEqualTo("decimal(10,2)");
|
||||
assertThat(converter.convert("clob")).isEqualTo("clob");
|
||||
assertThat(converter.convert("blob")).isEqualTo("blob");
|
||||
assertThat(converter.convert("tinyint")).isEqualTo("tinyint");
|
||||
assertThat(converter.convert("integer(8)")).isEqualTo("integer(8)");
|
||||
assertThat(converter.convert("funky")).isEqualTo("funky"); // unknown
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertJsonTypes_given_postgres() {
|
||||
|
||||
PostgresPlatform platform = new PostgresPlatform();
|
||||
DbPlatformTypeMapping dbTypeMap = platform.getDbTypeMap();
|
||||
|
||||
PlatformTypeConverter converter = new PlatformTypeConverter(dbTypeMap);
|
||||
|
||||
assertThat(converter.convert("jsonblob")).isEqualTo("bytea");
|
||||
assertThat(converter.convert("jsonclob")).isEqualTo("text");
|
||||
assertThat(converter.convert("jsonvarchar(200)")).isEqualTo("varchar(200)");
|
||||
assertThat(converter.convert("json")).isEqualTo("json");
|
||||
assertThat(converter.convert("jsonb")).isEqualTo("jsonb");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConvertJsonTypes_given_h2() {
|
||||
|
||||
H2Platform platform = new H2Platform();
|
||||
DbPlatformTypeMapping dbTypeMap = platform.getDbTypeMap();
|
||||
|
||||
PlatformTypeConverter converter = new PlatformTypeConverter(dbTypeMap);
|
||||
|
||||
assertThat(converter.convert("jsonblob")).isEqualTo("blob");
|
||||
assertThat(converter.convert("jsonclob")).isEqualTo("clob");
|
||||
assertThat(converter.convert("jsonvarchar(200)")).isEqualTo("varchar(200)");
|
||||
assertThat(converter.convert("json")).isEqualTo("clob");
|
||||
assertThat(converter.convert("jsonb")).isEqualTo("clob");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.ebean.dbmigration.ddlgeneration.platform.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class VowelRemoverTest {
|
||||
|
||||
@Test
|
||||
public void testTrim() throws Exception {
|
||||
|
||||
|
||||
assertEquals("fk_abcd", VowelRemover.trim("fk_abcde", 4));
|
||||
assertEquals("fk_a", VowelRemover.trim("fk_aaaaaa", 4));
|
||||
assertEquals("ab_avrylngtblnm", VowelRemover.trim("ab_averylongtablename", 4));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.ebean.dbmigration.migrationreader;
|
||||
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MigrationXmlWriterTest {
|
||||
|
||||
@Test
|
||||
public void testReadWrite() throws Exception {
|
||||
|
||||
Migration migration = MigrationXmlReader.read("/container/test-create-table.xml");
|
||||
assertThat(migration.getChangeSet()).hasSize(1);
|
||||
assertThat(migration.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
|
||||
File temp = File.createTempFile("migrationWrite", ".xml");
|
||||
new MigrationXmlWriter("THIS IS A GENERATED FILE - DO NOT MODIFY").write(migration, temp);
|
||||
|
||||
Migration migrationRead = MigrationXmlReader.read(temp);
|
||||
assertThat(migrationRead.getChangeSet()).hasSize(1);
|
||||
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
|
||||
temp = File.createTempFile("migrationWrite", ".xml");
|
||||
new MigrationXmlWriter(null).write(migration, temp);
|
||||
|
||||
Migration migrationRead2 = MigrationXmlReader.read(temp);
|
||||
|
||||
assertThat(migrationRead2.getChangeSet()).hasSize(1);
|
||||
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import io.ebean.dbmigration.migration.ChangeSet;
|
||||
import io.ebean.dbmigration.migration.DropColumn;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class EntryTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void test_when_empty() throws Exception {
|
||||
|
||||
PendingDrops.Entry entry = createEntry();
|
||||
assertThat(entry.hasPendingDrops()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_normal() throws Exception {
|
||||
|
||||
PendingDrops.Entry entry = createEntry(new ChangeSet());
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_suppressOnly() throws Exception {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs);
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_both() throws Exception {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs, new ChangeSet());
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_empty() {
|
||||
|
||||
PendingDrops.Entry entry = createEntry();
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_notSuppress() {
|
||||
|
||||
PendingDrops.Entry entry = createEntry(new ChangeSet());
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_suppress() {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
PendingDrops.Entry entry = createEntry(cs);
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_mixed() {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs, new ChangeSet());
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_columnsMatch() {
|
||||
|
||||
ChangeSet pending = changeSet("one", "two");
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one", "two"))).isTrue();
|
||||
assertThat(entry.list).asList().doesNotContain(pending);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_subset() {
|
||||
|
||||
DropColumn dropColumnTwo = col("two");
|
||||
ChangeSet pending = changeSet("one");
|
||||
pending.getChangeSetChildren().add(dropColumnTwo);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one"))).isFalse();
|
||||
assertThat(entry.list).asList().containsExactly(pending);
|
||||
assertThat(pending.getChangeSetChildren()).asList().containsExactly(dropColumnTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_columnsMatch_butSuppressed() {
|
||||
|
||||
ChangeSet pending = changeSet("one", "two");
|
||||
pending.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one", "two"))).isFalse();
|
||||
assertThat(entry.list).asList().contains(pending);
|
||||
assertThat(pending.getChangeSetChildren()).asList().hasSize(2);
|
||||
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(String... colName) {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
for (String col : colName) {
|
||||
cs.getChangeSetChildren().add(col(col));
|
||||
}
|
||||
return cs;
|
||||
}
|
||||
|
||||
static DropColumn col(String colName) {
|
||||
DropColumn drop = new DropColumn();
|
||||
drop.setColumnName(colName);
|
||||
drop.setTableName("tab");
|
||||
return drop;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
static PendingDrops.Entry createEntry(ChangeSet... pending) {
|
||||
|
||||
PendingDrops.Entry entry = new PendingDrops.Entry(MigrationVersion.parse("1.1"));
|
||||
for (ChangeSet changeSet : pending) {
|
||||
entry.add(changeSet);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import io.ebean.dbmigration.migration.AlterColumn;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class MColumnTest {
|
||||
|
||||
MTable table = new MTable("tab");
|
||||
|
||||
MColumn basic() {
|
||||
return new MColumn("col", "integer");
|
||||
}
|
||||
|
||||
ModelDiff diff() {
|
||||
return new ModelDiff();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noDiff() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
basic().compare(diff, table, basic());
|
||||
|
||||
assertThat(diff.getApplyChanges()).isEmpty();
|
||||
assertThat(diff.getDropChanges()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffType() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
basic().compare(diff, table, new MColumn("col", "integer(8)"));
|
||||
|
||||
assertChanges(diff);
|
||||
AlterColumn alterColumn = getAlterColumn(diff);
|
||||
assertThat(alterColumn.getType()).isEqualTo("integer(8)");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffNotNull() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setNotnull(true);
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
AlterColumn alterColumn = getAlterColumn(diff);
|
||||
assertThat(alterColumn.isNotnull()).isEqualTo(true);
|
||||
|
||||
assertThat(alterColumn.getType()).isNull();
|
||||
assertThat(alterColumn.getUnique()).isNull();
|
||||
assertThat(alterColumn.getUniqueOneToOne()).isNull();
|
||||
assertThat(alterColumn.getDefaultValue()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffNull() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
|
||||
MColumn newCol = basic();
|
||||
newCol.setNotnull(false);
|
||||
|
||||
MColumn baseCol = basic();
|
||||
baseCol.setNotnull(true);
|
||||
|
||||
baseCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
AlterColumn alterColumn = getAlterColumn(diff);
|
||||
assertThat(alterColumn.isNotnull()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyNotNull_expect_notNull() throws Exception {
|
||||
|
||||
MColumn newCol = basic();
|
||||
newCol.setNotnull(true);
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setNotnull(Boolean.FALSE);
|
||||
newCol.apply(alterColumn);
|
||||
|
||||
assertThat(newCol.isNotnull()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffCheckAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setCheckConstraint("abc");
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getCheckConstraint()).isEqualTo("abc");
|
||||
assertThat(getAlterColumn(diff).getDropCheckConstraint()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffCheckRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setCheckConstraint("z");
|
||||
oldCol.setCheckConstraintName("abc");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getCheckConstraint()).isNull();
|
||||
assertThat(getAlterColumn(diff).getDropCheckConstraint()).isEqualTo("abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffCheckChange() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setCheckConstraint("abc");
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setCheckConstraint("z");
|
||||
oldCol.setCheckConstraintName("d");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getCheckConstraint()).isEqualTo("abc");
|
||||
assertThat(getAlterColumn(diff).getDropCheckConstraint()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffDefaultValueAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setDefaultValue("abc");
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getDefaultValue()).isEqualTo("abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffDefaultValueRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setDefaultValue("abc");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getDefaultValue()).isEqualTo("DROP DEFAULT");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffDefaultValueChange() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setDefaultValue("abc");
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setDefaultValue("d");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getDefaultValue()).isEqualTo("abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffReferencesAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setReferences("abc");
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getReferences()).isEqualTo("abc");
|
||||
assertThat(getAlterColumn(diff).getDropForeignKey()).isNull();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void diffReferencesRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setReferences("abc");
|
||||
oldCol.setForeignKeyName("fk_ab");
|
||||
oldCol.setForeignKeyIndex("ix_ab");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getReferences()).isNull();
|
||||
assertThat(getAlterColumn(diff).getForeignKeyName()).isNull();
|
||||
assertThat(getAlterColumn(diff).getForeignKeyIndex()).isNull();
|
||||
|
||||
assertThat(getAlterColumn(diff).getDropForeignKey()).isEqualTo("fk_ab");
|
||||
assertThat(getAlterColumn(diff).getDropForeignKeyIndex()).isEqualTo("ix_ab");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffReferencesChange() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setReferences("ab");
|
||||
newCol.setForeignKeyName("fk_ab");
|
||||
newCol.setForeignKeyIndex("ix_ab");
|
||||
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setReferences("d");
|
||||
oldCol.setForeignKeyName("fk_d");
|
||||
oldCol.setForeignKeyIndex("ix_d");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
|
||||
assertThat(getAlterColumn(diff).getReferences()).isEqualTo("ab");
|
||||
assertThat(getAlterColumn(diff).getForeignKeyName()).isEqualTo("fk_ab");
|
||||
assertThat(getAlterColumn(diff).getForeignKeyIndex()).isEqualTo("ix_ab");
|
||||
|
||||
assertThat(getAlterColumn(diff).getDropForeignKey()).isEqualTo("fk_d");
|
||||
assertThat(getAlterColumn(diff).getDropForeignKeyIndex()).isEqualTo("ix_d");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffUniqueAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setUnique("uq_one");
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getUnique()).isEqualTo("uq_one");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffUniqueRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setUnique("uq_one");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getDropUnique()).isEqualTo("uq_one");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffUniqueOneToOneAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setUniqueOneToOne("uq_new");
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setUniqueOneToOne("uq_old");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getUniqueOneToOne()).isEqualTo("uq_new");
|
||||
assertThat(getAlterColumn(diff).getDropUnique()).isEqualTo("uq_old");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffUniqueOneToOneRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setUniqueOneToOne("uq_new");
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).getDropUnique()).isEqualTo("uq_new");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffHistoryExcludeAdd() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
newCol.setHistoryExclude(true);
|
||||
basic().compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).isHistoryExclude()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void diffHistoryExcludeRemove() throws Exception {
|
||||
|
||||
ModelDiff diff = diff();
|
||||
MColumn newCol = basic();
|
||||
MColumn oldCol = basic();
|
||||
oldCol.setHistoryExclude(true);
|
||||
oldCol.compare(diff, table, newCol);
|
||||
|
||||
assertChanges(diff);
|
||||
assertThat(getAlterColumn(diff).isHistoryExclude()).isEqualTo(false);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private AlterColumn getAlterColumn(ModelDiff diff) {
|
||||
return (AlterColumn) diff.getApplyChanges().get(0);
|
||||
}
|
||||
|
||||
private void assertChanges(ModelDiff diff) {
|
||||
assertThat(diff.getDropChanges()).isEmpty();
|
||||
assertThat(diff.getApplyChanges()).hasSize(1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import io.ebean.dbmigration.migration.AddColumn;
|
||||
import io.ebean.dbmigration.migration.AddHistoryTable;
|
||||
import io.ebean.dbmigration.migration.AlterColumn;
|
||||
import io.ebean.dbmigration.migration.DropColumn;
|
||||
import io.ebean.dbmigration.migration.DropHistoryTable;
|
||||
import io.ebean.dbmigration.migration.DropTable;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MTableTest {
|
||||
|
||||
static MTable base() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id", "bigint"));
|
||||
table.addColumn(new MColumn("name", "varchar(20)"));
|
||||
table.addColumn(new MColumn("status", "varchar(3)"));
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
static MTable newTable() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id", "bigint"));
|
||||
table.addColumn(new MColumn("name", "varchar(20)"));
|
||||
table.addColumn(new MColumn("comment", "varchar(1000)"));
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
static MTable newTableAdd2Columns() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id", "bigint"));
|
||||
table.addColumn(new MColumn("name", "varchar(20)"));
|
||||
table.addColumn(new MColumn("status", "varchar(3)"));
|
||||
table.addColumn(new MColumn("comment", "varchar(1000)"));
|
||||
table.addColumn(new MColumn("note", "varchar(2000)"));
|
||||
return table;
|
||||
}
|
||||
|
||||
static MTable newTableModifiedColumn() {
|
||||
MColumn modCol = new MColumn("name", "varchar(30)");// modified type
|
||||
modCol.setNotnull(true);
|
||||
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(modCol);
|
||||
table.addColumn(new MColumn("id", "bigint"));
|
||||
table.addColumn(new MColumn("status", "varchar(3)"));
|
||||
return table;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_allHistoryColumns() throws Exception {
|
||||
|
||||
MTable base = base();
|
||||
base.registerPendingDropColumn("fullName");
|
||||
base.registerPendingDropColumn("last");
|
||||
|
||||
assertThat(base.allHistoryColumns(false)).containsExactly("id", "name", "status");
|
||||
assertThat(base.allHistoryColumns(true)).containsExactly("id", "name", "status", "fullName", "last");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_dropTable() {
|
||||
|
||||
MTable base = base();
|
||||
DropTable dropTable = base.dropTable();
|
||||
assertThat(dropTable.getName()).isEqualTo(base.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addColumnDropColumn() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTable());
|
||||
|
||||
List<Object> createChanges = diff.getApplyChanges();
|
||||
assertThat(createChanges).hasSize(1);
|
||||
AddColumn addColumn = (AddColumn) createChanges.get(0);
|
||||
assertThat(addColumn.getColumn()).extracting("name").contains("comment");
|
||||
assertThat(addColumn.getColumn()).extracting("type").contains("varchar(1000)");
|
||||
|
||||
List<Object> dropChanges = diff.getDropChanges();
|
||||
assertThat(dropChanges).hasSize(1);
|
||||
|
||||
DropColumn dropColumn = (DropColumn) dropChanges.get(0);
|
||||
assertThat(dropColumn.getColumnName()).isEqualTo("status");
|
||||
assertThat(dropColumn.getTableName()).isEqualTo("tab");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addTwoColumnsToSameTable() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTableAdd2Columns());
|
||||
|
||||
List<Object> createChanges = diff.getApplyChanges();
|
||||
assertThat(createChanges).hasSize(1);
|
||||
|
||||
AddColumn addColumn = (AddColumn) createChanges.get(0);
|
||||
assertThat(addColumn.getColumn()).extracting("name").contains("comment", "note");
|
||||
assertThat(addColumn.getColumn()).extracting("type").contains("varchar(1000)", "varchar(2000)");
|
||||
|
||||
assertThat(diff.getDropChanges()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_modifyColumn() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTableModifiedColumn());
|
||||
|
||||
List<Object> createChanges = diff.getApplyChanges();
|
||||
assertThat(createChanges).hasSize(1);
|
||||
|
||||
AlterColumn alterColumn = (AlterColumn) createChanges.get(0);
|
||||
assertThat(alterColumn.getColumnName()).isEqualTo("name");
|
||||
assertThat(alterColumn.getType()).isEqualTo("varchar(30)");
|
||||
assertThat(alterColumn.isNotnull()).isEqualTo(true);
|
||||
assertThat(alterColumn.getUnique()).isNull();
|
||||
assertThat(alterColumn.getCheckConstraint()).isNull();
|
||||
assertThat(alterColumn.getReferences()).isNull();
|
||||
|
||||
assertThat(diff.getDropChanges()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_apply_dropColumn() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
DropColumn dropColumn = new DropColumn();
|
||||
dropColumn.setTableName("tab");
|
||||
dropColumn.setColumnName("name");
|
||||
|
||||
base.apply(dropColumn);
|
||||
assertThat(base.getColumn("name")).isNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void test_apply_dropColumn_doesNotExist() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
DropColumn dropColumn = new DropColumn();
|
||||
dropColumn.setTableName(base.getName());
|
||||
dropColumn.setColumnName("DoesNotExist");
|
||||
base.apply(dropColumn);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void test_apply_alterColumn_doesNotExist() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName(base.getName());
|
||||
alterColumn.setColumnName("DoesNotExist");
|
||||
alterColumn.setType("integer");
|
||||
base.apply(alterColumn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_apply_alterColumn_type() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName(base.getName());
|
||||
alterColumn.setColumnName("id");
|
||||
alterColumn.setType("uuid");
|
||||
base.apply(alterColumn);
|
||||
|
||||
assertThat(base.getColumn("id").getType()).isEqualTo("uuid");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addAndDropColumn() throws Exception {
|
||||
|
||||
MTable base = base();
|
||||
MTable newTable = newTable();
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
base.compare(diff, newTable);
|
||||
|
||||
assertThat(diff.getApplyChanges()).hasSize(1);
|
||||
assertThat(diff.getDropChanges()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addHistoryToTable() {
|
||||
|
||||
MTable base = base();
|
||||
MTable withHistory = base();
|
||||
withHistory.setWithHistory(true);
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
base.compare(diff, withHistory);
|
||||
|
||||
assertThat(diff.getDropChanges()).isEmpty();
|
||||
assertThat(diff.getApplyChanges()).hasSize(1);
|
||||
assertThat(diff.getApplyChanges().get(0)).isInstanceOf(AddHistoryTable.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_removeHistoryFromTable() throws Exception {
|
||||
|
||||
MTable withHistory = base();
|
||||
withHistory.setWithHistory(true);
|
||||
|
||||
MTable noHistory = base();
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
withHistory.compare(diff, noHistory);
|
||||
|
||||
assertThat(diff.getApplyChanges()).isEmpty();
|
||||
assertThat(diff.getDropChanges()).hasSize(1);
|
||||
assertThat(diff.getDropChanges().get(0)).isInstanceOf(DropHistoryTable.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class MigrationVersionTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void sort() {
|
||||
|
||||
List<MigrationVersion> list = new ArrayList<>();
|
||||
list.add(MigrationVersion.parse("1.1__point"));
|
||||
list.add(MigrationVersion.parse("3.0__three"));
|
||||
list.add(MigrationVersion.parse("1.0__init"));
|
||||
list.add(MigrationVersion.parse("R__beta"));
|
||||
list.add(MigrationVersion.parse("R__alpha"));
|
||||
|
||||
Collections.sort(list);
|
||||
|
||||
assertThat(list.get(0).getComment()).isEqualTo("init");
|
||||
assertThat(list.get(1).getComment()).isEqualTo("point");
|
||||
assertThat(list.get(2).getComment()).isEqualTo("three");
|
||||
assertThat(list.get(3).getComment()).isEqualTo("alpha");
|
||||
assertThat(list.get(4).getComment()).isEqualTo("beta");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_hyphenSnapshot() {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse("0.1.1-SNAPSHOT");
|
||||
assertThat(version.normalised()).isEqualTo("0.1.1");
|
||||
assertThat(version.getComment()).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_hyphenSnapshot_when_underscores() {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse("0_1_1-SNAPSHOT__Foo");
|
||||
assertThat(version.normalised()).isEqualTo("0.1.1");
|
||||
assertThat(version.getComment()).isEqualTo("Foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_when_repeatable() throws Exception {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse("R__Foo");
|
||||
assertThat(version.getComment()).isEqualTo("Foo");
|
||||
assertThat(version.normalised()).isEqualTo("R");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_when_repeatable_case() throws Exception {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse("r__Foo");
|
||||
assertThat(version.isRepeatable()).isTrue();
|
||||
assertThat(version.getComment()).isEqualTo("Foo");
|
||||
assertThat(version.normalised()).isEqualTo("R");
|
||||
assertThat(version.normalised()).isEqualTo("R");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_when_v_prefix() throws Exception {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse("v1_0__Foo");
|
||||
assertThat(version.isRepeatable()).isFalse();
|
||||
assertThat(version.getComment()).isEqualTo("Foo");
|
||||
assertThat(version.normalised()).isEqualTo("1.0");
|
||||
assertThat(version.asString()).isEqualTo("1_0");
|
||||
assertThat(version.getRaw()).isEqualTo("1_0__Foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void repeatable_compareTo() throws Exception {
|
||||
|
||||
MigrationVersion foo = MigrationVersion.parse("R__Foo");
|
||||
MigrationVersion bar = MigrationVersion.parse("R__Bar");
|
||||
assertThat(foo.compareTo(bar)).isGreaterThan(0);
|
||||
assertThat(bar.compareTo(foo)).isLessThan(0);
|
||||
|
||||
MigrationVersion bar2 = MigrationVersion.parse("R__Bar");
|
||||
assertThat(bar.compareTo(bar2)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void repeatable_compareTo_when_caseDifferent() throws Exception {
|
||||
|
||||
MigrationVersion none = MigrationVersion.parse("R__");
|
||||
MigrationVersion bar = MigrationVersion.parse("R__Bar");
|
||||
MigrationVersion bar2 = MigrationVersion.parse("R__bar");
|
||||
assertThat(none.compareTo(bar)).isLessThan(0);
|
||||
assertThat(bar.compareTo(bar2)).isLessThan(0);
|
||||
assertThat(none.compareTo(bar2)).isLessThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parse_getComment() throws Exception {
|
||||
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").getComment()).isEqualTo("Foo");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2__junk").getComment()).isEqualTo("junk");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_foo").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_d").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2").getComment()).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_nextVersion_expect_preserveUnderscores() {
|
||||
|
||||
assertThat(MigrationVersion.parse("2").nextVersion()).isEqualTo("3");
|
||||
assertThat(MigrationVersion.parse("1.0").nextVersion()).isEqualTo("1.1");
|
||||
assertThat(MigrationVersion.parse("2.0.b34").nextVersion()).isEqualTo("2.1");
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").nextVersion()).isEqualTo("1.1.1_3");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2_junk").nextVersion()).isEqualTo("1.1.1.3");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4__Foo").nextVersion()).isEqualTo("1_2.3_5");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4_").nextVersion()).isEqualTo("1_2.3_5");
|
||||
assertThat(MigrationVersion.parse("1_2_3_4__Foo").nextVersion()).isEqualTo("1_2_3_5");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_normalised_expect_periods() {
|
||||
|
||||
assertThat(MigrationVersion.parse("2").normalised()).isEqualTo("2");
|
||||
assertThat(MigrationVersion.parse("1.0").normalised()).isEqualTo("1.0");
|
||||
assertThat(MigrationVersion.parse("2.0.b34").normalised()).isEqualTo("2.0");
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").normalised()).isEqualTo("1.1.1.2");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2_junk").normalised()).isEqualTo("1.1.1.2");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4__Foo").normalised()).isEqualTo("1.2.3.4");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4_").normalised()).isEqualTo("1.2.3.4");
|
||||
assertThat(MigrationVersion.parse("1_2_3_4__Foo").normalised()).isEqualTo("1.2.3.4");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compareTo_isEqual() throws Exception {
|
||||
|
||||
MigrationVersion v0 = MigrationVersion.parse("1.1.1_2__Foo");
|
||||
MigrationVersion v1 = MigrationVersion.parse("1.1.1.2_junk");
|
||||
MigrationVersion v2 = MigrationVersion.parse("1.1_1.2_foo");
|
||||
MigrationVersion v3 = MigrationVersion.parse("1.1_1.2__foo");
|
||||
|
||||
assertThat(v0.compareTo(v1)).isGreaterThan(0);
|
||||
assertThat(v1.compareTo(v0)).isLessThan(0);
|
||||
assertThat(v1.compareTo(v2)).isEqualTo(0);
|
||||
|
||||
assertThat(v0.compareTo(v3)).isLessThan(0);
|
||||
assertThat(v3.compareTo(v0)).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compareTo() throws Exception {
|
||||
|
||||
MigrationVersion v0 = MigrationVersion.parse("1.1.1.1_junk");
|
||||
MigrationVersion v1 = MigrationVersion.parse("1.1.1.2_junk");
|
||||
MigrationVersion v2 = MigrationVersion.parse("1.1_1.3_junk");
|
||||
MigrationVersion v3 = MigrationVersion.parse("1.2_1.2_junk");
|
||||
MigrationVersion v4 = MigrationVersion.parse("2.1_1.2_junk");
|
||||
|
||||
assertThat(v1.compareTo(v0)).isEqualTo(1);
|
||||
|
||||
assertThat(v1.compareTo(v2)).isEqualTo(-1);
|
||||
assertThat(v1.compareTo(v3)).isEqualTo(-1);
|
||||
assertThat(v1.compareTo(v4)).isEqualTo(-1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import io.ebean.dbmigration.migration.AddColumn;
|
||||
import io.ebean.dbmigration.migration.ChangeSet;
|
||||
import io.ebean.dbmigration.migration.CreateTable;
|
||||
import io.ebean.dbmigration.migration.DropColumn;
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import io.ebean.dbmigration.migrationreader.MigrationXmlReader;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelContainerApplyTest {
|
||||
|
||||
@Test
|
||||
public void testApply() throws Exception {
|
||||
|
||||
Migration migration = MigrationXmlReader.read("/container/test-create-table.xml");
|
||||
|
||||
List<ChangeSet> changeSets = migration.getChangeSet();
|
||||
ChangeSet changeSet = changeSets.get(0);
|
||||
|
||||
List<Object> changeSetChildren = changeSet.getChangeSetChildren();
|
||||
assertThat(changeSetChildren).hasSize(3);
|
||||
assertThat(changeSetChildren.get(0)).isInstanceOf(CreateTable.class);
|
||||
assertThat(changeSetChildren.get(1)).isInstanceOf(AddColumn.class);
|
||||
assertThat(changeSetChildren.get(2)).isInstanceOf(DropColumn.class);
|
||||
|
||||
ModelContainer model = new ModelContainer();
|
||||
model.apply(migration, MigrationVersion.parse("1.1"));
|
||||
|
||||
MTable foo = model.getTable("foo");
|
||||
assertThat(foo.getComment()).isEqualTo("comment");
|
||||
assertThat(foo.getTablespace()).isEqualTo("fooSpace");
|
||||
assertThat(foo.getIndexTablespace()).isEqualTo("fooIndexSpace");
|
||||
assertThat(foo.isWithHistory()).isEqualTo(false);
|
||||
assertThat(foo.allColumns()).extracting("name").contains("col1", "col3", "added_to_foo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import io.ebean.dbmigration.migrationreader.MigrationXmlReader;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelContainerTest {
|
||||
|
||||
@Test
|
||||
public void apply_when_noPendingDrops_then_emptyPending() throws Exception {
|
||||
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("1.0.model.xml"), ver("1.1"));
|
||||
|
||||
assertThat(container.getPendingDrops()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void apply_when_pendingDrops_then_registeredHistoryTable() throws Exception {
|
||||
|
||||
ModelContainer base = container_1_1();
|
||||
|
||||
MTable table = base.getTable("document");
|
||||
assertThat(table.allHistoryColumns(true)).doesNotContain("zing");
|
||||
|
||||
container_1_1().registerPendingHistoryDropColumns(base);
|
||||
assertThat(table.allHistoryColumns(true)).contains("zing");
|
||||
assertThat(table.allHistoryColumns(false)).doesNotContain("zing");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void apply_when_pendingDropsApplied_then_droppedTableNotInHistory() throws Exception {
|
||||
|
||||
ModelContainer container = container_1_1();
|
||||
container.apply(mig("1.1_2__drops.model.xml"), ver("1.1_2"));
|
||||
|
||||
ModelContainer base = container_1_1();
|
||||
|
||||
container.registerPendingHistoryDropColumns(base);
|
||||
|
||||
assertThat(base.getTable("document").allHistoryColumns(false)).doesNotContain("zing");
|
||||
assertThat(base.getTable("document").allHistoryColumns(true)).doesNotContain("zing");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apply_when_apply_partial_pendingDrops_then_some_remainder() throws Exception {
|
||||
|
||||
ModelContainer container = container_2_1();
|
||||
container.apply(mig("2.2__drops.model.xml"), ver("2.2"));
|
||||
|
||||
ModelContainer base = container_2_1();
|
||||
|
||||
container.registerPendingHistoryDropColumns(base);
|
||||
|
||||
List<String> normalColumns = base.getTable("document").allHistoryColumns(false);
|
||||
List<String> historyColumns = base.getTable("document").allHistoryColumns(true);
|
||||
|
||||
assertThat(historyColumns).contains("zong", "boom", "baz", "bar");
|
||||
assertThat(normalColumns).doesNotContain("zing", "zong", "boom", "baz", "bar");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private ModelContainer container_2_1() {
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("2.0.model.xml"), ver("2.0"));
|
||||
container.apply(mig("2.1.model.xml"), ver("2.1"));
|
||||
return container;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private ModelContainer container_1_1() {
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("1.0.model.xml"), ver("1.0"));
|
||||
container.apply(mig("1.1.model.xml"), ver("1.1"));
|
||||
return container;
|
||||
}
|
||||
|
||||
private MigrationVersion ver(String version) {
|
||||
return MigrationVersion.parse(version);
|
||||
}
|
||||
|
||||
private Migration mig(String path) {
|
||||
return MigrationXmlReader.read(ModelContainerTest.class.getResourceAsStream(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class ModelDiffTest {
|
||||
|
||||
@Test
|
||||
public void test_compareTo_with_dropColumnOnHistoryTable_then_historyColumnRegistered() throws Exception {
|
||||
|
||||
ModelContainer base = new ModelContainer();
|
||||
base.addTable(MTableTest.base().setWithHistory(true));
|
||||
|
||||
ModelContainer newModel = new ModelContainer();
|
||||
newModel.addTable(MTableTest.newTable().setWithHistory(true));
|
||||
|
||||
ModelDiff diff = new ModelDiff(base);
|
||||
diff.compareTo(newModel);
|
||||
|
||||
MTable tab = newModel.getTable("tab");
|
||||
|
||||
assertThat(tab.allHistoryColumns(true)).contains("status");
|
||||
assertThat(tab.allColumns()).extracting("name").doesNotContain("status");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package io.ebean.dbmigration.model;
|
||||
|
||||
import io.ebean.dbmigration.migration.ChangeSet;
|
||||
import io.ebean.dbmigration.migration.DropColumn;
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class PendingDropsTest {
|
||||
|
||||
static final MigrationVersion V1_1 = MigrationVersion.parse("1.1");
|
||||
|
||||
static final MigrationVersion V1_2 = MigrationVersion.parse("1.2");
|
||||
|
||||
@Test
|
||||
public void test_add() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_matchesSome_then_removesMatched() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
DropColumn two = col("two");
|
||||
pendingDrops.add(V1_1, changeSet(one, two));
|
||||
pendingDrops.add(V1_1, changeSet("three", "four"));
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
|
||||
ChangeSet applied = changeSet("two");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list.get(0).getChangeSetChildren()).asList().containsExactly(one);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_matchesAll_then_removesChangeSet() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
DropColumn two = col("two");
|
||||
pendingDrops.add(V1_1, changeSet(one, two));
|
||||
pendingDrops.add(V1_1, changeSet("three", "four"));
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
|
||||
ChangeSet applied = changeSet("two", "one");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_changeSetSuppressed_isIgnored() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
ChangeSet changeSet = changeSet(one);
|
||||
changeSet.setSuppressDropsForever(true);
|
||||
pendingDrops.add(V1_1, changeSet);
|
||||
|
||||
ChangeSet applied = changeSet("one");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1", "1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops_when_suppressForever() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops_when_both() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1");
|
||||
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1", "1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
ChangeSet applyDropChangeSet1 = new ChangeSet();
|
||||
ChangeSet applyDropChangeSet2 = new ChangeSet();
|
||||
|
||||
MigrationVersion version = V1_1;
|
||||
pendingDrops.add(version, applyDropChangeSet1);
|
||||
pendingDrops.add(version, applyDropChangeSet2);
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("1_1");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet1, applyDropChangeSet2);
|
||||
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion_when_both() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
ChangeSet applyDropChangeSet = new ChangeSet();
|
||||
MigrationVersion version = V1_1;
|
||||
pendingDrops.add(version, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(version, applyDropChangeSet);
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("1_1");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet);
|
||||
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion_when_next() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
MigrationVersion version = V1_1;
|
||||
|
||||
ChangeSet applyDropChangeSet = new ChangeSet();
|
||||
pendingDrops.add(version, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(version, applyDropChangeSet);
|
||||
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("next");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet);
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isTrue();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_next_isSuppressForever() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
pendingDrops.migrationForVersion("next");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_doesNotExist() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.migrationForVersion("1_1");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_next_doesNotExist() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.migrationForVersion("next");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_registerPendingHistoryDropColumns() throws Exception {
|
||||
|
||||
TDModelContainer modelContainer = new TDModelContainer();
|
||||
|
||||
DropColumn drop1 = col("one");
|
||||
drop1.setWithHistory(Boolean.TRUE);
|
||||
|
||||
DropColumn drop2 = col("two");
|
||||
|
||||
ChangeSet changeSet = changeSet(drop1, drop2);
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, changeSet);
|
||||
pendingDrops.registerPendingHistoryDropColumns(modelContainer);
|
||||
|
||||
assertThat(modelContainer.drops).containsExactly(changeSet);
|
||||
}
|
||||
|
||||
class TDModelContainer extends ModelContainer {
|
||||
|
||||
List<ChangeSet> drops = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void registerPendingHistoryDropColumns(ChangeSet changeSet) {
|
||||
drops.add(changeSet);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private ChangeSet newSuppressForeverChangeSet() {
|
||||
ChangeSet changeSet = new ChangeSet();
|
||||
changeSet.setSuppressDropsForever(Boolean.TRUE);
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(String... colNames) {
|
||||
return EntryTest.changeSet(colNames);
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(DropColumn... drops) {
|
||||
ChangeSet changeSet = new ChangeSet();
|
||||
for (DropColumn dropColumn : drops) {
|
||||
changeSet.getChangeSetChildren().add(dropColumn);
|
||||
}
|
||||
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
static DropColumn col(String colName) {
|
||||
return EntryTest.col(colName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.ebean.dbmigration.model.build;
|
||||
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.config.DbConstraintNaming;
|
||||
import io.ebean.dbmigration.ddlgeneration.platform.DefaultConstraintMaxLength;
|
||||
import io.ebean.dbmigration.model.MTable;
|
||||
import io.ebean.dbmigration.model.ModelContainer;
|
||||
import io.ebean.dbmigration.model.visitor.VisitAllUsing;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelBuildBeanVisitorTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
SpiEbeanServer defaultServer = (SpiEbeanServer) Ebean.getDefaultServer();
|
||||
|
||||
ModelContainer model = new ModelContainer();
|
||||
|
||||
DbConstraintNaming constraintNaming = defaultServer.getServerConfig().getConstraintNaming();
|
||||
|
||||
DefaultConstraintMaxLength maxLength = new DefaultConstraintMaxLength(60);
|
||||
ModelBuildContext ctx = new ModelBuildContext(model, constraintNaming, maxLength, true);
|
||||
|
||||
ModelBuildBeanVisitor addTable = new ModelBuildBeanVisitor(ctx);
|
||||
|
||||
new VisitAllUsing(addTable, defaultServer).visitAllBeans();
|
||||
|
||||
MTable item = model.getTable("item");
|
||||
|
||||
assertThat(item).isNotNull();
|
||||
assertThat(item.primaryKeyColumns()).hasSize(2);
|
||||
|
||||
MTable customer = model.getTable("o_customer");
|
||||
assertThat(customer).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.ebean.dbmigration.model.build;
|
||||
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.dbmigration.ddlgeneration.Helper;
|
||||
import io.ebean.dbmigration.migration.Migration;
|
||||
import io.ebean.dbmigration.migrationreader.MigrationXmlReader;
|
||||
import io.ebean.dbmigration.model.CurrentModel;
|
||||
import io.ebean.dbmigration.model.MTable;
|
||||
import io.ebean.dbmigration.model.ModelContainer;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.tests.model.basic.CKeyAssoc;
|
||||
import org.tests.model.basic.CKeyDetail;
|
||||
import org.tests.model.basic.CKeyParent;
|
||||
import org.tests.model.basic.CKeyParentId;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelBuild_compoundKeyTest extends BaseTestCase {
|
||||
|
||||
private SpiEbeanServer getServer() {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("h2");
|
||||
config.loadFromProperties();
|
||||
config.setName("h2other");
|
||||
config.setH2ProductionMode(true);
|
||||
config.setDdlGenerate(false);
|
||||
config.setDdlRun(false);
|
||||
config.setDefaultServer(false);
|
||||
config.setRegister(false);
|
||||
|
||||
config.addClass(CKeyDetail.class);
|
||||
config.addClass(CKeyParent.class);
|
||||
config.addClass(CKeyAssoc.class);
|
||||
config.addClass(CKeyParentId.class);
|
||||
|
||||
return (SpiEbeanServer) EbeanServerFactory.create(config);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
|
||||
SpiEbeanServer ebeanServer = getServer();
|
||||
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
ModelContainer model = currentModel.read();
|
||||
|
||||
MTable parent = model.getTable("ckey_parent");
|
||||
MTable detail = model.getTable("ckey_detail");
|
||||
|
||||
assertThat(parent).isNotNull();
|
||||
assertThat(detail).isNotNull();
|
||||
assertThat(parent.primaryKeyColumns()).hasSize(2);
|
||||
assertThat(detail.getCompoundKeys()).hasSize(1);
|
||||
|
||||
String apply = Helper.asText(this, "/assert/ModelBuild_compoundKeyTest/apply.sql");
|
||||
|
||||
String createDdl = currentModel.getCreateDdl();
|
||||
assertThat(createDdl).isEqualTo(apply);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testFromMigration() throws IOException {
|
||||
|
||||
|
||||
Migration migration = MigrationXmlReader.read("/container/test-compoundkey.xml");
|
||||
|
||||
SpiEbeanServer ebeanServer = getServer();
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
currentModel.setChangeSet(migration.getChangeSet().get(0));
|
||||
|
||||
String createDdl = currentModel.getCreateDdl();
|
||||
String apply = Helper.asText(this, "/assert/ModelBuild_compoundKeyTest/apply.sql");
|
||||
|
||||
assertThat(createDdl).isEqualTo(apply);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.ebean.dbmigration.model.build;
|
||||
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.dbmigration.ddlgeneration.Helper;
|
||||
import io.ebean.dbmigration.model.CurrentModel;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.tests.model.basic.Person;
|
||||
import org.tests.model.basic.Phone;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelBuild_explicitSequencesTest extends BaseTestCase {
|
||||
|
||||
private SpiEbeanServer getServer(boolean postgres) {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
config.setName("h2");
|
||||
config.loadFromProperties();
|
||||
config.setName("h2other");
|
||||
config.setH2ProductionMode(true);
|
||||
config.setDdlGenerate(false);
|
||||
config.setDdlRun(false);
|
||||
config.setDefaultServer(false);
|
||||
config.setRegister(false);
|
||||
|
||||
config.setDatabasePlatformName(postgres ? "postgres" : "h2");
|
||||
|
||||
config.addClass(Person.class);
|
||||
config.addClass(Phone.class);
|
||||
|
||||
return (SpiEbeanServer) EbeanServerFactory.create(config);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() throws IOException {
|
||||
|
||||
SpiEbeanServer ebeanServer = getServer(false);
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
|
||||
String apply = currentModel.getCreateDdl();
|
||||
assertThat(apply).isEqualTo(Helper.asText(this, "/assert/ModelBuild_explicitSequencesTest/apply.sql"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_asPostgres() throws IOException {
|
||||
|
||||
SpiEbeanServer ebeanServer = getServer(true);
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
|
||||
String apply = currentModel.getCreateDdl();
|
||||
assertThat(apply).isEqualTo(Helper.asText(this, "/assert/ModelBuild_explicitSequencesTest/pg-apply.sql"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package io.ebean.event;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.bean.BeanCollection;
|
||||
import io.ebean.common.BeanList;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import org.tests.model.basic.EBasic;
|
||||
import org.tests.model.basic.ECustomId;
|
||||
import org.example.ModUuidGenerator;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class BeanFindControllerTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
|
||||
config.setName("h2otherfind");
|
||||
config.loadFromProperties();
|
||||
config.setDdlGenerate(true);
|
||||
config.setDdlRun(true);
|
||||
config.setRegister(false);
|
||||
config.setDefaultServer(false);
|
||||
config.add(new ModUuidGenerator());
|
||||
config.getClasses().add(EBasic.class);
|
||||
config.getClasses().add(ECustomId.class);
|
||||
|
||||
EBasicFindController findController = new EBasicFindController();
|
||||
config.getFindControllers().add(findController);
|
||||
|
||||
EbeanServer ebeanServer = EbeanServerFactory.create(config);
|
||||
|
||||
assertFalse(findController.calledInterceptFind);
|
||||
ebeanServer.find(EBasic.class, 42);
|
||||
assertTrue(findController.calledInterceptFind);
|
||||
|
||||
findController.findIntercept = true;
|
||||
EBasic eBasic = ebeanServer.find(EBasic.class, 42);
|
||||
|
||||
assertEquals(Integer.valueOf(47), eBasic.getId());
|
||||
assertEquals("47", eBasic.getName());
|
||||
|
||||
assertFalse(findController.calledInterceptFindMany);
|
||||
|
||||
List<EBasic> list = ebeanServer.find(EBasic.class).where().eq("name", "AnInvalidNameSoEmpty").findList();
|
||||
assertEquals(0, list.size());
|
||||
assertTrue(findController.calledInterceptFindMany);
|
||||
|
||||
findController.findManyIntercept = true;
|
||||
|
||||
list = ebeanServer.find(EBasic.class).where().eq("name", "AnInvalidNameSoEmpty").findList();
|
||||
assertEquals(1, list.size());
|
||||
|
||||
eBasic = list.get(0);
|
||||
assertEquals(Integer.valueOf(47), eBasic.getId());
|
||||
assertEquals("47", eBasic.getName());
|
||||
|
||||
ECustomId bean = new ECustomId("check");
|
||||
ebeanServer.save(bean);
|
||||
assertNotNull(bean.getId());
|
||||
}
|
||||
|
||||
static class EBasicFindController implements BeanFindController {
|
||||
|
||||
boolean findIntercept;
|
||||
boolean findManyIntercept;
|
||||
boolean calledInterceptFind;
|
||||
boolean calledInterceptFindMany;
|
||||
|
||||
@Override
|
||||
public boolean isRegisterFor(Class<?> cls) {
|
||||
return EBasic.class.equals(cls);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInterceptFind(BeanQueryRequest<?> request) {
|
||||
calledInterceptFind = true;
|
||||
return findIntercept;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T find(BeanQueryRequest<T> request) {
|
||||
return (T) createBean();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInterceptFindMany(BeanQueryRequest<?> request) {
|
||||
calledInterceptFindMany = true;
|
||||
return findManyIntercept;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> BeanCollection<T> findMany(BeanQueryRequest<T> request) {
|
||||
|
||||
BeanList<T> list = new BeanList<>();
|
||||
list.add((T) createBean());
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
private static EBasic createBean() {
|
||||
EBasic b = new EBasic();
|
||||
b.setId(47);
|
||||
b.setName("47");
|
||||
return b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package io.ebean.event;
|
||||
|
||||
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BeanPersistControllerTest {
|
||||
|
||||
PersistAdapter continuePersistingAdapter = new PersistAdapter(true);
|
||||
|
||||
PersistAdapter stopPersistingAdapter = new PersistAdapter(false);
|
||||
|
||||
@Test
|
||||
public void testInsertUpdateDelete_given_continuePersistingAdapter() {
|
||||
|
||||
EbeanServer ebeanServer = getEbeanServer(continuePersistingAdapter);
|
||||
|
||||
|
||||
EBasicVer bean = new EBasicVer("testController");
|
||||
|
||||
ebeanServer.save(bean);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).hasSize(2);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).containsExactly("preInsert", "postInsert");
|
||||
continuePersistingAdapter.methodsCalled.clear();
|
||||
|
||||
bean.setName("modified");
|
||||
ebeanServer.save(bean);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).hasSize(2);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).containsExactly("preUpdate", "postUpdate");
|
||||
continuePersistingAdapter.methodsCalled.clear();
|
||||
|
||||
ebeanServer.delete(bean);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).hasSize(2);
|
||||
assertThat(continuePersistingAdapter.methodsCalled).containsExactly("preDelete", "postDelete");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInsertUpdateDelete_given_stopPersistingAdapter() {
|
||||
|
||||
EbeanServer ebeanServer = getEbeanServer(stopPersistingAdapter);
|
||||
|
||||
EBasicVer bean = new EBasicVer("testController");
|
||||
|
||||
ebeanServer.save(bean);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).hasSize(1);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).containsExactly("preInsert");
|
||||
stopPersistingAdapter.methodsCalled.clear();
|
||||
|
||||
bean.setName("modified");
|
||||
ebeanServer.update(bean);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).hasSize(1);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).containsExactly("preUpdate");
|
||||
stopPersistingAdapter.methodsCalled.clear();
|
||||
|
||||
ebeanServer.delete(bean);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).hasSize(1);
|
||||
assertThat(stopPersistingAdapter.methodsCalled).containsExactly("preDelete");
|
||||
|
||||
}
|
||||
|
||||
private EbeanServer getEbeanServer(PersistAdapter persistAdapter) {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
ServerConfig config = new ServerConfig();
|
||||
|
||||
config.setName("h2ebasicver");
|
||||
config.setH2ProductionMode(true);
|
||||
config.loadFromProperties();
|
||||
config.setDdlGenerate(true);
|
||||
config.setDdlRun(true);
|
||||
|
||||
config.setRegister(false);
|
||||
config.setDefaultServer(false);
|
||||
config.getClasses().add(EBasicVer.class);
|
||||
|
||||
config.add(persistAdapter);
|
||||
|
||||
return EbeanServerFactory.create(config);
|
||||
}
|
||||
|
||||
static class PersistAdapter extends BeanPersistAdapter {
|
||||
|
||||
boolean continueDefaultPersisting;
|
||||
|
||||
List<String> methodsCalled = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* No default constructor so only registered manually.
|
||||
*/
|
||||
PersistAdapter(boolean continueDefaultPersisting) {
|
||||
this.continueDefaultPersisting = continueDefaultPersisting;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRegisterFor(Class<?> cls) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preDelete(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("preDelete");
|
||||
return continueDefaultPersisting;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preInsert(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("preInsert");
|
||||
return continueDefaultPersisting;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preUpdate(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("preUpdate");
|
||||
return continueDefaultPersisting;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postDelete(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("postDelete");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postInsert(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("postInsert");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postUpdate(BeanPersistRequest<?> request) {
|
||||
methodsCalled.add("postUpdate");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package io.ebean.event;
|
||||
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.BeanState;
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.EbeanServerFactory;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import org.tests.model.basic.EBasicVer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class BeanPostLoadTest extends BaseTestCase {
|
||||
|
||||
PostLoad postLoad = new PostLoad(false);
|
||||
|
||||
@Test
|
||||
public void testPostLoad() {
|
||||
|
||||
EbeanServer ebeanServer = getEbeanServer();
|
||||
|
||||
EBasicVer bean = new EBasicVer("testPostLoad");
|
||||
bean.setDescription("someDescription");
|
||||
bean.setOther("other");
|
||||
|
||||
ebeanServer.save(bean);
|
||||
|
||||
EBasicVer found = ebeanServer.find(EBasicVer.class)
|
||||
.select("name, other")
|
||||
.setId(bean.getId())
|
||||
.findUnique();
|
||||
|
||||
assertThat(postLoad.methodsCalled).hasSize(1);
|
||||
assertThat(postLoad.methodsCalled).containsExactly("postLoad");
|
||||
assertThat(postLoad.beanState.getLoadedProps()).containsExactly("id", "name", "other");
|
||||
assertThat(postLoad.bean).isSameAs(found);
|
||||
|
||||
ebeanServer.delete(bean);
|
||||
}
|
||||
|
||||
|
||||
private EbeanServer getEbeanServer() {
|
||||
|
||||
System.setProperty("ebean.ignoreExtraDdl", "true");
|
||||
|
||||
ServerConfig config = new ServerConfig();
|
||||
|
||||
config.setName("h2ebasicver");
|
||||
config.loadFromProperties();
|
||||
config.setH2ProductionMode(true);
|
||||
config.setDdlGenerate(true);
|
||||
config.setDdlRun(true);
|
||||
|
||||
config.setRegister(false);
|
||||
config.setDefaultServer(false);
|
||||
config.getClasses().add(EBasicVer.class);
|
||||
|
||||
config.add(postLoad);
|
||||
|
||||
return EbeanServerFactory.create(config);
|
||||
}
|
||||
|
||||
static class PostLoad implements BeanPostLoad {
|
||||
|
||||
|
||||
boolean dummy;
|
||||
|
||||
List<String> methodsCalled = new ArrayList<>();
|
||||
|
||||
Object bean;
|
||||
|
||||
BeanState beanState;
|
||||
|
||||
/**
|
||||
* No default constructor so only registered manually.
|
||||
*/
|
||||
PostLoad(boolean dummy) {
|
||||
this.dummy = dummy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRegisterFor(Class<?> cls) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postLoad(Object bean) {
|
||||
this.methodsCalled.add("postLoad");
|
||||
this.bean = bean;
|
||||
this.beanState = Ebean.getBeanState(bean);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.ebean.event.readaudit;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class ReadAuditQueryPlanTest {
|
||||
|
||||
@Test
|
||||
public void testEquals() {
|
||||
|
||||
ReadAuditQueryPlan plan1 = new ReadAuditQueryPlan("org.Bean", "queryKey", "select id from foo");
|
||||
|
||||
assertEquals(plan1, new ReadAuditQueryPlan("org.Bean", "queryKey", "select id from foo"));
|
||||
assertNotEquals(plan1, new ReadAuditQueryPlan("org.Bean", "queryKey", "select id from Notfoo"));
|
||||
assertNotEquals(plan1, new ReadAuditQueryPlan("org.Bean", "notQueryKey", "select id from foo"));
|
||||
assertNotEquals(plan1, new ReadAuditQueryPlan("org.NotBean", "queryKey", "select id from foo"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package io.ebean.json;
|
||||
|
||||
import io.ebean.text.json.EJson;
|
||||
import io.ebeaninternal.server.type.ModifyAwareMap;
|
||||
import io.ebeaninternal.server.type.ModifyAwareOwner;
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class EJsonTests {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(EJsonTests.class);
|
||||
|
||||
@Test
|
||||
public void test_map_simple() throws IOException {
|
||||
|
||||
JsonFactory factory = new JsonFactory();
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12}";
|
||||
|
||||
JsonParser jsonParser = factory.createParser(jsonInput);
|
||||
|
||||
Object result = EJson.parse(jsonParser);
|
||||
|
||||
assertTrue(result instanceof Map);
|
||||
Map<?, ?> map = (Map<?, ?>) result;
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertEquals(12L, map.get("age"));
|
||||
|
||||
String jsonOutput = EJson.write(result);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void write_withWriter_expect_writerNotClosed() throws IOException {
|
||||
|
||||
File temp = Files.createTempFile("some", ".json").toFile();
|
||||
FileWriter writer = new FileWriter(temp);
|
||||
Map<String,Object> map = new LinkedHashMap<>();
|
||||
map.put("foo", "bar");
|
||||
EJson.write(map, writer);
|
||||
writer.write("The end.");
|
||||
writer.flush();
|
||||
writer.close();
|
||||
|
||||
log.info("write to file {}", temp.getAbsolutePath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parseObject() throws IOException {
|
||||
|
||||
JsonFactory factory = new JsonFactory();
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12}";
|
||||
|
||||
JsonParser jsonParser = factory.createParser(jsonInput);
|
||||
|
||||
Map<String, Object> map = EJson.parseObject(jsonParser);
|
||||
|
||||
assertNotNull(map);
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertEquals(12L, map.get("age"));
|
||||
|
||||
String jsonOutput = EJson.write(map);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_parseObject_reader() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12}";
|
||||
|
||||
StringReader reader = new StringReader(jsonInput);
|
||||
|
||||
Map<String, Object> map = EJson.parseObject(reader);
|
||||
|
||||
assertNotNull(map);
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertEquals(12L, map.get("age"));
|
||||
|
||||
String jsonOutput = EJson.write(map);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_map_nested() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12,\"org\":{\"name\":\"superorg\",\"rating\":4},\"nums\":[1,2,3]}";
|
||||
Object result = EJson.parse(jsonInput);
|
||||
|
||||
assertTrue(result instanceof Map);
|
||||
Map<?, ?> map = (Map<?, ?>) result;
|
||||
assertEquals(4, map.size());
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertEquals(12L, map.get("age"));
|
||||
|
||||
Map<?, ?> org = (Map<?, ?>) map.get("org");
|
||||
assertEquals("superorg", org.get("name"));
|
||||
assertEquals(4L, org.get("rating"));
|
||||
|
||||
List<?> nums = (List<?>) map.get("nums");
|
||||
assertEquals(3, nums.size());
|
||||
assertEquals(1L, nums.get(0));
|
||||
assertEquals(2L, nums.get(1));
|
||||
assertEquals(3L, nums.get(2));
|
||||
|
||||
String jsonOutput = EJson.write(result);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_map_withNull() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":null}";
|
||||
Object result = EJson.parse(jsonInput);
|
||||
|
||||
assertTrue(result instanceof Map);
|
||||
Map<?, ?> map = (Map<?, ?>) result;
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertNull(map.get("age"));
|
||||
|
||||
String jsonOutput = EJson.write(result);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_list_simple() throws IOException {
|
||||
|
||||
String jsonInput = "[\"name\",\"rob\",12,13]";
|
||||
List<Object> list = EJson.parseList(jsonInput);
|
||||
|
||||
assertEquals(4, list.size());
|
||||
assertEquals("name", list.get(0));
|
||||
assertEquals("rob", list.get(1));
|
||||
assertEquals(12L, list.get(2));
|
||||
assertEquals(13L, list.get(3));
|
||||
|
||||
String jsonOutput = EJson.write(list);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_list_reader() throws IOException {
|
||||
|
||||
String jsonInput = "[\"name\",\"rob\",12,13]";
|
||||
StringReader reader = new StringReader(jsonInput);
|
||||
List<Object> list = EJson.parseList(reader);
|
||||
|
||||
assertEquals(4, list.size());
|
||||
assertEquals("name", list.get(0));
|
||||
assertEquals("rob", list.get(1));
|
||||
assertEquals(12L, list.get(2));
|
||||
assertEquals(13L, list.get(3));
|
||||
|
||||
String jsonOutput = EJson.write(list);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_list_jsonParser() throws IOException {
|
||||
|
||||
String jsonInput = "[\"name\",\"rob\",12,13]";
|
||||
|
||||
JsonFactory jsonFactory = new JsonFactory();
|
||||
JsonParser parser = jsonFactory.createParser(jsonInput);
|
||||
|
||||
List<Object> list = EJson.parseList(parser);
|
||||
|
||||
assertEquals(4, list.size());
|
||||
assertEquals("name", list.get(0));
|
||||
assertEquals("rob", list.get(1));
|
||||
assertEquals(12L, list.get(2));
|
||||
assertEquals(13L, list.get(3));
|
||||
|
||||
String jsonOutput = EJson.write(list);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void test_list_ofMaps() throws IOException {
|
||||
|
||||
String jsonInput = "[{\"name\":\"rob\",\"age\":12},{\"name\":\"mike\",\"age\":13}]";
|
||||
Object result = EJson.parse(jsonInput);
|
||||
|
||||
assertTrue(result instanceof List);
|
||||
|
||||
List<Map<?, ?>> list = (List<Map<?, ?>>) result;
|
||||
assertEquals(2, list.size());
|
||||
assertEquals("rob", list.get(0).get("name"));
|
||||
assertEquals(12L, list.get(0).get("age"));
|
||||
assertEquals("mike", list.get(1).get("name"));
|
||||
assertEquals(13L, list.get(1).get("age"));
|
||||
|
||||
String jsonOutput = EJson.write(result);
|
||||
assertEquals(jsonInput, jsonOutput);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_partial_read() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":null,\"friend\":{\"name\":\"mike\",\"age\":13}},some more json would follow...";
|
||||
StringReader reader = new StringReader(jsonInput);
|
||||
|
||||
Object result = EJson.parse(reader);
|
||||
|
||||
assertTrue(result instanceof Map);
|
||||
Map<?, ?> map = (Map<?, ?>) result;
|
||||
assertEquals("rob", map.get("name"));
|
||||
assertNull(map.get("age"));
|
||||
|
||||
Map<?, ?> friend = (Map<?, ?>) map.get("friend");
|
||||
assertEquals("mike", friend.get("name"));
|
||||
assertEquals(13L, friend.get("age"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_map_nested_modifyAware() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12,\"org\":{\"name\":\"superorg\",\"rating\":4},\"nums\":[1,2,3]}";
|
||||
ModifyAwareMap<String, Object> map = (ModifyAwareMap<String, Object>) EJson.parseObject(jsonInput, true);
|
||||
|
||||
assertFalse(map.isMarkedDirty());
|
||||
assertEquals(4, map.size());
|
||||
|
||||
map.put("name", "jim");
|
||||
assertTrue(map.isMarkedDirty());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void test_map_nested_modifyAwareNestedList() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12,\"org\":{\"name\":\"superorg\",\"rating\":4},\"nums\":[1,2,3]}";
|
||||
ModifyAwareMap<String, Object> map = (ModifyAwareMap<String, Object>) EJson.parseObject(jsonInput, true);
|
||||
assertFalse(map.isMarkedDirty());
|
||||
|
||||
List<Object> nums = (List<Object>) map.get("nums");
|
||||
nums.add(4);
|
||||
assertTrue(map.isMarkedDirty());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void test_map_nested_modifyAwareNestedObject() throws IOException {
|
||||
|
||||
String jsonInput = "{\"name\":\"rob\",\"age\":12,\"org\":{\"name\":\"superorg\",\"rating\":4},\"nums\":[1,2,3]}";
|
||||
ModifyAwareMap<String, Object> map = (ModifyAwareMap<String, Object>) EJson.parseObject(jsonInput, true);
|
||||
assertFalse(map.isMarkedDirty());
|
||||
|
||||
Map<String, Object> org = (Map<String, Object>) map.get("org");
|
||||
org.put("extra", "foo");
|
||||
assertTrue(map.isMarkedDirty());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void parse_when_null() throws IOException {
|
||||
|
||||
Object nothing = EJson.parse((String) null);
|
||||
assertNull(nothing);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseList_when_null() throws IOException {
|
||||
|
||||
Object nothing = EJson.parseList((String) null);
|
||||
assertNull(nothing);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSet_when_modifyAware() throws IOException {
|
||||
|
||||
String jsonInput = "[{\"name\":\"rob\",\"age\":12},{\"name\":\"jim\",\"age\":42}]";
|
||||
|
||||
Set set = EJson.parseSet(jsonInput, true);
|
||||
|
||||
ModifyAwareOwner modAware = (ModifyAwareOwner) set;
|
||||
assertFalse(modAware.isMarkedDirty());
|
||||
|
||||
Iterator iterator = set.iterator();
|
||||
if (iterator.hasNext()) {
|
||||
Map map = (Map) iterator.next();
|
||||
map.put("name", "stu");
|
||||
assertTrue(modAware.isMarkedDirty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package io.ebean.plugin;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.FetchPath;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.text.PathProperties;
|
||||
import io.ebeaninternal.api.SpiQuery;
|
||||
import io.ebeaninternal.server.querydefn.OrmQueryDetail;
|
||||
import org.tests.inheritance.Stockforecast;
|
||||
import org.tests.model.basic.Car;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.tests.model.basic.OrderDetail;
|
||||
import org.tests.model.basic.Person;
|
||||
import org.tests.model.basic.Product;
|
||||
import org.tests.model.basic.Vehicle;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class BeanTypeTest {
|
||||
|
||||
static EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
<T> BeanType<T> beanType(Class<T> cls) {
|
||||
return server.getPluginApi().getBeanType(cls);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanType() throws Exception {
|
||||
assertThat(beanType(Order.class).getBeanType()).isEqualTo(Order.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTypeAtPath_when_ManyToOne() throws Exception {
|
||||
BeanType<Order> orderType = beanType(Order.class);
|
||||
BeanType<?> customerType = orderType.getBeanTypeAtPath("customer");
|
||||
assertThat(customerType.getBeanType()).isEqualTo(Customer.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTypeAtPath_when_OneToMany() throws Exception {
|
||||
BeanType<Order> orderType = beanType(Order.class);
|
||||
BeanType<?> detailsType = orderType.getBeanTypeAtPath("details");
|
||||
assertThat(detailsType.getBeanType()).isEqualTo(OrderDetail.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTypeAtPath_when_nested() throws Exception {
|
||||
BeanType<Order> orderType = beanType(Order.class);
|
||||
BeanType<?> productType = orderType.getBeanTypeAtPath("details.product");
|
||||
assertThat(productType.getBeanType()).isEqualTo(Product.class);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void getTypeAtPath_when_simpleType() throws Exception {
|
||||
|
||||
beanType(Order.class).getBeanTypeAtPath("status");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createBean() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).createBean()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void property() throws Exception {
|
||||
|
||||
Order order = new Order();
|
||||
order.setStatus(Order.Status.APPROVED);
|
||||
Property statusProperty = beanType(Order.class).getProperty("status");
|
||||
|
||||
assertThat(statusProperty.getVal(order)).isEqualTo(order.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBaseTable() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).getBaseTable()).isEqualTo("o_order");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beanId_and_getBeanId() throws Exception {
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(42);
|
||||
|
||||
Object id1 = beanType(Order.class).beanId(order);
|
||||
Object id2 = beanType(Order.class).getBeanId(order);
|
||||
|
||||
assertThat(id1).isEqualTo(order.getId());
|
||||
assertThat(id2).isEqualTo(order.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBeanId() throws Exception {
|
||||
|
||||
Order order = new Order();
|
||||
beanType(Order.class).setBeanId(order, 42);
|
||||
|
||||
assertThat(42).isEqualTo(order.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isDocStoreIndex() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).isDocStoreMapped()).isFalse();
|
||||
assertThat(beanType(Person.class).isDocStoreMapped()).isFalse();
|
||||
|
||||
assertThat(beanType(Order.class).getDocMapping()).isNotNull();
|
||||
assertThat(beanType(Person.class).getDocMapping()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void docStore_getEmbedded() throws Exception {
|
||||
|
||||
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
|
||||
FetchPath customer = orderDocType.getEmbedded("customer");
|
||||
assertThat(customer).isNotNull();
|
||||
assertThat(customer.getProperties(null)).contains("id", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void docStore_getEmbeddedManyRoot() throws Exception {
|
||||
|
||||
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
|
||||
|
||||
FetchPath detailsPath = orderDocType.getEmbedded("details");
|
||||
assertThat(detailsPath).isNotNull();
|
||||
|
||||
FetchPath detailsRoot = orderDocType.getEmbeddedManyRoot("details");
|
||||
assertThat(detailsRoot).isNotNull();
|
||||
assertThat(detailsRoot.getProperties(null)).containsExactly("id", "details");
|
||||
assertThat(detailsRoot.hasPath("details")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getDocStoreQueueId() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).getDocStoreQueueId()).isEqualTo("order");
|
||||
assertThat(beanType(Customer.class).getDocStoreQueueId()).isEqualTo("customer");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getDocStoreIndexType() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).docStore().getIndexType()).isEqualTo("order");
|
||||
assertThat(beanType(Customer.class).docStore().getIndexType()).isEqualTo("customer");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getDocStoreIndexName() throws Exception {
|
||||
|
||||
assertThat(beanType(Order.class).docStore().getIndexType()).isEqualTo("order");
|
||||
assertThat(beanType(Customer.class).docStore().getIndexType()).isEqualTo("customer");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void docStoreNested() throws Exception {
|
||||
|
||||
FetchPath parse = PathProperties.parse("id,name");
|
||||
|
||||
FetchPath nestedCustomer = beanType(Order.class).docStore().getEmbedded("customer");
|
||||
assertThat(nestedCustomer.toString()).isEqualTo(parse.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void docStoreApplyPath() throws Exception {
|
||||
|
||||
SpiQuery<Order> orderQuery = (SpiQuery<Order>) server.find(Order.class);
|
||||
beanType(Order.class).docStore().applyPath(orderQuery);
|
||||
|
||||
OrmQueryDetail detail = orderQuery.getDetail();
|
||||
assertThat(detail.getChunk("customer", false).getSelectProperties())
|
||||
.containsExactly("id", "name");
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void docStoreIndex() throws Exception {
|
||||
beanType(Order.class).docStore().index(1, new Order(), null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void docStoreDeleteById() throws Exception {
|
||||
beanType(Order.class).docStore().deleteById(1, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void docStoreUpdateEmbedded() throws Exception {
|
||||
beanType(Order.class).docStore().updateEmbedded(1, "customer", "someJson", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasInheritance_when_not() {
|
||||
assertFalse(beanType(Order.class).hasInheritance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasInheritance_when_root() {
|
||||
assertTrue(beanType(Vehicle.class).hasInheritance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasInheritance_when_leaf() {
|
||||
assertTrue(beanType(Car.class).hasInheritance());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getDiscColumn_when_default() {
|
||||
assertEquals(beanType(Car.class).getDiscColumn(), "dtype");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getDiscColumn_when_set() {
|
||||
assertEquals(beanType(Stockforecast.class).getDiscColumn(), "type");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createBeanUsingDisc_when_set() {
|
||||
Vehicle vehicle = beanType(Vehicle.class).createBeanUsingDisc("C");
|
||||
assertTrue(vehicle instanceof Car);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addInheritanceWhere_when_leaf() {
|
||||
Query<Vehicle> query = server.find(Vehicle.class);
|
||||
beanType(Car.class).addInheritanceWhere((SpiQuery<?>) query);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addInheritanceWhere_when_root() {
|
||||
Query<Vehicle> query = server.find(Vehicle.class);
|
||||
beanType(Vehicle.class).addInheritanceWhere((SpiQuery<?>) query);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package io.ebean.plugin;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class ExpressionPathTest {
|
||||
|
||||
static EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
<T> BeanType<T> beanType(Class<T> cls) {
|
||||
return server.getPluginApi().getBeanType(cls);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_many() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("details").containsMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_manyChild() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("details.id").containsMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_manyGrandChild() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("details.product.sku").containsMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_one() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("customer.name").containsMany()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_oneWithMany() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("customer.contacts").containsMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void containsMany_when_oneWithManyChild() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
assertThat(beanType.getExpressionPath("customer.contacts.firstName").containsMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void set_when_basic() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
Order order = new Order();
|
||||
beanType.getExpressionPath("id").pathSet(order, 42);
|
||||
assertThat(order.getId()).isEqualTo(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void set_when_nested() throws Exception {
|
||||
|
||||
BeanType<Order> beanType = beanType(Order.class);
|
||||
Order order = new Order();
|
||||
beanType.getExpressionPath("customer.name").pathSet(order, "Rob");
|
||||
assertThat(order.getCustomer().getName()).isEqualTo("Rob");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_dirty() throws Exception {
|
||||
|
||||
BeanType<Customer> customerBeanType = beanType(Customer.class);
|
||||
BeanType<Order> orderBeanType = beanType(Order.class);
|
||||
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setName("foo");
|
||||
server.save(customer);
|
||||
|
||||
customer = server.find(Customer.class, customer.getId());
|
||||
assertThat(customer.getName()).isEqualTo("foo");
|
||||
|
||||
customerBeanType.getExpressionPath("name").pathSet(customer, "bar");
|
||||
server.save(customer);
|
||||
|
||||
customer = server.find(Customer.class, customer.getId());
|
||||
assertThat(customer.getName()).isEqualTo("bar");
|
||||
|
||||
|
||||
Order order = new Order();
|
||||
order.setCustomer(customer);
|
||||
|
||||
server.save(order);
|
||||
|
||||
order = server.find(Order.class, order.getId());
|
||||
|
||||
ExpressionPath customerNamePath = orderBeanType.getExpressionPath("customer.name");
|
||||
assertThat(customerNamePath.pathGet(order)).isEqualTo("bar");
|
||||
|
||||
customerNamePath.pathSet(order, "baz");
|
||||
server.save(order);
|
||||
|
||||
order = server.find(Order.class, order.getId());
|
||||
assertThat(order.getCustomer().getName()).isEqualTo("baz");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.ebean.plugin;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Order;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
/**
|
||||
*/
|
||||
public class PropertyTest {
|
||||
|
||||
static EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
<T> BeanType<T> beanType(Class<T> cls) {
|
||||
return server.getPluginApi().getBeanType(cls);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getVal() throws Exception {
|
||||
|
||||
Customer customer = new Customer();
|
||||
|
||||
Order order = new Order();
|
||||
order.setCustomer(customer);
|
||||
order.setStatus(Order.Status.APPROVED);
|
||||
|
||||
Property statusProperty = beanType(Order.class).getProperty("status");
|
||||
assertThat(statusProperty.getVal(order)).isEqualTo(order.getStatus());
|
||||
|
||||
Property customerProperty = beanType(Order.class).getProperty("customer");
|
||||
assertThat(customerProperty.getVal(order)).isEqualTo(customer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isMany_when_not() {
|
||||
|
||||
assertThat(beanType(Order.class).getProperty("status").isMany()).isFalse();
|
||||
assertThat(beanType(Order.class).getProperty("customer").isMany()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isMany_when_true() {
|
||||
|
||||
assertThat(beanType(Order.class).getProperty("details").isMany()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void name() {
|
||||
assertThat(beanType(Order.class).getProperty("status").getName()).isEqualTo("status");
|
||||
assertThat(beanType(Order.class).getProperty("customer").getName()).isEqualTo("customer");
|
||||
assertThat(beanType(Order.class).getProperty("details").getName()).isEqualTo("details");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.ebean.plugin;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class SpiServerTest {
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
EbeanServer defaultServer = Ebean.getDefaultServer();
|
||||
SpiServer pluginApi = defaultServer.getPluginApi();
|
||||
|
||||
BeanType<Customer> beanType = pluginApi.getBeanType(Customer.class);
|
||||
assertEquals("o_customer", beanType.getBaseTable());
|
||||
assertNotNull(pluginApi.getDatabasePlatform());
|
||||
assertNull(beanType.getFindController());
|
||||
assertNotNull(beanType.getPersistController());
|
||||
assertNull(beanType.getPersistListener());
|
||||
assertNull(beanType.getQueryAdapter());
|
||||
|
||||
assertTrue(beanType.isValidExpression("name"));
|
||||
assertTrue(beanType.isValidExpression("contacts.firstName"));
|
||||
assertTrue(beanType.isValidExpression("contacts.group.name"));
|
||||
assertFalse(beanType.isValidExpression("junk"));
|
||||
assertFalse(beanType.isValidExpression("Name"));
|
||||
assertFalse(beanType.isValidExpression("contacts.name"));
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setId(42);
|
||||
|
||||
assertEquals(42, beanType.getBeanId(customer));
|
||||
|
||||
List<? extends BeanType<?>> beanTypes = pluginApi.getBeanTypes("o_customer");
|
||||
assertEquals(1, beanTypes.size());
|
||||
assertSame(beanType, beanTypes.get(0));
|
||||
|
||||
List<? extends BeanType<?>> allTypes = pluginApi.getBeanTypes();
|
||||
assertTrue(!allTypes.isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.ebean.server.type;
|
||||
|
||||
import io.ebean.annotation.EnumValue;
|
||||
|
||||
/**
|
||||
* Enum test when DB CHAR column used with spaces.
|
||||
*/
|
||||
public enum MyDayOfWeek {
|
||||
|
||||
@EnumValue("MONDAY ")MONDAY,
|
||||
@EnumValue("TUESDAY ")TUESDAY,
|
||||
@EnumValue("WEDNESDAY")WEDNESDAY,
|
||||
@EnumValue("THURSDAY ")THURSDAY,
|
||||
@EnumValue("FRIDAY ")FRIDAY,
|
||||
@EnumValue("SATURDAY ")SATURDAY,
|
||||
@EnumValue("SUNDAY ")SUNDAY
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.ebean.server.type;
|
||||
|
||||
import io.ebean.annotation.EnumValue;
|
||||
|
||||
/**
|
||||
* Enum with method overrides (and hence multiple actual classes).
|
||||
*/
|
||||
public enum MyEnum {
|
||||
|
||||
@EnumValue("A")Aval {
|
||||
@Override
|
||||
public String doSomething() {
|
||||
return "bar";
|
||||
}
|
||||
},
|
||||
@EnumValue("B")Bval,
|
||||
|
||||
@EnumValue("C")Cval {
|
||||
@Override
|
||||
public String doSomething() {
|
||||
return "baz";
|
||||
}
|
||||
};
|
||||
|
||||
public String doSomething() {
|
||||
return "foo";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package io.ebean.server.type;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.h2.H2Platform;
|
||||
import io.ebeaninternal.server.core.bootup.BootupClasses;
|
||||
import io.ebeaninternal.server.type.DefaultTypeManager;
|
||||
import io.ebeaninternal.server.type.RsetDataReader;
|
||||
import io.ebeaninternal.server.type.ScalarType;
|
||||
import org.tests.model.ivo.Money;
|
||||
import org.tests.model.ivo.converter.MoneyTypeConverter;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TestTypeManager extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void testEnumWithSubclasses() throws SQLException {
|
||||
|
||||
DefaultTypeManager typeManager = createTypeManager();
|
||||
|
||||
ScalarType<?> type = typeManager.createEnumScalarType(MyEnum.class);
|
||||
typeManager.addEnumType(type, MyEnum.class);
|
||||
|
||||
Object val = type.read(new DummyDataReader("A"));
|
||||
assertThat(val).isEqualTo(MyEnum.Aval);
|
||||
val = type.read(new DummyDataReader("B"));
|
||||
assertThat(val).isEqualTo(MyEnum.Bval);
|
||||
val = type.read(new DummyDataReader("C"));
|
||||
assertThat(val).isEqualTo(MyEnum.Cval);
|
||||
|
||||
ScalarType<?> typeGeneral = typeManager.getScalarType(MyEnum.class);
|
||||
assertThat(typeGeneral).isNotNull();
|
||||
ScalarType<?> typeB = typeManager.getScalarType(MyEnum.Bval.getClass());
|
||||
assertThat(typeB).isNotNull();
|
||||
ScalarType<?> typeA = typeManager.getScalarType(MyEnum.Aval.getClass());
|
||||
assertThat(typeA).isNotNull();
|
||||
ScalarType<?> typeC = typeManager.getScalarType(MyEnum.Cval.getClass());
|
||||
assertThat(typeC).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnumWithChar() throws SQLException {
|
||||
|
||||
DefaultTypeManager typeManager = createTypeManager();
|
||||
|
||||
ScalarType<?> dayOfWeekType = typeManager.createEnumScalarType(MyDayOfWeek.class);
|
||||
|
||||
Object val = dayOfWeekType.read(new DummyDataReader("MONDAY "));
|
||||
assertThat(val).isEqualTo(MyDayOfWeek.MONDAY);
|
||||
|
||||
val = dayOfWeekType.read(new DummyDataReader("TUESDAY "));
|
||||
assertThat(val).isEqualTo(MyDayOfWeek.TUESDAY);
|
||||
|
||||
val = dayOfWeekType.read(new DummyDataReader("WEDNESDAY"));
|
||||
assertThat(val).isEqualTo(MyDayOfWeek.WEDNESDAY);
|
||||
|
||||
val = dayOfWeekType.read(new DummyDataReader("THURSDAY "));
|
||||
assertThat(val).isEqualTo(MyDayOfWeek.THURSDAY);
|
||||
|
||||
val = dayOfWeekType.read(new DummyDataReader("FRIDAY "));
|
||||
assertThat(val).isEqualTo(MyDayOfWeek.FRIDAY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
|
||||
DefaultTypeManager typeManager = createTypeManager();
|
||||
|
||||
ScalarType<?> scalarType = typeManager.getScalarType(Money.class);
|
||||
Assert.assertTrue(scalarType.getJdbcType() == Types.DECIMAL);
|
||||
Assert.assertTrue(!scalarType.isJdbcNative());
|
||||
Assert.assertEquals(Money.class, scalarType.getType());
|
||||
|
||||
}
|
||||
|
||||
private DefaultTypeManager createTypeManager() {
|
||||
|
||||
ServerConfig serverConfig = new ServerConfig();
|
||||
serverConfig.setDatabasePlatform(new H2Platform());
|
||||
|
||||
BootupClasses bootupClasses = new BootupClasses();
|
||||
bootupClasses.getAttributeConverters().add(MoneyTypeConverter.class);
|
||||
|
||||
return new DefaultTypeManager(serverConfig, bootupClasses);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test double DataReader implementation.
|
||||
*/
|
||||
private static class DummyDataReader extends RsetDataReader {
|
||||
|
||||
String val;
|
||||
|
||||
DummyDataReader(String val) {
|
||||
super(null, null);
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getString() throws SQLException {
|
||||
return val;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package io.ebean.text;
|
||||
|
||||
import io.ebean.FetchPath;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PathPropertiesTests {
|
||||
|
||||
|
||||
@Test
|
||||
public void test_noParentheses() {
|
||||
|
||||
PathProperties s0 = PathProperties.parse("id,name");
|
||||
|
||||
assertEquals(1, s0.getPathProps().size());
|
||||
assertTrue(s0.getProperties(null).contains("id"));
|
||||
assertTrue(s0.getProperties(null).contains("name"));
|
||||
assertFalse(s0.getProperties(null).contains("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_noParentheses_needTrim() {
|
||||
|
||||
PathProperties s0 = PathProperties.parse(" id, name ");
|
||||
|
||||
assertEquals(1, s0.getPathProps().size());
|
||||
assertTrue(s0.getProperties(null).contains("id"));
|
||||
assertTrue(s0.getProperties(null).contains("name"));
|
||||
assertFalse(s0.getProperties(null).contains("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_withParentheses() {
|
||||
|
||||
PathProperties s0 = PathProperties.parse("(id,name)");
|
||||
|
||||
assertEquals(1, s0.getPathProps().size());
|
||||
assertTrue(s0.getProperties(null).contains("id"));
|
||||
assertTrue(s0.getProperties(null).contains("name"));
|
||||
assertFalse(s0.getProperties(null).contains("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_withColon() {
|
||||
|
||||
PathProperties s0 = PathProperties.parse(":(id,name)");
|
||||
|
||||
assertEquals(1, s0.getPathProps().size());
|
||||
assertTrue(s0.getProperties(null).contains("id"));
|
||||
assertTrue(s0.getProperties(null).contains("name"));
|
||||
assertFalse(s0.getProperties(null).contains("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_nested() {
|
||||
|
||||
PathProperties s1 = PathProperties.parse("id,name,shipAddr(*)");
|
||||
assertEquals(2, s1.getPathProps().size());
|
||||
assertEquals(3, s1.getProperties(null).size());
|
||||
assertTrue(s1.getProperties(null).contains("id"));
|
||||
assertTrue(s1.getProperties(null).contains("name"));
|
||||
assertTrue(s1.getProperties(null).contains("shipAddr"));
|
||||
assertTrue(s1.getProperties("shipAddr").contains("*"));
|
||||
assertEquals(1, s1.getProperties("shipAddr").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_withParenthesesColonNested() {
|
||||
|
||||
PathProperties s1 = PathProperties.parse(":(id,name,shipAddr(*))");
|
||||
assertEquals(2, s1.getPathProps().size());
|
||||
assertEquals(3, s1.getProperties(null).size());
|
||||
assertTrue(s1.getProperties(null).contains("id"));
|
||||
assertTrue(s1.getProperties(null).contains("name"));
|
||||
assertTrue(s1.getProperties(null).contains("shipAddr"));
|
||||
assertTrue(s1.getProperties("shipAddr").contains("*"));
|
||||
assertEquals(1, s1.getProperties("shipAddr").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_add() {
|
||||
|
||||
PathProperties root = PathProperties.parse("status,date");
|
||||
root.addNested("customer", PathProperties.parse("id,name"));
|
||||
|
||||
FetchPath expect = PathProperties.parse("status,date,customer(id,name)");
|
||||
assertThat(root.toString()).isEqualTo(expect.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_add_nested() {
|
||||
|
||||
PathProperties root = PathProperties.parse("status,date");
|
||||
root.addNested("customer", PathProperties.parse("id,name,address(line1,city)"));
|
||||
|
||||
FetchPath expect = PathProperties.parse("status,date,customer(id,name,address(line1,city))");
|
||||
assertThat(root.toString()).isEqualTo(expect.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_all_properties() {
|
||||
|
||||
FetchPath root = PathProperties.parse("*");
|
||||
assertThat(root.getProperties(null)).containsExactly("*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_all_properties_multipleLevels() {
|
||||
|
||||
PathProperties root = PathProperties.parse("*,customer(*)");
|
||||
//PathProperties.Props rootProps = root.getProps(null);
|
||||
PathProperties.Props customerProps = root.getProps("customer");
|
||||
|
||||
assertThat(root.getProperties(null)).containsExactly("*", "customer");
|
||||
assertThat(customerProps.getPropertiesAsString()).isEqualTo("*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_includesProperty_when_wildcardUsed() {
|
||||
|
||||
PathProperties root = PathProperties.parse("*,customer(*)");
|
||||
|
||||
assertTrue(root.includesProperty("id"));
|
||||
assertTrue(root.includesProperty("name"));
|
||||
assertTrue(root.includesProperty("customer.id"));
|
||||
assertTrue(root.includesProperty("customer.name"));
|
||||
|
||||
assertFalse(root.includesProperty("details.id"));
|
||||
assertTrue(root.includesProperty("details"));
|
||||
|
||||
assertFalse(root.includesPath("details"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_includesProperty_when_specificPropertiesUsed() {
|
||||
|
||||
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
|
||||
|
||||
assertTrue(root.includesProperty("id"));
|
||||
assertTrue(root.includesProperty("name"));
|
||||
assertFalse(root.includesProperty("status"));
|
||||
|
||||
assertTrue(root.includesProperty("customer.id"));
|
||||
assertTrue(root.includesProperty("customer.foo"));
|
||||
assertTrue(root.includesProperty("customer.billingAddress"));
|
||||
assertTrue(root.includesProperty("customer.billingAddress.city"));
|
||||
|
||||
assertFalse(root.includesPath("customer.shippingAddress"));
|
||||
assertFalse(root.includesPath("customer", "shippingAddress"));
|
||||
assertFalse(root.includesProperty("customer.shippingAddress.city"));
|
||||
|
||||
assertTrue(root.includesPath(null));
|
||||
assertTrue(root.includesPath("customer"));
|
||||
assertTrue(root.includesPath("customer.billingAddress"));
|
||||
assertTrue(root.includesPath("customer", "billingAddress"));
|
||||
|
||||
assertFalse(root.includesPath("customer.shippingAddress"));
|
||||
assertFalse(root.includesPath("details"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_includesPropertyWithPrefix() {
|
||||
|
||||
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
|
||||
|
||||
assertTrue(root.includesProperty("customer", "id"));
|
||||
assertTrue(root.includesProperty("customer", "billingAddress"));
|
||||
assertTrue(root.includesProperty("customer.billingAddress", "city"));
|
||||
|
||||
assertFalse(root.includesPath("customer", "shippingAddress"));
|
||||
assertFalse(root.includesProperty("customer.shippingAddress", "city"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_includesPathWithPrefix() {
|
||||
|
||||
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
|
||||
|
||||
assertTrue(root.includesPath(null, "customer"));
|
||||
assertTrue(root.includesPath("customer", "billingAddress"));
|
||||
|
||||
assertFalse(root.includesPath(null, "details"));
|
||||
assertFalse(root.includesPath("customer", "shippingAddress"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package io.ebean.text.json;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.bean.PersistenceContext;
|
||||
import org.tests.model.basic.Customer;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.StringReader;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class JsonBeanReaderTest extends BaseTestCase {
|
||||
|
||||
static JsonContext json = Ebean.json();
|
||||
|
||||
@Test
|
||||
public void read() throws Exception {
|
||||
|
||||
JsonParser parser = getParser();
|
||||
JsonBeanReader<Customer> beanReader = json.createBeanReader(Customer.class, parser, null);
|
||||
|
||||
Customer customer = beanReader.read();
|
||||
assertThat(customer.getId()).isEqualTo(42);
|
||||
assertThat(customer.getName()).isEqualTo("dummy");
|
||||
}
|
||||
|
||||
private JsonParser getParser() {
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setId(42);
|
||||
customer.setName("dummy");
|
||||
|
||||
String rawJson = json.toJson(customer);
|
||||
StringReader reader = new StringReader(rawJson);
|
||||
|
||||
return json.createParser(reader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forJson() throws Exception {
|
||||
|
||||
JsonParser parser = getParser();
|
||||
JsonBeanReader<Customer> beanReader = json.createBeanReader(Customer.class, parser, null);
|
||||
beanReader.read();
|
||||
|
||||
JsonParser more = getParser();
|
||||
JsonBeanReader<Customer> moreReader = beanReader.forJson(more, true);
|
||||
|
||||
Customer customer = moreReader.read();
|
||||
assertThat(customer.getId()).isEqualTo(42);
|
||||
assertThat(customer.getName()).isEqualTo("dummy");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistenceContextPut_when_noPC() throws Exception {
|
||||
|
||||
JsonParser parser = getParser();
|
||||
JsonBeanReader<Customer> beanReader = json.createBeanReader(Customer.class, parser, null);
|
||||
beanReader.read();
|
||||
|
||||
Customer other = new Customer();
|
||||
other.setId(54);
|
||||
|
||||
beanReader.persistenceContextPut(54, other);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistenceContextPut_when_hasPC() throws Exception {
|
||||
|
||||
JsonReadOptions options = new JsonReadOptions().setEnableLazyLoading(true);
|
||||
|
||||
JsonParser parser = getParser();
|
||||
JsonBeanReader<Customer> beanReader = json.createBeanReader(Customer.class, parser, options);
|
||||
Customer customer = beanReader.read();
|
||||
|
||||
Customer other = new Customer();
|
||||
other.setId(54);
|
||||
|
||||
beanReader.persistenceContextPut(54, other);
|
||||
PersistenceContext pc = beanReader.getPersistenceContext();
|
||||
assertThat(pc.get(Customer.class, 54)).isSameAs(other);
|
||||
assertThat(pc.get(Customer.class, 42)).isSameAs(customer);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package io.ebean.text.json;
|
||||
|
||||
import io.ebean.Ebean;
|
||||
import io.ebean.EbeanServer;
|
||||
import io.ebean.text.PathProperties;
|
||||
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 com.fasterxml.jackson.core.JsonGenerator;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class JsonContextTest {
|
||||
|
||||
@Test
|
||||
public void testIsSupportedType() throws Exception {
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
JsonContext json = server.json();
|
||||
assertTrue(json.isSupportedType(Customer.class));
|
||||
assertFalse(json.isSupportedType(System.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_jsonWithPersistenceContext() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> orders = Ebean.find(Order.class)
|
||||
.fetch("customer", "id, name")
|
||||
.where().eq("customer.id", 1)
|
||||
.findList();
|
||||
|
||||
String json = Ebean.json().toJson(orders);
|
||||
|
||||
List<Order> orders1 = Ebean.json().toList(Order.class, json);
|
||||
|
||||
Customer customer = null;
|
||||
for (Order order : orders1) {
|
||||
Customer tempCustomer = order.getCustomer();
|
||||
if (customer == null) {
|
||||
customer = tempCustomer;
|
||||
} else {
|
||||
assertThat(tempCustomer).isSameAs(customer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_json_loadContext() {
|
||||
|
||||
ResetBasicData.reset();
|
||||
|
||||
List<Order> orders = Ebean.find(Order.class)
|
||||
.select("status")
|
||||
.fetch("customer", "id, name")
|
||||
.findList();
|
||||
|
||||
String json = Ebean.json().toJson(orders);
|
||||
|
||||
JsonReadOptions options = new JsonReadOptions().setEnableLazyLoading(true);
|
||||
|
||||
List<Order> orders1 = Ebean.json().toList(Order.class, json, options);
|
||||
|
||||
for (Order order : orders1) {
|
||||
Customer customer = order.getCustomer();
|
||||
customer.getName();
|
||||
customer.getSmallnote();
|
||||
List<Contact> contacts = customer.getContacts();
|
||||
contacts.size();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_toObject() throws Exception {
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
JsonContext json = server.json();
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setId(1);
|
||||
customer.setName("Jim");
|
||||
|
||||
String asJson = json.toJson(customer);
|
||||
|
||||
Object bean = json.toObject(Customer.class, asJson);
|
||||
|
||||
assertTrue(bean instanceof Customer);
|
||||
assertEquals(Integer.valueOf(1), ((Customer) bean).getId());
|
||||
assertEquals("Jim", ((Customer) bean).getName());
|
||||
|
||||
StringReader reader = new StringReader(asJson);
|
||||
bean = json.toObject(Customer.class, reader);
|
||||
assertTrue(bean instanceof Customer);
|
||||
assertEquals(Integer.valueOf(1), ((Customer) bean).getId());
|
||||
assertEquals("Jim", ((Customer) bean).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_unknownProperty() {
|
||||
|
||||
String jsonWithUnknown = "{\"id\":42,\"unknownProp\":\"foo\",\"name\":\"rob\",\"version\":1}";
|
||||
|
||||
Customer customer = Ebean.json().toBean(Customer.class, jsonWithUnknown);
|
||||
assertEquals(Integer.valueOf(42), customer.getId());
|
||||
assertEquals("rob", customer.getName());
|
||||
}
|
||||
|
||||
class CustReadVisitor implements JsonReadBeanVisitor<Customer> {
|
||||
|
||||
Customer bean;
|
||||
Map<String, Object> unmapped;
|
||||
|
||||
@Override
|
||||
public void visit(Customer bean, Map<String, Object> unmapped) {
|
||||
this.bean = bean;
|
||||
this.unmapped = unmapped;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void test_unknownProperty_withVisitor() {
|
||||
|
||||
String jsonWithUnknown = "{\"id\":42,\"unknownProp\":\"foo\",\"name\":\"rob\",\"version\":1,\"extraProp\":{\"name\":\"foobie\",\"sim\":\"bo\"}}";
|
||||
|
||||
CustReadVisitor custReadVisitor = new CustReadVisitor();
|
||||
JsonReadOptions options = new JsonReadOptions();
|
||||
options.addRootVisitor(custReadVisitor);
|
||||
|
||||
|
||||
Customer customer = Ebean.json().toBean(Customer.class, jsonWithUnknown, options);
|
||||
assertEquals(Integer.valueOf(42), customer.getId());
|
||||
assertEquals("rob", customer.getName());
|
||||
|
||||
assertSame(customer, custReadVisitor.bean);
|
||||
assertEquals("foo", custReadVisitor.unmapped.get("unknownProp"));
|
||||
assertEquals(2, custReadVisitor.unmapped.size());
|
||||
assertEquals("foobie", ((Map<String, Object>) custReadVisitor.unmapped.get("extraProp")).get("name"));
|
||||
assertEquals("bo", ((Map<String, Object>) custReadVisitor.unmapped.get("extraProp")).get("sim"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_withVisitor_noUnmapped() {
|
||||
|
||||
String someJsonAllKnown = "{\"id\":42,\"name\":\"rob\",\"version\":1}";
|
||||
|
||||
CustReadVisitor custReadVisitor = new CustReadVisitor();
|
||||
JsonReadOptions options = new JsonReadOptions();
|
||||
options.addRootVisitor(custReadVisitor);
|
||||
|
||||
Customer customer = Ebean.json().toBean(Customer.class, someJsonAllKnown, options);
|
||||
assertEquals(Integer.valueOf(42), customer.getId());
|
||||
assertEquals("rob", customer.getName());
|
||||
|
||||
assertSame(customer, custReadVisitor.bean);
|
||||
assertNull(custReadVisitor.unmapped);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGenerator() throws Exception {
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
JsonContext json = server.json();
|
||||
JsonGenerator generator = json.createGenerator(writer);
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setId(1);
|
||||
customer.setName("Jim");
|
||||
|
||||
|
||||
// we can use the generator before and after our json.toJson() call
|
||||
// ... confirming we are not closing the generator
|
||||
generator.writeStartArray();
|
||||
json.toJson(customer, generator, PathProperties.parse("id,name"));
|
||||
generator.writeEndArray();
|
||||
generator.close();
|
||||
|
||||
String jsonString = writer.toString();
|
||||
assertTrue(jsonString, jsonString.startsWith("["));
|
||||
assertTrue(jsonString, jsonString.endsWith("]"));
|
||||
assertTrue(jsonString, jsonString.contains("{\"id\":1,\"name\":\"Jim\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGenerator_writeRaw() throws Exception {
|
||||
|
||||
EbeanServer server = Ebean.getDefaultServer();
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
JsonContext json = server.json();
|
||||
JsonGenerator generator = json.createGenerator(writer);
|
||||
|
||||
// test that we can write anything via writeRaw()
|
||||
generator.writeRaw("START");
|
||||
generator.writeStartArray();
|
||||
generator.writeStartObject();
|
||||
generator.writeNumberField("count", 12);
|
||||
generator.writeEndObject();
|
||||
generator.writeEndArray();
|
||||
generator.writeRaw("END");
|
||||
generator.close();
|
||||
|
||||
assertEquals("START[{\"count\":12}]END", writer.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package io.ebean.text.json;
|
||||
|
||||
import io.ebean.FetchPath;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JsonWriteOptionsTests {
|
||||
|
||||
@Test
|
||||
public void test_parse() {
|
||||
|
||||
JsonWriteOptions options = JsonWriteOptions.parsePath("id,status,name");
|
||||
FetchPath pathProps = options.getPathProperties();
|
||||
|
||||
//Assert.assertEquals(1, pathProps.getPaths().size());
|
||||
assertTrue(pathProps.getProperties(null).contains("id"));
|
||||
assertTrue(pathProps.getProperties(null).contains("name"));
|
||||
assertTrue(pathProps.getProperties(null).contains("status"));
|
||||
assertFalse(pathProps.getProperties(null).contains("foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_with_depth() {
|
||||
|
||||
JsonWriteOptions options = JsonWriteOptions.parsePath("id,status,name,customer(id,name,address(street,city)),orders(qty,product(sku,prodName))");
|
||||
FetchPath pathProps = options.getPathProperties();
|
||||
|
||||
//Assert.assertEquals(5, pathProps.getPaths().size());
|
||||
assertTrue(pathProps.getProperties(null).contains("id"));
|
||||
assertTrue(pathProps.getProperties(null).contains("name"));
|
||||
assertTrue(pathProps.getProperties(null).contains("status"));
|
||||
assertTrue(pathProps.getProperties(null).contains("customer"));
|
||||
assertTrue(pathProps.getProperties(null).contains("orders"));
|
||||
assertFalse(pathProps.getProperties(null).contains("foo"));
|
||||
|
||||
Set<String> customer = pathProps.getProperties("customer");
|
||||
assertTrue(customer.contains("id"));
|
||||
assertTrue(customer.contains("name"));
|
||||
assertTrue(customer.contains("address"));
|
||||
|
||||
Set<String> address = pathProps.getProperties("customer.address");
|
||||
assertTrue(address.contains("street"));
|
||||
assertTrue(address.contains("city"));
|
||||
|
||||
Set<String> orders = pathProps.getProperties("orders");
|
||||
assertTrue(orders.contains("qty"));
|
||||
assertTrue(orders.contains("product"));
|
||||
|
||||
Set<String> product = pathProps.getProperties("orders.product");
|
||||
assertTrue(product.contains("sku"));
|
||||
assertTrue(product.contains("prodName"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.ebean.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CamelCaseHelperTest {
|
||||
|
||||
@Test
|
||||
public void when_underscore() throws Exception {
|
||||
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there"), "helloThere");
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there_jim"), "helloThereJim");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_trailing_numbers() throws Exception {
|
||||
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_1"), "hello1");
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello_there_2"), "helloThere2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_already_camel() throws Exception {
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("helloThere"), "helloThere");
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("helloThereJim"), "helloThereJim");
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("hello"), "hello");
|
||||
assertEquals(CamelCaseHelper.toCamelFromUnderscore("HELLO"), "HELLO");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package io.ebeaninternal.api;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class BindParamsTest {
|
||||
|
||||
@Test
|
||||
public void test_hash() {
|
||||
|
||||
BindParams bindParams = new BindParams();
|
||||
|
||||
List<String> ids = Arrays.asList("1", "2", "3");
|
||||
bindParams.setParameter("ids", ids);
|
||||
BindParams.Param param = bindParams.getParameter("ids");
|
||||
assertEquals(3, param.queryBindCount());
|
||||
assertFalse(bindParams.isSameBindHash());
|
||||
|
||||
List<String> ids2 = Arrays.asList("1", "2", "3", "4");
|
||||
bindParams.setParameter("ids", ids2);
|
||||
assertEquals(4, param.queryBindCount());
|
||||
assertFalse(bindParams.isSameBindHash());
|
||||
|
||||
List<String> ids3 = Arrays.asList("2", "99", "44");
|
||||
bindParams.setParameter("ids", ids3);
|
||||
assertEquals(3, param.queryBindCount());
|
||||
assertFalse(bindParams.isSameBindHash());
|
||||
|
||||
|
||||
List<String> ids4 = Arrays.asList("4545", "3499", "3444");
|
||||
bindParams.setParameter("ids", ids4);
|
||||
assertEquals(3, param.queryBindCount());
|
||||
assertTrue(bindParams.isSameBindHash());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.ebeaninternal.api;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class HashQueryPlanBuilderTest {
|
||||
|
||||
int combine(int v0, int v1) {
|
||||
return new HashQueryPlanBuilder().add(v0).add(v1).build().hashCode();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_1() {
|
||||
assertThat(combine(0, 31)).isNotEqualTo(combine(1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_0() {
|
||||
assertThat(combine(0, 310)).isNotEqualTo(combine(10, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_10() {
|
||||
assertThat(combine(0, 320)).isNotEqualTo(combine(10, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_40() {
|
||||
assertThat(combine(0, 350)).isNotEqualTo(combine(10, 40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_90() {
|
||||
assertThat(combine(0, 400)).isNotEqualTo(combine(10, 90));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package io.ebeaninternal.api;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class HashQueryPlanTest {
|
||||
|
||||
private HashQueryPlan hqp(String raw, int plan, int bind) {
|
||||
return new HashQueryPlan(raw, plan, bind);
|
||||
}
|
||||
|
||||
private int hc(String raw, int plan, int bind) {
|
||||
return hqp(raw, plan, bind).hashCode();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals() throws Exception {
|
||||
|
||||
assertThat(hqp("foo", 10, 7)).isEqualTo(hqp("foo", 10, 7));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp("foo", 11, 7));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp("foo", 9, 7));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp("foo", 10, 8));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp("foo", 10, 6));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp("bar", 10, 6));
|
||||
assertThat(hqp("foo", 10, 7)).isNotEqualTo(hqp(null, 10, 7));
|
||||
assertThat(hqp(null, 10, 7)).isNotEqualTo(hqp("foo", 10, 7));
|
||||
assertThat(hqp(null, 10, 7)).isEqualTo(hqp(null, 10, 7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashCode() throws Exception {
|
||||
|
||||
assertThat(hc("foo", 10, 7)).isEqualTo(hc("foo", 10, 7));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc("foo", 11, 7));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc("foo", 9, 7));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc("foo", 10, 8));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc("foo", 10, 6));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc("bar", 10, 6));
|
||||
assertThat(hc("foo", 10, 7)).isNotEqualTo(hc(null, 10, 7));
|
||||
assertThat(hc(null, 10, 7)).isNotEqualTo(hc("foo", 10, 7));
|
||||
assertThat(hc(null, 10, 7)).isEqualTo(hc(null, 10, 7));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,810 @@
|
||||
package io.ebeaninternal.api;
|
||||
|
||||
import io.ebean.AutoTune;
|
||||
import io.ebean.BackgroundExecutor;
|
||||
import io.ebean.BeanState;
|
||||
import io.ebean.CallableSql;
|
||||
import io.ebean.DocumentStore;
|
||||
import io.ebean.ExpressionFactory;
|
||||
import io.ebean.Filter;
|
||||
import io.ebean.FutureIds;
|
||||
import io.ebean.FutureList;
|
||||
import io.ebean.FutureRowCount;
|
||||
import io.ebean.PagedList;
|
||||
import io.ebean.PersistenceContextScope;
|
||||
import io.ebean.Query;
|
||||
import io.ebean.QueryIterator;
|
||||
import io.ebean.SqlQuery;
|
||||
import io.ebean.SqlRow;
|
||||
import io.ebean.SqlUpdate;
|
||||
import io.ebean.Transaction;
|
||||
import io.ebean.TransactionCallback;
|
||||
import io.ebean.TxCallable;
|
||||
import io.ebean.TxRunnable;
|
||||
import io.ebean.TxScope;
|
||||
import io.ebean.Update;
|
||||
import io.ebean.UpdateQuery;
|
||||
import io.ebean.ValuePair;
|
||||
import io.ebean.Version;
|
||||
import io.ebean.bean.BeanCollection;
|
||||
import io.ebean.bean.CallStack;
|
||||
import io.ebean.bean.EntityBeanIntercept;
|
||||
import io.ebean.bean.ObjectGraphNode;
|
||||
import io.ebean.cache.ServerCacheManager;
|
||||
import io.ebean.config.ServerConfig;
|
||||
import io.ebean.config.dbplatform.DatabasePlatform;
|
||||
import io.ebean.event.readaudit.ReadAuditLogger;
|
||||
import io.ebean.event.readaudit.ReadAuditPrepare;
|
||||
import io.ebean.meta.MetaInfoManager;
|
||||
import io.ebean.plugin.SpiServer;
|
||||
import io.ebean.text.csv.CsvReader;
|
||||
import io.ebean.text.json.JsonContext;
|
||||
import io.ebeaninternal.server.core.timezone.DataTimeZone;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.query.CQuery;
|
||||
import io.ebeaninternal.server.transaction.RemoteTransactionEvent;
|
||||
import io.ebean.TxIsolation;
|
||||
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
|
||||
/**
|
||||
* Test double for SpiEbeanServer.
|
||||
*/
|
||||
public class TDSpiEbeanServer implements SpiEbeanServer {
|
||||
|
||||
String name;
|
||||
|
||||
public TDSpiEbeanServer() {
|
||||
}
|
||||
|
||||
public TDSpiEbeanServer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdownManaged() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object currentTenantId() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataTimeZone getDataTimeZone() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpiServer getPluginApi() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCollectQueryOrigins() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUpdateAllPropertiesInBatch() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerConfig getServerConfig() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatabasePlatform getDatabasePlatform() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CallStack createCallStack() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersistenceContextScope getPersistenceContextScope(SpiQuery<?> query) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DocumentStore docStore() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadAuditLogger getReadAuditLogger() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadAuditPrepare getReadAuditPrepare() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearQueryStatistics() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public BeanDescriptor<?> getBeanDescriptorByQueueId(String queueId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BeanDescriptor<?>> getBeanDescriptors() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> BeanDescriptor<T> getBeanDescriptor(Class<T> type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BeanDescriptor<?> getBeanDescriptorById(String descriptorId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BeanDescriptor<?>> getBeanDescriptors(String tableName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void externalModification(TransactionEventTable event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpiTransaction getCurrentServerTransaction() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScopeTrans createScopeTrans(TxScope txScope) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpiTransaction createQueryTransaction(Object tenantId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remoteTransactionEvent(RemoteTransactionEvent event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> CQuery<T> compileQuery(Query<T> query, Transaction t) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> int delete(Query<T> query, Transaction t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> UpdateQuery<T> update(Class<T> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> int update(Query<T> query, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<Version<T>> findVersions(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A, T> List<A> findIdsWithCopy(Query<T> query, Transaction t) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> int findRowCountWithCopy(Query<T> query, Transaction t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadBean(LoadBeanRequest loadRequest) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadMany(LoadManyRequest loadRequest) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLazyLoadBatchSize() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSupportedType(Type genericType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void collectQueryStats(ObjectGraphNode objectGraphNode, long loadedBeanCount, long timeMicros) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadMany(BeanCollection<?> collection, boolean onlyIds) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadBean(EntityBeanIntercept ebi) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown(boolean shutdownDataSource, boolean deregisterDriver) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public AutoTune getAutoTune() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExpressionFactory getExpressionFactory() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MetaInfoManager getMetaInfoManager() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BeanState getBeanState(Object bean) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object setBeanId(Object bean, Object id) {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getBeanId(Object bean) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, ValuePair> diff(Object a, Object b) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T createEntityBean(Class<T> type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> CsvReader<T> createCsvReader(Class<T> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Query<T> createQuery(Class<T> beanType, String eql) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Query<T> createQuery(Class<T> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Query<T> find(Class<T> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Query<T> findNative(Class<T> beanType, String nativeSql) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Set<String> validateQuery(Query<T> query) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object nextId(Class<?> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Filter<T> filter(Class<T> beanType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void sort(List<T> list, String sortByClause) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Update<T> createUpdate(Class<T> beanType, String ormUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SqlQuery createSqlQuery(String sql) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SqlUpdate createSqlUpdate(String sql) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CallableSql createCallableSql(String callableSql) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(TransactionCallback transactionCallback) throws PersistenceException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T publish(Class<T> beanType, Object id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> publish(Query<T> query) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T publish(Class<T> beanType, Object id, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> publish(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T draftRestore(Class<T> beanType, Object id, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> draftRestore(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T draftRestore(Class<T> beanType, Object id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> draftRestore(Query<T> query) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction createTransaction() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction createTransaction(TxIsolation isolation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction beginTransaction() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction beginTransaction(TxScope scope) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction beginTransaction(TxIsolation isolation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Transaction currentTransaction() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commitTransaction() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rollbackTransaction() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endTransaction() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(Object bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refreshMany(Object bean, String propertyName) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T find(Class<T> beanType, Object uid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getReference(Class<T> beanType, Object id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> int findCount(Query<T> query, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A, T> List<A> findIds(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> QueryIterator<T> findIterate(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void findEach(Query<T> query, Consumer<T> consumer, Transaction transaction) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void findEachWhile(Query<T> query, Predicate<T> consumer, Transaction transaction) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> List<T> findList(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> FutureRowCount<T> findFutureCount(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> FutureIds<T> findFutureIds(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> FutureList<T> findFutureList(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> PagedList<T> findPagedList(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Set<T> findSet(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, T> Map<K, T> findMap(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A, T> List<A> findSingleAttributeList(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T findUnique(Query<T> query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SqlRow> findList(SqlQuery query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void findEach(SqlQuery query, Consumer<SqlRow> consumer, Transaction transaction) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void findEachWhile(SqlQuery query, Predicate<SqlRow> consumer, Transaction transaction) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public SqlRow findUnique(SqlQuery query, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Object bean) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(Object bean) throws OptimisticLockException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(Class<?> beanType, Object id) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(Class<?> beanType, Object id, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deletePermanent(Class<?> beanType, Object id) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deletePermanent(Class<?> beanType, Object id, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(SqlUpdate updSql) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(Update<?> update) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(Update<?> update, Transaction t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(CallableSql callableSql) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void externalModification(String tableName, boolean inserted, boolean updated, boolean deleted) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T find(Class<T> beanType, Object uid, Transaction transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Object bean, Transaction transaction) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markAsDirty(Object bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Object bean) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Object bean, Transaction t) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Object bean, Transaction transaction, boolean deleteMissingChildren) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(Object bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(Object bean, Transaction t) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(Object bean, Transaction t) throws OptimisticLockException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deletePermanent(Object bean) throws OptimisticLockException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deletePermanent(Object bean, Transaction transaction) throws OptimisticLockException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllPermanent(Collection<?> beans) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllPermanent(Collection<?> beans, Transaction transaction) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(SqlUpdate updSql, Transaction t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int execute(CallableSql callableSql, Transaction t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(TxScope scope, TxRunnable r) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(TxRunnable r) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T execute(TxScope scope, TxCallable<T> c) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T execute(TxCallable<T> c) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerCacheManager getServerCacheManager() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackgroundExecutor getBackgroundExecutor() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonContext json() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int saveAll(Collection<?> beans) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAll(Collection<?> beans) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAll(Collection<?> beans, Transaction transaction) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAll(Class<?> beanType, Collection<?> ids) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAll(Class<?> beanType, Collection<?> ids, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllPermanent(Class<?> beanType, Collection<?> ids) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllPermanent(Class<?> beanType, Collection<?> ids, Transaction transaction) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int saveAll(Collection<?> beans, Transaction transaction) throws OptimisticLockException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateAll(Collection<?> beans) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateAll(Collection<?> beans, Transaction transaction) throws OptimisticLockException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertAll(Collection<?> beans) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertAll(Collection<?> beans, Transaction transaction) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.ebeaninternal.extraddl.model;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class ExtraDdlXmlReaderTest {
|
||||
|
||||
@Test
|
||||
public void read() throws Exception {
|
||||
|
||||
ExtraDdl read = ExtraDdlXmlReader.read("/extra-ddl.xml");
|
||||
assertNotNull(read);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildExtra_when_h2() {
|
||||
|
||||
String ddl = ExtraDdlXmlReader.buildExtra("h2");
|
||||
|
||||
assertThat(ddl).contains("create or replace view order_agg_vw");
|
||||
assertThat(ddl).contains("-- h2 and postgres script");
|
||||
assertThat(ddl).doesNotContain(" -- oracle only script");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildExtra_when_oracle() {
|
||||
|
||||
String ddl = ExtraDdlXmlReader.buildExtra("oracle");
|
||||
|
||||
assertThat(ddl).contains("create or replace view order_agg_vw");
|
||||
assertThat(ddl).doesNotContain("-- h2 and postgres script");
|
||||
assertThat(ddl).contains(" -- oracle only script");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildExtra_when_mysql() {
|
||||
|
||||
String ddl = ExtraDdlXmlReader.buildExtra("mysql");
|
||||
|
||||
assertThat(ddl).contains("create or replace view order_agg_vw");
|
||||
assertThat(ddl).doesNotContain("-- h2 and postgres script");
|
||||
assertThat(ddl).doesNotContain(" -- oracle only script");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.ebeaninternal.server.autotune.service;
|
||||
|
||||
import io.ebeaninternal.server.autotune.model.Autotune;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class AutoTuneXmlReaderTest {
|
||||
|
||||
@Test
|
||||
public void read_file() throws Exception {
|
||||
|
||||
File testFile = new File("src/test/resources/autotune/test-autotune.xml");
|
||||
|
||||
Autotune tuneInfo = AutoTuneXmlReader.read(testFile);
|
||||
assertThat(tuneInfo.getOrigin()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void read_inputStream() throws Exception {
|
||||
|
||||
InputStream is = getClass().getResourceAsStream("/autotune/test-autotune.xml");
|
||||
|
||||
Autotune tuneInfo = AutoTuneXmlReader.read(is);
|
||||
assertThat(tuneInfo.getOrigin()).isNotEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package io.ebeaninternal.server.cache;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebean.bean.PersistenceContext;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
|
||||
import io.ebeaninternal.server.transaction.DefaultPersistenceContext;
|
||||
import org.tests.model.basic.Address;
|
||||
import org.tests.model.basic.Country;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.tests.model.basic.Customer.Status;
|
||||
import org.tests.model.embedded.EAddress;
|
||||
import org.tests.model.embedded.EPerson;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CacheBeanDataTest extends BaseTestCase {
|
||||
|
||||
@Test
|
||||
public void extract_load_on_customer() {
|
||||
|
||||
SpiEbeanServer server = spiEbeanServer();
|
||||
BeanDescriptor<Customer> desc = server.getBeanDescriptor(Customer.class);
|
||||
|
||||
Customer c = new Customer();
|
||||
c.setId(98989);
|
||||
c.setName("Rob");
|
||||
c.setCretime(new Timestamp(System.currentTimeMillis()));
|
||||
c.setUpdtime(new Timestamp(System.currentTimeMillis()));
|
||||
c.setStatus(Status.ACTIVE);
|
||||
c.setSmallnote("somenote");
|
||||
|
||||
Address billingAddress = new Address();
|
||||
billingAddress.setId((short) 12);
|
||||
billingAddress.setCity("Auckland");
|
||||
billingAddress.setCountry(server.getReference(Country.class, "NZ"));
|
||||
billingAddress.setLine1("92 Someplace Else");
|
||||
c.setBillingAddress(billingAddress);
|
||||
|
||||
((EntityBean) c)._ebean_getIntercept().setNewBeanForUpdate();
|
||||
|
||||
CachedBeanData cacheData = CachedBeanDataFromBean.extract(desc, (EntityBean) c);
|
||||
|
||||
|
||||
assertNotNull(cacheData);
|
||||
|
||||
Customer newCustomer = new Customer();
|
||||
newCustomer.setId(c.getId());
|
||||
CachedBeanDataToBean.load(desc, (EntityBean) newCustomer, cacheData, new DefaultPersistenceContext());
|
||||
|
||||
assertEquals(c.getId(), newCustomer.getId());
|
||||
assertEquals(c.getName(), newCustomer.getName());
|
||||
assertEquals(c.getStatus(), newCustomer.getStatus());
|
||||
assertEquals(c.getSmallnote(), newCustomer.getSmallnote());
|
||||
assertEquals(c.getCretime(), newCustomer.getCretime());
|
||||
assertEquals(c.getUpdtime(), newCustomer.getUpdtime());
|
||||
assertEquals(c.getBillingAddress().getId(), newCustomer.getBillingAddress().getId());
|
||||
|
||||
assertNotNull(newCustomer.getId());
|
||||
assertNotNull(newCustomer.getName());
|
||||
assertNotNull(newCustomer.getStatus());
|
||||
assertNotNull(newCustomer.getSmallnote());
|
||||
assertNotNull(newCustomer.getCretime());
|
||||
assertNotNull(newCustomer.getUpdtime());
|
||||
assertNotNull(newCustomer.getBillingAddress());
|
||||
assertNotNull(newCustomer.getBillingAddress().getId());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void extract_load_withEmbeddedBean() {
|
||||
|
||||
SpiEbeanServer server = spiEbeanServer();
|
||||
BeanDescriptor<EPerson> desc = server.getBeanDescriptor(EPerson.class);
|
||||
BeanPropertyAssocOne<?> addressBeanProperty = (BeanPropertyAssocOne<?>) desc.getBeanProperty("address");
|
||||
|
||||
EAddress address = new EAddress();
|
||||
address.setStreet("92 Someplace Else");
|
||||
address.setSuburb("Sandringham");
|
||||
address.setCity("Auckland");
|
||||
|
||||
EPerson person = new EPerson();
|
||||
person.setId(98989L);
|
||||
person.setName("Rob");
|
||||
person.setAddress(address);
|
||||
|
||||
CachedBeanData addressCacheData = (CachedBeanData) addressBeanProperty.getCacheDataValue((EntityBean) person);
|
||||
|
||||
PersistenceContext context = new DefaultPersistenceContext();
|
||||
|
||||
EPerson newPersonCheck = new EPerson();
|
||||
newPersonCheck.setId(98989L);
|
||||
addressBeanProperty.setCacheDataValue((EntityBean) newPersonCheck, addressCacheData, context);
|
||||
|
||||
EAddress newAddress = newPersonCheck.getAddress();
|
||||
assertEquals(address.getStreet(), newAddress.getStreet());
|
||||
assertEquals(address.getCity(), newAddress.getCity());
|
||||
assertEquals(address.getSuburb(), newAddress.getSuburb());
|
||||
|
||||
|
||||
CachedBeanData cacheData = desc.cacheEmbeddedBeanExtract((EntityBean) person);
|
||||
|
||||
assertNotNull(cacheData);
|
||||
|
||||
EPerson newPerson = (EPerson) desc.cacheEmbeddedBeanLoad(cacheData, context);
|
||||
|
||||
assertNotNull(newPerson.getId());
|
||||
assertNotNull(newPerson.getName());
|
||||
assertNotNull(newPerson.getAddress());
|
||||
|
||||
assertEquals(person.getId(), newPerson.getId());
|
||||
assertEquals(person.getName(), newPerson.getName());
|
||||
assertEquals(person.getAddress().getStreet(), newPerson.getAddress().getStreet());
|
||||
assertEquals(person.getAddress().getCity(), newPerson.getAddress().getCity());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.ebeaninternal.server.cache;
|
||||
|
||||
import io.ebean.BaseTestCase;
|
||||
import io.ebean.bean.EntityBean;
|
||||
import io.ebeaninternal.api.SpiEbeanServer;
|
||||
import io.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import io.ebeaninternal.server.transaction.DefaultPersistenceContext;
|
||||
import org.tests.model.basic.Address;
|
||||
import org.tests.model.basic.Car;
|
||||
import org.tests.model.basic.Customer;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.Date;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CachedBeanDataFromBeanTest extends BaseTestCase {
|
||||
|
||||
SpiEbeanServer server = spiEbeanServer();
|
||||
|
||||
@Test
|
||||
public void extract() throws Exception {
|
||||
|
||||
BeanDescriptor<Customer> desc = server.getBeanDescriptor(Customer.class);
|
||||
|
||||
Date largeDate = new Date(9223372036825200000L);
|
||||
|
||||
Customer customer = new Customer();
|
||||
customer.setId(42);
|
||||
customer.setName("Rob");
|
||||
customer.setAnniversary(largeDate);
|
||||
|
||||
Address billingAddress = new Address();
|
||||
billingAddress.setId(Short.valueOf("12"));
|
||||
billingAddress.setCity("SomePlace");
|
||||
|
||||
customer.setBillingAddress(billingAddress);
|
||||
|
||||
CachedBeanData cacheData = CachedBeanDataFromBean.extract(desc, (EntityBean) customer);
|
||||
|
||||
assertEquals(cacheData.getData("id"), "42");
|
||||
assertEquals(cacheData.getData("name"), "Rob");
|
||||
assertEquals(cacheData.getData("billingAddress"), "12");
|
||||
assertEquals(cacheData.getData("anniversary"), "9223372036825200000");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void inheritance() {
|
||||
|
||||
Car car = new Car();
|
||||
car.setId(42);
|
||||
car.setDriver("Jimmy");
|
||||
car.setNotes("some notes");
|
||||
|
||||
BeanDescriptor<Car> carDesc = server.getBeanDescriptor(Car.class);
|
||||
CachedBeanData cacheData = CachedBeanDataFromBean.extract(carDesc, (EntityBean) car);
|
||||
|
||||
Car newCar = new Car();
|
||||
EntityBean entityBean = (EntityBean) newCar;
|
||||
CachedBeanDataToBean.load(carDesc, entityBean, cacheData, new DefaultPersistenceContext());
|
||||
|
||||
assertEquals(newCar.getId(), car.getId());
|
||||
assertEquals(newCar.getDriver(), car.getDriver());
|
||||
assertEquals(newCar.getNotes(), car.getNotes());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user