QueryStatementSplitter { public List<String> split(String input) { List<String> statements = new ArrayList<String>(); StrBuilder currentSql = new StrBuilder(); StrTokenizer lineTokenizer = new StrTokenizer(input); lineTokenizer.setDelimiterMatcher(StrMatcher.charSetMatcher("\r\n")); for (String line : lineTokenizer.getTokenArray()) { String strippedLine = StringUtils.stripEnd(line, null); if (!currentSql.isEmpty()) { currentSql.append(lineEnding.get()); } currentSql.append(strippedLine); if (delimiterType.matches(strippedLine, delimiter)) { statements.add(currentSql.substring(0, currentSql.length() - delimiter.length())); currentSql.clear(); } } if (!currentSql.isEmpty()) { statements.add(currentSql.toString()); } return statements; } QueryStatementSplitter(); List<String> split(String input); String getDelimiter(); void setDelimiter(String delimiter); DelimiterType getDelimiterType(); void setDelimiterType(DelimiterType delimiterType); void setOutputLineEnding(LineEnding lineEnding);  }
@Test public void shouldNotSplitStatementsThatHaveNoDelimter() throws Exception { List<String> result = splitter.split("SELECT 1"); assertThat(result, hasItem("SELECT 1")); assertThat(result.size(), is(1)); }
@Test public void shouldIgnoreSemicolonsInTheMiddleOfALine() throws Exception { List<String> result = splitter.split("SELECT ';'"); assertThat(result, hasItem("SELECT ';'")); assertThat(result.size(), is(1)); }
@Test public void shouldSplitStatementsOnASemicolonAtTheEndOfALine() throws Exception { List<String> result = splitter.split("SELECT 1;\nSELECT 2;"); assertThat(result, hasItems("SELECT 1", "SELECT 2")); assertThat(result.size(), is(2)); }
@Test public void shouldSplitStatementsOnASemicolonAtTheEndOfALineEvenWithWindowsLineEndings() throws Exception { List<String> result = splitter.split("SELECT 1;\r\nSELECT 2;"); assertThat(result, hasItems("SELECT 1", "SELECT 2")); assertThat(result.size(), is(2)); }
@Test public void shouldSplitStatementsOnASemicolonAtTheEndOfALineIgnoringWhitespace() throws Exception { List<String> result = splitter.split("SELECT 1; \nSELECT 2; "); assertThat(result, hasItems("SELECT 1", "SELECT 2")); assertThat(result.size(), is(2)); }
@Test public void shouldLeaveLineBreaksAlone() throws Exception { assertThat(splitter.split("SELECT\n1"), hasItems("SELECT" + SystemUtils.LINE_SEPARATOR + "1")); assertThat(splitter.split("SELECT\r\n1"), hasItems("SELECT" + SystemUtils.LINE_SEPARATOR + "1")); }