/**
* 功能描述: sql字段解析器测试
**/
public class SimpleSqlFieldParserTest {
@Test
public void testParse() {
String sql;
List<SelectFieldClauseDescriptor> parsedFieldList;
sql = "select COALESCE(t1.xno, t2.xno, t3.xno) as xno,\n" +
" case when t1.xno is not null then 1 else null end as xxk001,\n" +
" case when t2.xno is not null then 1 else null end as xxk200,\n" +
" case when t3.xno is not null then 1 else null end as xx3200\n" +
" from xxk001 t1\n" +
" full join xxkj100 t2 on t1.xno = t2.xno\n" +
" full join xxkj200 t3 on t1.xno = t3.xno;";
parsedFieldList = SimpleSqlFieldParser.parse(sql);
System.out.println("result:");
parsedFieldList.forEach(System.out::println);
Assert.assertEquals("字段个数解析不正确",
4, parsedFieldList.size());
Assert.assertEquals("字段别名解析不正确",
"xno", parsedFieldList.get(0).getAlias());
Assert.assertEquals("字段别名解析不正确",
"xx3200", parsedFieldList.get(3).getAlias());
sql = "select cast(a as string) as b from ccc;";
parsedFieldList = SimpleSqlFieldParser.parse(sql);
System.out.println("result:");
parsedFieldList.forEach(System.out::println);
Assert.assertEquals("字段个数解析不正确",
1, parsedFieldList.size());
Assert.assertEquals("字段别名解析不正确",
"b", parsedFieldList.get(0).getAlias());
sql = "with a as(select cus,x1 from b1), b as (select cus,x2 from b2)\n" +
" select a.cus as a_cus, cast(a \nas string) as a_cus2, " +
"b.x2 b2 from a join b on a.cus=b.cus where xxx;";
parsedFieldList = SimpleSqlFieldParser.parse(sql);
System.out.println("result:");
parsedFieldList.forEach(System.out::println);
Assert.assertEquals("字段个数解析不正确",
3, parsedFieldList.size());
Assert.assertEquals("字段别名解析不正确",
"a_cus", parsedFieldList.get(0).getAlias());
Assert.assertEquals("字段别名解析不正确",
"b2", parsedFieldList.get(2).getAlias());
sql = "select a.xno,b.xx,qqq from a_tb as a join b_tb as b on a.id = b.id";
parsedFieldList = SimpleSqlFieldParser.parse(sql);
System.out.println("result:");
parsedFieldList.forEach(System.out::println);
Assert.assertEquals("字段个数解析不正确",
3, parsedFieldList.size());
Assert.assertEquals("字段别名解析不正确",
"xno", parsedFieldList.get(0).getAlias());
Assert.assertEquals("字段别名解析不正确",
"qqq", parsedFieldList.get(2).getAlias());
sql = "select cast (a.a_int as string) a_str, b.xx, coalesce \n( a, b, c) qqq from a_tb as a join b_tb as b on a.id = b.id";
parsedFieldList = SimpleSqlFieldParser.parse(sql);
System.out.println("result:");
parsedFieldList.forEach(System.out::println);
Assert.assertEquals("字段个数解析不正确",
3, parsedFieldList.size());
Assert.assertEquals("字段别名解析不正确",
"a_str", parsedFieldList.get(0).getAlias());
Assert.assertEquals("字段原始名解析不正确",
"cast (a.a_int as string)", parsedFieldList.get(0).getFieldName());
Assert.assertEquals("字段别名解析不正确",
"qqq", parsedFieldList.get(2).getAlias());
Assert.assertEquals("字段原始名解析不正确",
"coalesce \n( a, b, c)", parsedFieldList.get(2).getFieldName());
}
}