diff --git a/src/main/java/net/sf/jsqlparser/parser/NameKeywords.java b/src/main/java/net/sf/jsqlparser/parser/NameKeywords.java
new file mode 100644
index 000000000..abed4fdce
--- /dev/null
+++ b/src/main/java/net/sf/jsqlparser/parser/NameKeywords.java
@@ -0,0 +1,449 @@
+/*-
+ * #%L
+ * JSQLParser library
+ * %%
+ * Copyright (C) 2004 - 2026 JSQLParser
+ * %%
+ * Dual licensed under GNU LGPL 2.1 or Apache License 2.0
+ * #L%
+ */
+package net.sf.jsqlparser.parser;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * The keyword sets that decide which keywords the parser reads as names: in
+ * {@code RelObjectName()}, and with MySQL and PostgreSQL in {@code ObjectName()} and
+ * {@code AliasName()}.
+ *
+ *
+ * JavaCC needs the tokens of a choice spelled out, so the grammar lists the reserved keywords and
+ * the keywords of other dialects as alternatives as well; {@code NameKeywordsTest} checks that
+ * those alternatives and these sets agree. The lookahead helpers of the parser use these sets
+ * rather than copies of the lists. The class is kept apart from the parser, whose constant pool is
+ * close to what JaCoCo can still instrument.
+ */
+final class NameKeywords implements CCJSqlParserConstants {
+
+ /**
+ * MySQL 8.4's reserved keywords, as {@code INFORMATION_SCHEMA.KEYWORDS} lists them (RESERVED =
+ * 1).
+ */
+ private static final Set MYSQL_RESERVED_KEYWORDS = new HashSet(Arrays.asList(
+ "ACCESSIBLE", "ADD", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE",
+ "BEFORE", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE",
+ "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "CLUSTERING", "COLLATE", "COLUMN",
+ "CONDITION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CUME_DIST",
+ "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR",
+ "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND",
+ "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DELAYED", "DELETE", "DENSE_RANK", "DESC",
+ "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL",
+ "EACH", "ELSE", "ELSEIF", "EMPTY", "ENCLOSED", "ESCAPED", "EXCEPT", "EXISTS", "EXIT",
+ "EXPLAIN", "FALSE", "FETCH", "FIRST_VALUE", "FLOAT", "FLOAT4", "FLOAT8", "FOR", "FORCE",
+ "FOREIGN", "FROM", "FULLTEXT", "FUNCTION", "GENERATED", "GET", "GRANT", "GROUP",
+ "GROUPING", "GROUPS", "HAVING", "HIGH_PRIORITY", "HOUR_MICROSECOND", "HOUR_MINUTE",
+ "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", "INSENSITIVE",
+ "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERSECT",
+ "INTERVAL", "INTO", "IO_AFTER_GTIDS", "IO_BEFORE_GTIDS", "IS", "ITERATE", "JOIN",
+ "JSON_TABLE", "KEY", "KEYS", "KILL", "LAG", "LAST_VALUE", "LATERAL", "LEAD", "LEADING",
+ "LEAVE", "LEFT", "LIKE", "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME",
+ "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY",
+ "MATCH", "MAXVALUE", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT",
+ "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NOT",
+ "NO_WRITE_TO_BINLOG", "NTH_VALUE", "NTILE", "NULL", "NUMERIC", "OF", "ON", "OPTIMIZE",
+ "OPTIMIZER_COSTS", "OPTION", "OPTIONALLY", "OR", "ORDER", "OUT", "OUTER", "OUTFILE",
+ "OVER", "PARTITION", "PERCENT_RANK", "PERCONA_SEQUENCE_TABLE", "PRECISION", "PRIMARY",
+ "PROCEDURE", "PURGE", "RANGE", "RANK", "READ", "READS", "READ_WRITE", "REAL",
+ "RECURSIVE", "REFERENCES", "REGEXP", "RELEASE", "RENAME", "REPEAT", "REPLACE",
+ "REQUIRE", "RESIGNAL", "RESTRICT", "RETURN", "REVOKE", "RIGHT", "RLIKE", "ROW", "ROWS",
+ "ROW_NUMBER", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE",
+ "SEPARATOR", "SET", "SHOW", "SIGNAL", "SMALLINT", "SPATIAL", "SPECIFIC", "SQL",
+ "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS",
+ "SQL_SMALL_RESULT", "SSL", "STARTING", "STORED", "STRAIGHT_JOIN", "SYSTEM", "TABLE",
+ "TERMINATED", "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER",
+ "TRUE", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE",
+ "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR",
+ "VARCHARACTER", "VARYING", "VIRTUAL", "WHEN", "WHERE", "WHILE", "WINDOW", "WITH",
+ "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL"));
+
+ /**
+ * Keywords that {@code INFORMATION_SCHEMA.KEYWORDS} lists as non-reserved, but that MySQL 8.4
+ * rejects as the name of a table, a column or an alias.
+ */
+ private static final Set MYSQL_REJECTED_NAMES =
+ new HashSet(Arrays.asList("QUALIFY", "TABLESAMPLE"));
+
+ /**
+ * PostgreSQL 18's reserved keywords. Its grammar takes none of them as the name or the word
+ * value of a utility option, except ANALYZE and ANALYSE as names.
+ */
+ private static final Set POSTGRESQL_RESERVED_KEYWORDS =
+ new HashSet(Arrays.asList(
+ "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC",
+ "BOTH",
+ "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE",
+ "CURRENT_CATALOG",
+ "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP",
+ "CURRENT_USER",
+ "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT",
+ "FALSE",
+ "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN",
+ "INITIALLY",
+ "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME",
+ "LOCALTIMESTAMP", "NOT",
+ "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY",
+ "REFERENCES",
+ "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "SYSTEM_USER",
+ "TABLE", "THEN",
+ "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC",
+ "WHEN", "WHERE",
+ "WINDOW", "WITH"));
+
+ /**
+ * PostgreSQL 18's type and function name keywords. Like its reserved keywords, its grammar
+ * takes none of them as a column identifier (ColId).
+ */
+ private static final Set POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS =
+ new HashSet(Arrays.asList(
+ "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS",
+ "CURRENT_SCHEMA",
+ "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE",
+ "NATURAL",
+ "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE"));
+
+ /**
+ * PostgreSQL 18's column name keywords that are not a type name by themselves, so its grammar
+ * takes none of them as the single word of a definition value. NONE is one more, but a
+ * definition value takes it as the keyword it is.
+ */
+ private static final Set POSTGRESQL_NON_TYPE_COL_NAME_KEYWORDS =
+ new HashSet(Arrays.asList(
+ "BETWEEN", "COALESCE", "EXISTS", "EXTRACT", "GREATEST", "GROUPING", "INOUT",
+ "JSON_ARRAY",
+ "JSON_ARRAYAGG", "JSON_EXISTS", "JSON_OBJECT", "JSON_OBJECTAGG", "JSON_QUERY",
+ "JSON_SCALAR", "JSON_SERIALIZE", "JSON_TABLE", "JSON_VALUE", "LEAST",
+ "MERGE_ACTION",
+ "NATIONAL", "NORMALIZE", "NULLIF", "OUT", "OVERLAY", "POSITION", "PRECISION",
+ "ROW",
+ "SETOF", "SUBSTRING", "TREAT", "TRIM", "VALUES", "XMLATTRIBUTES", "XMLCONCAT",
+ "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLNAMESPACES", "XMLPARSE", "XMLPI",
+ "XMLROOT",
+ "XMLSERIALIZE", "XMLTABLE"));
+
+ /**
+ * PostgreSQL 18's unreserved keywords and its column name keywords that are type names: the
+ * keywords that are in none of the sets above.
+ */
+ private static final Set POSTGRESQL_OTHER_KEYWORDS = new HashSet(Arrays.asList(
+ "ABORT", "ABSENT", "ABSOLUTE", "ACCESS", "ACTION", "ADD", "ADMIN", "AFTER",
+ "AGGREGATE", "ALSO", "ALTER", "ALWAYS", "ASENSITIVE", "ASSERTION", "ASSIGNMENT",
+ "AT", "ATOMIC", "ATTACH", "ATTRIBUTE", "BACKWARD", "BEFORE", "BEGIN", "BIGINT",
+ "BIT", "BOOLEAN", "BREADTH", "BY", "CACHE", "CALL", "CALLED", "CASCADE", "CASCADED",
+ "CATALOG", "CHAIN", "CHAR", "CHARACTER", "CHARACTERISTICS", "CHECKPOINT", "CLASS",
+ "CLOSE", "CLUSTER", "COLUMNS", "COMMENT", "COMMENTS", "COMMIT", "COMMITTED",
+ "COMPRESSION", "CONDITIONAL", "CONFIGURATION", "CONFLICT", "CONNECTION",
+ "CONSTRAINTS", "CONTENT", "CONTINUE", "CONVERSION", "COPY", "COST", "CSV", "CUBE",
+ "CURRENT", "CURSOR", "CYCLE", "DATA", "DATABASE", "DAY", "DEALLOCATE", "DEC",
+ "DECIMAL", "DECLARE", "DEFAULTS", "DEFERRED", "DEFINER", "DELETE", "DELIMITER",
+ "DELIMITERS", "DEPENDS", "DEPTH", "DETACH", "DICTIONARY", "DISABLE", "DISCARD",
+ "DOCUMENT", "DOMAIN", "DOUBLE", "DROP", "EACH", "EMPTY", "ENABLE", "ENCODING",
+ "ENCRYPTED", "ENFORCED", "ENUM", "ERROR", "ESCAPE", "EVENT", "EXCLUDE", "EXCLUDING",
+ "EXCLUSIVE", "EXECUTE", "EXPLAIN", "EXPRESSION", "EXTENSION", "EXTERNAL", "FAMILY",
+ "FILTER", "FINALIZE", "FIRST", "FLOAT", "FOLLOWING", "FORCE", "FORMAT", "FORWARD",
+ "FUNCTION", "FUNCTIONS", "GENERATED", "GLOBAL", "GRANTED", "GROUPS", "HANDLER",
+ "HEADER", "HOLD", "HOUR", "IDENTITY", "IF", "IMMEDIATE", "IMMUTABLE", "IMPLICIT",
+ "IMPORT", "INCLUDE", "INCLUDING", "INCREMENT", "INDENT", "INDEX", "INDEXES",
+ "INHERIT", "INHERITS", "INLINE", "INPUT", "INSENSITIVE", "INSERT", "INSTEAD", "INT",
+ "INTEGER", "INTERVAL", "INVOKER", "ISOLATION", "JSON", "KEEP", "KEY", "KEYS",
+ "LABEL", "LANGUAGE", "LARGE", "LAST", "LEAKPROOF", "LEVEL", "LISTEN", "LOAD",
+ "LOCAL", "LOCATION", "LOCK", "LOCKED", "LOGGED", "MAPPING", "MATCH", "MATCHED",
+ "MATERIALIZED", "MAXVALUE", "MERGE", "METHOD", "MINUTE", "MINVALUE", "MODE",
+ "MONTH", "MOVE", "NAME", "NAMES", "NCHAR", "NESTED", "NEW", "NEXT", "NFC", "NFD",
+ "NFKC", "NFKD", "NO", "NONE", "NORMALIZED", "NOTHING", "NOTIFY", "NOWAIT", "NULLS",
+ "NUMERIC", "OBJECT", "OBJECTS", "OF", "OFF", "OIDS", "OLD", "OMIT", "OPERATOR",
+ "OPTION", "OPTIONS", "ORDINALITY", "OTHERS", "OVER", "OVERRIDING", "OWNED", "OWNER",
+ "PARALLEL", "PARAMETER", "PARSER", "PARTIAL", "PARTITION", "PASSING", "PASSWORD",
+ "PATH", "PERIOD", "PLAN", "PLANS", "POLICY", "PRECEDING", "PREPARE", "PREPARED",
+ "PRESERVE", "PRIOR", "PRIVILEGES", "PROCEDURAL", "PROCEDURE", "PROCEDURES",
+ "PROGRAM", "PUBLICATION", "QUOTE", "QUOTES", "RANGE", "READ", "REAL", "REASSIGN",
+ "RECURSIVE", "REF", "REFERENCING", "REFRESH", "REINDEX", "RELATIVE", "RELEASE",
+ "RENAME", "REPEATABLE", "REPLACE", "REPLICA", "RESET", "RESTART", "RESTRICT",
+ "RETURN", "RETURNS", "REVOKE", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE", "ROUTINES",
+ "ROWS", "RULE", "SAVEPOINT", "SCALAR", "SCHEMA", "SCHEMAS", "SCROLL", "SEARCH",
+ "SECOND", "SECURITY", "SEQUENCE", "SEQUENCES", "SERIALIZABLE", "SERVER", "SESSION",
+ "SET", "SETS", "SHARE", "SHOW", "SIMPLE", "SKIP", "SMALLINT", "SNAPSHOT", "SOURCE",
+ "SQL", "STABLE", "STANDALONE", "START", "STATEMENT", "STATISTICS", "STDIN",
+ "STDOUT", "STORAGE", "STORED", "STRICT", "STRING", "STRIP", "SUBSCRIPTION",
+ "SUPPORT", "SYSID", "SYSTEM", "TABLES", "TABLESPACE", "TARGET", "TEMP", "TEMPLATE",
+ "TEMPORARY", "TEXT", "TIES", "TIME", "TIMESTAMP", "TRANSACTION", "TRANSFORM",
+ "TRIGGER", "TRUNCATE", "TRUSTED", "TYPE", "TYPES", "UESCAPE", "UNBOUNDED",
+ "UNCOMMITTED", "UNCONDITIONAL", "UNENCRYPTED", "UNKNOWN", "UNLISTEN", "UNLOGGED",
+ "UNTIL", "UPDATE", "VACUUM", "VALID", "VALIDATE", "VALIDATOR", "VALUE", "VARCHAR",
+ "VARYING", "VERSION", "VIEW", "VIEWS", "VIRTUAL", "VOLATILE", "WHITESPACE",
+ "WITHIN", "WITHOUT", "WORK", "WRAPPER", "WRITE", "XML", "YEAR", "YES", "ZONE"));
+
+ private NameKeywords() {}
+
+ /**
+ * Whether the token is a name as it is: an identifier, a quoted identifier, a data type word or
+ * a date literal word.
+ */
+ static boolean isBaseName(int kind) {
+ switch (kind) {
+ case S_IDENTIFIER:
+ case S_QUOTED_IDENTIFIER:
+ case DATA_TYPE:
+ case K_DATETIMELITERAL:
+ case K_DATE_LITERAL:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /** Whether the token is an identifier, quoted or not, or a non-reserved keyword. */
+ static boolean isIdentifierOrNonReserved(int kind) {
+ return kind == S_IDENTIFIER || kind == S_QUOTED_IDENTIFIER || isNonReserved(kind);
+ }
+
+ /**
+ * Whether the token can be a name read by {@code RelObjectName()} with the dialect, where the
+ * position allows it: a name as it is, a non-reserved keyword, a reserved keyword that can
+ * still be a name, or a keyword of another dialect that the dialect does not know.
+ */
+ static boolean isName(String dialect, int kind) {
+ return isBaseName(kind) || isNonReserved(kind) || isReservedName(kind)
+ || isDialectName(dialect, kind);
+ }
+
+ /**
+ * Whether the keyword is non-reserved, a name wherever a name may stand: the grammar declares
+ * these keywords between the MIN_NON_RESERVED_WORD and MAX_NON_RESERVED_WORD tokens.
+ */
+ static boolean isNonReserved(int kind) {
+ return kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD;
+ }
+
+ /**
+ * Whether the reserved keyword is still a name where the parser finds a name position, as
+ * {@code isReservedKeywordAsIdentifier()} decides: after AS, a delimiter or a word that is
+ * always followed by a name, or before a follower that rules out the clause it would start.
+ */
+ static boolean isReservedName(int kind) {
+ switch (kind) {
+ case K_ALL:
+ case K_ANY:
+ case K_BETWEEN:
+ case K_CASEWHEN:
+ case K_CONNECT:
+ case K_CREATE:
+ case K_DEFAULT:
+ case K_FULL:
+ case K_GLOBAL:
+ case K_GROUP:
+ case K_GROUPING:
+ case K_IF:
+ case K_IIF:
+ case K_IGNORE:
+ case K_IN:
+ case K_INTERVAL:
+ case K_LEFT:
+ case K_LIMIT:
+ case K_NEXTVAL:
+ case K_OFFSET:
+ case K_ON:
+ case K_ONLY:
+ case K_OPTIMIZE:
+ case K_ORDER:
+ case K_PROCEDURE:
+ case K_PUBLIC:
+ case K_QUALIFY:
+ case K_RETURNING:
+ case K_RIGHT:
+ case K_SET:
+ case K_SOME:
+ case K_START:
+ case K_TABLES:
+ case K_TOP:
+ case K_VALUE:
+ case K_VALUES:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Whether the keyword is an alias without AS only when
+ * {@code isReservedKeywordSafeByFollower()} finds that its follower does not continue a clause,
+ * as in {@code SELECT a left FROM t} against {@code LEFT JOIN}. These are the reserved names
+ * except BETWEEN, ONLY and RETURNING, which never start such an alias, and ARRAY, which may
+ * start ARRAY JOIN.
+ */
+ static boolean isAliasCheckedByFollower(int kind) {
+ switch (kind) {
+ case K_BETWEEN:
+ case K_ONLY:
+ case K_RETURNING:
+ return false;
+ case K_ARRAY_LITERAL:
+ return true;
+ default:
+ return isReservedName(kind);
+ }
+ }
+
+ /**
+ * Whether the keyword is a name wherever the dialect takes one: it belongs to clauses of other
+ * dialects, and the dialect does not know it as a keyword at all. MySQL 8.4 and PostgreSQL 18
+ * have no PIVOT, MINUS, OUTPUT or SEMI JOIN, MySQL no ILIKE and, since 8.0, no SQL_CACHE, and
+ * PostgreSQL neither XOR, QUALIFY nor MySQL's select modifiers. Without a dialect these
+ * keywords stay reserved.
+ */
+ static boolean isDialectName(String dialect, int kind) {
+ if (AbstractJSqlParser.Dialect.MYSQL.name().equals(dialect)) {
+ return isMySqlName(kind);
+ }
+ if (AbstractJSqlParser.Dialect.POSTGRESQL.name().equals(dialect)) {
+ return isPostgreSqlName(kind);
+ }
+ return false;
+ }
+
+ private static boolean isMySqlName(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:
+ case K_PREFERRING:
+ case K_SEMI:
+ case K_SQL_CACHE:
+ case K_TOP:
+ case K_UNPIVOT:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isPostgreSqlName(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:
+ case K_PREFERRING:
+ case K_QUALIFY:
+ case K_SEMI:
+ case K_SQL_CACHE:
+ case K_SQL_CALC_FOUND_ROWS:
+ case K_STRAIGHT:
+ case K_TOP:
+ case K_UNPIVOT:
+ case K_USE:
+ case K_XOR:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Whether the dialect reads the reserved keyword, spelled as the word it is, as the name of a
+ * schema object, where {@code ObjectName()} stands: one of {@link #isReservedName(int)} that
+ * the dialect does not reserve. With PostgreSQL that is a column identifier (ColId) of
+ * {@link #isPostgreSqlColId(String)}, and with MySQL a word of
+ * {@link #isMySqlIdentifier(String)}.
+ */
+ static boolean isObjectName(String dialect, Token token) {
+ if (!isReservedName(token.kind)) {
+ return false;
+ }
+ int kind = token.kind;
+ String word = keywordOf(kind);
+ if (!word.equalsIgnoreCase(token.image)) {
+ return false;
+ }
+ if (AbstractJSqlParser.Dialect.MYSQL.name().equals(dialect)) {
+ return isMySqlIdentifier(word);
+ }
+ if (AbstractJSqlParser.Dialect.POSTGRESQL.name().equals(dialect)) {
+ return isPostgreSqlColId(word);
+ }
+ return false;
+ }
+
+ /**
+ * Whether the dialect reads the reserved keyword, spelled as the word it is, as the name of a
+ * role where {@code RoleName()} stands, or of a function before "(", although it is no name of
+ * an object: with PostgreSQL a type or function name keyword, which RoleSpec takes as a
+ * NonReservedWord and func_name as a type_function_name.
+ */
+ static boolean isTypeFuncName(String dialect, Token token) {
+ String word = keywordOf(token.kind);
+ return AbstractJSqlParser.Dialect.POSTGRESQL.name().equals(dialect)
+ && POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS.contains(word)
+ && word.equalsIgnoreCase(token.image) && !isNonReserved(token.kind);
+ }
+
+ /** The word of a keyword token, from its name: K_ALL is ALL. */
+ private static String keywordOf(int kind) {
+ String image = tokenImage[kind];
+ return image.startsWith("} won't match.
*/
private static final Pattern SIMPLE_TOKEN_PATTERN =
- Pattern.compile("", Pattern.MULTILINE);
+ Pattern.compile("", Pattern.MULTILINE);
private ParserKeywordsUtils() {
// utility class
diff --git a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
index 83f8d2464..f27ea0a03 100644
--- a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
+++ b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
@@ -463,6 +463,14 @@ public class CCJSqlParser extends AbstractJSqlParser {
private boolean isMySqlDatabaseOptionAhead(int offset) {
int start = getToken(offset).kind == K_DEFAULT ? offset + 1 : offset;
Token token = getToken(start);
+ Token next = getToken(start + 1);
+ // MySQL and PostgreSQL take ENCRYPTION, and PostgreSQL CHARACTER, as database names, as
+ // in CREATE SCHEMA encryption, so they start an option only before the rest of it
+ if (isPostgreSqlDialect() && token.kind == K_CHARACTER && next.kind != K_SET
+ || isEveryKeywordNameDialect() && token.kind == K_ENCRYPTION
+ && !"=".equals(next.image) && next.kind != S_CHAR_LITERAL) {
+ return false;
+ }
return token.kind == K_CHARACTER || token.kind == K_COLLATE || token.kind == K_ENCRYPTION
|| token.kind == K_CHAR && getToken(start + 1).kind == K_SET
|| token.kind == S_IDENTIFIER && "CHARSET".equalsIgnoreCase(token.image);
@@ -884,7 +892,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
case K_NULL: case K_TRUE: case K_FALSE:
return true;
default:
- return (t.kind >= MIN_NON_RESERVED_WORD && t.kind <= MAX_NON_RESERVED_WORD)
+ return NameKeywords.isNonReserved(t.kind)
|| ")".equals(t.image) || "]".equals(t.image)
|| "?".equals(t.image);
}
@@ -935,7 +943,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
case K_ASC: case K_DESC: case K_NULLS:
return false;
default:
- return kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD
+ return NameKeywords.isNonReserved(kind)
&& !isConditionKeywordAhead(2);
}
}
@@ -976,12 +984,6 @@ public class CCJSqlParser extends AbstractJSqlParser {
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) {
@@ -1004,7 +1006,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
// 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))) {
+ if (t.kind == K_APPROXIMATE && NameKeywords.isIdentifierOrNonReserved(getToken(2).kind)) {
t = getToken(2);
}
@@ -1102,7 +1104,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
if (op == K_AND || op == OP_DOUBLEAND) prec = 4;
// MySQL puts XOR between AND and OR; other dialects keep one
// left-associative level for OR and XOR.
- else if (op == K_XOR && !isDialectIdentifierKeyword(op))
+ else if (op == K_XOR && !isDialectName(op))
prec = Dialect.MYSQL.name().equals(getAsString(Feature.dialect)) ? 3 : 2;
else if (op == K_OR) prec = 2;
else if (ternary) prec = 2;
@@ -1396,7 +1398,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
Token token = getToken(offset);
do {
token = nextWithItemToken(token);
- if (!isIdentifierishNameToken(token)) {
+ if (!isNameToken(token)) {
return false;
}
token = nextWithItemToken(token);
@@ -1414,8 +1416,10 @@ public class CCJSqlParser extends AbstractJSqlParser {
try {
if (getToken(1).kind != OPENING_BRACKET) return false;
int k = getToken(2).kind;
- // DuckDB's (FROM t ...) and (TABLE t ...)
- return k == K_SELECT || k == K_WITH || k == K_VALUES || k == K_FROM
+ // DuckDB's (FROM t ...) and (TABLE t ...); PostgreSQL's VALUES lists start with "(",
+ // and otherwise VALUES is a column there, as in (values)
+ return k == K_SELECT || k == K_WITH || k == K_FROM
+ || k == K_VALUES && (getToken(3).kind == OPENING_BRACKET || !isPostgreSqlDialect())
|| k == K_TABLE && isTableQueryAhead(2);
} catch (TokenMgrException e) {
return false;
@@ -1428,26 +1432,11 @@ public class CCJSqlParser extends AbstractJSqlParser {
}
/**
- * Whether the token could start a {@link #RelObjectName()}, mirroring the token
- * alternatives accepted there (base identifiers, DATA_TYPE, non-reserved keywords
- * and the reserved-keyword-as-identifier list).
+ * Whether the token could start a {@link #RelObjectName()} with the selected dialect, as
+ * NameKeywords.isName() decides from the token alternatives accepted there.
*/
- private boolean isIdentifierishNameToken(Token t) {
- switch (t.kind) {
- case S_IDENTIFIER: case S_QUOTED_IDENTIFIER: case DATA_TYPE:
- case K_DATETIMELITERAL: case K_DATE_LITERAL:
- case K_ALL: case K_ANY: case K_BETWEEN: case K_CASEWHEN: case K_CONNECT: case K_CREATE:
- case K_DEFAULT: case K_FULL: case K_GLOBAL: case K_GROUP: case K_GROUPING: case K_IF:
- case K_IIF: case K_IGNORE: case K_IN: case K_INTERVAL: case K_LEFT:
- case K_LIMIT: case K_NEXTVAL: case K_OFFSET: case K_ON: case K_ONLY: case K_OPTIMIZE:
- case K_ORDER: case K_PROCEDURE: case K_PUBLIC: case K_QUALIFY: case K_RETURNING:
- case K_RIGHT: case K_SET: case K_SOME: case K_START: case K_TABLES:
- case K_TOP: case K_VALUE: case K_VALUES:
- return true;
- default:
- return t.kind >= MIN_NON_RESERVED_WORD && t.kind <= MAX_NON_RESERVED_WORD
- || isDialectIdentifierKeyword(t.kind);
- }
+ private boolean isNameToken(Token t) {
+ return NameKeywords.isName(getAsString(Feature.dialect), t.kind);
}
private Token nextWithItemToken(Token current) {
@@ -1481,7 +1470,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
if (t1.kind == K_FUNCTION || t1.kind == K_RECURSIVE) {
return false;
}
- if (!isIdentifierishNameToken(t1)) {
+ if (!isNameToken(t1)) {
return true;
}
Token next = getToken(2);
@@ -1693,10 +1682,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
return false;
}
int kind = getToken(2).kind;
- if (kind == S_IDENTIFIER || kind == S_QUOTED_IDENTIFIER) {
- return true;
- }
- return kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD
+ return NameKeywords.isIdentifierOrNonReserved(kind)
&& kind != K_OVERRIDING && kind != K_BY && kind != K_TABLE;
}
@@ -1884,7 +1870,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
private boolean isOptionHintWordAhead() {
int kind = getToken(1).kind;
if (kind == S_IDENTIFIER
- || (kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD)) {
+ || NameKeywords.isNonReserved(kind)) {
return true;
}
switch (kind) {
@@ -2079,11 +2065,6 @@ public class CCJSqlParser extends AbstractJSqlParser {
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
@@ -2180,6 +2161,24 @@ public class CCJSqlParser extends AbstractJSqlParser {
return isReservedKeywordSafeByFollower();
}
+ /**
+ * Whether ONLY starts PostgreSQL's prefix of a relation, as in ALTER TABLE ONLY t. MySQL and
+ * MariaDB have no such prefix, but the parser reads PostgreSQL's forms with them as well, so
+ * there ONLY is the prefix only before a name, or before "(" in LOCK and TRUNCATE
+ * (relationTarget), and otherwise the name of the relation, as in TRUNCATE TABLE only,
+ * ALTER TABLE only.t or CREATE INDEX i ON only (a).
+ */
+ private boolean isOnlyPrefixAhead(boolean relationTarget) {
+ if (getToken(1).kind != K_ONLY) {
+ return false;
+ }
+ if (!isMySqlDialect()) {
+ return true;
+ }
+ Token next = getToken(2);
+ return isNameToken(next) || relationTarget && next.kind == OPENING_BRACKET;
+ }
+
/**
* Whether ONLY is PostgreSQL's prefix of a relation name, as in DELETE FROM ONLY t,
* JOIN ONLY t or FROM a, ONLY b, rather than a table or column named only.
@@ -2406,7 +2405,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
/** SEMI/ANTI stay contextual identifiers unless they prefix a JOIN. */
private boolean isSemiAntiJoinAhead() {
int kind = getToken(1).kind;
- if (kind != K_SEMI && kind != K_ANTI || isDialectIdentifierKeyword(kind)) {
+ if (kind != K_SEMI && kind != K_ANTI || isDialectName(kind)) {
return false;
}
return getToken(2).kind == K_JOIN;
@@ -2481,9 +2480,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
Token next = getToken(1);
return next.kind == OPENING_BRACKET || next.kind == OP_CARET
|| next.kind == OPENING_CURLY_BRACKET && "-".equals(getToken(2).image)
- || next.kind == S_IDENTIFIER || next.kind == S_QUOTED_IDENTIFIER
- || next.kind == DATA_TYPE
- || next.kind >= MIN_NON_RESERVED_WORD && next.kind <= MAX_NON_RESERVED_WORD;
+ || next.kind == DATA_TYPE || NameKeywords.isIdentifierOrNonReserved(next.kind);
}
private static boolean isSliceDelimiter(Token token) {
@@ -2524,7 +2521,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
}
Token next = getToken(2);
int following = getToken(3).kind;
- if (isDialectIdentifierKeyword(next.kind)) {
+ if (isDialectName(next.kind)) {
return false;
}
switch (next.kind) {
@@ -2612,7 +2609,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
while (true) {
// column [. column]* AS name
while (true) {
- if (!isIdentifierishNameToken(token)) {
+ if (!isNameToken(token)) {
return false;
}
token = nextWithItemToken(token);
@@ -2625,7 +2622,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
return false;
}
token = nextWithItemToken(token);
- if (!isIdentifierishNameToken(token)) {
+ if (!isNameToken(token)) {
return false;
}
token = nextWithItemToken(token);
@@ -2656,7 +2653,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
case K_PARTITION: case K_ORDER: case K_ROWS: case K_RANGE: case K_GROUPS:
return false;
default:
- return isIdentifierishNameToken(token);
+ return isNameToken(token);
}
}
@@ -2700,7 +2697,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
// ClickHouse's PREWHERE and SETTINGS clauses, not aliases
if (kind == K_PREWHERE || kind == K_SETTINGS) {
- return false;
+ return isBareAliasAhead();
}
// MySQL's FORCE INDEX|KEY (...) index hint, not an alias
@@ -2714,42 +2711,70 @@ public class CCJSqlParser extends AbstractJSqlParser {
}
// A keyword of another dialect is a plain name in a dialect that lacks it
- if (isDialectIdentifierKeyword(kind)) {
+ if (isDialectName(kind)) {
+ return true;
+ }
+
+ if (isBareAliasAhead()) {
return true;
}
// For reserved keywords in alias position, skip the structural-
// keyword whitelist and go directly to follower disambiguation.
- // Only check keywords that are actually in RelObjectName's token
- // alternatives — don't fire for brackets, operators, literals, etc.
- switch (kind) {
- case K_ALL: case K_ARRAY_LITERAL: case K_ANY: case K_CASEWHEN: case K_CONNECT:
- case K_CREATE: case K_DEFAULT: case K_FULL:
- case K_GLOBAL: case K_GROUP: case K_GROUPING: case K_IF:
- case K_IIF: case K_IGNORE: case K_IN: case K_INTERVAL:
- case K_LEFT: case K_LIMIT: case K_NEXTVAL: case K_OFFSET:
- case K_ON: case K_OPTIMIZE: case K_ORDER: case K_PROCEDURE:
- case K_PUBLIC: case K_QUALIFY: case K_RIGHT:
- case K_SET: case K_SOME: case K_START: case K_TABLES:
- case K_TOP: case K_VALUE: case K_VALUES:
- return isReservedKeywordSafeByFollower();
- default:
- break;
+ if (NameKeywords.isAliasCheckedByFollower(kind)) {
+ return isReservedKeywordSafeByFollower();
}
- // Base identifier tokens
- if (kind == S_IDENTIFIER || kind == S_QUOTED_IDENTIFIER
- || kind == DATA_TYPE || kind == K_DATETIMELITERAL
- || kind == K_DATE_LITERAL) {
- return true;
- }
+ return NameKeywords.isBaseName(kind) || NameKeywords.isNonReserved(kind);
+ }
- // Non-reserved keywords
- if (kind >= MIN_NON_RESERVED_WORD && kind <= MAX_NON_RESERVED_WORD) {
- return true;
+ /**
+ * Whether a keyword that MySQL or PostgreSQL reads as a name is an alias without AS here, as
+ * the token after it ends the alias: SELECT a offset FROM t, SELECT a glob FROM t, FROM t only.
+ * The clause or the operator of another dialect that the keyword would start, OFFSET 5 or
+ * GLOB 'x*', needs more than that, so it keeps its reading; ISNULL and NOTNULL need nothing
+ * more and stay operators.
+ *
+ * The dialect reads the word as a name: MySQL one that it does not reserve, other than MEMBER,
+ * which starts MEMBER OF after an expression, and PostgreSQL a column identifier (ColId).
+ */
+ private boolean isBareAliasAhead() {
+ Token token = getToken(1);
+ String dialect = getAsString(Feature.dialect);
+ boolean name;
+ if (Dialect.MYSQL.name().equals(dialect)) {
+ name = token.kind != K_MEMBER && NameKeywords.isMySqlIdentifier(token.image);
+ } else if (Dialect.POSTGRESQL.name().equals(dialect)) {
+ name = NameKeywords.isPostgreSqlColId(token.image);
+ } else {
+ return false;
}
+ return name && token.kind != K_ISNULL && token.kind != K_NOTNULL
+ && (NameKeywords.isNonReserved(token.kind) || isDialectName(token.kind)
+ || isDialectObjectName())
+ && isAliasEndAt(2);
+ }
- return false;
+ /**
+ * Whether the token at the offset ends an alias: the end of the statement, a comma or ")", or
+ * a keyword that starts the next clause, a set operation or a join, none of which MySQL or
+ * PostgreSQL reads as a name or as the start of an expression.
+ */
+ private boolean isAliasEndAt(int offset) {
+ Token token = getToken(offset);
+ switch (token.kind) {
+ case EOF: case ST_SEMICOLON: case K_COMMA: case CLOSING_BRACKET:
+ case K_FROM: case K_WHERE: case K_HAVING: case K_WINDOW: case K_INTO:
+ case K_UNION: case K_INTERSECT: case K_EXCEPT:
+ case K_JOIN: case K_INNER: case K_CROSS: case K_NATURAL: case K_USING:
+ return true;
+ case K_GROUP: case K_ORDER:
+ return getToken(offset + 1).kind == K_BY;
+ case K_LEFT: case K_RIGHT: case K_FULL:
+ return getToken(offset + 1).kind == K_JOIN || getToken(offset + 1).kind == K_OUTER;
+ default:
+ return false;
+ }
}
private static void requireSyntax(boolean valid, String message) throws ParseException {
@@ -2862,8 +2887,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
int offset = 2;
while (true) {
int kind = getToken(offset).kind;
- if (kind != S_IDENTIFIER && kind != S_QUOTED_IDENTIFIER && kind != DATA_TYPE
- && (kind < MIN_NON_RESERVED_WORD || kind > MAX_NON_RESERVED_WORD)) {
+ if (kind != DATA_TYPE && !NameKeywords.isIdentifierOrNonReserved(kind)) {
return false;
}
String next = getToken(offset + 1).image;
@@ -2993,15 +3017,15 @@ public class CCJSqlParser extends AbstractJSqlParser {
return false;
}
int offset = 2;
- while (isIdentifierishNameToken(getToken(offset)) && ".".equals(getToken(offset + 1).image)) {
+ while (isNameToken(getToken(offset)) && ".".equals(getToken(offset + 1).image)) {
offset += 2;
}
- if (!isIdentifierishNameToken(getToken(offset))) {
+ if (!isNameToken(getToken(offset))) {
return false;
}
Token next = getToken(offset + 1);
return next.kind == K_AS || isMySqlLockTypeAhead(offset + 1)
- || isIdentifierishNameToken(next) && isMySqlLockTypeAhead(offset + 2);
+ || isNameToken(next) && isMySqlLockTypeAhead(offset + 2);
}
private boolean isMySqlLockTypeAhead(int offset) {
@@ -3069,11 +3093,11 @@ public class CCJSqlParser extends AbstractJSqlParser {
return false;
}
int offset = 2;
- while (isIdentifierishNameToken(getToken(offset)) && ".".equals(getToken(offset + 1).image)) {
+ while (isNameToken(getToken(offset)) && ".".equals(getToken(offset + 1).image)) {
offset += 2;
}
int action = getToken(offset + 1).kind;
- return isIdentifierishNameToken(getToken(offset))
+ return isNameToken(getToken(offset))
&& (action == K_OPEN || action == K_READ || action == K_CLOSE);
}
@@ -3086,9 +3110,9 @@ public class CCJSqlParser extends AbstractJSqlParser {
switch (next.kind) {
case K_FIRST: case K_NEXT: case K_LAST:
case OP_GREATERTHANEQUALS: case OP_MINORTHANEQUALS:
- return isIdentifierishNameToken(getToken(1));
+ return isNameToken(getToken(1));
default:
- return isIdentifierishNameToken(getToken(1)) && ("=".equals(next.image)
+ return isNameToken(getToken(1)) && ("=".equals(next.image)
|| "<".equals(next.image) || ">".equals(next.image)
|| next.kind == S_IDENTIFIER && "PREV".equalsIgnoreCase(next.image));
}
@@ -3110,7 +3134,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
Token next = getToken(3);
int end = getToken(4).kind;
return dialect == null && (next.kind == K_IF && end == K_EXISTS
- || isIdentifierishNameToken(next)
+ || isNameToken(next)
&& (end == EOF || end == ST_SEMICOLON || ".".equals(getToken(4).image)));
}
@@ -3343,7 +3367,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
return false;
}
Token channel = getToken(2);
- return getAsString(Feature.dialect) != null || isIdentifierishNameToken(channel)
+ return getAsString(Feature.dialect) != null || isNameToken(channel)
|| kind == K_UNLISTEN && "*".equals(channel.image);
}
@@ -3390,7 +3414,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
private boolean isCopyBinaryAhead() {
Token next = getToken(2);
return getToken(1).kind == K_BINARY && isPostgreSqlUtilityDialect()
- && next.kind != K_FROM && next.kind != K_TO && isIdentifierishNameToken(next);
+ && next.kind != K_FROM && next.kind != K_TO && isNameToken(next);
}
/** Whether an option of PostgreSQL's COPY syntax from before 9.0, as copy_opt_item, follows. */
@@ -3415,106 +3439,6 @@ public class CCJSqlParser extends AbstractJSqlParser {
return token.kind == S_IDENTIFIER && word.equalsIgnoreCase(token.image);
}
- /**
- * PostgreSQL 18's reserved keywords. Its grammar takes none of them as the name or the word
- * value of a utility option, except ANALYZE and ANALYSE as names.
- */
- private static final Set POSTGRESQL_RESERVED_KEYWORDS = new HashSet(Arrays.asList(
- "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC", "BOTH",
- "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", "CURRENT_CATALOG",
- "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER",
- "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE",
- "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY",
- "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP", "NOT",
- "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY", "REFERENCES",
- "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "SYSTEM_USER", "TABLE", "THEN",
- "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC", "WHEN", "WHERE",
- "WINDOW", "WITH"));
-
- /**
- * PostgreSQL 18's type and function name keywords. Like its reserved keywords, its grammar
- * takes none of them as a column identifier (ColId).
- */
- private static final Set POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS = new HashSet(Arrays.asList(
- "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA",
- "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL",
- "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE"));
-
- /**
- * PostgreSQL 18's column name keywords that are not a type name by themselves, so its grammar
- * takes none of them as the single word of a definition value. NONE is one more, but a
- * definition value takes it as the keyword it is.
- */
- private static final Set POSTGRESQL_NON_TYPE_COL_NAME_KEYWORDS = new HashSet(Arrays.asList(
- "BETWEEN", "COALESCE", "EXISTS", "EXTRACT", "GREATEST", "GROUPING", "INOUT", "JSON_ARRAY",
- "JSON_ARRAYAGG", "JSON_EXISTS", "JSON_OBJECT", "JSON_OBJECTAGG", "JSON_QUERY",
- "JSON_SCALAR", "JSON_SERIALIZE", "JSON_TABLE", "JSON_VALUE", "LEAST", "MERGE_ACTION",
- "NATIONAL", "NORMALIZE", "NULLIF", "OUT", "OVERLAY", "POSITION", "PRECISION", "ROW",
- "SETOF", "SUBSTRING", "TREAT", "TRIM", "VALUES", "XMLATTRIBUTES", "XMLCONCAT",
- "XMLELEMENT", "XMLEXISTS", "XMLFOREST", "XMLNAMESPACES", "XMLPARSE", "XMLPI", "XMLROOT",
- "XMLSERIALIZE", "XMLTABLE"));
-
- /**
- * PostgreSQL 18's unreserved keywords and its column name keywords that are type names: the
- * keywords that are in none of the sets above.
- */
- private static final Set POSTGRESQL_OTHER_KEYWORDS = new HashSet(Arrays.asList(
- "ABORT", "ABSENT", "ABSOLUTE", "ACCESS", "ACTION", "ADD", "ADMIN", "AFTER",
- "AGGREGATE", "ALSO", "ALTER", "ALWAYS", "ASENSITIVE", "ASSERTION", "ASSIGNMENT",
- "AT", "ATOMIC", "ATTACH", "ATTRIBUTE", "BACKWARD", "BEFORE", "BEGIN", "BIGINT",
- "BIT", "BOOLEAN", "BREADTH", "BY", "CACHE", "CALL", "CALLED", "CASCADE", "CASCADED",
- "CATALOG", "CHAIN", "CHAR", "CHARACTER", "CHARACTERISTICS", "CHECKPOINT", "CLASS",
- "CLOSE", "CLUSTER", "COLUMNS", "COMMENT", "COMMENTS", "COMMIT", "COMMITTED",
- "COMPRESSION", "CONDITIONAL", "CONFIGURATION", "CONFLICT", "CONNECTION",
- "CONSTRAINTS", "CONTENT", "CONTINUE", "CONVERSION", "COPY", "COST", "CSV", "CUBE",
- "CURRENT", "CURSOR", "CYCLE", "DATA", "DATABASE", "DAY", "DEALLOCATE", "DEC",
- "DECIMAL", "DECLARE", "DEFAULTS", "DEFERRED", "DEFINER", "DELETE", "DELIMITER",
- "DELIMITERS", "DEPENDS", "DEPTH", "DETACH", "DICTIONARY", "DISABLE", "DISCARD",
- "DOCUMENT", "DOMAIN", "DOUBLE", "DROP", "EACH", "EMPTY", "ENABLE", "ENCODING",
- "ENCRYPTED", "ENFORCED", "ENUM", "ERROR", "ESCAPE", "EVENT", "EXCLUDE", "EXCLUDING",
- "EXCLUSIVE", "EXECUTE", "EXPLAIN", "EXPRESSION", "EXTENSION", "EXTERNAL", "FAMILY",
- "FILTER", "FINALIZE", "FIRST", "FLOAT", "FOLLOWING", "FORCE", "FORMAT", "FORWARD",
- "FUNCTION", "FUNCTIONS", "GENERATED", "GLOBAL", "GRANTED", "GROUPS", "HANDLER",
- "HEADER", "HOLD", "HOUR", "IDENTITY", "IF", "IMMEDIATE", "IMMUTABLE", "IMPLICIT",
- "IMPORT", "INCLUDE", "INCLUDING", "INCREMENT", "INDENT", "INDEX", "INDEXES",
- "INHERIT", "INHERITS", "INLINE", "INPUT", "INSENSITIVE", "INSERT", "INSTEAD", "INT",
- "INTEGER", "INTERVAL", "INVOKER", "ISOLATION", "JSON", "KEEP", "KEY", "KEYS",
- "LABEL", "LANGUAGE", "LARGE", "LAST", "LEAKPROOF", "LEVEL", "LISTEN", "LOAD",
- "LOCAL", "LOCATION", "LOCK", "LOCKED", "LOGGED", "MAPPING", "MATCH", "MATCHED",
- "MATERIALIZED", "MAXVALUE", "MERGE", "METHOD", "MINUTE", "MINVALUE", "MODE",
- "MONTH", "MOVE", "NAME", "NAMES", "NCHAR", "NESTED", "NEW", "NEXT", "NFC", "NFD",
- "NFKC", "NFKD", "NO", "NONE", "NORMALIZED", "NOTHING", "NOTIFY", "NOWAIT", "NULLS",
- "NUMERIC", "OBJECT", "OBJECTS", "OF", "OFF", "OIDS", "OLD", "OMIT", "OPERATOR",
- "OPTION", "OPTIONS", "ORDINALITY", "OTHERS", "OVER", "OVERRIDING", "OWNED", "OWNER",
- "PARALLEL", "PARAMETER", "PARSER", "PARTIAL", "PARTITION", "PASSING", "PASSWORD",
- "PATH", "PERIOD", "PLAN", "PLANS", "POLICY", "PRECEDING", "PREPARE", "PREPARED",
- "PRESERVE", "PRIOR", "PRIVILEGES", "PROCEDURAL", "PROCEDURE", "PROCEDURES",
- "PROGRAM", "PUBLICATION", "QUOTE", "QUOTES", "RANGE", "READ", "REAL", "REASSIGN",
- "RECURSIVE", "REF", "REFERENCING", "REFRESH", "REINDEX", "RELATIVE", "RELEASE",
- "RENAME", "REPEATABLE", "REPLACE", "REPLICA", "RESET", "RESTART", "RESTRICT",
- "RETURN", "RETURNS", "REVOKE", "ROLE", "ROLLBACK", "ROLLUP", "ROUTINE", "ROUTINES",
- "ROWS", "RULE", "SAVEPOINT", "SCALAR", "SCHEMA", "SCHEMAS", "SCROLL", "SEARCH",
- "SECOND", "SECURITY", "SEQUENCE", "SEQUENCES", "SERIALIZABLE", "SERVER", "SESSION",
- "SET", "SETS", "SHARE", "SHOW", "SIMPLE", "SKIP", "SMALLINT", "SNAPSHOT", "SOURCE",
- "SQL", "STABLE", "STANDALONE", "START", "STATEMENT", "STATISTICS", "STDIN",
- "STDOUT", "STORAGE", "STORED", "STRICT", "STRING", "STRIP", "SUBSCRIPTION",
- "SUPPORT", "SYSID", "SYSTEM", "TABLES", "TABLESPACE", "TARGET", "TEMP", "TEMPLATE",
- "TEMPORARY", "TEXT", "TIES", "TIME", "TIMESTAMP", "TRANSACTION", "TRANSFORM",
- "TRIGGER", "TRUNCATE", "TRUSTED", "TYPE", "TYPES", "UESCAPE", "UNBOUNDED",
- "UNCOMMITTED", "UNCONDITIONAL", "UNENCRYPTED", "UNKNOWN", "UNLISTEN", "UNLOGGED",
- "UNTIL", "UPDATE", "VACUUM", "VALID", "VALIDATE", "VALIDATOR", "VALUE", "VARCHAR",
- "VARYING", "VERSION", "VIEW", "VIEWS", "VIRTUAL", "VOLATILE", "WHITESPACE",
- "WITHIN", "WITHOUT", "WORK", "WRAPPER", "WRITE", "XML", "YEAR", "YES", "ZONE"));
-
- /** Whether the word is a keyword of PostgreSQL 18, of any kind. A quoted identifier is none. */
- private static boolean isPostgreSqlKeyword(String word) {
- String upper = word.toUpperCase(Locale.ROOT);
- return POSTGRESQL_RESERVED_KEYWORDS.contains(upper)
- || POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS.contains(upper)
- || POSTGRESQL_NON_TYPE_COL_NAME_KEYWORDS.contains(upper)
- || POSTGRESQL_OTHER_KEYWORDS.contains(upper);
- }
-
/**
* Checks an operator name the way PostgreSQL's lexer delimits one. A name of several characters
* ends in + or - only if it has one of ~ ! @ # % ^ & | ` ?, since the lexer otherwise leaves
@@ -3608,7 +3532,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
*/
private void requireOldAggregateDefinition(List definition) throws ParseException {
for (DefinitionElement element : definition) {
- requireDdlSyntax(element.getArgument() != null && !isPostgreSqlKeyword(element.getName()),
+ requireDdlSyntax(element.getArgument() != null && !NameKeywords.isPostgreSqlKeyword(element.getName()),
"PostgreSQL expects an identifier and a value: " + element);
}
}
@@ -3661,10 +3585,10 @@ public class CCJSqlParser extends AbstractJSqlParser {
if (token.kind == K_NONE) {
return DefinitionArgument.none();
}
- if (POSTGRESQL_RESERVED_KEYWORDS.contains(upper)) {
+ if (NameKeywords.isPostgreSqlReserved(upper)) {
return DefinitionArgument.keyword(token.image);
}
- requireDdlSyntax(!POSTGRESQL_NON_TYPE_COL_NAME_KEYWORDS.contains(upper),
+ requireDdlSyntax(!NameKeywords.isPostgreSqlNonTypeColName(upper),
"PostgreSQL does not take " + token.image + " as a definition value");
return DefinitionArgument.type(linkToLastToken(new ColDataType(token.image)));
}
@@ -3672,7 +3596,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
/** Rejects an unquoted utility option name or word value that PostgreSQL reserves. */
private void requireUtilityOptionWord(String word, boolean name) throws ParseException {
String upper = word.toUpperCase(Locale.ROOT);
- requireDdlSyntax(!POSTGRESQL_RESERVED_KEYWORDS.contains(upper)
+ requireDdlSyntax(!NameKeywords.isPostgreSqlReserved(upper)
|| name && ("ANALYZE".equals(upper) || "ANALYSE".equals(upper)),
"PostgreSQL reserves " + word + " in utility options");
}
@@ -3680,8 +3604,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
/** Rejects an unquoted name that PostgreSQL does not take as a column or channel name. */
private void requirePostgreSqlColId(String name) throws ParseException {
String upper = name.toUpperCase(Locale.ROOT);
- requireDdlSyntax(!POSTGRESQL_RESERVED_KEYWORDS.contains(upper)
- && !POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS.contains(upper),
+ requireDdlSyntax(NameKeywords.isPostgreSqlColId(upper),
"PostgreSQL does not take " + name + " as a name here");
}
@@ -3724,7 +3647,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
|| next.kind == K_ANALYSE || "FREEZE".equalsIgnoreCase(next.image))) {
return true;
}
- return isIdentifierishNameToken(next) && isMaintenanceTableEnd(getToken(3), targets);
+ return isNameToken(next) && isMaintenanceTableEnd(getToken(3), targets);
}
/**
@@ -3784,12 +3707,11 @@ public class CCJSqlParser extends AbstractJSqlParser {
/** Whether the token can name a cursor: PostgreSQL takes any column identifier (ColId). */
private boolean isCursorNameToken(Token token) {
- if (!isIdentifierishNameToken(token)) {
+ if (!isNameToken(token)) {
return false;
}
String word = token.image.toUpperCase(Locale.ROOT);
- return !POSTGRESQL_RESERVED_KEYWORDS.contains(word)
- && !POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS.contains(word);
+ return NameKeywords.isPostgreSqlColId(word);
}
/**
@@ -3907,7 +3829,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
}
Token next = getToken(2);
return getAsString(Feature.dialect) != null || next.kind == K_ONLY
- || isIdentifierishNameToken(next) && isMaintenanceTableEnd(getToken(3), true);
+ || isNameToken(next) && isMaintenanceTableEnd(getToken(3), true);
}
/**
@@ -4080,7 +4002,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
private boolean isConstraintNameBeforeKindAhead() {
int kind = getToken(1).kind;
// PRIMARY is reserved in MySQL and PostgreSQL, and MySQL reserves the index words too
- if (!isIdentifierishNameToken(getToken(1)) || kind == K_PRIMARY || isMySqlDialect()
+ if (!isNameToken(getToken(1)) || kind == K_PRIMARY || isMySqlDialect()
&& (kind == K_KEY || kind == K_INDEX || kind == K_FULLTEXT || kind == K_SPATIAL)) {
return false;
}
@@ -4689,106 +4611,33 @@ public class CCJSqlParser extends AbstractJSqlParser {
* 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) {
- return DialectKeywordNames.isIdentifier(getAsString(Feature.dialect), kind);
+ private boolean isDialectName(int kind) {
+ return NameKeywords.isDialectName(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.
+ * Dialect.MYSQL, whose keywords NameKeywords holds. MariaDB, which isMySqlDialect() also
+ * covers, keeps its readings.
*/
- 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:
- case K_PREFERRING: case K_SEMI: case K_TOP: case K_UNPIVOT:
- return true;
- default:
- return false;
- }
- }
-
- 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:
- case K_PREFERRING: case K_QUALIFY: case K_SEMI: case K_SQL_CACHE:
- case K_SQL_CALC_FOUND_ROWS: case K_STRAIGHT: case K_TOP: case K_UNPIVOT:
- case K_USE: case K_XOR:
- return true;
- default:
- 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 boolean isMySqlNameDialect() {
+ return Dialect.MYSQL.name().equals(getAsString(Feature.dialect));
+ }
- 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);
- }
- }
+ /** MySQL and PostgreSQL read every keyword after "." as a name. */
+ private boolean isEveryKeywordNameDialect() {
+ String dialect = getAsString(Feature.dialect);
+ return Dialect.MYSQL.name().equals(dialect) || Dialect.POSTGRESQL.name().equals(dialect);
+ }
- 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);
- }
- }
+ /**
+ * Whether the selected dialect reads the next keyword as the name of a schema object wherever
+ * ObjectName() stands, although this parser reserves it, as NameKeywords.isObjectName()
+ * decides. With PostgreSQL, ONLY before a relation stays its prefix; MySQL has no such prefix.
+ */
+ private boolean isDialectObjectName() {
+ int kind = getToken(1).kind;
+ return NameKeywords.isObjectName(getAsString(Feature.dialect), getToken(1))
+ && !(kind == K_ONLY && !isMySqlDialect() && isRelationOnlyAhead(getToken(0)));
}
/** MySQL's EXPLAIN, PREPARE, EXECUTE, DROP PREPARE and DO: MySQL, MariaDB or no dialect. */
@@ -5330,10 +5179,14 @@ public class CCJSqlParser extends AbstractJSqlParser {
private boolean isMySqlSelectModifierAhead() {
Token token = getToken(1);
+ // MySQL 8 removed SQL_CACHE, so with MySQL it is a name, and a modifier only before a
+ // select item, as SQL_NO_CACHE below
+ boolean mySqlSqlCache = token.kind == K_SQL_CACHE
+ && Dialect.MYSQL.name().equals(getAsString(Feature.dialect));
// These existing modifiers remain available without a dialect preset.
- if (token.kind == K_STRAIGHT || token.kind == K_SQL_CACHE
- || token.kind == K_SQL_CALC_FOUND_ROWS) {
- return !isDialectIdentifierKeyword(token.kind);
+ if ((token.kind == K_STRAIGHT || token.kind == K_SQL_CACHE
+ || token.kind == K_SQL_CALC_FOUND_ROWS) && !mySqlSqlCache) {
+ return !isDialectName(token.kind);
}
// Keep qualified names, aliases and standalone identifier expressions intact.
int next = getToken(2).kind;
@@ -5342,8 +5195,14 @@ public class CCJSqlParser extends AbstractJSqlParser {
|| ")".equals(getToken(2).image)) {
return false;
}
+ // Where the dialect has no such modifier, SQL_CACHE with MySQL and the others with
+ // PostgreSQL, an operator that cannot start a select item continues an expression that
+ // the word starts, as in SELECT sql_no_cache IN (1, 2) FROM t
+ if ((mySqlSqlCache || isPostgreSqlDialect()) && isInfixOperatorAt(2)) {
+ return false;
+ }
// SQL_NO_CACHE is a non-reserved word, so it is a modifier only before a select item.
- if (token.kind == K_SQL_NO_CACHE) {
+ if (token.kind == K_SQL_NO_CACHE || mySqlSqlCache) {
return true;
}
if (getAsString(Feature.dialect) != null && !isMySqlDialect()) {
@@ -5355,6 +5214,22 @@ public class CCJSqlParser extends AbstractJSqlParser {
|| "SQL_BUFFER_RESULT".equalsIgnoreCase(token.image));
}
+ /**
+ * Whether the token at the offset is a comparison, IN, IS, LIKE or BETWEEN, which continue an
+ * expression and cannot start one.
+ */
+ private boolean isInfixOperatorAt(int offset) {
+ Token token = getToken(offset);
+ switch (token.kind) {
+ case K_IN: case K_IS: case K_LIKE: case K_BETWEEN:
+ return true;
+ default:
+ return "=".equals(token.image) || "<".equals(token.image) || ">".equals(token.image)
+ || "<=".equals(token.image) || ">=".equals(token.image)
+ || "<>".equals(token.image) || "!=".equals(token.image);
+ }
+ }
+
/** Recognizes PostgreSQL's language form without taking other products' opaque LANGUAGE DDL. */
private boolean isCreateLanguageAhead() {
if (isPostgreSqlDialect() && isAnyWordAt(1, "TRUSTED", "PROCEDURAL", "LANGUAGE")) {
@@ -5432,10 +5307,9 @@ public class CCJSqlParser extends AbstractJSqlParser {
int dot = name.indexOf('.');
String upper = (dot < 0 ? name : name.substring(0, dot)).toUpperCase(Locale.ROOT);
boolean valid = role
- ? !POSTGRESQL_RESERVED_KEYWORDS.contains(upper) || "CURRENT_ROLE".equals(upper)
+ ? !NameKeywords.isPostgreSqlReserved(upper) || "CURRENT_ROLE".equals(upper)
|| "CURRENT_USER".equals(upper) || "SESSION_USER".equals(upper)
- : !POSTGRESQL_RESERVED_KEYWORDS.contains(upper)
- && !POSTGRESQL_TYPE_FUNC_NAME_KEYWORDS.contains(upper);
+ : NameKeywords.isPostgreSqlColId(upper);
requireDdlSyntax(valid, "PostgreSQL does not take " + name + " as a name here");
}
@@ -5857,7 +5731,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
boolean name = next == S_IDENTIFIER || next == S_QUOTED_IDENTIFIER || next == OPENING_BRACKET;
switch (prev.kind) {
case K_FROM: case K_JOIN: case K_UPDATE: case K_INTO: case K_USING:
- return name || next >= MIN_NON_RESERVED_WORD && next <= MAX_NON_RESERVED_WORD;
+ return next == OPENING_BRACKET || NameKeywords.isIdentifierOrNonReserved(next);
case K_COMMA:
// a column definition continues with its type, as in (a INT, only INT)
return name;
@@ -6071,6 +5945,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
*/
protected boolean isConditionSuffixAhead() {
Token t = getToken(1);
+ if (isBareAliasAhead()) return false;
if (isLikeOperator(t)) return true;
// Inline isComparisonOperatorAhead for single getToken(1) call
if (t.kind == OPENING_BRACKET && getToken(2).image.equals("+")) {
@@ -6084,7 +5959,7 @@ public class CCJSqlParser extends AbstractJSqlParser {
}
private boolean isConditionKeywordAhead(int offset) {
- if (isDialectIdentifierKeyword(getToken(offset).kind)) {
+ if (isDialectName(getToken(offset).kind)) {
return false;
}
switch (getToken(offset).kind) {
@@ -6245,6 +6120,9 @@ TOKEN_MGR_DECLS : {
t.absoluteBegin = getCurrentTokenAbsolutePosition();
t.absoluteEnd = t.absoluteBegin + t.image.length();
positionComments(t);
+ lexSelAsName(t);
+ lexMySqlSimilarTo(t);
+ lexMySqlNameBeforeDot(t);
lastToken = t;
// Track the lexical region independently of parser lookahead: nested SELECT
// disambiguation can fetch PATTERN tokens before its production is entered.
@@ -6262,6 +6140,77 @@ TOKEN_MGR_DECLS : {
// the last token handed out with a token action, whose successor is the first end-of-file token
private Token lastToken;
+ /**
+ * SEL, the short form of SELECT that this parser reads, is no keyword of MySQL or PostgreSQL:
+ * with their dialects it is an identifier.
+ */
+ private void lexSelAsName(Token t) {
+ if (t.kind == K_SELECT && t.image.length() == 3) {
+ Object dialect = configuration.getValue(Feature.dialect);
+ if (AbstractJSqlParser.Dialect.MYSQL.name().equals(dialect)
+ || AbstractJSqlParser.Dialect.POSTGRESQL.name().equals(dialect)) {
+ t.kind = S_IDENTIFIER;
+ }
+ }
+ }
+
+ /**
+ * The lexer reads "similar TO" as the one token of SIMILAR TO. MySQL has no SIMILAR TO and
+ * takes similar as a name, so with Dialect.MYSQL the token is the word similar, and TO follows
+ * it, as in RENAME COLUMN similar TO c.
+ */
+ private void lexMySqlSimilarTo(Token t) {
+ if (t.kind == K_SIMILAR_TO
+ && AbstractJSqlParser.Dialect.MYSQL.name().equals(configuration.getValue(Feature.dialect))) {
+ truncateIdentifierToken(t, t.image.indexOf(' '));
+ t.kind = K_SIMILAR;
+ }
+ }
+
+ /**
+ * MySQL's lexer does not look a word up as a keyword when "." and an identifier character
+ * follow it directly, so that any word starts a qualified name there, as in and.t or
+ * all.a. With Dialect.MYSQL a reserved keyword becomes an identifier there too.
+ */
+ private void lexMySqlNameBeforeDot(Token t) {
+ if (NameKeywords.isBaseName(t.kind) || NameKeywords.isNonReserved(t.kind)
+ || !tokenImage[t.kind].startsWith("= 0x80 || Character.isLetterOrDigit(c) || c == '_' || c == '$';
+ }
+
/**
* Gives the comments before the end of input their positions. The end-of-file token gets no
* token action, and it is the first one after the last token that does which holds them.
@@ -8118,7 +8067,7 @@ AlterInstance AlterInstance():
|
ContextualKeyword("TLS") { statement = new AlterInstance(AlterInstance.Action.RELOAD_TLS); }
[
- ContextualKeyword("CHANNEL") channel=RelObjectName()
+ ContextualKeyword("CHANNEL") channel=ObjectName()
{
// a double-quoted name is a string in MySQL, which takes an identifier here
requireDdlSyntax(!channel.startsWith("\"") && !channel.startsWith("["),
@@ -8235,7 +8184,8 @@ TableReference RelationTarget():
TableReference target;
}
{
- [ LOOKAHEAD(2) { only = true; } ]
+ // A choice rather than [ ... ], so that the check also holds while scanning ahead
+ ( LOOKAHEAD({ isOnlyPrefixAhead(true) }) { only = true; } | {} )
( "(" table=Table() ")" { parenthesized = true; } | table=Table() )
[ "*" { descendants = true; } ]
{
@@ -8959,7 +8909,7 @@ ConnectionDefinition ConnectionDefinition(): {
} {
(
- connectionObjectName = RelObjectName() { connectionDefinition.setConnectionObjectName(connectionObjectName); }
+ connectionObjectName = ObjectName() { connectionDefinition.setConnectionObjectName(connectionObjectName); }
| token= { connectionDefinition.setConnectionDefinition(stringValue(token)); }
)
@@ -8987,7 +8937,7 @@ ConnectionDefinition CloudConnectionDefinition(): {
)
(
- connectionObjectName = RelObjectName() { connectionDefinition.setConnectionObjectName(connectionObjectName); }
+ connectionObjectName = ObjectName() { connectionDefinition.setConnectionObjectName(connectionObjectName); }
| token = { connectionDefinition.setConnectionDefinition(stringValue(token)); }
)
@@ -9175,7 +9125,7 @@ CursorOption CursorOption():
String CursorName():
{ Token token = getToken(1); String name; }
{
- name=RelObjectName()
+ name=ObjectName()
{
requireDdlSyntax(isCursorNameToken(token), "Invalid cursor name: " + token.image);
return name;
@@ -9540,7 +9490,7 @@ ResetStatement ResetPersist():
[
// MySQL reserves IF, so IF without EXISTS starts the next statement
LOOKAHEAD({ getToken(1).kind == K_IF ? getToken(2).kind == K_EXISTS
- : isIdentifierishNameToken(getToken(1)) })
+ : isNameToken(getToken(1)) })
[ LOOKAHEAD(2) { reset.setIfExists(true); } ]
// MySQL's persisted_variable_ident: ident, ident.ident or DEFAULT.ident
(
@@ -9736,7 +9686,7 @@ void CopyLegacyOptionColumns(CopyLegacyOption option):
String CopyLegacyColumnName():
{ String name; }
{
- name=RelObjectName() { requirePostgreSqlColId(name); return name; }
+ name=ObjectName() { requirePostgreSqlColId(name); return name; }
}
/**
@@ -9992,7 +9942,7 @@ PluginStatement PluginStatement():
(
LOOKAHEAD({ isKeywordAhead("PLUGIN") }) ContextualKeyword("PLUGIN")
{ statement = new PluginStatement(action, PluginStatement.ObjectType.PLUGIN); }
- name=RelObjectName() { statement.setPluginName(name); }
+ name=ObjectName() { statement.setPluginName(name); }
[ LOOKAHEAD({ isKeywordAhead("SONAME") }) ContextualKeyword("SONAME") token=
{ statement.setLibrary(mySqlTextString(token)); } ]
{
@@ -10393,7 +10343,7 @@ PurgeStatement PurgeStatement(): {
{ purgeStatement = new PurgeStatement(PurgeObjectType.DBA_RECYCLEBIN); }
|
// the names take non-reserved keywords such as STOP, which were plain identifiers before
- tableSpaceName=RelObjectName() [ userName=RelObjectName() ] {
+ tableSpaceName=ObjectName() [ userName=ObjectName() ] {
purgeStatement = new PurgeStatement(PurgeObjectType.TABLESPACE, tableSpaceName, userName);
}
)
@@ -10486,14 +10436,14 @@ ReplicationSourceOption ReplicationSourceOption():
String ReplicationFilterDatabase():
{ String name; }
{
- name=RelObjectName() { return name; }
+ name=ObjectName() { return name; }
}
/** A table of a replication filter, which names its database. */
Table ReplicationFilterTable():
{ Token first = getToken(1); String database; String name; Table table; }
{
- database=RelObjectName() "." name=RelObjectName()
+ database=ObjectName() "." name=RelObjectName()
{
table = createTable(Arrays.asList(database, name));
linkAST(table, first);
@@ -10671,7 +10621,7 @@ Expression DescribeColumnPattern():
|
token= { pattern = linkToLastToken(new HexValue(token.image)); }
|
- name=RelObjectName() { pattern = linkToLastToken(new Column(name)); }
+ name=ObjectName() { pattern = linkToLastToken(new Column(name)); }
)
{ return pattern; }
}
@@ -10714,7 +10664,7 @@ ExplainStatement MySqlExplain():
|
[
( { explain.setSchemaKeyword(true); } | )
- ( schema=RelObjectName() | token= { schema = token.image; } )
+ ( schema=ObjectName() | token= { schema = token.image; } )
{ explain.setSchemaName(schema); }
]
statement=ExplainableStatement(false) { explain.setStatement(statement); }
@@ -10954,7 +10904,7 @@ UseStatement Use(): {
boolean hasSchemaKeyword = false;
}
{
- [ LOOKAHEAD(2) { hasSchemaKeyword = true; } ] name = RelObjectName()
+ [ LOOKAHEAD(2) { hasSchemaKeyword = true; } ] name = ObjectName()
{
return new UseStatement(name, hasSchemaKeyword);
}
@@ -11042,7 +10992,7 @@ ShowDbSelection ShowDbSelection():
}
{
( | { selection.setSelectionMode(ShowTablesStatement.SelectionMode.IN); } )
- name = RelObjectName() { selection.setName(name); }
+ name = ObjectName() { selection.setName(name); }
{
return selection;
}
@@ -11231,7 +11181,7 @@ ShowCreateStatement ShowCreate(): {
( | { statement.setSchemaKeyword(true); } )
{ statement.setObjectType(ShowCreateStatement.ObjectType.DATABASE); }
[ LOOKAHEAD(3) { statement.setIfNotExists(true); } ]
- databaseName = RelObjectName() { statement.setDatabaseName(databaseName); }
+ databaseName = ObjectName() { statement.setDatabaseName(databaseName); }
|
{ statement.setObjectType(ShowCreateStatement.ObjectType.USER); }
(
@@ -11444,7 +11394,7 @@ void ShowRoutineName(MySqlShowStatement statement):
Table table;
}
{
- name = RelObjectName() [ "." routine = RelObjectName() ]
+ name = ObjectName() [ "." routine = RelObjectName() ]
{
table = routine == null ? new Table(name) : new Table(name, routine);
linkAST(table, first);
@@ -11683,7 +11633,7 @@ ReturningOutputAlias ReturningOutputAliasDefinition():
{
refType = ReturningReferenceKind()
- aliasName = RelObjectName()
+ aliasName = AliasName()
{
return new ReturningOutputAlias(refType, aliasName);
}
@@ -11791,7 +11741,7 @@ ForPortionClause ForPortionClause() #ForPortionClause:
ForPortionClause clause;
}
{
- AccessKeyword("PORTION") periodName=RelObjectName()
+ AccessKeyword("PORTION") periodName=ObjectName()
fromExpression=Expression() toExpression=Expression()
{
clause = new ForPortionClause(periodName, fromExpression, toExpression);
@@ -11873,7 +11823,7 @@ String WhereCurrentOfClause():
String cursorName;
}
{
- cursorName=RelObjectName()
+ cursorName=ObjectName()
{ return cursorName; }
}
@@ -11959,8 +11909,8 @@ ColumnDefinition InsertBulkColumn():
ColumnDefinition column;
}
{
- name=RelObjectName() type=ColDataType() { column = new ColumnDefinition(name, type); }
- [ collation=RelObjectName() { column.setColumnSpecs(Arrays.asList("COLLATE", collation)); } ]
+ name=ObjectName() type=ColDataType() { column = new ColumnDefinition(name, type); }
+ [ collation=ObjectName() { column.setColumnSpecs(Arrays.asList("COLLATE", collation)); } ]
{ return column; }
}
@@ -12133,7 +12083,7 @@ Insert Insert():
[ LOOKAHEAD({ isAliasAhead() && !isColumnMatchingAhead() && !isInsertTableSourceAhead()
&& !(getToken(1).kind == K_OVERRIDING
&& (getToken(2).kind == K_SYSTEM || getToken(2).kind == K_USER)) })
- [ { useAs = true; } ] name=RelObjectName() { table.setAlias(new Alias(name,useAs)); }]
+ [ { useAs = true; } ] name=AliasName() { table.setAlias(new Alias(name,useAs)); }]
[ LOOKAHEAD(2) columns=InsertColumnList() ]
@@ -12373,7 +12323,9 @@ InsertDuplicateAction InsertDuplicateAction():
}
{
(
- LOOKAHEAD(2) (
+ // with MySQL, which has no ON DUPLICATE KEY UPDATE NOTHING, nothing = 1 sets a column
+ LOOKAHEAD({ getToken(1).kind == K_NOTHING && !(isMySqlNameDialect()
+ && ("=".equals(getToken(2).image) || ".".equals(getToken(2).image))) }) (
{ duplicateAction = new InsertDuplicateAction( ConflictActionType.NOTHING ); }
)
|
@@ -12699,7 +12651,7 @@ ObjectNames RelObjectNames() : {
List data = new ArrayList();
List delimiters = new ArrayList();
} {
- token = RelObjectName() { data.add(token); }
+ token = ObjectName() { data.add(token); }
(
LOOKAHEAD (2) (
( delimiter = "..." { delimiters.add("."); data.add(null); delimiters.add("."); data.add(null); delimiters.add("."); } )
@@ -12709,7 +12661,7 @@ ObjectNames RelObjectNames() : {
( ( delimiter = "." | delimiter = ":" ) { delimiters.add(delimiter.image); } )
)
- token = RelObjectNameExt() { data.add(token); }
+ token = NamePart() { data.add(token); }
) *
{ return new ObjectNames(data, delimiters); }
@@ -12722,6 +12674,8 @@ ObjectNames ColumnIdentifier() : {
List data = new ArrayList();
List delimiters = new ArrayList();
} {
+ // RelObjectName() rather than ObjectName(): in an expression a keyword such as BETWEEN or
+ // INTERVAL that a dialect takes as a name may start syntax
token = RelObjectName() { data.add(token); }
(
LOOKAHEAD (2) (
@@ -12732,7 +12686,7 @@ ObjectNames ColumnIdentifier() : {
( delimiter = "." { delimiters.add(delimiter.image); } )
)
- token = RelObjectNameExt() { data.add(token); }
+ token = NamePart() { data.add(token); }
) *
{ return new ObjectNames(data, delimiters); }
@@ -12783,6 +12737,11 @@ Column Column() #Column :
* valid as identifiers in dotted-name continuations (after '.'), named
* parameters (after ':'), index columns, constraint names, and similar
* restricted contexts. Those call sites add the two tokens inline.
+ *
+ * Names of schema objects, parts of qualified names and aliases are read through ObjectName(),
+ * NamePart(), AliasName() and SelectItemAlias(), where the dialect decides which other keywords
+ * are names. The other words that are read as names, such as option names or field names, call
+ * RelObjectName() directly.
*/
String RelObjectName() :
{ Token tk = null; String result = null; }
@@ -12796,13 +12755,12 @@ String RelObjectName() :
| tk=
/* ── Non-reserved keywords (range-guarded) ──────────────────────── */
- | LOOKAHEAD({ getToken(1).kind >= MIN_NON_RESERVED_WORD
- && getToken(1).kind <= MAX_NON_RESERVED_WORD })
+ | LOOKAHEAD({ NameKeywords.isNonReserved(getToken(1).kind) })
result = NonReservedWord()
/* ── Keywords of other dialects that the selected dialect lacks ──── */
/* (before the guarded list, whose guard checks the position only) */
- | LOOKAHEAD({ isDialectIdentifierKeyword(getToken(1).kind) })
+ | LOOKAHEAD({ isDialectName(getToken(1).kind) })
( tk= | tk= | tk= | tk=
| tk= | tk= | tk= | tk= | tk=
| tk= | tk= | tk= | tk= | tk=
@@ -12810,20 +12768,60 @@ String RelObjectName() :
| tk= | tk= )
/* ── Reserved keywords usable as identifiers (context-guarded) ─── */
- | LOOKAHEAD({ isReservedKeywordAsIdentifier() })
- ( tk= | tk= | tk= | tk= | tk=
- | tk= | tk= | tk=
- | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= | tk=
- | tk= | tk= | tk= )
+ | LOOKAHEAD({ isReservedKeywordAsIdentifier() }) tk=ReservedName()
)
{ return result != null ? result : tk.image; }
}
+/*
+ * The reserved keywords that can still be names, NameKeywords.isReservedName(). The caller decides
+ * whether the keyword is a name where it stands.
+ */
+Token ReservedName() :
+{ Token tk; }
+{
+ ( tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= )
+ { return tk; }
+}
+
+/*
+ * Every keyword of one word that this parser reserves, for the positions where a dialect takes any
+ * keyword as a name; NEXTVAL, which may also be spelled NEXT VALUE FOR, is left out.
+ * NameKeywordsTest checks that each of them is a name there.
+ */
+Token ReservedKeyword() :
+{ Token tk; }
+{
+ (
+ tk= | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk= | tk= | tk= | tk= | tk=
+ | tk= | tk=