Skip to content

Commit ab3d9bb

Browse files
authored
fix: parse MySQL mixed ADD COLUMN groups (#2930)
* fix: parse MySQL mixed ADD COLUMN groups Preserve parenthesized ADD declarations in source order using existing table-element models and traversal. Retain mutable column accessors and visit/deparse every mixed column, constraint and index declaration. Cover mixed order, constraints first, metadata validation, expression visitors and compatibility with column-only groups. * fix: make mixed ADD element updates explicit Update the backing group list directly when replacing or removing its first constraint or index. This preserves filtered-view semantics while letting SpotBugs observe the mutation without a suppression. Cover append when an element kind is absent and preservation of the remaining declarations when the first constraint is removed.
1 parent 5f6fb83 commit ab3d9bb

9 files changed

Lines changed: 447 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ and missing syntax gets added on demand — [open an issue](https://github.com/J
157157
| **MySQL table maintenance** | `ANALYZE` · `CHECK` · `CHECKSUM` · `OPTIMIZE` · `REPAIR TABLE` |
158158
| **MySQL locks** | `LOCK TABLES` · `UNLOCK TABLES` · `LOCK INSTANCE FOR BACKUP` · `UNLOCK INSTANCE` |
159159
| **MySQL resource groups** | `CREATE`/`ALTER`/`DROP RESOURCE GROUP` · `SET RESOURCE GROUP` |
160+
| **MySQL mixed ADD groups** | `ALTER TABLE … ADD [COLUMN] (columns, indexes, constraints)` |
160161
| **MySQL loadable functions** | `CREATE [AGGREGATE] FUNCTION … RETURNS … SONAME` |
161162
| **MySQL servers, plugins and components** | `CREATE SERVER` · `ALTER SERVER` with `OPTIONS (… PORT 3306)` · `INSTALL`/`UNINSTALL PLUGIN` · `INSTALL`/`UNINSTALL COMPONENT` |
162163
| **MySQL server administration** | `FLUSH` · `KILL` · `RESET PERSIST` · `HANDLER … OPEN`/`READ`/`CLOSE` |

‎src/main/java/net/sf/jsqlparser/statement/alter/AlterExpression.java‎

Lines changed: 109 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import net.sf.jsqlparser.statement.create.table.NamedConstraint;
3131
import net.sf.jsqlparser.statement.create.table.KeyConstraint;
3232
import net.sf.jsqlparser.statement.create.table.TableElement;
33+
import net.sf.jsqlparser.statement.create.table.TableElementList;
3334
import net.sf.jsqlparser.statement.create.table.IndexOptionSource;
3435
import net.sf.jsqlparser.statement.create.table.ConstraintKind;
3536
import net.sf.jsqlparser.statement.create.table.PartitionDefinition;
@@ -50,6 +51,7 @@ public enum TableRenameKeyword {
5051
// private ColDataType dataType;
5152
private String columnOldName;
5253
private List<ColumnDataType> colDataTypeList;
54+
private List<TableElement> addGroupElements;
5355
private List<ColumnDropNotNull> columnDropNotNullList;
5456
private List<ColumnSetNotNull> columnSetNotNullList;
5557
private List<ColumnDropDefault> columnDropDefaultList;
@@ -434,15 +436,73 @@ private void setForeignKeyTablePart(String value, int partIndex) {
434436
table.setNameParts(parts);
435437
}
436438

439+
/**
440+
* Returns the mutable column list, filtering out the other declarations of a mixed ADD group.
441+
*/
437442
public List<ColumnDataType> getColDataTypeList() {
443+
if (hasAddGroupElements()) {
444+
return new TableElementList<>(addGroupElements, ColumnDataType.class);
445+
}
438446
return colDataTypeList;
439447
}
440448

449+
/**
450+
* Returns the mutable declarations of a parenthesized mixed ADD group in source order. Parsed
451+
* columns are {@link ColumnDataType} nodes shared with {@link #getColDataTypeList()}.
452+
*/
453+
public List<TableElement> getAddGroupElements() {
454+
return addGroupElements;
455+
}
456+
457+
/** Copies the group membership, retaining the mutable column, index and constraint nodes. */
458+
public void setAddGroupElements(List<TableElement> elements) {
459+
addGroupElements = elements == null ? null : new ArrayList<>(elements);
460+
if (elements != null) {
461+
colDataTypeList = null;
462+
constraint = null;
463+
index = null;
464+
useBrackets = true;
465+
}
466+
}
467+
468+
public boolean hasAddGroupElements() {
469+
return operation == AlterOperation.ADD && addGroupElements != null;
470+
}
471+
472+
private <E extends TableElement> E firstAddGroupElement(Class<E> type) {
473+
for (TableElement element : addGroupElements) {
474+
if (type.isInstance(element)) {
475+
return type.cast(element);
476+
}
477+
}
478+
return null;
479+
}
480+
481+
private <E extends TableElement> void replaceFirstAddGroupElement(Class<E> type, E element) {
482+
for (int i = 0; i < addGroupElements.size(); i++) {
483+
if (type.isInstance(addGroupElements.get(i))) {
484+
if (element == null) {
485+
addGroupElements.remove(i);
486+
} else {
487+
addGroupElements.set(i, element);
488+
}
489+
return;
490+
}
491+
}
492+
if (element != null) {
493+
addGroupElements.add(element);
494+
}
495+
}
496+
441497
public void addColDataType(String columnName, ColDataType colDataType) {
442498
addColDataType(new ColumnDataType(columnName, false, colDataType, null));
443499
}
444500

445501
public void addColDataType(ColumnDataType columnDataType) {
502+
if (hasAddGroupElements()) {
503+
addGroupElements.add(columnDataType);
504+
return;
505+
}
446506
if (colDataTypeList == null) {
447507
colDataTypeList = new ArrayList<>();
448508
}
@@ -782,7 +842,11 @@ public void setUkName(String ukName) {
782842
}
783843
}
784844

845+
/** Returns the ordinary index, or the first ordinary index in a mixed ADD group. */
785846
public Index getIndex() {
847+
if (hasAddGroupElements()) {
848+
return firstAddGroupElement(Index.class);
849+
}
786850
return index;
787851
}
788852

@@ -878,22 +942,39 @@ public boolean hasActiveConstraintHeader() {
878942
return hasExplicitConstraintHeader();
879943
}
880944

881-
/** Sets an index definition or target; a non-null value replaces any constraint definition. */
945+
/**
946+
* Sets an index definition or target; a non-null value replaces any constraint definition. In a
947+
* mixed ADD group, replaces or removes only its first ordinary index.
948+
*/
882949
public void setIndex(Index index) {
950+
if (hasAddGroupElements()) {
951+
replaceFirstAddGroupElement(Index.class, index);
952+
return;
953+
}
883954
this.index = index;
884955
if (index != null) {
885956
clearReplacedConstraintAliases(null);
886957
constraint = null;
887958
}
888959
}
889960

890-
/** Returns the constraint definition, distinct from an ordinary index or a named target. */
961+
/** Returns the constraint definition, or the first constraint in a mixed ADD group. */
891962
public NamedConstraint getConstraint() {
963+
if (hasAddGroupElements()) {
964+
return firstAddGroupElement(NamedConstraint.class);
965+
}
892966
return constraint;
893967
}
894968

895-
/** Sets a constraint definition; a non-null value replaces any ordinary index definition. */
969+
/**
970+
* Sets a constraint definition; a non-null value replaces any ordinary index definition. In a
971+
* mixed ADD group, replaces or removes only its first constraint.
972+
*/
896973
public void setConstraint(NamedConstraint constraint) {
974+
if (hasAddGroupElements()) {
975+
replaceFirstAddGroupElement(NamedConstraint.class, constraint);
976+
return;
977+
}
897978
clearReplacedConstraintAliases(constraint);
898979
this.constraint = constraint;
899980
if (constraint != null) {
@@ -1208,7 +1289,9 @@ public final String toString() {
12081289
@SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.NPathComplexity",
12091290
"PMD.ExcessiveMethodLength", "PMD.SwitchStmtsShouldHaveDefault"})
12101291
protected void appendBody(StringBuilder b) {
1211-
if (operation == AlterOperation.UNSPECIFIC) {
1292+
if (hasAddGroupElements()) {
1293+
appendAddGroupBody(b, b::append);
1294+
} else if (operation == AlterOperation.UNSPECIFIC) {
12121295
b.append(optionalSpecifier);
12131296
} else if (hasActiveConstraintHeader()) {
12141297
toStringConstraintAlter(b);
@@ -1250,7 +1333,28 @@ protected boolean usesColumnActionBody() {
12501333
* deparsing. Subclasses with their own body dispatch override this method accordingly.
12511334
*/
12521335
public boolean hasActiveColumnDefinitions() {
1253-
return hasColumnDefinitionPayload() && usesGeneralBody();
1336+
return hasAddGroupElements() || hasColumnDefinitionPayload() && usesGeneralBody();
1337+
}
1338+
1339+
/** Appends a mixed ADD group using the supplied renderer for every declaration. */
1340+
public void appendAddGroupTo(StringBuilder b, Consumer<TableElement> elementPrinter) {
1341+
appendAddGroupBody(b, elementPrinter);
1342+
appendCommonTail(b);
1343+
}
1344+
1345+
private void appendAddGroupBody(StringBuilder b, Consumer<TableElement> elementPrinter) {
1346+
b.append("ADD ");
1347+
if (hasColumn) {
1348+
b.append("COLUMN ");
1349+
}
1350+
b.append('(');
1351+
for (int i = 0; i < addGroupElements.size(); i++) {
1352+
if (i > 0) {
1353+
b.append(", ");
1354+
}
1355+
elementPrinter.accept(addGroupElements.get(i));
1356+
}
1357+
b.append(')');
12541358
}
12551359

12561360
/** Whether this action selects the general body, before choosing its active payload. */

‎src/main/java/net/sf/jsqlparser/statement/create/table/TableElementList.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020
import java.util.Objects;
2121

2222
/** A mutable, filtered view preserving the other declarations in a table definition. */
23-
final class TableElementList<E extends TableElement> extends AbstractList<E>
23+
public final class TableElementList<E extends TableElement> extends AbstractList<E>
2424
implements Serializable {
2525
private final List<TableElement> elements;
2626
private final Class<E> type;
2727

28-
TableElementList(List<TableElement> elements, Class<E> type) {
28+
public TableElementList(List<TableElement> elements, Class<E> type) {
2929
this.elements = elements;
3030
this.type = type;
3131
}

‎src/main/java/net/sf/jsqlparser/util/TableDefinitionTraversal.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ public static void visit(CreateIndex createIndex, Consumer<Expression> expressio
5959
*/
6060
public static void visit(AlterExpression action, Consumer<Expression> expressions,
6161
Consumer<Table> tables) {
62+
if (action.hasAddGroupElements()) {
63+
action.getAddGroupElements().forEach(element -> visit(element, expressions, tables));
64+
return;
65+
}
6266
if (visitSpecialBody(action, expressions, tables)) {
6367
return;
6468
}

‎src/main/java/net/sf/jsqlparser/util/deparser/AlterDeParser.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ public void deParse(Alter alter) {
4545
}
4646

4747
private void deParseAction(AlterExpression action) {
48+
if (action.hasAddGroupElements()) {
49+
TableElementDeParser elements = new TableElementDeParser(builder, expressionVisitor);
50+
action.appendAddGroupTo(builder, elements::deParse);
51+
return;
52+
}
4853
if (action instanceof AlterForeignDataOptions) {
4954
((AlterForeignDataOptions) action).appendTo(builder,
5055
expression -> expression.accept(expressionVisitor, null));

‎src/main/java/net/sf/jsqlparser/util/validation/validator/AlterValidator.java‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,15 @@ public void validate(Alter alter, AlterExpression e) {
8585
validateOptionalColumnNames(c, e.getDropColumns());
8686
}
8787

88-
validateConstraint(c, definition);
89-
validateIndex(c, e, definition);
88+
if (e.hasAddGroupElements()) {
89+
for (TableElement element : e.getAddGroupElements()) {
90+
validateConstraint(c, element);
91+
validateIndex(c, e, element);
92+
}
93+
} else {
94+
validateConstraint(c, definition);
95+
validateIndex(c, e, definition);
96+
}
9097
}
9198
}
9299

@@ -137,7 +144,9 @@ private boolean hasActiveDropColumns(AlterExpression expression) {
137144

138145
private void validateIndex(ValidationCapability capability, AlterExpression expression,
139146
TableElement definition) {
140-
Index index = expression.getIndex();
147+
Index index = expression.hasAddGroupElements() && definition instanceof Index
148+
? (Index) definition
149+
: expression.getIndex();
141150
boolean rename = expression.getOperation() == AlterOperation.RENAME_INDEX
142151
|| expression.getOperation() == AlterOperation.RENAME_KEY;
143152
if (index == null || definition != index && !rename) {

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25379,6 +25379,47 @@ Truncate Truncate():
2537925379
}
2538025380
}
2538125381

25382+
25383+
/** MySQL ADD (table_element_list), preserving interleaved columns, indexes and constraints. */
25384+
void MySqlAlterAddGroup(AlterExpression alterExp):
25385+
{
25386+
List<TableElement> elements = new ArrayList<TableElement>();
25387+
TableElement element;
25388+
boolean mixed = false;
25389+
}
25390+
{
25391+
[ <K_COLUMN> { alterExp.hasColumn(true); } ]
25392+
"(" element=MySqlAlterAddGroupElement() { elements.add(element); }
25393+
( "," element=MySqlAlterAddGroupElement() { elements.add(element); } )*
25394+
")"
25395+
{
25396+
for (TableElement item : elements) {
25397+
if (!(item instanceof AlterExpression.ColumnDataType)) {
25398+
mixed = true;
25399+
}
25400+
}
25401+
if (mixed) {
25402+
alterExp.setAddGroupElements(elements);
25403+
} else {
25404+
// Keep the existing representation and accessors for column-only groups.
25405+
alterExp.useBrackets(true);
25406+
for (TableElement item : elements) {
25407+
alterExp.addColDataType((AlterExpression.ColumnDataType) item);
25408+
}
25409+
}
25410+
}
25411+
}
25412+
25413+
TableElement MySqlAlterAddGroupElement():
25414+
{
25415+
TableElement element;
25416+
}
25417+
{
25418+
( LOOKAHEAD(3) element=CreateTableConstraint()
25419+
| element=AlterExpressionColumnDataType() )
25420+
{ return element; }
25421+
}
25422+
2538225423
/**
2538325424
* Parses common column-level changes shared between the COLUMN-prefixed and bare forms:
2538425425
* DROP DEFAULT, SET DEFAULT, SET NOT NULL, SET VISIBLE/INVISIBLE, and bracketed multi-column
@@ -26570,6 +26611,13 @@ AlterExpression AlterExpressionAddAlterModify():
2657026611
{ alterExp.getOperation() == AlterOperation.ADD })
2657126612
alterExp=AddPartition()
2657226613
|
26614+
LOOKAHEAD({ alterExp.getOperation() == AlterOperation.ADD
26615+
&& (getAsString(Feature.dialect) == null
26616+
|| Dialect.MYSQL.name().equals(getAsString(Feature.dialect)))
26617+
&& (getToken(1).kind == OPENING_BRACKET
26618+
|| getToken(1).kind == K_COLUMN && getToken(2).kind == OPENING_BRACKET) })
26619+
MySqlAlterAddGroup(alterExp)
26620+
|
2657326621
LOOKAHEAD(3) (
2657426622
( LOOKAHEAD(2)
2657526623
(

0 commit comments

Comments
 (0)