yazabara
yazabara

Reputation: 1353

Spring Boot Application: how to create shema using flyway on startup?

There is spring boot application. Here is configuration:

spring
  flyway:
    locations: classpath:db/migration
    baseline-on-migrate: true
    schemas: ${app.db.schema}
    placeholders:
      schema: ${app.db.schema}
    init-sqls: CREATE SCHEMA IF NOT EXISTS ${app.db.schema}

And it doesn't work.

I need to create db schema before flyway will run migrations.

Upvotes: 2

Views: 11203

Answers (2)

yazabara
yazabara

Reputation: 1353

There is documentation link: https://flywaydb.org/documentation/commandline/migrate#schemas

Actually FlyWay is responsible for creating schemas if they don't exist.

Here is an example in changelog-history table:

enter image description here

Upvotes: 1

V. Mokrecov
V. Mokrecov

Reputation: 1094

Flyway tries to read database migration scripts from classpath:db/migration folder by default.

All the migration scripts must follow a particular naming convention - V<VERSION_NUMBER>__<NAME>.sql.

Create a new file named V1__Create_Tables.sql inside src/main/resources/db/migration directory and add the sql script, for example:

-- ----------------------------
-- Schema for helloservice
-- ----------------------------
CREATE SCHEMA IF NOT EXISTS helloworld;
-- ----------------------------
-- Table structure for user
-- ----------------------------
CREATE TABLE helloworld.users (
  id                  BIGSERIAL        PRIMARY KEY NOT NULL UNIQUE,
  username            VARCHAR(255)     UNIQUE NOT NULL,
  password            VARCHAR(255)     NOT NULL,
  first_name          VARCHAR(255),
  middle_name         VARCHAR(255),
  last_name           VARCHAR(255),
  email               VARCHAR(255),
  enabled             bool             NOT NULL DEFAULT true,
  account_locked      bool             NOT NULL,
  account_expired     bool             NOT NULL,
  credential_expired  bool             NOT NULL,
  created_on timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_on timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
COMMENT ON TABLE helloworld.users IS 'User table';

When you run the application, flyway will automatically check the current database version and apply any pending migrations. By default, no additional properties are required. You can also create a schema in this script. Or flyway will do it for you if you specify a non-existent scheme.

If you are using hibernate, check this property:

spring.jpa.hibernate.ddl-auto=validate

For more information, see the instructions.

Upvotes: 1

Related Questions