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