Skip to content

Commit 27cdde8

Browse files
committed
fix: read keywords that MySQL or PostgreSQL does not reserve as names of objects
With Dialect.MYSQL or Dialect.POSTGRESQL, ObjectName() reads the reserved keywords of this parser that the dialect does not reserve as names wherever it stands (NameKeywords.isObjectName()), as in CHANGE c offset INT or REFERENCES value (b). The previous-token rule isNameAfter() is no longer needed. Column references in expressions keep reading RelObjectName(), as a keyword such as BETWEEN or INTERVAL may start syntax there. MySQL and MariaDB have no ONLY prefix of a relation. There ONLY is now the prefix only before a name, or before "(" in LOCK and TRUNCATE, and otherwise the name of the relation, as in TRUNCATE TABLE only, ALTER TABLE only.t or CREATE INDEX i ON only (a). With MySQL, UPDATE ONLY t and DELETE FROM ONLY t read only as the table and t as its alias, as MySQL does. Signed-off-by: minleejae <mmj9808@gmail.com>
1 parent 276628b commit 27cdde8

3 files changed

Lines changed: 125 additions & 87 deletions

File tree

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

Lines changed: 43 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010
package net.sf.jsqlparser.parser;
1111

1212
/**
13-
* The keyword sets that decide which keywords {@code RelObjectName()} reads as names.
13+
* The keyword sets that decide which keywords the parser reads as names: in
14+
* {@code RelObjectName()}, and with MySQL and PostgreSQL in {@code ObjectName()}.
1415
*
1516
* <p>
1617
* JavaCC needs the tokens of a choice spelled out, so the grammar lists the reserved keywords and
17-
* the keywords of other dialects as alternatives of {@code RelObjectName()} as well;
18-
* {@code NameKeywordsTest} checks that those alternatives and these sets agree. The lookahead
19-
* helpers of the parser use these sets rather than copies of the lists. The class is kept apart
20-
* from the parser, whose constant pool is close to what JaCoCo can still instrument.
18+
* the keywords of other dialects as alternatives as well; {@code NameKeywordsTest} checks that
19+
* those alternatives and these sets agree. The lookahead helpers of the parser use these sets
20+
* rather than copies of the lists. The class is kept apart from the parser, whose constant pool is
21+
* close to what JaCoCo can still instrument.
2122
*/
2223
final class NameKeywords implements CCJSqlParserConstants {
2324

@@ -182,75 +183,59 @@ private static boolean isPostgreSqlName(int kind) {
182183
}
183184

184185
/**
185-
* Whether the keyword is a name right after a word that DDL always follows with a name,
186-
* although elsewhere it starts a clause or an operator. MySQL does not reserve OFFSET, ONLY,
187-
* RETURNING, ANY, SOME and VALUE, as in ADD COLUMN c INT AFTER offset or KEY any (a), and
188-
* PostgreSQL does not reserve SET and takes BETWEEN, IF, GROUPING and VALUES as names there, as
189-
* in ADD set INT or REFERENCES if (b).
186+
* Whether the dialect reads the reserved keyword as the name of a schema object, where
187+
* {@code ObjectName()} stands: one of {@link #isReservedName(int)} that the dialect does not
188+
* reserve. These are the keywords that PostgreSQL 18's {@code pg_get_keywords()} lists as
189+
* unreserved or col_name, or does not list, and the keywords that MySQL 8.4 does not reserve or
190+
* does not know. QUALIFY is left out for MySQL: {@code INFORMATION_SCHEMA.KEYWORDS} lists it as
191+
* non-reserved, but MySQL rejects it as a name.
190192
*/
191-
static boolean isNameAfter(String dialect, Token previous, int kind) {
193+
static boolean isObjectName(String dialect, int kind) {
192194
if (AbstractJSqlParser.Dialect.MYSQL.name().equals(dialect)) {
193195
switch (kind) {
196+
case K_ANY:
197+
case K_CASEWHEN:
198+
case K_CONNECT:
199+
case K_FULL:
200+
case K_GLOBAL:
201+
case K_IIF:
194202
case K_OFFSET:
195203
case K_ONLY:
204+
case K_PUBLIC:
196205
case K_RETURNING:
197-
case K_ANY:
198206
case K_SOME:
207+
case K_START:
208+
case K_TABLES:
199209
case K_VALUE:
200-
return isMySqlNameIntroducer(previous);
210+
return true;
201211
default:
202212
return false;
203213
}
204214
}
205215
if (AbstractJSqlParser.Dialect.POSTGRESQL.name().equals(dialect)) {
206-
if (kind == K_SET || kind == K_BETWEEN) {
207-
return isPostgreSqlNameIntroducer(previous);
216+
switch (kind) {
217+
case K_BETWEEN:
218+
case K_CASEWHEN:
219+
case K_CONNECT:
220+
case K_GLOBAL:
221+
case K_GROUPING:
222+
case K_IF:
223+
case K_IIF:
224+
case K_INTERVAL:
225+
case K_OPTIMIZE:
226+
case K_PROCEDURE:
227+
case K_PUBLIC:
228+
case K_SET:
229+
case K_START:
230+
case K_TABLES:
231+
case K_VALUE:
232+
case K_VALUES:
233+
return true;
234+
default:
235+
return false;
208236
}
209-
return (kind == K_IF || kind == K_GROUPING || kind == K_VALUES)
210-
&& previous.kind == K_REFERENCES;
211237
}
212238
return false;
213239
}
214240

215-
private static boolean isMySqlNameIntroducer(Token previous) {
216-
switch (previous.kind) {
217-
case K_ADD:
218-
case K_ALTER:
219-
case K_DROP:
220-
case K_MODIFY:
221-
case K_TO:
222-
case K_INDEX:
223-
case K_KEY:
224-
case K_REFERENCES:
225-
case K_DATABASE:
226-
case K_SCHEMA:
227-
case K_VIEW:
228-
case K_TRIGGER:
229-
case K_PARTITION:
230-
return true;
231-
default:
232-
return "AFTER".equalsIgnoreCase(previous.image);
233-
}
234-
}
235-
236-
private static boolean isPostgreSqlNameIntroducer(Token previous) {
237-
switch (previous.kind) {
238-
case K_ADD:
239-
case K_ALTER:
240-
case K_DROP:
241-
case K_TO:
242-
case K_INDEX:
243-
case K_PARTITION:
244-
case K_SCHEMA:
245-
case K_SEQUENCE:
246-
case K_VIEW:
247-
case K_TRIGGER:
248-
case K_REFERENCES:
249-
case K_AUTHORIZATION:
250-
return true;
251-
default:
252-
return "INHERIT".equalsIgnoreCase(previous.image)
253-
|| "ATTRIBUTE".equalsIgnoreCase(previous.image);
254-
}
255-
}
256241
}

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

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2066,11 +2066,6 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
20662066
return false;
20672067
}
20682068

2069-
// A keyword the dialect does not reserve, after a word that DDL follows with a name
2070-
if (NameKeywords.isNameAfter(getAsString(Feature.dialect), prev, getToken(1).kind)) {
2071-
return true;
2072-
}
2073-
20742069
// ── 2. After delimiters and operators: expression position ─────
20752070
// With K_FROM/K_SELECT removed from RelObjectName's
20762071
// token list, accepting all remaining keywords after these
@@ -2167,6 +2162,24 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
21672162
return isReservedKeywordSafeByFollower();
21682163
}
21692164

