How to use runInitScriptIfRequired method of org.testcontainers.containers.JdbcDatabaseContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.JdbcDatabaseContainer.runInitScriptIfRequired

Source:ContainerDatabaseDriver.java Github

copy

Full Screen

...134 an init script or function has been specified, use it135 */136 if (!initializedContainers.contains(container.getContainerId())) {137 DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container);138 runInitScriptIfRequired(url, databaseDelegate);139 runInitFunctionIfRequired(url, connection);140 initializedContainers.add(container.getContainerId());141 }142 return wrapConnection(connection, container, url);143 }144 }145 private Map<String, String> getContainerParameters(String url) {146 Map<String, String> results = new HashMap<>();147 Matcher matcher = TC_PARAM_MATCHING_PATTERN.matcher(url);148 while (matcher.find()) {149 String key = matcher.group(1);150 String value = matcher.group(2);151 results.put(key, value);152 }153 return results;154 }155 /**156 * Wrap the connection, setting up a callback to be called when the connection is closed.157 * <p>158 * When there are no more open connections, the container itself will be stopped.159 *160 * @param connection the new connection to be wrapped161 * @param container the container which the connection is associated with162 * @param url the testcontainers JDBC URL for this connection163 * @return the connection, wrapped164 */165 private Connection wrapConnection(final Connection connection, final JdbcDatabaseContainer container, final String url) {166 final Matcher matcher = DAEMON_MATCHING_PATTERN.matcher(url);167 final boolean isDaemon = matcher.matches() ? Boolean.parseBoolean(matcher.group(2)) : false;168 Set<Connection> connections = containerConnections.get(container.getContainerId());169 if (connections == null) {170 connections = new HashSet<>();171 containerConnections.put(container.getContainerId(), connections);172 }173 connections.add(connection);174 final Set<Connection> finalConnections = connections;175 return new ConnectionWrapper(connection, () -> {176 finalConnections.remove(connection);177 if (!isDaemon && finalConnections.isEmpty()) {178 container.stop();179 jdbcUrlContainerCache.remove(url);180 }181 });182 }183 /**184 * Run an init script from the classpath.185 *186 * @param url the JDBC URL to check for init script declarations.187 * @param databaseDelegate database delegate to apply init scripts to the database188 * @throws SQLException on script or DB error189 */190 private void runInitScriptIfRequired(String url, DatabaseDelegate databaseDelegate) throws SQLException {191 Matcher matcher = INITSCRIPT_MATCHING_PATTERN.matcher(url);192 if (matcher.matches()) {193 String initScriptPath = matcher.group(2);194 try {195 URL resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath);196 if (resource == null) {197 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);198 throw new SQLException("Could not load classpath init script: " + initScriptPath + ". Resource not found.");199 }200 String sql = IOUtils.toString(resource, StandardCharsets.UTF_8);201 ScriptUtils.executeDatabaseScript(databaseDelegate, initScriptPath, sql);202 } catch (IOException e) {203 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);204 throw new SQLException("Could not load classpath init script: " + initScriptPath, e);...

Full Screen

Full Screen

Source:SharedContainerDatabaseDriver.java Github

copy

Full Screen

