Skip to content

Commit

Permalink
Merge branch feature/remove_sql_comments into develop
Browse files Browse the repository at this point in the history
        Title: 移除sql前后的注释,从而支持多set单query的执行 
        Link: https://code.alibaba-inc.com/odps/odps-jdbc/codereview/12205311
  • Loading branch information
zhenhong.gzh committed Apr 3, 2023
2 parents 024727d + 85f629f commit a245cfb
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/main/java/com/aliyun/odps/jdbc/utils/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ public static String parseSetting(String sql, Properties properties) {
throw new IllegalArgumentException("Invalid query :" + sql);
}

sql = sql.trim();
//移除comments
sql = removeComments(sql);
if (!sql.endsWith(";")) {
sql += ";";
}
Expand Down Expand Up @@ -158,4 +159,31 @@ public static String parseSetting(String sql, Properties properties) {
return sql.substring(index).trim();
}
}

private static String removeComments(String sql) {
String[] sqlArray = sql.trim().split(";");

StringBuilder sb = new StringBuilder();
for (String s : sqlArray) {
int index;
boolean isComments = false;
s = s.trim();

while (!StringUtils.isEmpty(s) && s.startsWith("--")) {
index = s.indexOf("\n");
if (index == -1) {
isComments = true;
break;
}
s = s.substring(index + 1).trim();
}

if (!isComments) {
sb.append(s).append(";");
}
}
return sb.toString();
}


}
20 changes: 20 additions & 0 deletions src/test/java/com/aliyun/odps/jdbc/utils/UtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,24 @@ public void testParseSetting() {
Assert.assertTrue(properties.isEmpty());
}
}

@Test
public void testParseSettingWithComments() {
String comment1 = "-- I am Comment1;\n";
String comment2 = "-- I am Comment2\n";
String setting1 = "set 1= 1;\n";
String setting2 = "set 2=2;";
String query = "select 1;";

String sql = comment1 + comment2 + setting1 + comment1 + setting2 + comment2 + query;

Properties properties = new Properties();
String res = Utils.parseSetting(sql, properties);

Assert.assertEquals(query, res);
Assert.assertEquals(properties.size(), 2);
Assert.assertEquals(properties.getProperty("1"), "1");
Assert.assertEquals(properties.getProperty("2"), "2");
}

}

0 comments on commit a245cfb

Please sign in to comment.