Skip to content

Commit 2119fea

Browse files
fix: lex // as a line comment only for H2 and Snowflake (#2957)
LINE_COMMENT matched // in every dialect, but only H2 and Snowflake have // comments. Everywhere else //* is a division followed by a block comment, so SELECT 6 //*x*/ 2, (SELECT max(pw) FROM secrets) parsed as SELECT 6 while MySQL, MariaDB, PostgreSQL, SQL Server and SQLite run the subquery. // comments are now a lexer switch like # comments (Feature.allowDoubleSlashLineComments, withDoubleSlashLineComments), turned on by the H2 and SNOWFLAKE presets.
1 parent ba9291f commit 2119fea

7 files changed

Lines changed: 92 additions & 15 deletions

File tree

‎src/main/java/net/sf/jsqlparser/parser/AbstractJSqlParser.java‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,17 @@ public enum Dialect {
4242
Feature.allowSquareBracketQuotation), POSTGRESQL(
4343
AdjacentStringLiterals.NEWLINE,
4444
Feature.allowDollarQuotedStringTags,
45-
Feature.allowDigitSeparators), H2, EXASOL, BIGQUERY(
46-
AdjacentStringLiterals.WHITESPACE,
47-
Feature.allowDoubleQuotedStrings,
48-
Feature.allowHashLineComments,
49-
Feature.allowBackslashEscapeCharacter), DATABRICKS(
45+
Feature.allowDigitSeparators), H2(
46+
Feature.allowDoubleSlashLineComments), EXASOL, BIGQUERY(
5047
AdjacentStringLiterals.WHITESPACE,
5148
Feature.allowDoubleQuotedStrings,
52-
Feature.allowBackslashEscapeCharacter), SNOWFLAKE(
53-
Feature.allowBackslashEscapeCharacter), INFORMIX, SPANNER, DORIS, COCKROACHDB, TERADATA, SQLITE;
49+
Feature.allowHashLineComments,
50+
Feature.allowBackslashEscapeCharacter), DATABRICKS(
51+
AdjacentStringLiterals.WHITESPACE,
52+
Feature.allowDoubleQuotedStrings,
53+
Feature.allowBackslashEscapeCharacter), SNOWFLAKE(
54+
Feature.allowBackslashEscapeCharacter,
55+
Feature.allowDoubleSlashLineComments), INFORMIX, SPANNER, DORIS, COCKROACHDB, TERADATA, SQLITE;
5456

5557
private final Set<Feature> lexerFeatures;
5658
private final AdjacentStringLiterals adjacentStringLiterals;
@@ -197,6 +199,14 @@ public P withHashLineComments(boolean allowHashLineComments) {
197199
return withFeature(Feature.allowHashLineComments, allowHashLineComments);
198200
}
199201

