Skip to content

Commit 4946b5d

Browse files
committed
fix: read KEY, INDEX, EXCLUDE and OPTIONS as names where their element does not follow
Signed-off-by: minleejae <mmj9808@gmail.com>
1 parent 08e222f commit 4946b5d

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
@@ -3945,6 +3945,12 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
39453945
|| "VALID".equalsIgnoreCase(getToken(offset + 1).image));
39463946
}
39473947

3948+
/** Whether OPTIONS and its parenthesized list start at the given token. */
3949+
private boolean isForeignDataOptionsAt(int offset) {
3950+
return "OPTIONS".equalsIgnoreCase(getToken(offset).image)
3951+
&& getToken(offset + 1).kind == OPENING_BRACKET;
3952+
}
3953+
39483954
/** EXCLUDE starts an exclusion constraint only before USING, its elements or WHERE. */
39493955
private boolean isExcludeConstraintAhead() {
39503956
int next = getToken(2).kind;
@@ -4032,11 +4038,37 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
40324038
switch (getToken(1).kind) {
40334039
case K_PRIMARY:
40344040
case K_UNIQUE:
4041+
return true;
4042+
// PostgreSQL has no inline index definition, so these words name a column there
40354043
case K_INDEX:
40364044
case K_KEY:
40374045
case K_FULLTEXT:
40384046
case K_SPATIAL:
4047+
return !isPostgreSqlDialect();
4048+
default:
4049+
return false;
4050+
}
4051+
}
4052+
4053+
/**
4054+
* Whether the word after CONSTRAINT is the constraint's name although it could start a
4055+
* constraint itself, as KEY in PostgreSQL's CONSTRAINT key UNIQUE (a): the constraint kind
4056+
* follows the word.
4057+
*/
4058+
private boolean isConstraintNameBeforeKindAhead() {
4059+
int kind = getToken(1).kind;
4060+
// PRIMARY is reserved in MySQL and PostgreSQL, and MySQL reserves the index words too
4061+
if (!isIdentifierishNameToken(getToken(1)) || kind == K_PRIMARY || isMySqlDialect()
4062+
&& (kind == K_KEY || kind == K_INDEX || kind == K_FULLTEXT || kind == K_SPATIAL)) {
4063+
return false;
4064+
}
4065+
switch (getToken(2).kind) {
4066+
case K_PRIMARY:
4067+
return getToken(3).kind == K_KEY;
4068+
case K_UNIQUE: case K_FOREIGN: case K_CHECK: case K_EXCLUDE:
40394069
return true;
4070+
case K_NOT:
4071+
return getToken(3).kind == K_NULL;
40404072
default:
40414073
return false;
40424074
}
@@ -22902,8 +22934,9 @@ TableElement TableConstraint(boolean createContext):
2290222934
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext)
2290322935
|
2290422936
<K_CONSTRAINT>
22905-
[ LOOKAHEAD({ !isTableIndexAhead() && getToken(1).kind != K_FOREIGN
22906-
&& getToken(1).kind != K_CHECK && getToken(1).kind != K_EXCLUDE
22937+
[ LOOKAHEAD({ isConstraintNameBeforeKindAhead() || !isTableIndexAhead()
22938+
&& getToken(1).kind != K_FOREIGN && getToken(1).kind != K_CHECK
22939+
&& getToken(1).kind != K_EXCLUDE
2290722940
&& !(getToken(1).kind == K_NOT && getToken(2).kind == K_NULL) }) constraintName=RelObjectName() ]
2290822941
(
2290922942
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext) {
@@ -26794,8 +26827,9 @@ AlterExpression AlterExpressionAddAlterModify():
2679426827
alterExp.setConstraint(constraint);
2679526828
}
2679626829
|
26830+
// MySQL's ALTER INDEX name {VISIBLE | INVISIBLE}; PostgreSQL's ALTER index alters a column
2679726831
LOOKAHEAD({ alterExp.getOperation() == AlterOperation.ALTER
26798-
&& getToken(1).kind == K_INDEX })
26832+
&& getToken(1).kind == K_INDEX && !isPostgreSqlDialect() })
2679926833
tk=<K_INDEX> sk3=RelObjectName() TableIndexOptions(false, indexSpec) {
2680026834
index = new Index().withIndexKeyword(tk.image).withName(sk3)
2680126835
.withKind(Index.Kind.INDEX).withSpecOptions(indexSpec);
@@ -26822,7 +26856,7 @@ AlterExpression AlterExpressionAddAlterModify():
2682226856
|| Dialect.MYSQL.name().equals(getAsString(Feature.dialect)))
2682326857
&& (getToken(1).kind == K_CONSTRAINT || getToken(1).kind == K_PRIMARY
2682426858
|| getToken(1).kind == K_UNIQUE || getToken(1).kind == K_FOREIGN
26825-
|| getToken(1).kind == K_CHECK || getToken(1).kind == K_EXCLUDE
26859+
|| getToken(1).kind == K_CHECK || isExcludeConstraintAhead()
2682626860
|| getToken(1).kind == K_NOT
2682726861
&& Dialect.POSTGRESQL.name().equals(getAsString(Feature.dialect)))
2682826862
|| AlterConstraintLookahead.needsSharedTableConstraint(getToken(1), token_source)
@@ -27129,8 +27163,10 @@ AlterExpression AlterExpression():
2712927163
{
2713027164

2713127165
(
27132-
LOOKAHEAD({ isKeywordAhead("OPTIONS") || getToken(1).kind == K_ALTER
27133-
&& "OPTIONS".equalsIgnoreCase(getToken(getToken(2).kind == K_COLUMN ? 4 : 3).image) })
27166+
// OPTIONS takes a parenthesized list; otherwise it names an index or a constraint, as in
27167+
// ALTER INDEX options INVISIBLE
27168+
LOOKAHEAD({ isKeywordAhead("OPTIONS") && getToken(2).kind == OPENING_BRACKET
27169+
|| getToken(1).kind == K_ALTER && isForeignDataOptionsAt(getToken(2).kind == K_COLUMN ? 4 : 3) })
2713427170
alterExp=AlterForeignDataOptions()
2713527171
|
2713627172
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)