Extend SimpleSQLParser to support more SQL, add tests

This commit is contained in:
Travis Burtrum 2020-03-31 21:26:37 -04:00
parent c327f24e02
commit aac0f30e8a
2 changed files with 25 additions and 4 deletions

View File

@ -1,5 +1,6 @@
package com.moparisthebest.jdbc.codegen;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@ -9,6 +10,7 @@ public class SimpleSQLParser extends AbstractSQLParser {
private static final Pattern aliasPattern = Pattern.compile("^.*\\.");
private static final Pattern parenPattern = Pattern.compile("\\([^)]+\\)");
private static final Pattern fromPattern = Pattern.compile("\\s+FROM\\s+");
public SimpleSQLParser() {
super(null, false);
@ -30,7 +32,9 @@ public class SimpleSQLParser extends AbstractSQLParser {
// (SELECT some_column from some_table where other_column = 'YAY') as tom -> () as tom
sql = parenPattern.matcher(sql).replaceAll("()").trim();
// 6 is length of "SELECT" which we already verified it starts with...
final String columns = sql.substring(6, sql.indexOf("FROM"));
final Matcher fromMatcher = fromPattern.matcher(sql);
// is a SELECT without a FROM valid? I guess maybe...
final String columns = sql.substring(6, fromMatcher.find() ? fromMatcher.start() : sql.length());
final String[] splitColumns = columns.split(",");
columnNames = new String[splitColumns.length + 1];
int index = 0;

View File

@ -17,9 +17,26 @@ public class SimpleSQLParserTest {
@Test
public void testSingleSelect() {
final SQLParser ret = getFactory().parse("select bob from tom");
assertTrue(ret.isSelect());
assertArrayEquals(new String[]{null, "BOB"}, ret.columnNames());
{
final SQLParser ret = getFactory().parse("select bob from tom");
assertTrue(ret.isSelect());
assertArrayEquals(new String[]{null, "BOB"}, ret.columnNames());
}
{
final SQLParser ret = getFactory().parse("select bob_from from tom");
assertTrue(ret.isSelect());
assertArrayEquals(new String[]{null, "BOB_FROM"}, ret.columnNames());
}
{
final SQLParser ret = getFactory().parse("select from_bob from tom");
assertTrue(ret.isSelect());
assertArrayEquals(new String[]{null, "FROM_BOB"}, ret.columnNames());
}
{
final SQLParser ret = getFactory().parse("select something_from_bob from tom");
assertTrue(ret.isSelect());
assertArrayEquals(new String[]{null, "SOMETHING_FROM_BOB"}, ret.columnNames());
}
}
@Test