Java Code Examples for org.testcontainers.containers.JdbcDatabaseContainer

The following examples show how to use org.testcontainers.containers.JdbcDatabaseContainer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: testcontainers-java   Source File: ContainerDatabaseDriver.java    License: MIT License 6 votes vote down vote up
/**
 * Wrap the connection, setting up a callback to be called when the connection is closed.
 * <p>
 * When there are no more open connections, the container itself will be stopped.
 *
 * @param connection    the new connection to be wrapped
 * @param container     the container which the connection is associated with
 * @param connectionUrl {@link ConnectionUrl} instance representing JDBC Url for this connection
 * @return the connection, wrapped
 */
private Connection wrapConnection(final Connection connection, final JdbcDatabaseContainer container, final ConnectionUrl connectionUrl) {

    final boolean isDaemon = connectionUrl.isInDaemonMode() || connectionUrl.isReusable();

    Set<Connection> connections = containerConnections.computeIfAbsent(container.getContainerId(), k -> new HashSet<>());

    connections.add(connection);

    final Set<Connection> finalConnections = connections;

    return new ConnectionWrapper(connection, () -> {
        finalConnections.remove(connection);
        if (!isDaemon && finalConnections.isEmpty()) {
            container.stop();
            jdbcUrlContainerCache.remove(connectionUrl.getUrl());
        }
    });
}
 
Example 2
Source Project: testcontainers-java   Source File: DatabaseDriverTmpfsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testDatabaseHasTmpFsViaConnectionString() throws Exception {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename?TC_TMPFS=/testtmpfs:rw";
    try (Connection ignored = DriverManager.getConnection(jdbcUrl)) {

        JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
        // check file doesn't exist
        String path = "/testtmpfs/test.file";
        Container.ExecResult execResult = container.execInContainer("ls", path);
        assertNotEquals("tmpfs inside container doesn't have file that doesn't exist", 0, execResult.getExitCode());
        // touch && check file does exist
        container.execInContainer("touch", path);
        execResult = container.execInContainer("ls", path);
        assertEquals("tmpfs inside container has file that does exist", 0, execResult.getExitCode());
    }
}
 
Example 3
Source Project: elepy   Source File: DatabaseConfigurations.java    License: Apache License 2.0 5 votes vote down vote up
public static Configuration createTestContainerConfiguration(JdbcDatabaseContainer container, String dialect) {
    return new WithSetupConfiguration(
            container::start,
            createInMemoryHibernateConfig(
                    container.getDriverClassName(),
                    container.getJdbcUrl(),
                    dialect,
                    container.getUsername(),
                    container.getPassword()
            ),
            container::stop);
}
 
Example 4
private JdbcDatabaseContainer<?> initContainer()
{
    DhisPostgreSQLContainer<?> postgisContainer = ((DhisPostgreSQLContainer<?>) new DhisPostgisContainerProvider().newInstance())
        .appendCustomPostgresConfig( "max_locks_per_transaction=100" )
        .withDatabaseName( POSTGRES_DATABASE_NAME )
        .withUsername( POSTGRES_CREDENTIALS )
        .withPassword( POSTGRES_CREDENTIALS );

    postgisContainer.start();

    log.info( String.format( "PostGIS container initialized: %s", postgisContainer.getJdbcUrl() ) );

    return postgisContainer;
}
 
Example 5
Source Project: nomulus   Source File: JpaTransactionManagerRule.java    License: Apache License 2.0 5 votes vote down vote up
private static JdbcDatabaseContainer create() {
  PostgreSQLContainer container =
      new PostgreSQLContainer(NomulusPostgreSql.getDockerTag())
          .withDatabaseName(POSTGRES_DB_NAME);
  container.start();
  return container;
}
 
Example 6
protected ResultSet performQuery(JdbcDatabaseContainer<?> container, String sql) throws SQLException {
    DataSource ds = getDataSource(container);
    Statement statement = ds.getConnection().createStatement();
    statement.execute(sql);
    ResultSet resultSet = statement.getResultSet();

    resultSet.next();
    return resultSet;
}
 
Example 7
protected DataSource getDataSource(JdbcDatabaseContainer<?> container) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(container.getJdbcUrl());
    hikariConfig.setUsername(container.getUsername());
    hikariConfig.setPassword(container.getPassword());
    hikariConfig.setDriverClassName(container.getDriverClassName());

    return new HikariDataSource(hikariConfig);
}
 
Example 8
Source Project: testcontainers-java   Source File: ContainerDatabaseDriver.java    License: MIT License 5 votes vote down vote up
/**
 * Utility method to kill ALL database containers directly from test support code. It shouldn't be necessary to use this,
 * but it is provided for convenience - e.g. for situations where many different database containers are being
 * tested and cleanup is needed to limit resource usage.
 */
public static void killContainers() {
    synchronized (jdbcUrlContainerCache) {
        jdbcUrlContainerCache.values().forEach(JdbcDatabaseContainer::stop);
        jdbcUrlContainerCache.clear();
        containerConnections.clear();
        initializedContainers.clear();
    }

}
 
Example 9
Source Project: testcontainers-java   Source File: ContainerDatabaseDriver.java    License: MIT License 5 votes vote down vote up
/**
 * Utility method to kill a database container directly from test support code. It shouldn't be necessary to use this,
 * but it is provided for convenience - e.g. for situations where many different database containers are being
 * tested and cleanup is needed to limit resource usage.
 *
 * @param jdbcUrl the JDBC URL of the container which should be killed
 */
