001package io.ebean.migration.runner;
002
003import io.ebean.migration.MigrationConfig;
004import org.slf4j.Logger;
005import org.slf4j.LoggerFactory;
006
007import java.sql.Connection;
008import java.sql.ResultSet;
009import java.sql.SQLException;
010import java.sql.Statement;
011
012/**
013 * Create Schema if needed and set current Schema in Migration
014 */
015public class MigrationSchema {
016
017  private static final Logger logger = LoggerFactory.getLogger(MigrationSchema.class);
018
019  private final Connection connection;
020
021  private final String dbSchema;
022
023  private final boolean createSchemaIfNotExists;
024
025  private final boolean setCurrentSchema;
026
027  /**
028   * Construct with configuration and connection.
029   */
030  public MigrationSchema(MigrationConfig migrationConfig, Connection connection) {
031    this.dbSchema = trim(migrationConfig.getDbSchema());
032    this.createSchemaIfNotExists = migrationConfig.isCreateSchemaIfNotExists();
033    this.setCurrentSchema = migrationConfig.isSetCurrentSchema();
034    this.connection = connection;
035  }
036
037  private String trim(String dbSchema) {
038    return (dbSchema == null) ? null : dbSchema.trim();
039  }
040
041  /**
042   * Create and set the DB schema if desired.
043   */
044  public void createAndSetIfNeeded() throws SQLException {
045    if (dbSchema != null) {
046      logger.info("Migration Schema: {}", dbSchema);
047      if (createSchemaIfNotExists) {
048        createSchemaIfNeeded();
049      }
050      if (setCurrentSchema) {
051        setSchema();
052      }
053    }
054  }
055
056  private void createSchemaIfNeeded() throws SQLException {
057    if (!schemaExists()) {
058      logger.info("Creating Schema: {}", dbSchema);
059      try (Statement query = connection.createStatement()) {
060        query.executeUpdate("CREATE SCHEMA " + dbSchema);
061      }
062    }
063  }
064
065  private boolean schemaExists() throws SQLException {
066
067    try (ResultSet schemas = connection.getMetaData().getSchemas()) {
068      while (schemas.next()) {
069        String schema = schemas.getString(1);
070        if (schema.equalsIgnoreCase(dbSchema)) {
071          return true;
072        }
073      }
074    }
075    return false;
076  }
077
078  private void setSchema() throws SQLException {
079
080    logger.info("Setting Schema: {}", dbSchema);
081    connection.setSchema(dbSchema);
082  }
083
084}