202+
public P withDoubleSlashLineComments() {
203+
return withFeature(Feature.allowDoubleSlashLineComments, true);
204+
}
205+
206+
public P withDoubleSlashLineComments(boolean allowDoubleSlashLineComments) {
207+
return withFeature(Feature.allowDoubleSlashLineComments, allowDoubleSlashLineComments);
208+
}
209+
200210
public P withBlankLinesAsSeparator(boolean allowBlankLinesAsStatementSeparator) {
201211
return withFeature(Feature.allowBlankLinesAsStatementSeparator,
202212
allowBlankLinesAsStatementSeparator);

‎src/main/java/net/sf/jsqlparser/parser/SimpleCharStream.java‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
/* Generated By:JavaCC: Do not edit this line by hand. SimpleCharStream.java Version 8.0.0 */
1111
/*
1212
* Warning: this file is maintained by hand on top of the JavaCC template. Among other manual
13-
* adjustments it carries the in-buffer '#' and blank line rewrites in BeginToken(), which
14-
* Feature.allowHashLineComments and Feature.allowBlankLinesAsStatementSeparator depend on. Never
15-
* overwrite it with a freshly generated SimpleCharStream, that would silently drop the rewrites and
16-
* break both features.
13+
* adjustments it carries the in-buffer '#', '//' and blank line rewrites in BeginToken(), which
14+
* Feature.allowHashLineComments, Feature.allowDoubleSlashLineComments and
15+
* Feature.allowBlankLinesAsStatementSeparator depend on. Never overwrite it with a freshly
16+
* generated SimpleCharStream, that would silently drop the rewrites and break these features.
1717
*/
1818
package net.sf.jsqlparser.parser;
1919

@@ -66,6 +66,10 @@ public class SimpleCharStream {
6666
static final char HASH_SUBSTITUTION = '\u0001';
6767
static final char MYSQL_MINUS_SUBSTITUTION = '\u0002';
6868
static final char MYSQL_COMMENT_ERROR = '\u0003';
69+
// H2 and Snowflake `//` line comments: the same rewrite for the first `/`
70+
// of a token-start `//` under Feature.allowDoubleSlashLineComments. Without
71+
// it no rule matches `//`, so `//*` is a division and a block comment.
72+
static final char DOUBLE_SLASH_SUBSTITUTION = '\u0004';
6973
FeatureConfiguration featureConfiguration;
7074
private boolean mySqlExecutableComment;
7175
String mySqlCommentError;
@@ -241,6 +245,11 @@ public final char BeginToken() throws java.io.IOException {
241245
&& featureConfiguration.getAsBoolean(Feature.allowHashLineComments)) {
242246
buffer[bufpos] = HASH_SUBSTITUTION;
243247
c = HASH_SUBSTITUTION;
248+
} else if (c == '/' && featureConfiguration != null
249+
&& featureConfiguration.getAsBoolean(Feature.allowDoubleSlashLineComments)
250+
&& peekCharacters(1).equals("/")) {
251+
buffer[bufpos] = DOUBLE_SLASH_SUBSTITUTION;
252+
c = DOUBLE_SLASH_SUBSTITUTION;
244253
} else if ((c == '-' || c == '/' || c == '*') && featureConfiguration != null
245254
&& AbstractJSqlParser.Dialect.MYSQL.name()
246255
.equals(featureConfiguration.getValue(Feature.dialect))) {
@@ -526,6 +535,8 @@ public String GetImage() {
526535
image = "#" + image.substring(1);
527536
} else if (!image.isEmpty() && image.charAt(0) == MYSQL_MINUS_SUBSTITUTION) {
528537
image = "-" + image.substring(1);
538+
} else if (!image.isEmpty() && image.charAt(0) == DOUBLE_SLASH_SUBSTITUTION) {
539+
image = "/" + image.substring(1);
529540
}
530541
return image;
531542
}

‎src/main/java/net/sf/jsqlparser/parser/feature/Feature.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,6 +1426,12 @@ public enum Feature {
14261426
*/
14271427
allowHashLineComments(false),
14281428

1429+
/**
1430+
* allows H2 and Snowflake `//` line comments; disabled by default, where `//*` is a division
1431+
* followed by a block comment as in MySQL, PostgreSQL, SQL Server and SQLite
1432+
*/
1433+
allowDoubleSlashLineComments(false),
1434+
14291435
/**
14301436
* treats three consecutive newlines as a statement separator (enabled by default). When
14311437
* disabled, blank lines are plain whitespace, so a statement containing them is parsed whole

‎src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6855,9 +6855,13 @@ TOKEN : /* Numeric Constants */
68556855
| < #HEX_DIGIT: ["0"-"9","A"-"F"] >
68566856
}
68576857

6858+
// `//` starts a line comment only under Feature.allowDoubleSlashLineComments
6859+
// (H2, Snowflake), where the stream rewrites its first `/` to
6860+
// SimpleCharStream.DOUBLE_SLASH_SUBSTITUTION as for `#` below. Elsewhere
6861+
// `//*` is a division followed by a block comment.
68586862
SPECIAL_TOKEN:
68596863
{
6860-
< LINE_COMMENT: ("--" | "//") (~["\r","\n"])*>
6864+
< LINE_COMMENT: ("--" | "\u0004/") (~["\r","\n"])*>
68616865
}
68626866

68636867
// MySQL `#` line comment (#2499), flag-gated. Under

‎src/site/sphinx/usage.rst‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1745,7 +1745,9 @@ One grammar covers every supported RDBMS, but a few pieces of syntax mean differ
17451745
* - ``DATABRICKS``
17461746
- ``withDoubleQuotedStrings``, ``withBackslashEscapeCharacter``, any-whitespace rule for adjacent string literals
17471747
* - ``SNOWFLAKE``
1748-
- ``withBackslashEscapeCharacter`` only, double quotes stay quoted identifiers
1748+
- ``withBackslashEscapeCharacter`` and ``withDoubleSlashLineComments``, double quotes stay quoted identifiers
1749+
* - ``H2``
1750+
- ``withDoubleSlashLineComments``
17491751
* - ``INFORMIX``
17501752
- Informix ``ALTER TABLE ... ADD CONSTRAINT`` definitions with optional trailing constraint names
17511753
* - ``SPANNER``
@@ -2097,6 +2099,8 @@ The individual features
20972099
- ``".."`` reads as a string literal instead of a quoted identifier (BigQuery, Spark/Databricks, MySQL default ``sql_mode``); combined with ``withBackslashEscapeCharacter``, ``\\"`` does not end the literal, as in MySQL ``"it\\"s"``
20982100
* - ``withHashLineComments``
20992101
- ``#`` starts a line comment
2102+
* - ``withDoubleSlashLineComments``
2103+
- ``//`` starts a line comment (H2, Snowflake); otherwise ``//*`` is a division followed by a block comment
21002104
* - ``withBlankLinesAsSeparator``
21012105
- ``false`` stops two empty lines (``\n\n\n``) ending a statement, so they read as plain whitespace
21022106
* - ``withAdjacentStringLiterals``

‎src/test/java/net/sf/jsqlparser/parser/CCJSqlParserUtilTest.java‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,8 @@ public void testNestingDepth() throws Exception {
367367
@Test
368368
public void testParseStatementIssue1250() throws Exception {
369369
Statement result = CCJSqlParserUtil.parse(
370-
"Select test.* from (Select * from sch.PERSON_TABLE // root test\n) as test");
370+
"Select test.* from (Select * from sch.PERSON_TABLE // root test\n) as test",
371+
parser -> parser.withDoubleSlashLineComments());
371372
assertEquals("SELECT test.* FROM (SELECT * FROM sch.PERSON_TABLE) AS test",
372373
result.toString());
373374
}
@@ -668,6 +669,46 @@ public void testHashLineCommentsMySQLStatementSemantics() throws Exception {
668669
CCJSqlParserUtil.parse("SELECT 1 # comment").toString());
669670
}
670671

672+
@Test
673+
public void testDoubleSlashLineCommentsFeature() throws Exception {
674+
// default (flag off): `//*` is a division followed by a block comment, as on MySQL,
675+
// MariaDB, PostgreSQL, SQL Server and SQLite, which all return the subquery here
676+
String sql = "SELECT 6 //*x*/ 2, (SELECT max(pw) FROM secrets)";
677+
assertEquals("SELECT 6 / 2, (SELECT max(pw) FROM secrets)",
678+
CCJSqlParserUtil.parse(sql).toString());
679+
for (AbstractJSqlParser.Dialect dialect : new AbstractJSqlParser.Dialect[] {
680+
AbstractJSqlParser.Dialect.MYSQL, AbstractJSqlParser.Dialect.POSTGRESQL,
681+
AbstractJSqlParser.Dialect.SQLSERVER, AbstractJSqlParser.Dialect.SQLITE}) {
682+
assertEquals("SELECT 6 / 2, (SELECT max(pw) FROM secrets)",
683+
CCJSqlParserUtil.parse(sql, p -> p.withDialect(dialect)).toString());
684+
}
685+
assertEquals(2,
686+
CCJSqlParserUtil.parseStatements("SELECT 1 //**/ 1; DROP TABLE users").size());
687+
assertThrows(JSQLParserException.class,
688+
() -> CCJSqlParserUtil.parse("SELECT 1 // comment"));
689+
690+
// with the flag or the H2 and SNOWFLAKE presets: `//` to the end of the line, `//*`
691+
// included, as H2 and Snowflake read it
692+
for (Consumer<CCJSqlParser> consumer : List.<Consumer<CCJSqlParser>>of(
693+
p -> p.withDoubleSlashLineComments(),
694+
p -> p.withDialect(AbstractJSqlParser.Dialect.H2),
695+
p -> p.withDialect(AbstractJSqlParser.Dialect.SNOWFLAKE))) {
696+
assertEquals("SELECT 6", CCJSqlParserUtil.parse(sql, consumer).toString());
697+
assertEquals("SELECT 1 FROM t",
698+
CCJSqlParserUtil.parse("SELECT 1 // comment\nFROM t", consumer).toString());
699+
assertEquals("SELECT 'a//b'",
700+
CCJSqlParserUtil.parse("SELECT 'a//b'", consumer).toString());
701+
}
702+
assertEquals(List.of("// leading"),
703+
((PlainSelect) CCJSqlParserUtil.parse("// leading\nSELECT 1",
704+
p -> p.withDoubleSlashLineComments())).getLeadingComments());
705+
// an explicit switch after the preset wins
706+
assertEquals("SELECT 6 / 2", CCJSqlParserUtil.parse("SELECT 6 //*x*/ 2",
707+
p -> p.withDialect(AbstractJSqlParser.Dialect.H2)
708+
.withDoubleSlashLineComments(false))
709+
.toString());
710+
}
711+
671712
@Test
672713
public void testDialectPresets() throws Exception {
673714
// MYSQL and MARIADB: backslash escapes and # line comments (MySQL 8

‎src/test/java/net/sf/jsqlparser/parser/LeadingCommentsTest.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ public void lineCommentsExcludeLineTerminators(String lineTerminator)
4242
@Test
4343
public void mixedCommentsRetainExactImagesAndSourceOrder() throws JSQLParserException {
4444
Select select = (Select) CCJSqlParserUtil
45-
.parse("/* a */ -- b\r\n// c\r/* d */ SELECT 1");
45+
.parse("/* a */ -- b\r\n// c\r/* d */ SELECT 1",
46+
parser -> parser.withDoubleSlashLineComments());
4647
assertEquals(List.of("/* a */", "-- b", "// c", "/* d */"), select.getLeadingComments());
4748
}
4849

0 commit comments

Comments
 (0)