Best Testcontainers-java code snippet using org.testcontainers.ext.ScriptUtils.ScriptParseException
Source:ScriptUtils.java  
...148						i = indexOfCommentEnd + blockCommentEndDelimiter.length() - 1;149						continue;150					}151					else {152						throw new ScriptParseException(String.format("Missing block comment end delimiter [%s].",153							blockCommentEndDelimiter), resource);154					}155				}156				else if (c == ' ' || c == '\n' || c == '\t') {157					// avoid multiple adjacent whitespace characters158					if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') {159						c = ' ';160					}161					else {162						continue;163					}164				}165			}166			sb.append(c);167		}168		if (StringUtils.isNotEmpty(sb.toString())) {169			statements.add(sb.toString());170		}171	}172	private static void checkArgument(boolean expression, String errorMessage) {173		if (!expression) {174			throw new IllegalArgumentException(errorMessage);175		}176	}177    /**178	 * Does the provided SQL script contain the specified delimiter?179	 * @param script the SQL script180	 * @param delim String delimiting each statement - typically a ';' character181	 */182	public static boolean containsSqlScriptDelimiters(String script, String delim) {183		boolean inLiteral = false;184		char[] content = script.toCharArray();185		for (int i = 0; i < script.length(); i++) {186			if (content[i] == '\'') {187				inLiteral = !inLiteral;188			}189			if (!inLiteral && script.startsWith(delim, i)) {190				return true;191			}192		}193		return false;194	}195    public static void executeDatabaseScript(DatabaseDelegate databaseDelegate, String scriptPath, String script) throws ScriptException {196        executeDatabaseScript(databaseDelegate, scriptPath, script, false, false, DEFAULT_COMMENT_PREFIX, DEFAULT_STATEMENT_SEPARATOR, DEFAULT_BLOCK_COMMENT_START_DELIMITER, DEFAULT_BLOCK_COMMENT_END_DELIMITER);197    }198    /**199	 * Execute the given database script.200	 * <p>Statement separators and comments will be removed before executing201	 * individual statements within the supplied script.202     * <p><b>Do not use this method to execute DDL if you expect rollback.</b>203     * @param databaseDelegate database delegate for script execution204     * @param scriptPath the resource (potentially associated with a specific encoding)205     * to load the SQL script from206     * @param script the raw script content207     *@param continueOnError whether or not to continue without throwing an exception208     * in the event of an error209     * @param ignoreFailedDrops whether or not to continue in the event of specifically210* an error on a {@code DROP} statement211     * @param commentPrefix the prefix that identifies comments in the SQL script —212* typically "--"213     * @param separator the script statement separator; defaults to214* {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to215* {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort216     * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter; never217* {@code null} or empty218     * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter; never219* {@code null} or empty       @throws ScriptException if an error occurred while executing the SQL script220	 */221	public static void executeDatabaseScript(DatabaseDelegate databaseDelegate, String scriptPath, String script, boolean continueOnError,222			boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter,223			String blockCommentEndDelimiter) throws ScriptException {224		try {225			if (LOGGER.isInfoEnabled()) {226				LOGGER.info("Executing database script from " + scriptPath);227			}228			long startTime = System.currentTimeMillis();229			List<String> statements = new LinkedList<>();230			if (separator == null) {231				separator = DEFAULT_STATEMENT_SEPARATOR;232			}233			if (!containsSqlScriptDelimiters(script, separator)) {234				separator = FALLBACK_STATEMENT_SEPARATOR;235			}236			splitSqlScript(scriptPath, script, separator, commentPrefix, blockCommentStartDelimiter,237				blockCommentEndDelimiter, statements);238			try (DatabaseDelegate closeableDelegate = databaseDelegate) {239				closeableDelegate.execute(statements, scriptPath, continueOnError, ignoreFailedDrops);240			}241			long elapsedTime = System.currentTimeMillis() - startTime;242			if (LOGGER.isInfoEnabled()) {243				LOGGER.info("Executed database script from " + scriptPath + " in " + elapsedTime + " ms.");244			}245		}246		catch (Exception ex) {247			if (ex instanceof ScriptException) {248				throw (ScriptException) ex;249			}250			throw new UncategorizedScriptException(251				"Failed to execute database script from resource [" + script + "]", ex);252		}253	}254    private static class ScriptParseException extends RuntimeException {255        public ScriptParseException(String format, String scriptPath) {256            super(String.format(format, scriptPath));257        }258    }259    public static class ScriptStatementFailedException extends RuntimeException {260        public ScriptStatementFailedException(String statement, int lineNumber, String scriptPath, Exception ex) {261            super(String.format("Script execution failed (%s:%d): %s", scriptPath, lineNumber, statement), ex);262        }263    }264    private static class UncategorizedScriptException extends RuntimeException {265        public UncategorizedScriptException(String s, Exception ex) {266            super(s, ex);267        }268    }269}...Source:ScriptSplittingTest.java  
...236        String script = "SELECT 'foo `bar`'; /*";237        try {238            doSplit(script);239            fail("Should have thrown!");240        } catch (ScriptUtils.ScriptParseException expected) {241            // ignore expected exception242        }243    }244    @Test245    public void testIssue1452Case() {246        String script = "create table test (text VARCHAR(255));\n" +247            "\n" +248            "/* some comment */\n" +249            "insert into `test` (`text`) values ('a     b');";250        List<String> expected = asList(251            "create table test (text VARCHAR(255))",252            "insert into `test` (`text`) values ('a     b')"253        );254        splitAndCompare(script, expected);...ScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils;2import org.testcontainers.ext.ScriptUtils.ScriptParseException;3public class 1 {4    public static void main(String[] args) {5        try {6            ScriptUtils.ScriptParseException ex = new ScriptUtils.ScriptParseException("message", new Throwable());7            System.out.println(ex);8        } catch (Exception e) {9            e.printStackTrace();10        }11    }12}13	at org.testcontainers.ext.ScriptUtils$ScriptParseException.<init>(ScriptUtils.java:55)14	at 1.main(1.java:6)ScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils.ScriptParseException;2import org.testcontainers.ext.ScriptUtils;3public class 1 {4    public static void main(String[] args) {5        try {6            ScriptUtils.parseSqlScript(null, null);7        } catch (ScriptParseException e) {8            e.printStackTrace();9        }10    }11}ScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils;2import java.io.IOException;3import java.sql.SQLException;4public class TestContainer {5    public static void main(String[] args) throws IOException, SQLException, ScriptParseException {6        ScriptUtils.ScriptParseResult scriptParseResult = ScriptUtils.parseScript("CREATE TABLE T1 (ID INT)");7        System.out.println(scriptParseResult.getStatements());8    }9}10import org.testcontainers.containers.JdbcDatabaseContainer;11import java.io.IOException;12import java.sql.SQLException;13public class TestContainer {14    public static void main(String[] args) throws IOException, SQLException, JdbcDatabaseContainer.ScriptParseException {15        JdbcDatabaseContainer.ScriptParseResult scriptParseResult = JdbcDatabaseContainer.parseScript("CREATE TABLE T1 (ID INT)");16        System.out.println(scriptParseResult.getStatements());17    }18}19import org.testcontainers.containers.JdbcDatabaseContainer;20import java.io.IOException;21import java.sql.SQLException;22public class TestContainer {23    public static void main(String[] args) throws IOException, SQLException, JdbcDatabaseContainer.ScriptParseException {24        JdbcDatabaseContainer.ScriptParseResult scriptParseResult = JdbcDatabaseContainer.parseScript("CREATE TABLE T1 (ID INT)");25        System.out.println(scriptParseResult.getStatements());26    }27}28import org.testcontainers.containers.JdbcDatabaseContainer;29import java.io.IOException;30import java.sql.SQLException;31public class TestContainer {32    public static void main(String[] args) throws IOException, SQLException, JdbcDatabaseContainer.ScriptParseException {33        JdbcDatabaseContainer.ScriptParseResult scriptParseResult = JdbcDatabaseContainer.parseScript("CREATE TABLE T1 (ID INT)");34        System.out.println(scriptParseResult.getStatements());35    }36}37import org.testcontainers.containers.JdbcDatabaseScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils;2import org.testcontainers.ext.ScriptUtils.ScriptParseException;3import java.io.IOException;4public class 1 {5    public static void main(String[] args) throws IOException, ScriptParseException {6        String script = ScriptUtils.readScriptFile("src/main/resources/1.sql");7        ScriptUtils.ScriptParseResult parseResult = ScriptUtils.parseScript("src/main/resources/1.sql", script, true);8        System.out.println(parseResult);9    }10}11CREATE TABLE `user` (12  `id` int(11) NOT NULL AUTO_INCREMENT,13  `name` varchar(255) NOT NULL,14  `age` int(11) NOT NULL,15  PRIMARY KEY (`id`)16) ENGINE=InnoDB DEFAULT CHARSET=utf8;17import org.testcontainers.ext.ScriptUtils;18import java.io.IOException;19public class 2 {20    public static void main(String[] args) throws IOException {21        String script = ScriptUtils.readScriptFile("src/main/resources/1.sql");22        String[] statements = ScriptUtils.splitSqlScript(script, true);23        System.out.println(statements);24    }25}26CREATE TABLE `user` (27  `id` int(11) NOT NULL AUTO_INCREMENT,28  `name` varchar(255) NOT NULL,29  `age` int(11) NOT NULL,30  PRIMARY KEY (`id`)31) ENGINE=InnoDB DEFAULT CHARSET=utf8;32CREATE TABLE `user` (33  `id` int(11) NOT NULL AUTO_INCREMENT,34  `name` varchar(255) NOT NULL,35  `age` int(11) NOT NULL,36  PRIMARY KEY (`id`)37) ENGINE=InnoDB DEFAULT CHARSET=utf8;38CREATE TABLE `user` (39  `id` int(11) NOT NULL AUTO_INCREMENT,40  `name` varchar(255) NOT NULL,41  `age` int(11) NOT NULL,42  PRIMARY KEY (`id`)43) ENGINE=InnoDB DEFAULT CHARSET=utf8;44CREATE TABLE `user` (45  `id` int(11) NOT NULL AUTO_INCREMENT,46  `name` varchar(255) NOT NULL,47  `age` int(11) NOTScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils.ScriptParseException;2import org.testcontainers.ext.ScriptUtils;3import org.testcontainers.ext.ScriptUtils.ScriptParseOption;4import java.util.List;5import java.util.ArrayList;6import java.util.Arrays;7import java.util.Collections;8import java.util.stream.Collectors;9import java.util.stream.Stream;10import java.util.regex.Matcher;11import java.util.regex.Pattern;12import java.nio.file.Paths;13import java.nio.file.Path;14import java.nio.file.Files;15import java.util.Set;16import java.util.HashSet;17import java.util.Map;18import java.util.HashMap;19import java.util.Optional;20import java.util.concurrent.atomic.AtomicInteger;21import java.util.function.Predicate;22import java.util.function.Function;23public class 1 {24    public static void main(String[] args) {25        try {26            ScriptUtils.ScriptParseOption parseOption = new ScriptUtils.ScriptParseOption();27            parseOption.setDelimiter(";");28            parseOption.setCommentPrefix("--");29            parseOption.setBlockCommentStartDelimiter("/*");30            parseOption.setBlockCommentEndDelimiter("*/");31            parseOption.setEscapeCharacter("\\");32            parseOption.setStrictDelimiterMatching(false);33            parseOption.setSkipComments(false);34            parseOption.setSkipBlockComments(false);35            parseOption.setSkipEmptyLines(false);36            parseOption.setSkipLeadingWhitespaces(false);37            parseOption.setSkipTrailingWhitespaces(false);38            parseOption.setThrowExceptionOnParseError(true);39            parseOption.setThrowExceptionOnMissingFile(false);40            parseOption.setIgnoreFailedDrops(false);41            parseOption.setIgnoreFailedCreates(false);42            parseOption.setIgnoreFailedFullScript(false);43            parseOption.setIgnoreFailedSingleStatements(false);44            parseOption.setIgnoreIgnoredStatements(false);45            parseOption.setIgnoreIgnoredStatementsForDrops(false);46            parseOption.setIgnoreIgnoredStatementsForCreates(false);47            parseOption.setIgnoreIgnoredStatementsForFullScript(false);48            parseOption.setIgnoreIgnoredStatementsForSingleStatements(false);49            parseOption.setIgnoreIgnoredStatementsForAll(false);50            parseOption.setIgnoreIgnoredStatementsForAllDrops(false);51            parseOption.setIgnoreIgnoredStatementsForAllCreates(false);52            parseOption.setIgnoreIgnoredStatementsForAllFullScript(false);53            parseOption.setIgnoreIgnoredStatementsForAllSingleStatements(false);54            parseOption.setContinueOnError(false);55            parseOption.setStopOnError(false);56            parseOption.setIgnoreFailedDrops(false);57            parseOption.setIgnoreFailedCreates(false);ScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils.ScriptParseException;2public class 1 {3    public static void main(String[] args) {4        String sql = "CREATE TABLE `foo` ( `id` int(11) NOT NULL, `bar` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";5        try {6            ScriptUtils.parseScript(sql);7        } catch (ScriptParseException e) {8            System.out.println(e.getMessage());9        }10    }11}12CREATE TABLE `foo` ( `id` int(11) NOT NULL, `bar` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; (line 1, column 0): Syntax error in SQL statement "CREATE TABLE `foo` [(*]ScriptParseException
Using AI Code Generation
1import org.testcontainers.ext.ScriptUtils.ScriptParseException;2import java.io.IOException;3import java.util.List;4public class 1 {5    public static void main(String[] args) throws ScriptParseException, IOException {6        List<String> statements = ScriptUtils.parse("/path/to/your/script.sql");7        System.out.println(statements);8    }9}10[CREATE TABLE IF NOT EXISTS `user` (11  `id` int(11) NOT NULL AUTO_INCREMENT,12  `name` varchar(255) NOT NULL,13  `email` varchar(255) NOT NULL,14  `password` varchar(255) NOT NULL,15  PRIMARY KEY (`id`)16) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;,17CREATE TABLE IF NOT EXISTS `user_role` (18  `id` int(11) NOT NULL AUTO_INCREMENT,19  `user_id` int(11) NOT NULL,20  `role` varchar(255) NOT NULL,21  PRIMARY KEY (`id`),22  KEY `fk_user_role_user_id` (`user_id`),23  CONSTRAINT `fk_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)24) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;]ScriptParseException
Using AI Code Generation
1import java.io.IOException;2import java.io.InputStream;3import java.io.InputStreamReader;4import java.io.Reader;5import java.io.StringReader;6import java.nio.charset.StandardCharsets;7import java.sql.Connection;8import java.sql.SQLException;9import java.sql.Statement;10import java.util.ArrayList;11import java.util.List;12import org.apache.commons.io.IOUtils;13import org.apache.commons.logging.Log;14import org.apache.commons.logging.LogFactory;15import org.springframework.core.io.Resource;16import org.springframework.core.io.support.EncodedResource;17import org.springframework.jdbc.datasource.init.ScriptUtils;18import org.springframework.jdbc.datasource.init.UncategorizedScriptException;19import org.springframework.jdbc.datasource.init.UncategorizedScriptFormatException;20import org.springframework.jdbc.datasource.init.UncategorizedSQLException;21import org.springframework.util.Assert;22import org.springframework.util.StringUtils;23public abstract class ScriptUtils {24	private static final Log logger = LogFactory.getLog(ScriptUtils.class);25	 * Default statement separator within SQL scripts: {@value}26	public static final String DEFAULT_STATEMENT_SEPARATOR = ";";27	 * Fallback statement separator within SQL scripts: {@value}28	public static final String FALLBACK_STATEMENT_SEPARATOR = "\n";29	 * End of file (EOF) statement separator: {@value}30	public static final String EOF_STATEMENT_SEPARATOR = "___EOF___";31	 * Custom SQL comment start delimiter: {@value}32	public static final String CUSTOM_SQL_COMMENT_START_DELIMITER = "/*";33	 * Custom SQL comment end delimiter: {@value}34	public static final String CUSTOM_SQL_COMMENT_END_DELIMITER = "*/";ScriptParseException
Using AI Code Generation
1public class Test {2    public static void main(String[] args) throws ScriptParseException {3        String script = "CREATE TABLE IF NOT EXISTS test (id int);";4        ScriptUtils.parseScript(script, new ScriptUtils.ScriptStatementCallback() {5            public void handleStatement(String statement) {6                System.out.println(statement);7            }8        }, new ScriptUtils.ScriptParseException() {9            public void handleException(SQLException e) {10                System.out.println(e);11            }12        });13    }14}15	at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:419)16	at org.testcontainers.containers.GenericContainer.lambda$doStart$0(GenericContainer.java:325)17	at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:81)18	at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:323)19	at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:312)20	at org.testcontainers.containers.PostgreSQLContainer.start(PostgreSQLContainer.java:154)21	at org.testcontainers.containers.PostgreSQLContainer.starting(PostgreSQLContainer.java:130)22	at org.testcontainers.containers.FailureDetectingExternalResource$1.evaluate(FailureDetectingExternalResource.java:29)23	at org.junit.rules.RunRules.evaluate(RunRules.java:20)24	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)25	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)26	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)27	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)28	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)29	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)30	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)31	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)32	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)33	at org.junit.runner.JUnitCore.run(JLearn 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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