2165+
/**
2166+
* Whether ONLY starts PostgreSQL's prefix of a relation, as in ALTER TABLE ONLY t. MySQL and
2167+
* MariaDB have no such prefix, but the parser reads PostgreSQL's forms with them as well, so
2168+
* there ONLY is the prefix only before a name, or before "(" in LOCK and TRUNCATE
2169+
* (relationTarget), and otherwise the name of the relation, as in TRUNCATE TABLE only,
2170+
* ALTER TABLE only.t or CREATE INDEX i ON only (a).
2171+
*/
2172+
private boolean isOnlyPrefixAhead(boolean relationTarget) {
2173+
if (getToken(1).kind != K_ONLY) {
2174+
return false;
2175+
}
2176+
if (!isMySqlDialect()) {
2177+
return true;
2178+
}
2179+
Token next = getToken(2);
2180+
return isIdentifierishNameToken(next) || relationTarget && next.kind == OPENING_BRACKET;
2181+
}
2182+
21702183
/**
21712184
* Whether ONLY is PostgreSQL's prefix of a relation name, as in DELETE FROM ONLY t,
21722185
* JOIN ONLY t or FROM a, ONLY b, rather than a table or column named only.
@@ -4655,6 +4668,17 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
46554668
return NameKeywords.isDialectName(getAsString(Feature.dialect), kind);
46564669
}
46574670

4671+
/**
4672+
* Whether the selected dialect reads the next keyword as the name of a schema object wherever
4673+
* ObjectName() stands, although this parser reserves it, as NameKeywords.isObjectName()
4674+
* decides. With PostgreSQL, ONLY before a relation stays its prefix; MySQL has no such prefix.
4675+
*/
4676+
private boolean isDialectObjectName() {
4677+
int kind = getToken(1).kind;
4678+
return NameKeywords.isObjectName(getAsString(Feature.dialect), kind)
4679+
&& !(kind == K_ONLY && !isMySqlDialect() && isRelationOnlyAhead(getToken(0)));
4680+
}
4681+
46584682
/** MySQL's EXPLAIN, PREPARE, EXECUTE, DROP PREPARE and DO: MySQL, MariaDB or no dialect. */
46594683
private boolean isMySqlUtilityDialect() {
46604684
return getAsString(Feature.dialect) == null || isMySqlDialect();
@@ -8099,7 +8123,8 @@ TableReference RelationTarget():
80998123
TableReference target;
81008124
}
81018125
{
8102-
[ LOOKAHEAD(2) <K_ONLY> { only = true; } ]
8126+
// A choice rather than [ ... ], so that the check also holds while scanning ahead
8127+
( LOOKAHEAD({ isOnlyPrefixAhead(true) }) <K_ONLY> { only = true; } | {} )
81038128
( "(" table=Table() ")" { parenthesized = true; } | table=Table() )
81048129
[ "*" { descendants = true; } ]
81058130
{
@@ -12586,6 +12611,8 @@ ObjectNames ColumnIdentifier() : {
1258612611
List<String> data = new ArrayList<String>();
1258712612
List<String> delimiters = new ArrayList<String>();
1258812613
} {
12614+
// RelObjectName() rather than ObjectName(): in an expression a keyword such as BETWEEN or
12615+
// INTERVAL that a dialect takes as a name may start syntax
1258912616
token = RelObjectName() { data.add(token); }
1259012617
(
1259112618
LOOKAHEAD (2) (
@@ -12648,7 +12675,8 @@ Column Column() #Column :
1264812675
* parameters (after ':'), index columns, constraint names, and similar
1264912676
* restricted contexts. Those call sites add the two tokens inline.
1265012677
*
12651-
* Names of schema objects are read through ObjectName(), which names that position.
12678+
* Names of schema objects are read through ObjectName(), where the dialect decides which other
12679+
* keywords are names.
1265212680
*/
1265312681
String RelObjectName() :
1265412682
{ Token tk = null; String result = null; }
@@ -12675,20 +12703,30 @@ String RelObjectName() :
1267512703
| tk=<K_USE> | tk=<K_XOR> )
1267612704

1267712705
/* ── Reserved keywords usable as identifiers (context-guarded) ─── */
12678-
| LOOKAHEAD({ isReservedKeywordAsIdentifier() })
12679-
( tk=<K_ALL> | tk=<K_ANY> | tk=<K_BETWEEN> | tk=<K_CASEWHEN> | tk=<K_CONNECT>
12680-
| tk=<K_CREATE> | tk=<K_DEFAULT> | tk=<K_FULL>
12681-
| tk=<K_GLOBAL> | tk=<K_GROUP> | tk=<K_GROUPING> | tk=<K_IF>
12682-
| tk=<K_IIF> | tk=<K_IGNORE> | tk=<K_IN> | tk=<K_INTERVAL>
12683-
| tk=<K_LEFT> | tk=<K_LIMIT> | tk=<K_NEXTVAL> | tk=<K_OFFSET>
12684-
| tk=<K_ON> | tk=<K_ONLY> | tk=<K_OPTIMIZE> | tk=<K_ORDER> | tk=<K_PROCEDURE>
12685-
| tk=<K_PUBLIC> | tk=<K_QUALIFY> | tk=<K_RETURNING> | tk=<K_RIGHT>
12686-
| tk=<K_SET> | tk=<K_SOME> | tk=<K_START> | tk=<K_TABLES>
12687-
| tk=<K_TOP> | tk=<K_VALUE> | tk=<K_VALUES> )
12706+
| LOOKAHEAD({ isReservedKeywordAsIdentifier() }) tk=ReservedName()
1268812707
)
1268912708
{ return result != null ? result : tk.image; }
1269012709
}
1269112710

12711+
/*
12712+
* The reserved keywords that can still be names, NameKeywords.isReservedName(). The caller decides
12713+
* whether the keyword is a name where it stands.
12714+
*/
12715+
Token ReservedName() :
12716+
{ Token tk; }
12717+
{
12718+
( tk=<K_ALL> | tk=<K_ANY> | tk=<K_BETWEEN> | tk=<K_CASEWHEN> | tk=<K_CONNECT>
12719+
| tk=<K_CREATE> | tk=<K_DEFAULT> | tk=<K_FULL>
12720+
| tk=<K_GLOBAL> | tk=<K_GROUP> | tk=<K_GROUPING> | tk=<K_IF>
12721+
| tk=<K_IIF> | tk=<K_IGNORE> | tk=<K_IN> | tk=<K_INTERVAL>
12722+
| tk=<K_LEFT> | tk=<K_LIMIT> | tk=<K_NEXTVAL> | tk=<K_OFFSET>
12723+
| tk=<K_ON> | tk=<K_ONLY> | tk=<K_OPTIMIZE> | tk=<K_ORDER> | tk=<K_PROCEDURE>
12724+
| tk=<K_PUBLIC> | tk=<K_QUALIFY> | tk=<K_RETURNING> | tk=<K_RIGHT>
12725+
| tk=<K_SET> | tk=<K_SOME> | tk=<K_START> | tk=<K_TABLES>
12726+
| tk=<K_TOP> | tk=<K_VALUE> | tk=<K_VALUES> )
12727+
{ return tk; }
12728+
}
12729+
1269212730
/*
1269312731
* Extended version of RelObjectName that additionally accepts FROM and SELECT
1269412732
* as unquoted identifiers.
@@ -12714,13 +12752,18 @@ String RelObjectNameExt() :
1271412752
* DDL, and the like, whether it is defined, changed or referenced. This is the position of
1271512753
* PostgreSQL's ColId.
1271612754
*
12717-
* It reads the same names as RelObjectName(). Naming the position keeps the decision of which
12718-
* keywords are names here in one place, so that it can depend on the dialect.
12755+
* With MySQL and PostgreSQL it also reads the keywords that this parser reserves but the dialect
12756+
* does not, wherever they stand (NameKeywords.isObjectName()); otherwise it reads what
12757+
* RelObjectName() reads.
1271912758
*/
1272012759
String ObjectName() :
12721-
{ String name; }
12760+
{ String name; Token tk; }
1272212761
{
12723-
name = RelObjectName()
12762+
(
12763+
LOOKAHEAD({ isDialectObjectName() }) tk=ReservedName() { name = tk.image; }
12764+
|
12765+
name = RelObjectName()
12766+
)
1272412767
{ return name; }
1272512768
}
1272612769

@@ -21012,7 +21055,7 @@ CreateIndex CreateIndex():
2101221055
name=RelObjectNames() { index.setName(name.getNames()); } ]
2101321056
(
2101421057
LOOKAHEAD(3)(
21015-
<K_ON> [ LOOKAHEAD(2) <K_ONLY> { createIndex.setOnly(true); } ] table=Table()
21058+
<K_ON> ( LOOKAHEAD({ isOnlyPrefixAhead(false) }) <K_ONLY> { createIndex.setOnly(true); } | {} ) table=Table()
2101621059
[ indexType=UsingIndexType() { index.setUsing(indexType); } ]
2101721060
)
2101821061
|
@@ -21022,7 +21065,7 @@ CreateIndex CreateIndex():
2102221065
createIndex.setIndexTypeBeforeOn(true);
2102321066
}
2102421067
]
21025-
<K_ON> [ LOOKAHEAD(2) <K_ONLY> { createIndex.setOnly(true); } ] table=Table()
21068+
<K_ON> ( LOOKAHEAD({ isOnlyPrefixAhead(false) }) <K_ONLY> { createIndex.setOnly(true); } | {} ) table=Table()
2102621069
)
2102721070
)
2102821071
colNames = IndexColumnsWithParamsList()
@@ -27854,7 +27897,7 @@ Alter AlterTable(boolean foreign):
2785427897
{
2785527898
<K_TABLE> { alter.setForeignTable(foreign); }
2785627899
[ LOOKAHEAD(2) <K_IF> <K_EXISTS> { alter.setUseTableIfExists(true); } ]
27857-
[ LOOKAHEAD(2) <K_ONLY> { alter.setUseOnly(true); } ]
27900+
( LOOKAHEAD({ isOnlyPrefixAhead(false) }) <K_ONLY> { alter.setUseOnly(true); } | {} )
2785827901
[ LOOKAHEAD(2) <K_IF> <K_EXISTS> {
2785927902
requireDdlSyntax(!alter.isUseTableIfExists(), "Duplicate IF EXISTS");
2786027903
alter.setUseTableIfExists(true);

‎src/test/java/net/sf/jsqlparser/statement/PostgreSQLModifyFormsTest.java‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,12 +248,22 @@ void rejectedTargets(String sql) {
248248

249249
@Test
250250
void mySqlHasNoOnlyTargets() throws JSQLParserException {
251-
// MySQL's ONLY is no keyword of UPDATE or DELETE; the forms stay as they were
251+
// MySQL has no ONLY in UPDATE or DELETE and reads it as the table, t as its alias
252+
Update onlyTable =
253+
(Update) assertSqlCanBeParsedAndDeparsed("UPDATE ONLY t SET a = 1", false,
254+
MYSQL);
255+
assertEquals("ONLY", onlyTable.getTable().getName());
256+
assertEquals("t", onlyTable.getTable().getAlias().getName());
257+
assertFalse(onlyTable.getTableReference().hasInheritanceScope());
258+
Delete onlyDelete = (Delete) assertSqlCanBeParsedAndDeparsed(
259+
"DELETE FROM ONLY t WHERE a = 1", false, MYSQL);
260+
assertEquals("ONLY", onlyDelete.getTable().getName());
261+
assertFalse(onlyDelete.getTableReference().isOnly());
262+
assertThrows(JSQLParserException.class,
263+
() -> CCJSqlParserUtil.parse("UPDATE ONLY t SET a = 1", MARIADB));
264+
assertThrows(JSQLParserException.class,
265+
() -> CCJSqlParserUtil.parse("DELETE FROM ONLY t WHERE a = 1", MARIADB));
252266
for (Consumer<CCJSqlParser> dialect : Arrays.asList(MYSQL, MARIADB)) {
253-
assertThrows(JSQLParserException.class,
254-
() -> CCJSqlParserUtil.parse("UPDATE ONLY t SET a = 1", dialect));
255-
assertThrows(JSQLParserException.class,
256-
() -> CCJSqlParserUtil.parse("DELETE FROM ONLY t WHERE a = 1", dialect));
257267
Delete delete = (Delete) assertSqlCanBeParsedAndDeparsed("DELETE FROM only WHERE a = 1",
258268
false, dialect);
259269
assertEquals("only", delete.getTable().getName());

0 commit comments

Comments
 (0)