...86 }87 Connection connection = container.createConnection(queryString);88 LOGGER.debug("Connection to container: {} -> URL {}", connection, connection.getMetaData().getURL());89 DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container, queryString);90 runInitScriptIfRequired(connectionUrl, databaseDelegate);91 runClearFlywayIfRequired(connection);92 runInitFunctionIfRequired(connectionUrl, connection);93 return wrapConnection(connection, container, connectionUrl);94 }95 @Override96 public DriverPropertyInfo[] getPropertyInfo(String url, Properties properties) throws SQLException {97 return this.delegate.getPropertyInfo(url, properties);98 }99 @Override100 public int getMajorVersion() {101 return this.delegate.getMajorVersion();102 }103 @Override104 public int getMinorVersion() {105 return this.delegate.getMinorVersion();106 }107 @Override108 public boolean jdbcCompliant() {109 return this.delegate.jdbcCompliant();110 }111 @Override112 public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {113 return this.delegate.getParentLogger();114 }115 public static void killContainers() {116 jdbcUrlContainerCache.values().forEach(JdbcDatabaseContainer::stop);117 jdbcUrlContainerCache.clear();118 containerConnections.clear();119 }120 public static void killContainer(String jdbcUrl) {121 JdbcDatabaseContainer container = jdbcUrlContainerCache.get(jdbcUrl);122 if (container != null) {123 container.stop();124 jdbcUrlContainerCache.remove(jdbcUrl);125 containerConnections.remove(container.getContainerId());126 }127 }128 private void runInitScriptIfRequired(final ConnectionUrl connectionUrl, DatabaseDelegate databaseDelegate) throws SQLException {129 if (connectionUrl.getInitScriptPath().isPresent()) {130 String initScriptPath = connectionUrl.getInitScriptPath().get();131 LOGGER.debug("About to execute script: {}", initScriptPath);132 if (initializedScripts.contains(initScriptPath)) {133 LOGGER.debug("... aborted, already executed");134 return;135 }136 LOGGER.debug("... script execution added to history");137 initializedScripts.add(initScriptPath);138 try {139 URL resource;140 if (initScriptPath.startsWith(FILE_PATH_PREFIX)) {141 //relative workdir path142 resource = new URL(initScriptPath);...

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.JdbcDatabaseContainer;2import org.testcontainers.containers.JdbcDatabaseContainerProvider;3import org.testcontainers.containers.MSSQLServerContainer;4import org.testcontainers.containers.MSSQLServerContainerProvider;5import org.testcontainers.containers.MSSQLServerContainerProvider.MSSQLServer;6import org.testcontainers.containers.MSSQLServerContainerProvider.MSSQLServerProvider;7import org.testcontainers.utility.DockerImageName;8import org.testcontainers.utility.MSSQLServerContainer;9import org.testcontainers.utility.MSSQLServerContainerProvider;10import org.testcontainers.utility.MSSQLServerContainerProvider.MSSQLServer;11import org.testcontainers.utility.MSSQLServerContainerProvider.MSSQLServerProvider;12import java.sql.Connection;13import java.sql.DriverManager;14import java.sql.ResultSet;15import java.sql.SQLException;16import java.sql.Statement;17public class TestContainer {

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import java.io.File;3import java.io.IOException;4import java.nio.charset.StandardCharsets;5import java.nio.file.Files;6import java.nio.file.Path;7import java.nio.file.Paths;8import java.sql.SQLException;9import org.junit.Test;10import org.testcontainers.containers.JdbcDatabaseContainer;11import org.testcontainers.containers.PostgreSQLContainer;12public class TestContainersDemo {13 public void test() throws SQLException, IOException {14 String scriptContent = "CREATE TABLE public.test_table (id BIGSERIAL PRIMARY KEY, name VARCHAR(255));";15 Path scriptPath = Paths.get("initScript.sql");16 Files.write(scriptPath, scriptContent.getBytes(StandardCharsets.UTF_8));17 JdbcDatabaseContainer container = new PostgreSQLContainer().withInitScript(scriptPath.toString());18 container.start();19 container.runInitScriptIfRequired(scriptPath.toString());20 container.stop();21 Files.deleteIfExists(scriptPath);22 }23}24package org.testcontainers.containers;25import java.io.File;26import java.io.IOException;27import java.nio.charset.StandardCharsets;28import java.nio.file.Files;29import java.nio.file.Path;30import java.nio.file.Paths;31import java.sql.SQLException;32import org.junit.Test;33import org.testcontainers.containers.JdbcDatabaseContainer;34import org.testcontainers.containers.PostgreSQLContainer;35public class TestContainersDemo {36 public void test() throws SQLException, IOException {37 String scriptContent = "CREATE TABLE public.test_table (id BIGSERIAL PRIMARY KEY, name VARCHAR(255));";38 Path scriptPath = Paths.get("initScript.sql");39 Files.write(scriptPath, scriptContent.getBytes(StandardCharsets.UTF_8));40 JdbcDatabaseContainer container = new PostgreSQLContainer().withInitScript(scriptPath.toString());41 container.start();42 container.runInitScriptIfRequired(scriptContent);43 container.stop();44 Files.deleteIfExists(scriptPath);45 }46}47package org.testcontainers.containers;48import java.io.File;49import java.io.IOException;50import java.nio.charset.StandardCharsets;51import java.nio.file.Files;52import java.nio.file.Path;53import java.nio.file.Paths;54import java.sql.SQLException;55import org.junit.Test;56import org.test

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.JdbcDatabaseContainer;2import org.testcontainers.containers.PostgreSQLContainer;3import org.testcontainers.containers.output.Slf4jLogConsumer;4import org.testcontainers.utility.MountableFile;5public class TestContainerTest {6 public static void main(String[] args) {7 try (PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer()) {8 postgreSQLContainer.withLogConsumer(new Slf4jLogConsumer(System.out));9 postgreSQLContainer.start();10 JdbcDatabaseContainer jdbcDatabaseContainer = postgreSQLContainer;11 jdbcDatabaseContainer.runInitScriptIfRequired(MountableFile.forClasspathResource("1.sql"));12 }13 }14}15import org.testcontainers.containers.JdbcDatabaseContainer;16import org.testcontainers.containers.PostgreSQLContainer;17import org.testcontainers.containers.output.Slf4jLogConsumer;18import org.testcontainers.utility.MountableFile;19public class TestContainerTest {20 public static void main(String[] args) {21 try (PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer()) {22 postgreSQLContainer.withLogConsumer(new Slf4jLogConsumer(System.out));23 postgreSQLContainer.start();24 postgreSQLContainer.runInitScriptIfRequired(MountableFile.forClasspathResource("1.sql"));25 }26 }27}

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.JdbcDatabaseContainer;2public class 1 {3 public static void main(String[] args) {4 JdbcDatabaseContainer container = new JdbcDatabaseContainer() {5 public void start() {6 }7 public void stop() {8 }9 };10 container.runInitScriptIfRequired("init.sql");11 }12}

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.junit.Test;3import java.sql.Connection;4import java.sql.DriverManager;5import java.sql.SQLException;6import java.sql.Statement;7public class TestContainerTest {8 public void test() throws SQLException {9 Statement statement = connection.createStatement();10 statement.execute("CREATE TABLE test (id integer);");11 }12 }13}14package org.testcontainers.containers;15import org.junit.Test;16import java.sql.Connection;17import java.sql.DriverManager;18import java.sql.SQLException;19import java.sql.Statement;20public class TestContainerTest {21 public void test() throws SQLException {22 Statement statement = connection.createStatement();23 statement.execute("CREATE TABLE test (id integer);");24 }25 }26}27package org.testcontainers.containers;28import org.junit.Test;29import java.sql.Connection;30import java.sql.DriverManager;31import java.sql.SQLException;32import java.sql.Statement;33public class TestContainerTest {34 public void test() throws SQLException {35 Statement statement = connection.createStatement();36 statement.execute("CREATE TABLE test (id integer);");37 }38 }39}40package org.testcontainers.containers;41import org.junit.Test;42import java.sql.Connection;43import java.sql.DriverManager;44import java.sql.SQLException;45import java.sql.Statement;46public class TestContainerTest {47 public void test() throws SQLException {48 Statement statement = connection.createStatement();49 statement.execute("CREATE TABLE test (id integer);");50 }51 }52}

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.junit.Test;3import org.testcontainers.containers.JdbcDatabaseContainer;4public class TestContainer {5 public void test1() {6 JdbcDatabaseContainer container = new JdbcDatabaseContainer() {7 public String getDriverClassName() {8 return null;9 }10 public String getJdbcUrl() {11 return null;12 }13 };14 container.runInitScriptIfRequired("select 1 from dual");15 }16}17package org.testcontainers.containers;18import org.junit.Test;19import org.testcontainers.containers.JdbcDatabaseContainer;20public class TestContainer {21 public void test1() {22 JdbcDatabaseContainer container = new JdbcDatabaseContainer() {23 public String getDriverClassName() {24 return null;25 }26 public String getJdbcUrl() {27 return null;28 }29 };30 container.runInitScriptIfRequired("select 1 from dual");31 }32}33package org.testcontainers.containers;34import org.junit.Test;35import org.testcontainers.containers.JdbcDatabaseContainer;36public class TestContainer {37 public void test1() {38 JdbcDatabaseContainer container = new JdbcDatabaseContainer() {39 public String getDriverClassName() {40 return null;41 }42 public String getJdbcUrl() {43 return null;44 }45 };46 container.runInitScriptIfRequired("select 1 from dual");47 }48}49package org.testcontainers.containers;50import org.junit.Test;51import org.testcontainers.containers.JdbcDatabaseContainer;52public class TestContainer {53 public void test1() {54 JdbcDatabaseContainer container = new JdbcDatabaseContainer() {55 public String getDriverClassName() {56 return null;57 }58 public String getJdbcUrl() {

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1package com.mycompany.app;2import java.io.File;3import java.io.IOException;4import java.net.URL;5import java.util.Arrays;6import java.util.Collections;7import java.util.List;8import org.testcontainers.containers.JdbcDatabaseContainer;9import org.testcontainers.containers.PostgreSQLContainer;10{11 public static void main( String[] args ) throws IOException12 {13 PostgreSQLContainer container = new PostgreSQLContainer("postgres:11.1");14 container.start();15 URL resource = App.class.getClassLoader().getResource("init.sql");16 if (resource == null) {17 throw new IllegalStateException("init.sql not found");18 }19 File initScript = new File(resource.getFile());20 JdbcDatabaseContainer<?> jdbcDatabaseContainer = container;21 jdbcDatabaseContainer.runInitScriptIfRequired(initScript);22 container.stop();23 }24}25package com.mycompany.app;26import java.io.File;27import java.io.IOException;28import java.net.URL;29import org.testcontainers.containers.PostgreSQLContainer;30{31 public static void main( String[] args ) throws IOException32 {33 PostgreSQLContainer container = new PostgreSQLContainer("postgres:11.1");34 container.start();35 URL resource = App.class.getClassLoader().getResource("init.sql");36 if (resource == null) {37 throw new IllegalStateException("init.sql not found");38 }39 File initScript = new File(resource.getFile());40 container.runInitScriptIfRequired(initScript);41 container.stop();42 }43}44package com.mycompany.app;45import java.io.File;46import java.io.IOException;47import java.net.URL;48import org.testcontainers.containers.PostgreSQLContainer;49{50 public static void main( String[] args ) throws IOException51 {52 PostgreSQLContainer container = new PostgreSQLContainer("postgres:11.1");53 container.start();54 URL resource = App.class.getClassLoader().getResource("init.sql");55 if (resource == null) {56 throw new IllegalStateException("init.sql not found");57 }58 File initScript = new File(resource.getFile());59 container.runInitScriptIfRequired(initScript.getAbsolutePath());60 container.stop();61 }62}

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.JdbcDatabaseContainer;2import org.testcontainers.containers.PostgreSQLContainer;3public class Main {4 public static void main(String[] args) {5 JdbcDatabaseContainer container = new PostgreSQLContainer("postgres:latest")6 .withDatabaseName("test")7 .withUsername("user")8 .withPassword("password")9 .withInitScript("init.sql");10 container.start();11 System.out.println(container.getJdbcUrl());12 }13}14import org.testcontainers.containers.JdbcDatabaseContainer;15import org.testcontainers.containers.PostgreSQLContainer;16public class Main {17 public static void main(String[] args) {18 JdbcDatabaseContainer container = new PostgreSQLContainer("postgres:latest")19 .withDatabaseName("test")20 .withUsername("user")21 .withPassword("password");22 container.start();23 container.runInitScriptIfRequired("init.sql");24 System.out.println(container.getJdbcUrl());25 }26}27import org.testcontainers.containers.JdbcDatabaseContainer;28import org.testcontainers.containers.PostgreSQLContainer;29public class Main {30 public static void main(String[] args) {31 JdbcDatabaseContainer container = new PostgreSQLContainer("postgres:latest")32 .withDatabaseName("test")33 .withUsername("user")34 .withPassword("password");35 container.start();36 container.runInitScriptIfRequired("init.sql");37 System.out.println(container.getJdbcUrl());38 }39}40import org.testcontainers.containers.JdbcDatabaseContainer;41import org.testcontainers.containers.PostgreSQLContainer;42public class Main {43 public static void main(String[] args) {44 JdbcDatabaseContainer container = new PostgreSQLContainer("postgres:latest")45 .withDatabaseName("test")46 .withUsername("user")47 .withPassword("password")48 .withInitScript("init.sql");

Full Screen

Full Screen

runInitScriptIfRequired

Using AI Code Generation

copy

Full Screen

1public class 1 {2 public static void main(String[] args) {3 String sql = "CREATE TABLE IF NOT EXISTS test (id INT, name VARCHAR(255));";4 try (MySQLContainer container = new MySQLContainer()) {5 container.start();6 container.runInitScriptIfRequired(sql);7 System.out.println("Success");8 }9 }10}11public class 2 {12 public static void main(String[] args) {13 String sql = "CREATE TABLE IF NOT EXISTS test (id INT, name VARCHAR(255));";14 try (MySQLContainer container = new MySQLContainer()) {15 container.start();16 container.runInitScriptIfRequired(sql);17 System.out.println("Success");18 }19 }20}21public class 3 {22 public static void main(String[] args) {23 String sql = "CREATE TABLE IF NOT EXISTS test (id INT, name VARCHAR(255));";24 try (MySQLContainer container = new MySQLContainer()) {25 container.start();26 container.runInitScriptIfRequired(sql);27 System.out.println("Success");28 }29 }30}31public class 4 {32 public static void main(String[] args) {33 String sql = "CREATE TABLE IF NOT EXISTS test (id INT, name VARCHAR(255));";34 try (MySQLContainer container = new MySQLContainer()) {35 container.start();36 container.runInitScriptIfRequired(sql);37 System.out.println("Success");38 }39 }40}41public class 5 {42 public static void main(String[] args) {43 String sql = "CREATE TABLE IF NOT EXISTS test (id INT, name VARCHAR(255));";44 try (MySQLContainer container = new MySQLContainer()) {45 container.start();46 container.runInitScriptIfRequired(sql);47 System.out.println("Success");48 }49 }50}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful