Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 106 additions & 11 deletions src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,12 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
return result;
}

/** Whether the token can name a function: an identifier or a non-reserved keyword. */
private static boolean isFunctionNameToken(Token t) {
return t.kind == S_IDENTIFIER || t.kind == S_QUOTED_IDENTIFIER
|| t.kind >= MIN_NON_RESERVED_WORD && t.kind <= MAX_NON_RESERVED_WORD;
}

// True when a fresh evaluation started at this token would pass all
// first-token guards and run the same chain walk.
private boolean isFunctionAheadChainStartEligible(Token t) {
Expand All @@ -996,8 +1002,9 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
return getToken(2).kind == K_FN ? 1 : 0;
}

// Optional APPROXIMATE keyword
if (t.kind == K_APPROXIMATE) {
// Optional APPROXIMATE keyword, only before a function name: approximate IN (1, 2)
// compares a column named approximate, and approximate(x) calls a function of that name
if (t.kind == K_APPROXIMATE && isFunctionNameToken(getToken(2))) {
t = getToken(2);
}

Expand Down Expand Up @@ -2072,6 +2079,11 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
return false;
}

// A keyword the dialect does not reserve, after a word that DDL follows with a name
if (DialectKeywordNames.isNameAfter(getAsString(Feature.dialect), prev, getToken(1).kind)) {
return true;
}

// ── 2. After delimiters and operators: expression position ─────
// With K_FROM/K_SELECT removed from RelObjectName's
// token list, accepting all remaining keywords after these
Expand Down Expand Up @@ -4674,13 +4686,37 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {

/**
* Whether the keyword belongs only to clauses of other dialects and the selected dialect does
* not know it as a keyword at all, so it is a plain identifier there. MySQL 8.4 and
* PostgreSQL 18 have no PIVOT, MINUS, OUTPUT or SEMI JOIN, MySQL no ILIKE, and PostgreSQL
* neither XOR, QUALIFY nor MySQL's select modifiers. Without a dialect they stay reserved.
* not know it as a keyword at all, so it is a plain identifier there. Without a dialect it
* stays reserved.
*/
private boolean isDialectIdentifierKeyword(int kind) {
String dialect = getAsString(Feature.dialect);
if (Dialect.MYSQL.name().equals(dialect)) {
return DialectKeywordNames.isIdentifier(getAsString(Feature.dialect), kind);
}

/**
* The reserved keywords of this parser that MySQL 8.4 or PostgreSQL 18 reads as names. A nested
* class keeps these lists out of CCJSqlParser.class, whose constant pool is close to what JaCoCo
* can still instrument.
*/
private static final class DialectKeywordNames {
private DialectKeywordNames() {}

/**
* Whether the keyword is a name wherever the dialect takes one. MySQL 8.4 and PostgreSQL 18
* have no PIVOT, MINUS, OUTPUT or SEMI JOIN, MySQL no ILIKE, and PostgreSQL neither XOR,
* QUALIFY nor MySQL's select modifiers.
*/
static boolean isIdentifier(String dialect, int kind) {
if (Dialect.MYSQL.name().equals(dialect)) {
return isMySqlIdentifier(kind);
}
if (Dialect.POSTGRESQL.name().equals(dialect)) {
return isPostgreSqlIdentifier(kind);
}
return false;
}

private static boolean isMySqlIdentifier(int kind) {
switch (kind) {
case K_CONNECT_BY_ROOT: case K_EXCLUDES: case K_FINAL: case K_ILIKE:
case K_INCLUDES: case K_MINUS: case K_NOCYCLE: case K_OUTPUT: case K_PIVOT:
Expand All @@ -4690,7 +4726,8 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
return false;
}
}
if (Dialect.POSTGRESQL.name().equals(dialect)) {

private static boolean isPostgreSqlIdentifier(int kind) {
switch (kind) {
case K_CONNECT_BY_ROOT: case K_DISTINCTROW: case K_EXCLUDES: case K_FINAL:
case K_INCLUDES: case K_MINUS: case K_NOCYCLE: case K_OUTPUT: case K_PIVOT:
Expand All @@ -4702,7 +4739,56 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
return false;
}
}
return false;

/**
* Whether the keyword is a name right after a word that DDL always follows with a name,
* although elsewhere it starts a clause or an operator. MySQL does not reserve OFFSET,
* ONLY, RETURNING, ANY, SOME and VALUE, as in ADD COLUMN c INT AFTER offset or
* KEY any (a), and PostgreSQL does not reserve SET and takes BETWEEN, IF, GROUPING and
* VALUES as names there, as in ADD set INT or REFERENCES if (b).
*/
static boolean isNameAfter(String dialect, Token previous, int kind) {
if (Dialect.MYSQL.name().equals(dialect)) {
switch (kind) {
case K_OFFSET: case K_ONLY: case K_RETURNING:
case K_ANY: case K_SOME: case K_VALUE:
return isMySqlNameIntroducer(previous);
default:
return false;
}
}
if (Dialect.POSTGRESQL.name().equals(dialect)) {
if (kind == K_SET || kind == K_BETWEEN) {
return isPostgreSqlNameIntroducer(previous);
}
return (kind == K_IF || kind == K_GROUPING || kind == K_VALUES)
&& previous.kind == K_REFERENCES;
}
return false;
}

private static boolean isMySqlNameIntroducer(Token previous) {
switch (previous.kind) {
case K_ADD: case K_ALTER: case K_DROP: case K_MODIFY: case K_TO: case K_INDEX:
case K_KEY: case K_REFERENCES: case K_DATABASE: case K_SCHEMA: case K_VIEW:
case K_TRIGGER: case K_PARTITION:
return true;
default:
return "AFTER".equalsIgnoreCase(previous.image);
}
}

private static boolean isPostgreSqlNameIntroducer(Token previous) {
switch (previous.kind) {
case K_ADD: case K_ALTER: case K_DROP: case K_TO: case K_INDEX: case K_PARTITION:
case K_SCHEMA: case K_SEQUENCE: case K_VIEW: case K_TRIGGER: case K_REFERENCES:
case K_AUTHORIZATION:
return true;
default:
return "INHERIT".equalsIgnoreCase(previous.image)
|| "ATTRIBUTE".equalsIgnoreCase(previous.image);
}
}
}

/** MySQL's EXPLAIN, PREPARE, EXECUTE, DROP PREPARE and DO: MySQL, MariaDB or no dialect. */
Expand Down Expand Up @@ -17672,8 +17758,11 @@ Expression PrimaryExpression() #PrimaryExpression:

| LOOKAHEAD(2, {!interrupted}) retval= CastExpression()

// RUNNING and FINAL start a row pattern function only before a function name, so
// running IN (1, 2) compares a column named running
| LOOKAHEAD({ !interrupted && (isKeywordAhead("RUNNING") || getToken(1).kind == K_FINAL)
&& getToken(3).kind == OPENING_BRACKET }) retval=RowPatternFunction()
&& isFunctionNameToken(getToken(2)) && getToken(3).kind == OPENING_BRACKET })
retval=RowPatternFunction()

| LOOKAHEAD({ !interrupted && isFunctionAhead() })
retval = Function() [ LOOKAHEAD(2) retval = AnalyticExpression( (Function) retval ) ]
Expand Down Expand Up @@ -19877,7 +19966,13 @@ Function InternalFunction(boolean escaped):
ColDataType castType = null;
}
{
[ LOOKAHEAD(2) prefixToken = <K_APPROXIMATE> ]
// A choice rather than [ ... ], so that the check also holds while scanning ahead
(
LOOKAHEAD({ getToken(1).kind == K_APPROXIMATE && isFunctionNameToken(getToken(2)) })
prefixToken = <K_APPROXIMATE>
|
{}
)
funcName = RelObjectNames() { if (prefixToken!=null) funcName.getNames().add(0, prefixToken.image ); retval.setName(funcName.getNames()); }

"(" { consumeXmlLeadingKeyword(retval); }
Expand Down
117 changes: 117 additions & 0 deletions src/test/java/net/sf/jsqlparser/statement/KeywordsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import net.sf.jsqlparser.expression.JsonFunction;
import net.sf.jsqlparser.expression.TernaryExpression;
import net.sf.jsqlparser.expression.Function;
import net.sf.jsqlparser.expression.RowPatternFunction;
import net.sf.jsqlparser.expression.WindowElement;
import net.sf.jsqlparser.expression.WindowOffset;
import net.sf.jsqlparser.expression.XMLSerializeExpr;
Expand Down Expand Up @@ -54,6 +55,7 @@
import net.sf.jsqlparser.statement.select.SetOperationList;
import net.sf.jsqlparser.statement.select.SampleClause;
import net.sf.jsqlparser.statement.select.WithItem;
import net.sf.jsqlparser.statement.truncate.Truncate;
import net.sf.jsqlparser.util.TablesNamesFinder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
Expand Down Expand Up @@ -784,4 +786,119 @@ void testOtherDialectKeywordsKeepTheirClausesWithoutTheDialect() throws JSQLPars
assertEquals("xor", ((PlainSelect) assertRoundTrip("SELECT a xor FROM t",
Dialect.POSTGRESQL)).getSelectItem(0).getAlias().getName());
}

// MySQL does not reserve OFFSET, ONLY and RETURNING, and ANY, SOME and VALUE are its index and
// referenced table names; PostgreSQL does not reserve SET, and takes BETWEEN, IF, GROUPING and
// VALUES as these names too.
public static Stream<Arguments> dialectNamePositions() {
Stream<Arguments> mySqlClauseWords = Stream.of("offset", "only", "returning")
.flatMap(word -> Stream.of("ALTER TABLE t ADD COLUMN c INT AFTER " + word,
"ALTER TABLE t DROP " + word, "ALTER TABLE t ADD " + word + " INT",
"ALTER TABLE t MODIFY " + word + " INT NOT NULL",
"ALTER TABLE t ALTER " + word + " DROP DEFAULT",
"ALTER TABLE t RENAME COLUMN c TO " + word,
"ALTER TABLE t RENAME TO " + word,
"ALTER TABLE t ADD INDEX " + word + " (a)",
"ALTER TABLE t RENAME INDEX " + word + " TO ix",
"CREATE INDEX " + word + " ON t (a)",
"CREATE VIEW " + word + " AS SELECT 1"))
.map(sql -> Arguments.of(sql, Dialect.MYSQL));
Stream<Arguments> mySqlIndexWords = Stream.of("any", "some", "value")
.flatMap(word -> Stream.of("CREATE TABLE t (a INT, KEY " + word + " (a))",
"ALTER TABLE t ADD UNIQUE INDEX " + word + " (a)",
"ALTER TABLE t ADD FOREIGN KEY " + word + " (a) REFERENCES p (b)",
"ALTER TABLE t ADD FOREIGN KEY (a) REFERENCES " + word + " (b)"))
.map(sql -> Arguments.of(sql, Dialect.MYSQL));
Stream<Arguments> postgreSqlWords = Stream.of("set", "between")
.flatMap(word -> Stream.of("ALTER TABLE t ADD " + word + " INT",
"ALTER TABLE t ALTER " + word + " TYPE BIGINT",
"ALTER TABLE t DROP " + word,
"ALTER TABLE t RENAME COLUMN c TO " + word,
"ALTER INDEX " + word + " RENAME TO ix",
"CREATE INDEX " + word + " ON t (a)",
"DROP INDEX " + word, "ALTER TABLE t SET SCHEMA " + word,
"CREATE SEQUENCE " + word, "CREATE VIEW " + word + " AS SELECT 1",
"ALTER TABLE t ATTACH PARTITION " + word + " FOR VALUES IN (1)",
"ALTER TABLE t OWNER TO " + word))
.map(sql -> Arguments.of(sql, Dialect.POSTGRESQL));
Stream<Arguments> postgreSqlReferences = Stream.of("set", "between", "if", "grouping",
"values")
.map(word -> Arguments.of(
"ALTER TABLE t ADD CONSTRAINT fk FOREIGN KEY (a) REFERENCES " + word
+ " (b)",
Dialect.POSTGRESQL));
return Stream.of(mySqlClauseWords, mySqlIndexWords, postgreSqlWords, postgreSqlReferences)
.flatMap(stream -> stream);
}

@ParameterizedTest(name = "{1}: {0}")
@MethodSource("dialectNamePositions")
void testDialectNonReservedKeywordAsName(String sql, Dialect dialect)
throws JSQLParserException {
assertRoundTrip(sql, dialect);
}

@Test
void testDialectNonReservedKeywordsKeepTheirClauses() throws JSQLParserException {
assertRoundTrip("SELECT a FROM t LIMIT 10 OFFSET 5", Dialect.MYSQL);
assertRoundTrip("START TRANSACTION READ ONLY", Dialect.MYSQL);
assertRoundTrip("SELECT JSON_VALUE(j, '$.a' RETURNING DECIMAL (10, 2)) FROM t",
Dialect.MYSQL);
assertRoundTrip("SELECT * FROM t WHERE a = ANY (SELECT b FROM u)", Dialect.MYSQL);
assertRoundTrip("INSERT INTO t VALUES (1)", Dialect.MYSQL);

assertRoundTrip("UPDATE t SET a = 1", Dialect.POSTGRESQL);
assertRoundTrip("SELECT * FROM t WHERE a BETWEEN 1 AND 2", Dialect.POSTGRESQL);
assertRoundTrip("CREATE INDEX ON t (a)", Dialect.POSTGRESQL);
assertRoundTrip("CREATE INDEX IF NOT EXISTS i ON t (a)", Dialect.POSTGRESQL);
assertRoundTrip("DROP INDEX IF EXISTS i", Dialect.POSTGRESQL);
assertRoundTrip("ALTER TYPE ty ADD VALUE 'x'", Dialect.POSTGRESQL);
assertRoundTrip("ALTER TABLE t ALTER COLUMN c SET DEFAULT 1", Dialect.POSTGRESQL);

// PostgreSQL's ONLY prefix
assertTrue(((Alter) assertRoundTrip("ALTER TABLE ONLY t ADD COLUMN c INT",
Dialect.POSTGRESQL)).isUseOnly());
assertTrue(((Truncate) assertRoundTrip("TRUNCATE ONLY t", Dialect.POSTGRESQL))
.isOnly());
}

// RUNNING, FINAL and APPROXIMATE start a function call only before a function name.
public static Stream<Arguments> functionPrefixWordsAsNames() {
return Stream.of(Arguments.of("running", null), Arguments.of("running", Dialect.MYSQL),
Arguments.of("running", Dialect.POSTGRESQL), Arguments.of("approximate", null),
Arguments.of("approximate", Dialect.MYSQL),
Arguments.of("approximate", Dialect.POSTGRESQL),
Arguments.of("final", Dialect.MYSQL), Arguments.of("final", Dialect.POSTGRESQL));
}

@ParameterizedTest(name = "{1} {0}")
@MethodSource("functionPrefixWordsAsNames")
void testFunctionPrefixWordBeforeParenthesis(String word, Dialect dialect)
throws JSQLParserException {
PlainSelect select = (PlainSelect) assertRoundTrip(
"SELECT * FROM t WHERE " + word + " IN (1, 2)", dialect);
assertEquals(word, assertInstanceOf(Column.class,
assertInstanceOf(InExpression.class, select.getWhere()).getLeftExpression())
.getColumnName());
assertRoundTrip("SELECT * FROM t WHERE " + word + " LIKE ('a%')", dialect);
assertRoundTrip("SELECT " + word + " = (1) FROM t", dialect);
assertRoundTrip("CREATE TABLE t (" + word + " INT, CHECK (" + word + " IN (1, 2)))",
dialect);
}

@Test
void testFunctionPrefixWordsKeepTheirFunctionCalls() throws JSQLParserException {
assertRoundTrip("CREATE TABLE t (running INT) PARTITION BY RANGE (running)"
+ " (PARTITION p0 VALUES LESS THAN (10))", Dialect.MYSQL);
assertEquals("approximate", assertInstanceOf(Function.class, ((PlainSelect) assertRoundTrip(
"SELECT approximate(x) FROM t", null)).getSelectItem(0).getExpression()).getName());
assertInstanceOf(Function.class, ((PlainSelect) assertRoundTrip(
"SELECT APPROXIMATE COUNT(DISTINCT a) FROM t", null)).getSelectItem(0)
.getExpression());
assertSqlCanBeParsedAndDeparsed("SELECT * FROM t MATCH_RECOGNIZE (ORDER BY a"
+ " MEASURES FINAL COUNT(*) AS c, RUNNING LAST(a) AS l PATTERN (x+)"
+ " DEFINE x AS a > 0)", true);
assertInstanceOf(RowPatternFunction.class,
CCJSqlParserUtil.parseExpression("FINAL COUNT(*)"));
}
}
Loading