au.net.causal.maven.plugins.boxdb.SqlDivider Maven / Gradle / Ivy
Show all versions of boxdb-maven-plugin Show documentation
package au.net.causal.maven.plugins.boxdb;
import org.codehaus.mojo.sql.SqlSplitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Split SQL read from reader into statements that can be executed with JDBC connection.
*
*
* SQL statements are split semi-intelligently according to ';' and line breaks. SQL comments are ignored.
*
* @see SqlSplitter
*/
public class SqlDivider
{
private static final List SQL_COMMENT_STARTS = Collections.unmodifiableList(Arrays.asList("--", "//"));
/**
* Splits SQL statements read from a reader and processes them in a consumer.
*
* @param reader the reader to read SQL from.
* @param sqlProcessor a consumer that accepts SQL statements. Each SQL statement read from the reader
* will be passed to this consumer one-at-a-time.
*
* @param type of exceptions thrown from the consumer.
*
* @throws IOException if an I/O error occurs reading from the reader.
* @throws E if an exception is thrown from the consumer.
*/
public void splitAndProcessSql(BufferedReader reader, ExceptionalConsumer super String, E> sqlProcessor)
throws IOException, E
{
int overflow = SqlSplitter.NO_END;
StringBuilder sql = new StringBuilder();
String line;
while ((line = reader.readLine() ) != null)
{
line = line.trim();
if (!line.isEmpty() && !SQL_COMMENT_STARTS.stream().anyMatch(line::startsWith))
{
if (sql.length() > 0)
sql.append(' ');
sql.append(line);
overflow = SqlSplitter.containsSqlEnd(line, ";", overflow);
if (overflow > 0)
{
String sqlToExecute = sql.substring(0, sql.length() - 1);
sqlProcessor.accept(sqlToExecute);
sql.setLength(0);
overflow = SqlSplitter.NO_END;
}
}
}
if (sql.length() > 0)
sqlProcessor.accept(sql.toString());
}
}