diff --git a/src/main/java/com/aliyun/odps/jdbc/utils/Utils.java b/src/main/java/com/aliyun/odps/jdbc/utils/Utils.java index 807d9466..8eb823f6 100644 --- a/src/main/java/com/aliyun/odps/jdbc/utils/Utils.java +++ b/src/main/java/com/aliyun/odps/jdbc/utils/Utils.java @@ -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 += ";"; } @@ -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(); + } + + } diff --git a/src/test/java/com/aliyun/odps/jdbc/utils/UtilsTest.java b/src/test/java/com/aliyun/odps/jdbc/utils/UtilsTest.java index 4704b543..03728f2a 100644 --- a/src/test/java/com/aliyun/odps/jdbc/utils/UtilsTest.java +++ b/src/test/java/com/aliyun/odps/jdbc/utils/UtilsTest.java @@ -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"); + } + }