public static void killContainer(String jdbcUrl) {
    synchronized (jdbcUrlContainerCache) {
        JdbcDatabaseContainer container = jdbcUrlContainerCache.get(jdbcUrl);
        if (container != null) {
            container.stop();
            jdbcUrlContainerCache.remove(jdbcUrl);
            containerConnections.remove(container.getContainerId());
            initializedContainers.remove(container.getContainerId());
        }
    }
}
 
Example 10
Source Project: testcontainers-java   Source File: DatabaseDriverShutdownTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldStopContainerWhenAllConnectionsClosed() throws SQLException {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename";

    getConnectionAndClose(jdbcUrl);

    JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
    assertNull("Database container instance is null as expected", container);
}
 
Example 11
Source Project: testcontainers-java   Source File: DatabaseDriverShutdownTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotStopDaemonContainerWhenAllConnectionsClosed() throws SQLException {
    final String jdbcUrl = "jdbc:tc:postgresql:9.6.8://hostname/databasename?TC_DAEMON=true";

    getConnectionAndClose(jdbcUrl);

    JdbcDatabaseContainer<?> container = ContainerDatabaseDriver.getContainer(jdbcUrl);
    assertNotNull("Database container instance is not null as expected", container);
    assertTrue("Database container is running as expected", container.isRunning());
}
 
Example 12
Source Project: gocd   Source File: AbstractMigratorIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void migrate(JdbcDatabaseContainer container, String listTableQuery, String username, String password) throws SQLException {
    Source source = new Source(container.getJdbcUrl(), username, password);
    assertThat(new Request(source, listTableQuery))
            .hasNumberOfRows(0);

    try (Connection connection = container.createConnection("")) {
        new DatabaseMigrator().migrate(connection);
    }

    assertThat(new Request(source, listTableQuery))
            .hasNumberOfRowsGreaterThan(10);
}
 
Example 13
Source Project: syndesis   Source File: SqlMetaDataITCase.java    License: Apache License 2.0 4 votes vote down vote up
public SqlMetaDataITCase(final JdbcDatabaseContainer<?> database) {
    this.database = database;
}
 
Example 14
@Override
public JdbcDatabaseContainer newInstance()
{
    return newInstance( DEFAULT_TAG );
}
 
Example 15
@Override
public JdbcDatabaseContainer newInstance( String tag )
{
    return new DhisPostgreSQLContainer( DEFAULT_IMAGE + ":" + tag );
}
 
Example 16
Source Project: testcontainers-java   Source File: JdbcDatabaseDelegate.java    License: MIT License 4 votes vote down vote up
public JdbcDatabaseDelegate(JdbcDatabaseContainer container, String queryString) {
    this.container = container;
    this.queryString = queryString;
}
 
Example 17
Source Project: testcontainers-java   Source File: ContainerDatabaseDriver.java    License: MIT License 4 votes vote down vote up
@Override
public synchronized Connection connect(String url, final Properties info) throws SQLException {

    /*
      The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL.
     */
    if (!acceptsURL(url)) {
        return null;
    }

    ConnectionUrl connectionUrl = ConnectionUrl.newInstance(url);

    synchronized (jdbcUrlContainerCache) {

        String queryString = connectionUrl.getQueryString().orElse("");
        /*
          If we already have a running container for this exact connection string, we want to connect
          to that rather than create a new container
         */
        JdbcDatabaseContainer container = jdbcUrlContainerCache.get(connectionUrl.getUrl());
        if (container == null) {

            LOGGER.debug("Container not found in cache, creating new instance");

            Map<String, String> parameters = connectionUrl.getContainerParameters();

            /*
              Find a matching container type using ServiceLoader.
             */
            ServiceLoader<JdbcDatabaseContainerProvider> databaseContainers = ServiceLoader.load(JdbcDatabaseContainerProvider.class);
            for (JdbcDatabaseContainerProvider candidateContainerType : databaseContainers) {
                if (candidateContainerType.supports(connectionUrl.getDatabaseType())) {
                    container = candidateContainerType.newInstance(connectionUrl);
                    container.withTmpFs(connectionUrl.getTmpfsOptions());
                    delegate = container.getJdbcDriverInstance();
                }
            }
            if (container == null) {
                throw new UnsupportedOperationException("Database name " + connectionUrl.getDatabaseType() + " not supported");
            }

            /*
              Cache the container before starting to prevent race conditions when a connection
              pool is started up
             */
            jdbcUrlContainerCache.put(url, container);

            /*
              Pass possible container-specific parameters
             */
            container.setParameters(parameters);

            /*
              Start the container
             */
            container.start();
        }

        /*
          Create a connection using the delegated driver. The container must be ready to accept connections.
         */
        Connection connection = container.createConnection(queryString);

        /*
          If this container has not been initialized, AND
          an init script or function has been specified, use it
         */
        if (!initializedContainers.contains(container.getContainerId())) {
            DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container, queryString);
            runInitScriptIfRequired(connectionUrl, databaseDelegate);
            runInitFunctionIfRequired(connectionUrl, connection);
            initializedContainers.add(container.getContainerId());
        }

        return wrapConnection(connection, container, connectionUrl);
    }
}
 
Example 18
Source Project: testcontainers-java   Source File: ContainerDatabaseDriver.java    License: MIT License 2 votes vote down vote up
/**
 * Utility method to get an instance of a database container given its JDBC URL.
 *
 * @param jdbcUrl the JDBC URL of the container instance to get
 * @return an instance of database container or <code>null</code> if no container associated with JDBC URL
 */
static JdbcDatabaseContainer getContainer(String jdbcUrl) {
    synchronized (jdbcUrlContainerCache) {
        return jdbcUrlContainerCache.get(jdbcUrl);
    }
}