How to use runInitFunctionIfRequired method of org.testcontainers.jdbc.ContainerDatabaseDriver class

Best Testcontainers-java code snippet using org.testcontainers.jdbc.ContainerDatabaseDriver.runInitFunctionIfRequired

Source:ContainerDatabaseDriver.java Github

copy

Full Screen

...108 */109 if (!initializedContainers.contains(container.getContainerId())) {110 DatabaseDelegate databaseDelegate = new JdbcDatabaseDelegate(container, queryString);111 runInitScriptIfRequired(connectionUrl, databaseDelegate);112 runInitFunctionIfRequired(connectionUrl, connection);113 initializedContainers.add(container.getContainerId());114 }115 return wrapConnection(connection, container, connectionUrl);116 }117 }118 /**119 * Wrap the connection, setting up a callback to be called when the connection is closed.120 * <p>121 * When there are no more open connections, the container itself will be stopped.122 *123 * @param connection the new connection to be wrapped124 * @param container the container which the connection is associated with125 * @param connectionUrl {@link ConnectionUrl} instance representing JDBC Url for this connection126 * @return the connection, wrapped127 */128 private Connection wrapConnection(final Connection connection, final JdbcDatabaseContainer container, final ConnectionUrl connectionUrl) {129 final boolean isDaemon = connectionUrl.isInDaemonMode() || connectionUrl.isReusable();130 Set<Connection> connections = containerConnections.computeIfAbsent(container.getContainerId(), k -> new HashSet<>());131 connections.add(connection);132 final Set<Connection> finalConnections = connections;133 return new ConnectionWrapper(connection, () -> {134 finalConnections.remove(connection);135 if (!isDaemon && finalConnections.isEmpty()) {136 container.stop();137 jdbcUrlContainerCache.remove(connectionUrl.getUrl());138 }139 });140 }141 /**142 * Run an init script from the classpath.143 *144 * @param connectionUrl {@link ConnectionUrl} instance representing JDBC Url with init script.145 * @param databaseDelegate database delegate to apply init scripts to the database146 * @throws SQLException on script or DB error147 */148 private void runInitScriptIfRequired(final ConnectionUrl connectionUrl, DatabaseDelegate databaseDelegate) throws SQLException {149 if (connectionUrl.getInitScriptPath().isPresent()) {150 String initScriptPath = connectionUrl.getInitScriptPath().get();151 try {152 URL resource;153 if (initScriptPath.startsWith(FILE_PATH_PREFIX)) {154 //relative workdir path155 resource = new URL(initScriptPath);156 } else {157 //classpath resource158 resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath);159 }160 if (resource == null) {161 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);162 throw new SQLException("Could not load classpath init script: " + initScriptPath + ". Resource not found.");163 }164 String sql = IOUtils.toString(resource, StandardCharsets.UTF_8);165 ScriptUtils.executeDatabaseScript(databaseDelegate, initScriptPath, sql);166 } catch (IOException e) {167 LOGGER.warn("Could not load classpath init script: {}", initScriptPath);168 throw new SQLException("Could not load classpath init script: " + initScriptPath, e);169 } catch (ScriptException e) {170 LOGGER.error("Error while executing init script: {}", initScriptPath, e);171 throw new SQLException("Error while executing init script: " + initScriptPath, e);172 }173 }174 }175 /**176 * Run an init function (must be a public static method on an accessible class).177 *178 * @param connectionUrl {@link ConnectionUrl} instance representing JDBC Url with r init function declarations.179 * @param connection JDBC connection to apply init functions to.180 * @throws SQLException on script or DB error181 */182 private void runInitFunctionIfRequired(final ConnectionUrl connectionUrl, Connection connection) throws SQLException {183 if (connectionUrl.getInitFunction().isPresent()) {184 String className = connectionUrl.getInitFunction().get().getClassName();185 String methodName = connectionUrl.getInitFunction().get().getMethodName();186 try {187 Class<?> initFunctionClazz = Class.forName(className);188 Method method = initFunctionClazz.getMethod(methodName, Connection.class);189 method.invoke(null, connection);190 } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {191 LOGGER.error("Error while executing init function: {}::{}", className, methodName, e);192 throw new SQLException("Error while executing init function: " + className + "::" + methodName, e);193 }194 }195 }196 @Override...

Full Screen

Full Screen

runInitFunctionIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.jdbc.ContainerDatabaseDriver;2import org.testcontainers.jdbc.ContainerDatabaseDriver.InitFunction;3import java.sql.Connection;4import java.sql.DriverManager;5import java.sql.SQLException;6import java.util.Properties;7public class Test {8 public static void main(String[] args) throws SQLException {9 public void apply(Connection connection) throws SQLException {10 }11 });12 Properties properties = new Properties();13 properties.put("user", "root");14 properties.put("password", "");15 }16}17import org.testcontainers.jdbc.ContainerDatabaseDriver;18import org.testcontainers.jdbc.ContainerDatabaseDriver.InitFunction;19import java.sql.Connection;20import java.sql.DriverManager;21import java.sql.SQLException;22import java.util.Properties;23public class Test {

Full Screen

Full Screen

runInitFunctionIfRequired

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.JdbcDatabaseContainer2import org.testcontainers.containers.PostgreSQLContainerProvider3import org.testcontainers.jdbc.ContainerDatabaseDriver4import java.sql.Connection5import java.sql.DriverManager6import java.sql.ResultSet7import java.sql.SQLException8import static org.testcontainers.jdbc.ContainerDatabaseDriver.DEFAULT_JDBC_DRIVER_CLASS_NAME9public class TestContainersDemo {10 public static void main(String[] args) throws SQLException {11 ContainerDatabaseDriver driver = ContainerDatabaseDriver.instance();12 JdbcDatabaseContainer container = new PostgreSQLContainerProvider().newInstance();13 Connection connection = DriverManager.getConnection(14 driver.getJdbcUrl(container),15 driver.getUsername(container),16 driver.getPassword(container));17 connection.createStatement().execute("CREATE TABLE IF NOT EXISTS person (id int not null, name varchar(255))");18 connection.createStatement().execute("INSERT INTO person VALUES (1, 'Jane Doe')");19 connection.createStatement().execute("INSERT INTO person VALUES (2, 'John Doe')");20 ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM person");21 while (resultSet.next()) {22 System.out.println(resultSet.getString("name"));23 }24 connection.close();25 }26}

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.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful