Skip to content

Commit 1038c30

Browse files
authored
fix: read KEY, INDEX, EXCLUDE and OPTIONS as names where their element does not follow (#2970)
Signed-off-by: minleejae <mmj9808@gmail.com>
1 parent 78b33b1 commit 1038c30

2 files changed

Lines changed: 176 additions & 6 deletions

File tree

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

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3955,6 +3955,12 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
39553955
|| "VALID".equalsIgnoreCase(getToken(offset + 1).image));
39563956
}
39573957

3958+
/** Whether OPTIONS and its parenthesized list start at the given token. */
3959+
private boolean isForeignDataOptionsAt(int offset) {
3960+
return "OPTIONS".equalsIgnoreCase(getToken(offset).image)
3961+
&& getToken(offset + 1).kind == OPENING_BRACKET;
3962+
}
3963+
39583964
/** EXCLUDE starts an exclusion constraint only before USING, its elements or WHERE. */
39593965
private boolean isExcludeConstraintAhead() {
39603966
int next = getToken(2).kind;
@@ -4042,11 +4048,37 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
40424048
switch (getToken(1).kind) {
40434049
case K_PRIMARY:
40444050
case K_UNIQUE:
4051+
return true;
4052+
// PostgreSQL has no inline index definition, so these words name a column there
40454053
case K_INDEX:
40464054
case K_KEY:
40474055
case K_FULLTEXT:
40484056
case K_SPATIAL:
4057+
return !isPostgreSqlDialect();
4058+
default:
4059+
return false;
4060+
}
4061+
}
4062+
4063+
/**
4064+
* Whether the word after CONSTRAINT is the constraint's name although it could start a
4065+
* constraint itself, as KEY in PostgreSQL's CONSTRAINT key UNIQUE (a): the constraint kind
4066+
* follows the word.
4067+
*/
4068+
private boolean isConstraintNameBeforeKindAhead() {
4069+
int kind = getToken(1).kind;
4070+
// PRIMARY is reserved in MySQL and PostgreSQL, and MySQL reserves the index words too
4071+
if (!isIdentifierishNameToken(getToken(1)) || kind == K_PRIMARY || isMySqlDialect()
4072+
&& (kind == K_KEY || kind == K_INDEX || kind == K_FULLTEXT || kind == K_SPATIAL)) {
4073+
return false;
4074+
}
4075+
switch (getToken(2).kind) {
4076+
case K_PRIMARY:
4077+
return getToken(3).kind == K_KEY;
4078+
case K_UNIQUE: case K_FOREIGN: case K_CHECK: case K_EXCLUDE:
40494079
return true;
4080+
case K_NOT:
4081+
return getToken(3).kind == K_NULL;
40504082
default:
40514083
return false;
40524084
}
@@ -22954,8 +22986,9 @@ TableElement TableConstraint(boolean createContext):
2295422986
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext)
2295522987
|
2295622988
<K_CONSTRAINT>
22957-
[ LOOKAHEAD({ !isTableIndexAhead() && getToken(1).kind != K_FOREIGN
22958-
&& getToken(1).kind != K_CHECK && getToken(1).kind != K_EXCLUDE
22989+
[ LOOKAHEAD({ isConstraintNameBeforeKindAhead() || !isTableIndexAhead()
22990+
&& getToken(1).kind != K_FOREIGN && getToken(1).kind != K_CHECK
22991+
&& getToken(1).kind != K_EXCLUDE
2295922992
&& !(getToken(1).kind == K_NOT && getToken(2).kind == K_NULL) }) constraintName=RelObjectName() ]
2296022993
(
2296122994
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext) {
@@ -26848,8 +26881,9 @@ AlterExpression AlterExpressionAddAlterModify():
2684826881
alterExp.setConstraint(constraint);
2684926882
}
2685026883
|
26884+
// MySQL's ALTER INDEX name {VISIBLE | INVISIBLE}; PostgreSQL's ALTER index alters a column
2685126885
LOOKAHEAD({ alterExp.getOperation() == AlterOperation.ALTER
26852-
&& getToken(1).kind == K_INDEX })
26886+
&& getToken(1).kind == K_INDEX && !isPostgreSqlDialect() })
2685326887
tk=<K_INDEX> sk3=RelObjectName() TableIndexOptions(false, indexSpec) {
2685426888
index = new Index().withIndexKeyword(tk.image).withName(sk3)
2685526889
.withKind(Index.Kind.INDEX).withSpecOptions(indexSpec);
@@ -26876,7 +26910,7 @@ AlterExpression AlterExpressionAddAlterModify():
2687626910
|| Dialect.MYSQL.name().equals(getAsString(Feature.dialect)))
2687726911
&& (getToken(1).kind == K_CONSTRAINT || getToken(1).kind == K_PRIMARY
2687826912
|| getToken(1).kind == K_UNIQUE || getToken(1).kind == K_FOREIGN
26879-
|| getToken(1).kind == K_CHECK || getToken(1).kind == K_EXCLUDE
26913+
|| getToken(1).kind == K_CHECK || isExcludeConstraintAhead()
2688026914
|| getToken(1).kind == K_NOT
2688126915
&& Dialect.POSTGRESQL.name().equals(getAsString(Feature.dialect)))
2688226916
|| AlterConstraintLookahead.needsSharedTableConstraint(getToken(1), token_source)
@@ -27186,8 +27220,10 @@ AlterExpression AlterExpression():
2718627220
{
2718727221

2718827222
(
27189-
LOOKAHEAD({ isKeywordAhead("OPTIONS") || getToken(1).kind == K_ALTER
27190-
&& "OPTIONS".equalsIgnoreCase(getToken(getToken(2).kind == K_COLUMN ? 4 : 3).image) })
27223+
// OPTIONS takes a parenthesized list; otherwise it names an index or a constraint, as in
27224+
// ALTER INDEX options INVISIBLE
27225+
LOOKAHEAD({ isKeywordAhead("OPTIONS") && getToken(2).kind == OPENING_BRACKET
27226+
|| getToken(1).kind == K_ALTER && isForeignDataOptionsAt(getToken(2).kind == K_COLUMN ? 4 : 3) })
2719127227
alterExp=AlterForeignDataOptions()
2719227228
|
2719327229
LOOKAHEAD({ isAlterValidationModifierAhead() }) validationMode=AlterValidationMode()
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/*-
2+
* #%L
3+
* JSQLParser library
4+
* %%
5+
* Copyright (C) 2004 - 2026 JSQLParser
6+
* %%
7+
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
8+
* #L%
9+
*/
10+
package net.sf.jsqlparser.statement;
11+
12+
import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed;
13+
import static org.junit.jupiter.api.Assertions.assertEquals;
14+
import static org.junit.jupiter.api.Assertions.assertNull;
15+
import static org.junit.jupiter.api.Assertions.assertThrows;
16+
17+
import java.util.stream.Stream;
18+
import net.sf.jsqlparser.JSQLParserException;
19+
import net.sf.jsqlparser.parser.AbstractJSqlParser.Dialect;
20+
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
21+
import net.sf.jsqlparser.statement.alter.Alter;
22+
import net.sf.jsqlparser.statement.alter.AlterExpression;
23+
import net.sf.jsqlparser.statement.create.table.CreateTable;
24+
import org.junit.jupiter.api.Test;
25+
import org.junit.jupiter.params.ParameterizedTest;
26+
import org.junit.jupiter.params.provider.Arguments;
27+
import org.junit.jupiter.params.provider.MethodSource;
28+
import org.junit.jupiter.params.provider.ValueSource;
29+
30+
/**
31+
* Words that may start a table element or an ALTER action, but name a column, a constraint, an
32+
* index or a check where that element or action does not follow.
33+
*/
34+
public class ContextualKeywordNamesTest {
35+
36+
private static Statement parse(String sql, Dialect dialect) throws JSQLParserException {
37+
return assertSqlCanBeParsedAndDeparsed(sql, true, parser -> {
38+
if (dialect != null) {
39+
parser.withDialect(dialect);
40+
}
41+
});
42+
}
43+
44+
private static AlterExpression alterExpression(String sql, Dialect dialect)
45+
throws JSQLParserException {
46+
return ((Alter) parse(sql, dialect)).getAlterExpressions().get(0);
47+
}
48+
49+
// PostgreSQL has no inline index definition: KEY, INDEX, FULLTEXT and SPATIAL name columns.
50+
@ParameterizedTest
51+
@ValueSource(strings = {"key", "index", "fulltext", "spatial"})
52+
void testPostgreSqlIndexWordsAsColumns(String word) throws JSQLParserException {
53+
CreateTable createTable = (CreateTable) parse(
54+
"CREATE TABLE kv (id INT, " + word + " VARCHAR (10) NOT NULL)", Dialect.POSTGRESQL);
55+
assertEquals(word, createTable.getColumnDefinitions().get(1).getColumnName());
56+
assertEquals(2, createTable.getTableElements().size());
57+
58+
assertEquals(word,
59+
alterExpression("ALTER TABLE kv ADD " + word + " INT", Dialect.POSTGRESQL)
60+
.getColDataTypeList().get(0).getColumnName());
61+
assertEquals(word, alterExpression("ALTER TABLE kv ALTER " + word + " TYPE BIGINT",
62+
Dialect.POSTGRESQL).getColDataTypeList().get(0).getColumnName());
63+
}
64+
65+
@Test
66+
void testMySqlIndexDefinitionsStay() throws JSQLParserException {
67+
CreateTable createTable = (CreateTable) parse("CREATE TABLE t (a INT, KEY k (a),"
68+
+ " CONSTRAINT UNIQUE KEY u (a), CONSTRAINT PRIMARY KEY (a))", Dialect.MYSQL);
69+
assertEquals("k", createTable.getIndexes().get(0).getName());
70+
assertEquals(2, createTable.getTableConstraints().size());
71+
assertNull(createTable.getTableConstraints().get(1).getName());
72+
assertEquals("k", alterExpression("ALTER TABLE t ADD INDEX k (a)", Dialect.MYSQL).getIndex()
73+
.getName());
74+
assertEquals("k", alterExpression("ALTER TABLE t ALTER INDEX k INVISIBLE", Dialect.MYSQL)
75+
.getIndex().getName());
76+
// MySQL reserves KEY, so it cannot name a column there
77+
assertThrows(JSQLParserException.class, () -> CCJSqlParserUtil.parse(
78+
"ALTER TABLE t ADD key INT", parser -> parser.withDialect(Dialect.MYSQL)));
79+
}
80+
81+
// A word that could start a constraint is its name when the constraint kind follows it.
82+
public static Stream<Arguments> constraintNames() {
83+
return Stream.of(Arguments.of("key", Dialect.POSTGRESQL),
84+
Arguments.of("index", Dialect.POSTGRESQL),
85+
Arguments.of("fulltext", Dialect.POSTGRESQL),
86+
Arguments.of("spatial", Dialect.POSTGRESQL),
87+
Arguments.of("exclude", Dialect.POSTGRESQL),
88+
Arguments.of("exclude", Dialect.MYSQL), Arguments.of("key", null),
89+
Arguments.of("exclude", null));
90+
}
91+
92+
@ParameterizedTest(name = "{0} {1}")
93+
@MethodSource("constraintNames")
94+
void testConstraintNameBeforeConstraintKind(String word, Dialect dialect)
95+
throws JSQLParserException {
96+
CreateTable createTable = (CreateTable) parse(
97+
"CREATE TABLE t (a INT, CONSTRAINT " + word + " UNIQUE (a))", dialect);
98+
assertEquals(word, createTable.getTableConstraints().get(0).getName());
99+
100+
AlterExpression add = alterExpression(
101+
"ALTER TABLE t ADD CONSTRAINT " + word + " PRIMARY KEY (a)", dialect);
102+
assertEquals(word, add.getConstraint() != null ? add.getConstraint().getName()
103+
: add.getIndex().getName());
104+
}
105+
106+
// EXCLUDE starts an exclusion constraint only with USING, its elements or WHERE.
107+
@ParameterizedTest
108+
@MethodSource("excludeDialects")
109+
void testExcludeAsAddedColumn(Dialect dialect) throws JSQLParserException {
110+
assertEquals("exclude", alterExpression("ALTER TABLE t ADD exclude INT", dialect)
111+
.getColDataTypeList().get(0).getColumnName());
112+
}
113+
114+
public static Stream<Dialect> excludeDialects() {
115+
return Stream.of(null, Dialect.MYSQL, Dialect.POSTGRESQL);
116+
}
117+
118+
@Test
119+
void testExclusionConstraintStays() throws JSQLParserException {
120+
AlterExpression exclude = alterExpression(
121+
"ALTER TABLE t ADD CONSTRAINT x EXCLUDE USING gist (a WITH =)", Dialect.POSTGRESQL);
122+
assertEquals("x", exclude.getConstraint().getName());
123+
}
124+
125+
// OPTIONS starts PostgreSQL's foreign-data options only before its parenthesized list.
126+
@Test
127+
void testOptionsAsIndexAndConstraintName() throws JSQLParserException {
128+
assertEquals("options", alterExpression("ALTER TABLE t ALTER INDEX options INVISIBLE",
129+
Dialect.MYSQL).getIndex().getName());
130+
parse("ALTER TABLE t ALTER CHECK options NOT ENFORCED", Dialect.MYSQL);
131+
parse("ALTER TABLE t ALTER CONSTRAINT options ENFORCED", Dialect.MYSQL);
132+
parse("ALTER FOREIGN TABLE t ALTER COLUMN c OPTIONS (ADD x 'y')", Dialect.POSTGRESQL);
133+
}
134+
}

0 commit comments

Comments
 (0)