我在src/main/resources/
下的schema.sql
中有下面的一块SQL DDL
。
ALTER TABLE `user` ADD INDEX IF NOT EXISTS `user_id_index`(user_name(30));
现在测试用例失败了,因为它试图在测试数据库配置中不存在给定表的测试执行中创建索引。
下面是我的测试数据库配置。
public DataSource dataSource() {
DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder();
config.setPort(0);
DB db = newEmbeddedDB(config.build());
db.start();
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(config.getURL("unit-test"));
return new HikariDataSource(hikariConfig) {
@PreDestroy
@SneakyThrows
public void shutdown() {
db.stop();
}
};
}
测试失败:
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file: xyz/target/classes/schema.sql]: ALTER TABLE `user` ADD INDEX IF NOT EXISTS `user_id_index`(user_name(30)); nested exception is java.sql.SQLSyntaxErrorException: Table 'unit-test.user' doesn't exist
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:622)
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254)
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:49)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:202)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.createSchema(DataSourceInitializer.java:101)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker.afterPropertiesSet(DataSourceInitializerInvoker.java:63)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1847)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1784)
... 101 common frames omitted
Caused by: java.sql.SQLSyntaxErrorException: Table 'unit-test.user' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
如何在测试执行中跳过正在执行的schema.sql
?或者有其他的尝试方式吗?
目前,在创建索引之前添加了一个表创建语句来修复测试失败。
CREATE TABLE IF NOT EXISTS `user` (
`id` varchar(255) NOT NULL,
`user_name` text DEFAULT NULL,
PRIMARY KEY (`id`)
)