diff options
Diffstat (limited to 'spring-jdbc/src/test/java')
16 files changed, 820 insertions, 381 deletions
diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/Customer.java b/spring-jdbc/src/test/java/org/springframework/jdbc/Customer.java index 7c804be1..46b646b0 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/Customer.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/Customer.java @@ -43,6 +43,7 @@ public class Customer { } + @Override public String toString() { return "Customer: id=" + id + "; forename=" + forename; } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java index c789afa3..396418b9 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,68 +42,68 @@ import static org.junit.Assert.*; * @author Dave Syer * @author Juergen Hoeller * @author Chris Beams + * @author Sam Brannen */ public class JdbcNamespaceIntegrationTests { @Rule public ExpectedException expected = ExpectedException.none(); + @Test - public void testCreateEmbeddedDatabase() throws Exception { + public void createEmbeddedDatabase() throws Exception { Assume.group(TestGroup.LONG_RUNNING); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-config.xml"); - assertCorrectSetup(context, "dataSource", "h2DataSource", "derbyDataSource"); - context.close(); + assertCorrectSetup("jdbc-config.xml", "dataSource", "h2DataSource", "derbyDataSource"); } @Test - public void testCreateEmbeddedDatabaseAgain() throws Exception { + public void createEmbeddedDatabaseAgain() throws Exception { // If Derby isn't cleaned up properly this will fail... Assume.group(TestGroup.LONG_RUNNING); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-config.xml"); - assertCorrectSetup(context, "derbyDataSource"); - context.close(); + assertCorrectSetup("jdbc-config.xml", "derbyDataSource"); } @Test - public void testCreateWithResourcePattern() throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-config-pattern.xml"); - assertCorrectSetup(context, "dataSource"); - context.close(); + public void createWithResourcePattern() throws Exception { + assertCorrectSetup("jdbc-config-pattern.xml", "dataSource"); } @Test - public void testCreateWithEndings() throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-initialize-endings-config.xml"); - assertCorrectSetup(context, 2, "dataSource"); - context.close(); + public void createWithEndings() throws Exception { + assertCorrectSetupAndCloseContext("jdbc-initialize-endings-config.xml", 2, "dataSource"); } @Test - public void testCreateWithEndingsNested() throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-initialize-endings-nested-config.xml"); - assertCorrectSetup(context, 2, "dataSource"); - context.close(); + public void createWithEndingsNested() throws Exception { + assertCorrectSetupAndCloseContext("jdbc-initialize-endings-nested-config.xml", 2, "dataSource"); } @Test - public void testCreateAndDestroy() throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-destroy-config.xml"); + public void createAndDestroy() throws Exception { + ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml"); try { DataSource dataSource = context.getBean(DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); - assertEquals(1, template.queryForInt("select count(*) from T_TEST")); + assertNumRowsInTestTable(template, 1); context.getBean(DataSourceInitializer.class).destroy(); expected.expect(BadSqlGrammarException.class); // Table has been dropped - assertEquals(1, template.queryForInt("select count(*) from T_TEST")); + assertNumRowsInTestTable(template, 1); + } + finally { + context.close(); + } + } + + @Test + public void createAndDestroyNestedWithHsql() throws Exception { + ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml"); + try { + DataSource dataSource = context.getBean(DataSource.class); + JdbcTemplate template = new JdbcTemplate(dataSource); + assertNumRowsInTestTable(template, 1); + context.getBean(EmbeddedDatabaseFactoryBean.class).destroy(); + expected.expect(BadSqlGrammarException.class); // Table has been dropped + assertNumRowsInTestTable(template, 1); } finally { context.close(); @@ -111,16 +111,15 @@ public class JdbcNamespaceIntegrationTests { } @Test - public void testCreateAndDestroyNested() throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - "org/springframework/jdbc/config/jdbc-destroy-nested-config.xml"); + public void createAndDestroyNestedWithH2() throws Exception { + ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml"); try { DataSource dataSource = context.getBean(DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); - assertEquals(1, template.queryForInt("select count(*) from T_TEST")); + assertNumRowsInTestTable(template, 1); context.getBean(EmbeddedDatabaseFactoryBean.class).destroy(); expected.expect(BadSqlGrammarException.class); // Table has been dropped - assertEquals(1, template.queryForInt("select count(*) from T_TEST")); + assertNumRowsInTestTable(template, 1); } finally { context.close(); @@ -128,14 +127,18 @@ public class JdbcNamespaceIntegrationTests { } @Test - public void testMultipleDataSourcesHaveDifferentDatabaseNames() throws Exception { + public void multipleDataSourcesHaveDifferentDatabaseNames() throws Exception { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(new ClassPathResource( - "org/springframework/jdbc/config/jdbc-config-multiple-datasources.xml")); + "jdbc-config-multiple-datasources.xml", getClass())); assertBeanPropertyValueOf("databaseName", "firstDataSource", factory); assertBeanPropertyValueOf("databaseName", "secondDataSource", factory); } + private ClassPathXmlApplicationContext context(String file) { + return new ClassPathXmlApplicationContext(file, getClass()); + } + private void assertBeanPropertyValueOf(String propertyName, String expected, DefaultListableBeanFactory factory) { BeanDefinition bean = factory.getBeanDefinition(expected); PropertyValue value = bean.getPropertyValues().getPropertyValue(propertyName); @@ -143,22 +146,26 @@ public class JdbcNamespaceIntegrationTests { assertThat(value.getValue().toString(), is(expected)); } - private void assertCorrectSetup(ConfigurableApplicationContext context, String... dataSources) { - assertCorrectSetup(context, 1, dataSources); + private void assertNumRowsInTestTable(JdbcTemplate template, int count) { + assertEquals(count, template.queryForObject("select count(*) from T_TEST", Integer.class).intValue()); } - private void assertCorrectSetup(ConfigurableApplicationContext context, int count, String... dataSources) { + private void assertCorrectSetup(String file, String... dataSources) { + assertCorrectSetupAndCloseContext(file, 1, dataSources); + } + + private void assertCorrectSetupAndCloseContext(String file, int count, String... dataSources) { + ConfigurableApplicationContext context = context(file); try { for (String dataSourceName : dataSources) { DataSource dataSource = context.getBean(dataSourceName, DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); - assertEquals(count, template.queryForInt("select count(*) from T_TEST")); + assertNumRowsInTestTable(template, count); } } finally { context.close(); } - } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java index ffa2d74d..e8d9e19c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java @@ -16,6 +16,7 @@ package org.springframework.jdbc.core; +import java.sql.BatchUpdateException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -459,6 +460,24 @@ public class JdbcTemplateTests { } @Test + public void testBatchUpdateWithBatchFailure() throws Exception { + final String[] sql = {"A", "B", "C", "D"}; + given(this.statement.executeBatch()).willThrow( + new BatchUpdateException(new int[] { 1, Statement.EXECUTE_FAILED, 1, + Statement.EXECUTE_FAILED })); + mockDatabaseMetaData(true); + given(this.connection.createStatement()).willReturn(this.statement); + + JdbcTemplate template = new JdbcTemplate(this.dataSource, false); + try { + template.batchUpdate(sql); + } + catch (UncategorizedSQLException ex) { + assertThat(ex.getSql(), equalTo("B; D")); + } + } + + @Test public void testBatchUpdateWithNoBatchSupport() throws Exception { final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1", "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 2"}; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java index a44686f3..c31d0809 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java @@ -50,6 +50,7 @@ public class RowMapperTests extends TestCase { private List<TestBean> result; + @Override @Before public void setUp() throws SQLException { connection = mock(Connection.class); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java index d9d6dd15..88f1e510 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java @@ -109,7 +109,7 @@ public class StatementCreatorUtilsTests { @Test public void testSetParameterValueWithNullAndGetParameterTypeWorkingButNotForOtherDriver() throws SQLException { StatementCreatorUtils.driversWithNoSupportForGetParameterType.clear(); - StatementCreatorUtils.driversWithNoSupportForGetParameterType.put("Oracle JDBC Driver", Boolean.TRUE); + StatementCreatorUtils.driversWithNoSupportForGetParameterType.add("Oracle JDBC Driver"); Connection con = mock(Connection.class); DatabaseMetaData dbmd = mock(DatabaseMetaData.class); ParameterMetaData pmd = mock(ParameterMetaData.class); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java index 05295b56..5782fc2e 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.sql.Connection; import javax.sql.DataSource; -import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.*; @@ -34,17 +33,11 @@ import static org.mockito.BDDMockito.*; * * @author Phillip Webb */ -public class DelegatingDataSourceTest { +public class DelegatingDataSourceTests { - private DataSource delegate; + private final DataSource delegate = mock(DataSource.class); - private DelegatingDataSource dataSource; - - @Before - public void setup() { - this.delegate = mock(DataSource.class); - this.dataSource = new DelegatingDataSource(delegate); - } + private DelegatingDataSource dataSource = new DelegatingDataSource(delegate); @Test public void shouldDelegateGetConnection() throws Exception { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java index 8ad40961..f3a43be8 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,65 +18,150 @@ package org.springframework.jdbc.datasource.embedded; import org.junit.Test; import org.springframework.core.io.ClassRelativeResourceLoader; -import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.CannotReadScriptException; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; import static org.junit.Assert.*; +import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.*; /** + * Integration tests for {@link EmbeddedDatabaseBuilder}. + * * @author Keith Donald + * @author Sam Brannen */ public class EmbeddedDatabaseBuilderTests { + private final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader( + getClass())); + + + @Test + public void addDefaultScripts() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = new EmbeddedDatabaseBuilder()// + .addDefaultScripts()// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); + } + + @Test(expected = CannotReadScriptException.class) + public void addScriptWithBogusFileName() { + new EmbeddedDatabaseBuilder().addScript("bogus.sql").build(); + } + + @Test + public void addScript() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .addScript("db-schema.sql")// + .addScript("db-test-data.sql")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); + } + @Test - public void testBuildDefaultScripts() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.addDefaultScripts().build(); - assertDatabaseCreatedAndShutdown(db); + public void addScripts() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .addScripts("db-schema.sql", "db-test-data.sql")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); } @Test - public void testBuild() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())); - EmbeddedDatabase db = builder.addScript("db-schema.sql").addScript("db-test-data.sql").build(); - assertDatabaseCreatedAndShutdown(db); + public void addScriptsWithDefaultCommentPrefix() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .addScripts("db-schema-comments.sql", "db-test-data.sql")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); } @Test - public void testBuildWithComments() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())); - EmbeddedDatabase db = builder.addScript("db-schema-comments.sql").addScript("db-test-data.sql").build(); - assertDatabaseCreatedAndShutdown(db); + public void addScriptsWithCustomCommentPrefix() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .addScripts("db-schema-custom-comments.sql", "db-test-data.sql")// + .setCommentPrefix("~")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); } @Test - public void testBuildH2() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("db-schema.sql").addScript("db-test-data.sql").build(); - assertDatabaseCreatedAndShutdown(db); + public void addScriptsWithCustomBlockComments() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .addScripts("db-schema-block-comments.sql", "db-test-data.sql")// + .setBlockCommentStartDelimiter("{*")// + .setBlockCommentEndDelimiter("*}")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); } @Test - public void testBuildDerby() { - Assume.group(TestGroup.LONG_RUNNING); + public void setTypeToH2() throws Exception { + doTwice(new Runnable() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass())); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.DERBY).addScript("db-schema-derby.sql").addScript("db-test-data.sql").build(); - assertDatabaseCreatedAndShutdown(db); + @Override + public void run() { + EmbeddedDatabase db = builder// + .setType(H2)// + .addScripts("db-schema.sql", "db-test-data.sql")// + .build(); + assertDatabaseCreatedAndShutdown(db); + } + }); } @Test - public void testBuildNoSuchScript() { - try { - new EmbeddedDatabaseBuilder().addScript("bogus.sql").build(); - fail("Should have failed"); - } - catch (DataAccessResourceFailureException ex) { - assertTrue(ex.getCause() instanceof CannotReadScriptException); - } + public void setTypeToDerbyAndIgnoreFailedDrops() throws Exception { + doTwice(new Runnable() { + + @Override + public void run() { + EmbeddedDatabase db = builder// + .setType(DERBY)// + .ignoreFailedDrops(true)// + .addScripts("db-schema-derby-with-drop.sql", "db-test-data.sql").build(); + assertDatabaseCreatedAndShutdown(db); + } + }); + } + + private void doTwice(Runnable test) { + test.run(); + test.run(); } private void assertDatabaseCreatedAndShutdown(EmbeddedDatabase db) { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java index 1ad8cbd8..8d9bf392 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java @@ -1,25 +1,48 @@ -package org.springframework.jdbc.datasource.embedded; +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import static org.junit.Assert.assertEquals; +package org.springframework.jdbc.datasource.embedded; import javax.sql.DataSource; import org.junit.Test; -import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.ClassRelativeResourceLoader; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +import static org.junit.Assert.*; + +/** + * @author Keith Donald + */ public class EmbeddedDatabaseFactoryBeanTests { + private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass()); + + + Resource resource(String path) { + return resourceLoader.getResource(path); + } + @Test public void testFactoryBeanLifecycle() throws Exception { EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean(); - ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); - populator.setScripts(new Resource[] { - new ClassPathResource("db-schema.sql", getClass()), - new ClassPathResource("db-test-data.sql", getClass()) - }); + ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"), + resource("db-test-data.sql")); bean.setDatabasePopulator(populator); bean.afterPropertiesSet(); DataSource ds = bean.getObject(); @@ -27,4 +50,5 @@ public class EmbeddedDatabaseFactoryBeanTests { assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class)); bean.destroy(); } + } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java index 77970dbe..ed585d50 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java @@ -1,16 +1,37 @@ -package org.springframework.jdbc.datasource.embedded; +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import static org.junit.Assert.assertTrue; +package org.springframework.jdbc.datasource.embedded; import java.sql.Connection; import org.junit.Test; + import org.springframework.jdbc.datasource.init.DatabasePopulator; +import static org.junit.Assert.*; + +/** + * @author Keith Donald + */ public class EmbeddedDatabaseFactoryTests { private EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory(); + @Test public void testGetDataSource() { StubDatabasePopulator populator = new StubDatabasePopulator(); @@ -20,6 +41,7 @@ public class EmbeddedDatabaseFactoryTests { db.shutdown(); } + private static class StubDatabasePopulator implements DatabasePopulator { private boolean populateCalled; @@ -28,6 +50,6 @@ public class EmbeddedDatabaseFactoryTests { public void populate(Connection connection) { this.populateCalled = true; } - } + } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java new file mode 100644 index 00000000..5be6e26d --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabaseInitializationTests.java @@ -0,0 +1,84 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import org.junit.After; +import org.junit.Before; +import org.springframework.core.io.ClassRelativeResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +/** + * Abstract base class for integration tests involving database initialization. + * + * @author Sam Brannen + * @since 4.0.3 + */ +public abstract class AbstractDatabaseInitializationTests { + + private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass()); + + EmbeddedDatabase db; + + JdbcTemplate jdbcTemplate; + + + @Before + public void setUp() { + db = new EmbeddedDatabaseBuilder().setType(getEmbeddedDatabaseType()).build(); + jdbcTemplate = new JdbcTemplate(db); + } + + @After + public void shutDown() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.unbindResource(db); + } + db.shutdown(); + } + + abstract EmbeddedDatabaseType getEmbeddedDatabaseType(); + + Resource resource(String path) { + return resourceLoader.getResource(path); + } + + Resource defaultSchema() { + return resource("db-schema.sql"); + } + + Resource usersSchema() { + return resource("users-schema.sql"); + } + + void assertUsersDatabaseCreated(String... lastNames) { + for (String lastName : lastNames) { + assertThat("Did not find user with last name [" + lastName + "].", + jdbcTemplate.queryForObject("select count(0) from users where last_name = ?", Integer.class, lastName), + equalTo(1)); + } + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java new file mode 100644 index 00000000..82d8acfe --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java @@ -0,0 +1,202 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import java.sql.Connection; +import java.sql.SQLException; + +import org.junit.Test; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +/** + * Abstract base class for integration tests for {@link ResourceDatabasePopulator} + * and {@link DatabasePopulatorUtils}. + * + * @author Dave Syer + * @author Sam Brannen + * @author Oliver Gierke + */ +public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseInitializationTests { + + private final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); + + + @Test + public void buildWithCommentsAndFailedDrop() throws Exception { + databasePopulator.addScript(resource("db-schema-failed-drop-comments.sql")); + databasePopulator.addScript(resource("db-test-data.sql")); + databasePopulator.setIgnoreFailedDrops(true); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertTestDatabaseCreated(); + } + + @Test + public void buildWithNormalEscapedLiteral() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-escaped-literal.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertTestDatabaseCreated("'Keith'"); + } + + @Test + public void buildWithMySQLEscapedLiteral() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-mysql-escaped-literal.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertTestDatabaseCreated("\\$Keith\\$"); + } + + @Test + public void buildWithMultipleStatements() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-multiple.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + @Test + public void buildWithMultipleStatementsLongSeparator() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-endings.sql")); + databasePopulator.setSeparator("@@"); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + @Test + public void buildWithMultipleStatementsWhitespaceSeparator() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-whitespace.sql")); + databasePopulator.setSeparator("/\n"); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + @Test + public void buildWithMultipleStatementsNewlineSeparator() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-newline.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + @Test + public void buildWithMultipleStatementsMultipleNewlineSeparator() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-multi-newline.sql")); + databasePopulator.setSeparator("\n\n"); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + @Test + public void scriptWithEolBetweenTokens() throws Exception { + databasePopulator.addScript(usersSchema()); + databasePopulator.addScript(resource("users-data.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertUsersDatabaseCreated("Brannen"); + } + + @Test + public void scriptWithCommentsWithinStatements() throws Exception { + databasePopulator.addScript(usersSchema()); + databasePopulator.addScript(resource("users-data-with-comments.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertUsersDatabaseCreated("Brannen", "Hoeller"); + } + + @Test + public void scriptWithoutStatementSeparator() throws Exception { + databasePopulator.setSeparator(ScriptUtils.EOF_STATEMENT_SEPARATOR); + databasePopulator.addScript(resource("drop-users-schema.sql")); + databasePopulator.addScript(resource("users-schema-without-separator.sql")); + databasePopulator.addScript(resource("users-data.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + + assertUsersDatabaseCreated("Brannen"); + } + + @Test + public void constructorWithMultipleScriptResources() throws Exception { + final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(usersSchema(), + resource("users-data-with-comments.sql")); + DatabasePopulatorUtils.execute(populator, db); + assertUsersDatabaseCreated("Brannen", "Hoeller"); + } + + @Test + public void buildWithSelectStatements() throws Exception { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-select.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Keith'", Integer.class), + equalTo(1)); + assertThat(jdbcTemplate.queryForObject("select COUNT(NAME) from T_TEST where NAME='Dave'", Integer.class), + equalTo(1)); + } + + /** + * See SPR-9457 + */ + @Test + public void usesBoundConnectionIfAvailable() throws SQLException { + TransactionSynchronizationManager.initSynchronization(); + Connection connection = DataSourceUtils.getConnection(db); + DatabasePopulator populator = mock(DatabasePopulator.class); + DatabasePopulatorUtils.execute(populator, db); + verify(populator).populate(connection); + } + + /** + * See SPR-9781 + */ + @Test(timeout = 1000) + public void executesHugeScriptInReasonableTime() throws SQLException { + databasePopulator.addScript(defaultSchema()); + databasePopulator.addScript(resource("db-test-data-huge.sql")); + DatabasePopulatorUtils.execute(databasePopulator, db); + } + + private void assertTestDatabaseCreated() { + assertTestDatabaseCreated("Keith"); + } + + private void assertTestDatabaseCreated(String name) { + assertEquals(name, jdbcTemplate.queryForObject("select NAME from T_TEST", String.class)); + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java deleted file mode 100644 index 64f09cc7..00000000 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.jdbc.datasource.init; - -import java.sql.Connection; -import java.sql.SQLException; - -import org.junit.After; -import org.junit.Test; -import org.springframework.core.io.ClassRelativeResourceLoader; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceUtils; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.*; - -/** - * @author Dave Syer - * @author Sam Brannen - * @author Oliver Gierke - */ -public class DatabasePopulatorTests { - - private final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - - private final EmbeddedDatabase db = builder.build(); - - private final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - - private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass()); - - private final JdbcTemplate jdbcTemplate = new JdbcTemplate(db); - - - private void assertTestDatabaseCreated() { - assertTestDatabaseCreated("Keith"); - } - - private void assertTestDatabaseCreated(String name) { - assertEquals(name, jdbcTemplate.queryForObject("select NAME from T_TEST", String.class)); - } - - private void assertUsersDatabaseCreated(String... lastNames) { - for (String lastName : lastNames) { - assertEquals("Did not find user with last name [" + lastName + "].", 1, - jdbcTemplate.queryForInt("select count(0) from users where last_name = ?", lastName)); - } - } - - @After - public void shutDown() { - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clear(); - TransactionSynchronizationManager.unbindResource(db); - } - db.shutdown(); - } - - @Test - public void testBuildWithCommentsAndFailedDrop() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema-failed-drop-comments.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data.sql")); - databasePopulator.setIgnoreFailedDrops(true); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertTestDatabaseCreated(); - } - - @Test - public void testBuildWithNormalEscapedLiteral() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-escaped-literal.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertTestDatabaseCreated("'Keith'"); - } - - @Test - public void testBuildWithMySQLEscapedLiteral() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-mysql-escaped-literal.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertTestDatabaseCreated("\\$Keith\\$"); - } - - @Test - public void testBuildWithMultipleStatements() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-multiple.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - @Test - public void testBuildWithMultipleStatementsLongSeparator() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-endings.sql")); - databasePopulator.setSeparator("@@"); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - @Test - public void testBuildWithMultipleStatementsWhitespaceSeparator() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-whitespace.sql")); - databasePopulator.setSeparator("/\n"); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - @Test - public void testBuildWithMultipleStatementsNewlineSeparator() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-newline.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - @Test - public void testBuildWithMultipleStatementsMultipleNewlineSeparator() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-multi-newline.sql")); - databasePopulator.setSeparator("\n\n"); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - @Test - public void scriptWithEolBetweenTokens() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("users-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("users-data.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertUsersDatabaseCreated("Brannen"); - } - - @Test - public void scriptWithCommentsWithinStatements() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("users-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("users-data-with-comments.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertUsersDatabaseCreated("Brannen", "Hoeller"); - } - - @Test - public void testBuildWithSelectStatements() throws Exception { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-select.sql")); - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'")); - assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'")); - } - - /** - * See SPR-9457 - */ - @Test - public void usesBoundConnectionIfAvailable() throws SQLException { - TransactionSynchronizationManager.initSynchronization(); - Connection connection = DataSourceUtils.getConnection(db); - DatabasePopulator populator = mock(DatabasePopulator.class); - DatabasePopulatorUtils.execute(populator, db); - verify(populator).populate(connection); - } - - /** - * See SPR-9781 - */ - @Test(timeout = 1000) - public void executesHugeScriptInReasonableTime() throws SQLException { - databasePopulator.addScript(resourceLoader.getResource("db-schema.sql")); - databasePopulator.addScript(resourceLoader.getResource("db-test-data-huge.sql")); - - Connection connection = db.getConnection(); - try { - databasePopulator.populate(connection); - } - finally { - connection.close(); - } - } - -} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java new file mode 100644 index 00000000..699ea75b --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/H2DatabasePopulatorTests.java @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +/** + * @author Sam Brannen + * @since 4.0.3 + */ +public class H2DatabasePopulatorTests extends AbstractDatabasePopulatorTests { + + protected EmbeddedDatabaseType getEmbeddedDatabaseType() { + return EmbeddedDatabaseType.H2; + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/HsqlDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/HsqlDatabasePopulatorTests.java new file mode 100644 index 00000000..9ab79b60 --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/HsqlDatabasePopulatorTests.java @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +/** + * @author Sam Brannen + * @since 4.0.3 + */ +public class HsqlDatabasePopulatorTests extends AbstractDatabasePopulatorTests { + + protected EmbeddedDatabaseType getEmbeddedDatabaseType() { + return EmbeddedDatabaseType.HSQL; + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsIntegrationTests.java new file mode 100644 index 00000000..76f03a93 --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsIntegrationTests.java @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import java.sql.SQLException; + +import org.junit.Test; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +import static org.springframework.jdbc.datasource.init.ScriptUtils.*; + +/** + * Integration tests for {@link ScriptUtils}. + * + * @author Sam Brannen + * @see ScriptUtilsUnitTests + * @since 4.0.3 + */ +public class ScriptUtilsIntegrationTests extends AbstractDatabaseInitializationTests { + + protected EmbeddedDatabaseType getEmbeddedDatabaseType() { + return EmbeddedDatabaseType.HSQL; + } + + @Test + public void executeSqlScriptContainingMuliLineComments() throws SQLException { + executeSqlScript(db.getConnection(), usersSchema()); + executeSqlScript(db.getConnection(), resource("test-data-with-multi-line-comments.sql")); + + assertUsersDatabaseCreated("Hoeller", "Brannen"); + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java new file mode 100644 index 00000000..6df2eb17 --- /dev/null +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java @@ -0,0 +1,172 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.datasource.init; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.support.EncodedResource; + +import static org.junit.Assert.*; +import static org.springframework.jdbc.datasource.init.ScriptUtils.*; + +/** + * Unit tests for {@link ScriptUtils}. + * + * @author Thomas Risberg + * @author Sam Brannen + * @author Phillip Webb + * @author Chris Baldwin + * @see ScriptUtilsIntegrationTests + * @since 4.0.3 + */ +public class ScriptUtilsUnitTests { + + @Test + public void splitSqlScriptDelimitedWithSemicolon() { + String rawStatement1 = "insert into customer (id, name)\nvalues (1, 'Rod ; Johnson'), (2, 'Adrian \n Collier')"; + String cleanedStatement1 = "insert into customer (id, name) values (1, 'Rod ; Johnson'), (2, 'Adrian \n Collier')"; + String rawStatement2 = "insert into orders(id, order_date, customer_id)\nvalues (1, '2008-01-02', 2)"; + String cleanedStatement2 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + String rawStatement3 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + String cleanedStatement3 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + char delim = ';'; + String script = rawStatement1 + delim + rawStatement2 + delim + rawStatement3 + delim; + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, delim, statements); + assertEquals("wrong number of statements", 3, statements.size()); + assertEquals("statement 1 not split correctly", cleanedStatement1, statements.get(0)); + assertEquals("statement 2 not split correctly", cleanedStatement2, statements.get(1)); + assertEquals("statement 3 not split correctly", cleanedStatement3, statements.get(2)); + } + + @Test + public void splitSqlScriptDelimitedWithNewLine() { + String statement1 = "insert into customer (id, name) values (1, 'Rod ; Johnson'), (2, 'Adrian \n Collier')"; + String statement2 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + String statement3 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + char delim = '\n'; + String script = statement1 + delim + statement2 + delim + statement3 + delim; + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, delim, statements); + assertEquals("wrong number of statements", 3, statements.size()); + assertEquals("statement 1 not split correctly", statement1, statements.get(0)); + assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertEquals("statement 3 not split correctly", statement3, statements.get(2)); + } + + @Test + public void splitSqlScriptDelimitedWithNewLineButDefaultDelimiterSpecified() { + String statement1 = "do something"; + String statement2 = "do something else"; + char delim = '\n'; + String script = statement1 + delim + statement2 + delim; + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, DEFAULT_STATEMENT_SEPARATOR, statements); + assertEquals("wrong number of statements", 1, statements.size()); + assertEquals("script should have been 'stripped' but not actually 'split'", script.replace('\n', ' '), + statements.get(0)); + } + + /** + * See <a href="https://jira.spring.io/browse/SPR-11560">SPR-11560</a> + */ + @Test + public void readAndSplitScriptWithMultipleNewlinesAsSeparator() throws Exception { + String script = readScript("db-test-data-multi-newline.sql"); + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, "\n\n", statements); + + String statement1 = "insert into T_TEST (NAME) values ('Keith')"; + String statement2 = "insert into T_TEST (NAME) values ('Dave')"; + + assertEquals("wrong number of statements", 2, statements.size()); + assertEquals("statement 1 not split correctly", statement1, statements.get(0)); + assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + } + + @Test + public void readAndSplitScriptContainingComments() throws Exception { + String script = readScript("test-data-with-comments.sql"); + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, ';', statements); + + String statement1 = "insert into customer (id, name) values (1, 'Rod; Johnson'), (2, 'Adrian Collier')"; + String statement2 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + String statement3 = "insert into orders(id, order_date, customer_id) values (1, '2008-01-02', 2)"; + // Statement 4 addresses the error described in SPR-9982. + String statement4 = "INSERT INTO persons( person_id , name) VALUES( 1 , 'Name' )"; + + assertEquals("wrong number of statements", 4, statements.size()); + assertEquals("statement 1 not split correctly", statement1, statements.get(0)); + assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertEquals("statement 3 not split correctly", statement3, statements.get(2)); + assertEquals("statement 4 not split correctly", statement4, statements.get(3)); + } + + /** + * See <a href="https://jira.spring.io/browse/SPR-10330">SPR-10330</a> + */ + @Test + public void readAndSplitScriptContainingCommentsWithLeadingTabs() throws Exception { + String script = readScript("test-data-with-comments-and-leading-tabs.sql"); + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, ';', statements); + + String statement1 = "insert into customer (id, name) values (1, 'Sam Brannen')"; + String statement2 = "insert into orders(id, order_date, customer_id) values (1, '2013-06-08', 1)"; + String statement3 = "insert into orders(id, order_date, customer_id) values (2, '2013-06-08', 1)"; + + assertEquals("wrong number of statements", 3, statements.size()); + assertEquals("statement 1 not split correctly", statement1, statements.get(0)); + assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertEquals("statement 3 not split correctly", statement3, statements.get(2)); + } + + /** + * See <a href="https://jira.spring.io/browse/SPR-9531">SPR-9531</a> + */ + @Test + public void readAndSplitScriptContainingMuliLineComments() throws Exception { + String script = readScript("test-data-with-multi-line-comments.sql"); + List<String> statements = new ArrayList<String>(); + splitSqlScript(script, ';', statements); + + String statement1 = "INSERT INTO users(first_name, last_name) VALUES('Juergen', 'Hoeller')"; + String statement2 = "INSERT INTO users(first_name, last_name) VALUES( 'Sam' , 'Brannen' )"; + + assertEquals("wrong number of statements", 2, statements.size()); + assertEquals("statement 1 not split correctly", statement1, statements.get(0)); + assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + } + + @Test + public void containsDelimiters() { + assertTrue("test with ';' is wrong", !containsSqlScriptDelimiters("select 1\n select ';'", ";")); + assertTrue("test with delimiter ; is wrong", containsSqlScriptDelimiters("select 1; select 2", ";")); + assertTrue("test with '\\n' is wrong", !containsSqlScriptDelimiters("select 1; select '\\n\n';", "\n")); + assertTrue("test with delimiter \\n is wrong", containsSqlScriptDelimiters("select 1\n select 2", "\n")); + } + + private String readScript(String path) throws Exception { + EncodedResource resource = new EncodedResource(new ClassPathResource(path, getClass())); + return ScriptUtils.readScript(resource); + } + +} |