使用 Flyway 迁移的 Micronaut 项目上的 H2 数据库测试失败 运行

Tests fail to run with H2 database on Micronaut project with Flyway migrations

我在 Micronaut 2.0.3 项目中有一个单元测试套件,它应该 运行 在 H2 数据库上。自从我开始使用 Flyway 进行数据库迁移后,我收到一个错误,来自 H2 无法 运行 迁移。

错误是

Bean definition [javax.sql.DataSource] could not be loaded: Migration V1__schema.sql failed
-------------------------------
SQL State  : 42001
Error Code : 42001
Message    : Syntax error in SQL statement "CREATE DATABASE[*] IF NOT EXISTS MY_DB"; expected "OR, FORCE, VIEW, ALIAS, SEQUENCE, USER, TRIGGER, ROLE, SCHEMA, CONSTANT, DOMAIN, TYPE, DATATYPE, AGGREGATE, LINKED, MEMORY, CACHED, LOCAL, GLOBAL, TEMP, TEMPORARY, TABLE, SYNONYM, PRIMARY, UNIQUE, HASH, SPATIAL, INDEX"; SQL statement:
CREATE DATABASE if not exists my_db [42001-200]
Location   : db/migration/V1__schema.sql (/somelocation/build/resources/main/db/migration/V1__schema.sql)
Line       : 1
Statement  : CREATE DATABASE if not exists my_db

io.micronaut.context.exceptions.BeanInstantiationException: Bean definition [javax.sql.DataSource] could not be loaded: Migration V1__schema.sql failed
-------------------------------

我的 application.yml 配置为指向 Azure 中的 MariaDB 实例,如下所示:

micronaut:
  application:
    name: myapp
  server:
    context-path: /myapp/api
    cors:
      enabled: true

endpoints:
  all:
    enabled: true
    sensitive: false

datasources:
  default:
    url: jdbc:mariadb://${ENV_DB_HOST_PORT:myurl.mariadb.database.azure.com}:${ENV_DB_PORT:3306}/${ENV_DB_SCHEMA:my_db}?useSSL=${ENV_DB_USE_SSL:true}&useUnicode=true&serverTimezone=Europe/London&autoReconnect=true
    driverClassName: org.mariadb.jdbc.Driver
    username: myusername
    password: mypassword
    dialect: MYSQL
    allow-pool-suspension: false
    connection-test-query: SELECT 1
    connection-timeout: 30000
    max-lifetime: 60000
    maximum-pool-size: 10
    minimum-idle: 1

flyway:
  datasources:
    default:
      enabled: true

但是我的应用程序-test.yml 指向 H2 数据库以进行测试:

datasources:
  default:
    url: jdbc:h2:mem:devDb;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    driverClassName: org.h2.Driver
    username: sa
    password: ''

jpa:
  default:
    properties:
      hibernate:
        hbm2ddl:
          auto: update

我的迁移文件 V1__schema.sql 如下所示:

CREATE DATABASE if not exists my_db;
use my_db;

DROP TABLE IF EXISTS `preset`;
CREATE TABLE `preset` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `preset_name` varchar(30) NOT NULL,
    `preset_value` varchar(4000) DEFAULT NULL,
    PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `note`;
CREATE TABLE `note` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `code` varchar(30) NOT NULL,
    `text` varchar(4000) DEFAULT NULL,
    PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这个错误很容易解释

Message    : Syntax error in SQL statement "CREATE DATABASE[*] IF NOT EXISTS MY_DB";

CREATE DATABASE if not exists my_db;

根据 H2 commandsCREATE DATABASE 不是 H2 的有效命令。您可能需要命令 CREATE SCHEMA if not exists my_db;