001package io.ebean.docker.commands;
002
003import io.ebean.docker.container.Container;
004import org.slf4j.Logger;
005import org.slf4j.LoggerFactory;
006
007/**
008 * Common DB Container.
009 */
010public abstract class BaseDbContainer extends DbContainer implements Container {
011
012  protected static final Logger log = LoggerFactory.getLogger(Commands.class);
013
014  BaseDbContainer(DbConfig config) {
015    super(config);
016  }
017
018  /**
019   * Create the database, schema and user via docker commands.
020   */
021  protected abstract void createDbPreConnectivity();
022
023  /**
024   * Drop and create the database, schema and user via docker commands.
025   */
026  protected abstract void dropCreateDbPreConnectivity();
027
028  /**
029   * Create database, schema and user via JDBC .
030   */
031  protected void createDbPostConnectivity() {
032    // do nothing by default
033  }
034
035  /**
036   * Drop and create database, schema and user via JDBC .
037   */
038  protected void dropCreateDbPostConnectivity() {
039    // do nothing by default
040  }
041
042  /**
043   * Start the container and wait for it to be ready.
044   * <p>
045   * This checks if the container is already running.
046   * </p>
047   * <p>
048   * Returns false if the wait for ready was unsuccessful.
049   * </p>
050   */
051  @Override
052  public boolean startWithCreate() {
053    if (startIfNeeded() && fastStart()) {
054      // container was running, fast start enabled and passed
055      // so skip the usual checks for user, extensions and connectivity
056      createDbPostConnectivity();
057      return true;
058    }
059    if (!waitForDatabaseReady()) {
060      log.warn("Failed waitForDatabaseReady for container {}", config.containerName());
061      return false;
062    }
063    createDbPreConnectivity();
064    if (!waitForConnectivity()) {
065      log.warn("Failed waiting for connectivity");
066      return false;
067    }
068    createDbPostConnectivity();
069    return true;
070  }
071
072  /**
073   * Start with a drop and create of the database and user.
074   */
075  @Override
076  public boolean startWithDropCreate() {
077    startIfNeeded();
078    if (!waitForDatabaseReady()) {
079      log.warn("Failed waitForDatabaseReady for container {}", config.containerName());
080      return false;
081    }
082
083    dropCreateDbPreConnectivity();
084    if (!waitForConnectivity()) {
085      log.warn("Failed waiting for connectivity");
086      return false;
087    }
088    dropCreateDbPostConnectivity();
089    return true;
090  }
091
092}