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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 42 additions & 6 deletions src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
Original file line number Diff line number Diff line change
Expand Up @@ -3945,6 +3945,12 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
|| "VALID".equalsIgnoreCase(getToken(offset + 1).image));
}

/** Whether OPTIONS and its parenthesized list start at the given token. */
private boolean isForeignDataOptionsAt(int offset) {
return "OPTIONS".equalsIgnoreCase(getToken(offset).image)
&& getToken(offset + 1).kind == OPENING_BRACKET;
}

/** EXCLUDE starts an exclusion constraint only before USING, its elements or WHERE. */
private boolean isExcludeConstraintAhead() {
int next = getToken(2).kind;
Expand Down Expand Up @@ -4032,11 +4038,37 @@ public class CCJSqlParser extends AbstractJSqlParser<CCJSqlParser> {
switch (getToken(1).kind) {
case K_PRIMARY:
case K_UNIQUE:
return true;
// PostgreSQL has no inline index definition, so these words name a column there
case K_INDEX:
case K_KEY:
case K_FULLTEXT:
case K_SPATIAL:
return !isPostgreSqlDialect();
default:
return false;
}
}

/**
* Whether the word after CONSTRAINT is the constraint's name although it could start a
* constraint itself, as KEY in PostgreSQL's CONSTRAINT key UNIQUE (a): the constraint kind
* follows the word.
*/
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()
&& (kind == K_KEY || kind == K_INDEX || kind == K_FULLTEXT || kind == K_SPATIAL)) {
return false;
}
switch (getToken(2).kind) {
case K_PRIMARY:
return getToken(3).kind == K_KEY;
case K_UNIQUE: case K_FOREIGN: case K_CHECK: case K_EXCLUDE:
return true;
case K_NOT:
return getToken(3).kind == K_NULL;
default:
return false;
}
Expand Down Expand Up @@ -22902,8 +22934,9 @@ TableElement TableConstraint(boolean createContext):
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext)
|
<K_CONSTRAINT>
[ LOOKAHEAD({ !isTableIndexAhead() && getToken(1).kind != K_FOREIGN
&& getToken(1).kind != K_CHECK && getToken(1).kind != K_EXCLUDE
[ LOOKAHEAD({ isConstraintNameBeforeKindAhead() || !isTableIndexAhead()
&& getToken(1).kind != K_FOREIGN && getToken(1).kind != K_CHECK
&& getToken(1).kind != K_EXCLUDE
&& !(getToken(1).kind == K_NOT && getToken(2).kind == K_NULL) }) constraintName=RelObjectName() ]
(
LOOKAHEAD({ isTableIndexAhead() }) index=TableIndexSpec(createContext) {
Expand Down Expand Up @@ -26794,8 +26827,9 @@ AlterExpression AlterExpressionAddAlterModify():
alterExp.setConstraint(constraint);
}
|
// MySQL's ALTER INDEX name {VISIBLE | INVISIBLE}; PostgreSQL's ALTER index alters a column
LOOKAHEAD({ alterExp.getOperation() == AlterOperation.ALTER
&& getToken(1).kind == K_INDEX })
&& getToken(1).kind == K_INDEX && !isPostgreSqlDialect() })
tk=<K_INDEX> sk3=RelObjectName() TableIndexOptions(false, indexSpec) {
index = new Index().withIndexKeyword(tk.image).withName(sk3)
.withKind(Index.Kind.INDEX).withSpecOptions(indexSpec);
Expand All @@ -26822,7 +26856,7 @@ AlterExpression AlterExpressionAddAlterModify():
|| Dialect.MYSQL.name().equals(getAsString(Feature.dialect)))
&& (getToken(1).kind == K_CONSTRAINT || getToken(1).kind == K_PRIMARY
|| getToken(1).kind == K_UNIQUE || getToken(1).kind == K_FOREIGN
|| getToken(1).kind == K_CHECK || getToken(1).kind == K_EXCLUDE
|| getToken(1).kind == K_CHECK || isExcludeConstraintAhead()
|| getToken(1).kind == K_NOT
&& Dialect.POSTGRESQL.name().equals(getAsString(Feature.dialect)))
|| AlterConstraintLookahead.needsSharedTableConstraint(getToken(1), token_source)
Expand Down Expand Up @@ -27129,8 +27163,10 @@ AlterExpression AlterExpression():
{

(
LOOKAHEAD({ isKeywordAhead("OPTIONS") || getToken(1).kind == K_ALTER
&& "OPTIONS".equalsIgnoreCase(getToken(getToken(2).kind == K_COLUMN ? 4 : 3).image) })
// OPTIONS takes a parenthesized list; otherwise it names an index or a constraint, as in
// ALTER INDEX options INVISIBLE
LOOKAHEAD({ isKeywordAhead("OPTIONS") && getToken(2).kind == OPENING_BRACKET
|| getToken(1).kind == K_ALTER && isForeignDataOptionsAt(getToken(2).kind == K_COLUMN ? 4 : 3) })
alterExp=AlterForeignDataOptions()
|
LOOKAHEAD({ isAlterValidationModifierAhead() }) validationMode=AlterValidationMode()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*-
* #%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.statement;

import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.stream.Stream;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.AbstractJSqlParser.Dialect;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.alter.Alter;
import net.sf.jsqlparser.statement.alter.AlterExpression;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

/**
* Words that may start a table element or an ALTER action, but name a column, a constraint, an
* index or a check where that element or action does not follow.
*/
public class ContextualKeywordNamesTest {

private static Statement parse(String sql, Dialect dialect) throws JSQLParserException {
return assertSqlCanBeParsedAndDeparsed(sql, true, parser -> {
if (dialect != null) {
parser.withDialect(dialect);
}
});
}

private static AlterExpression alterExpression(String sql, Dialect dialect)
throws JSQLParserException {
return ((Alter) parse(sql, dialect)).getAlterExpressions().get(0);
}

// PostgreSQL has no inline index definition: KEY, INDEX, FULLTEXT and SPATIAL name columns.
@ParameterizedTest
@ValueSource(strings = {"key", "index", "fulltext", "spatial"})
void testPostgreSqlIndexWordsAsColumns(String word) throws JSQLParserException {
CreateTable createTable = (CreateTable) parse(
"CREATE TABLE kv (id INT, " + word + " VARCHAR (10) NOT NULL)", Dialect.POSTGRESQL);
assertEquals(word, createTable.getColumnDefinitions().get(1).getColumnName());
assertEquals(2, createTable.getTableElements().size());

assertEquals(word,
alterExpression("ALTER TABLE kv ADD " + word + " INT", Dialect.POSTGRESQL)
.getColDataTypeList().get(0).getColumnName());
assertEquals(word, alterExpression("ALTER TABLE kv ALTER " + word + " TYPE BIGINT",
Dialect.POSTGRESQL).getColDataTypeList().get(0).getColumnName());
}

@Test
void testMySqlIndexDefinitionsStay() throws JSQLParserException {
CreateTable createTable = (CreateTable) parse("CREATE TABLE t (a INT, KEY k (a),"
+ " CONSTRAINT UNIQUE KEY u (a), CONSTRAINT PRIMARY KEY (a))", Dialect.MYSQL);
assertEquals("k", createTable.getIndexes().get(0).getName());
assertEquals(2, createTable.getTableConstraints().size());
assertNull(createTable.getTableConstraints().get(1).getName());
assertEquals("k", alterExpression("ALTER TABLE t ADD INDEX k (a)", Dialect.MYSQL).getIndex()
.getName());
assertEquals("k", alterExpression("ALTER TABLE t ALTER INDEX k INVISIBLE", Dialect.MYSQL)
.getIndex().getName());
// MySQL reserves KEY, so it cannot name a column there
assertThrows(JSQLParserException.class, () -> CCJSqlParserUtil.parse(
"ALTER TABLE t ADD key INT", parser -> parser.withDialect(Dialect.MYSQL)));
}

// A word that could start a constraint is its name when the constraint kind follows it.
public static Stream<Arguments> constraintNames() {
return Stream.of(Arguments.of("key", Dialect.POSTGRESQL),
Arguments.of("index", Dialect.POSTGRESQL),
Arguments.of("fulltext", Dialect.POSTGRESQL),
Arguments.of("spatial", Dialect.POSTGRESQL),
Arguments.of("exclude", Dialect.POSTGRESQL),
Arguments.of("exclude", Dialect.MYSQL), Arguments.of("key", null),
Arguments.of("exclude", null));
}

@ParameterizedTest(name = "{0} {1}")
@MethodSource("constraintNames")
void testConstraintNameBeforeConstraintKind(String word, Dialect dialect)
throws JSQLParserException {
CreateTable createTable = (CreateTable) parse(
"CREATE TABLE t (a INT, CONSTRAINT " + word + " UNIQUE (a))", dialect);
assertEquals(word, createTable.getTableConstraints().get(0).getName());

AlterExpression add = alterExpression(
"ALTER TABLE t ADD CONSTRAINT " + word + " PRIMARY KEY (a)", dialect);
assertEquals(word, add.getConstraint() != null ? add.getConstraint().getName()
: add.getIndex().getName());
}

// EXCLUDE starts an exclusion constraint only with USING, its elements or WHERE.
@ParameterizedTest
@MethodSource("excludeDialects")
void testExcludeAsAddedColumn(Dialect dialect) throws JSQLParserException {
assertEquals("exclude", alterExpression("ALTER TABLE t ADD exclude INT", dialect)
.getColDataTypeList().get(0).getColumnName());
}

public static Stream<Dialect> excludeDialects() {
return Stream.of(null, Dialect.MYSQL, Dialect.POSTGRESQL);
}

@Test
void testExclusionConstraintStays() throws JSQLParserException {
AlterExpression exclude = alterExpression(
"ALTER TABLE t ADD CONSTRAINT x EXCLUDE USING gist (a WITH =)", Dialect.POSTGRESQL);
assertEquals("x", exclude.getConstraint().getName());
}

// OPTIONS starts PostgreSQL's foreign-data options only before its parenthesized list.
@Test
void testOptionsAsIndexAndConstraintName() throws JSQLParserException {
assertEquals("options", alterExpression("ALTER TABLE t ALTER INDEX options INVISIBLE",
Dialect.MYSQL).getIndex().getName());
parse("ALTER TABLE t ALTER CHECK options NOT ENFORCED", Dialect.MYSQL);
parse("ALTER TABLE t ALTER CONSTRAINT options ENFORCED", Dialect.MYSQL);
parse("ALTER FOREIGN TABLE t ALTER COLUMN c OPTIONS (ADD x 'y')", Dialect.POSTGRESQL);
}
}
Loading