in baremaps-core/src/main/java/org/apache/baremaps/workflow/tasks/ExecuteSql.java [26:70]
public record ExecuteSql(String database, Path file, boolean parallel) implements Task {
private static final Logger logger = LoggerFactory.getLogger(ExecuteSql.class);
@Override
public void execute(WorkflowContext context) throws Exception {
var sql = removeComments(Files.readString(file));
var queries = Arrays.stream(sql.split(";"));
if (parallel) {
queries = queries.parallel();
}
queries.forEach(
query -> {
var dataSource = context.getDataSource(database);
try (var connection = dataSource.getConnection()) {
connection.createStatement().execute(query);
} catch (SQLException e) {
throw new WorkflowException(e);
}
});
}
/**
* Remove comments from a SQL string.
*
* @param sql The SQL string.
* @return The SQL string without comments.
*/
public static String removeComments(String sql) {
var result = sql;
// remove single line comments
var singleLineCommentPattern = Pattern.compile("--.*", Pattern.MULTILINE);
var singleLineCommentMatcher = singleLineCommentPattern.matcher(result);
result = singleLineCommentMatcher.replaceAll("");
// remove multi line comments
var multiLineCommentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
var multiLineMatcher = multiLineCommentPattern.matcher(result);
result = multiLineMatcher.replaceAll("");
return result;
}
}