From ffda807e217d4989cff0c661af3b375987725373 Mon Sep 17 00:00:00 2001 From: gitmotte Date: Sun, 23 Aug 2020 22:07:53 +0200 Subject: [PATCH] Fluent builder api #1004 (#1014) * https://github.com/JSQLParser/JSqlParser/issues/1004 * create(...) methods * chaining - methods returning "this" * overwrite chaining - methods of abstract parents/interfaces for returning concrete type * add methods on collection-fields with varargs-parameter * add public T get(Class) - casting and returning an inner interface-type * 1004 add chaining - methods returning "this" * #1004 add chaining - methods returning "this" * * add methods on collection-fields with varargs-parameter * add methods on collection-fields with collection-parameter https://github.com/JSQLParser/JSqlParser/issues/1004 * * add chaining - methods returning "this" * add methods on collection-fields with varargs-parameter * add methods on collection-fields with collection-parameter https://github.com/JSQLParser/JSqlParser/issues/1004 * * add public T get(Class) - casting and returning the concrete type https://github.com/JSQLParser/JSqlParser/issues/1004 * * add public T get(Class) - casting and returning the concrete type (swap Class for Class) https://github.com/JSQLParser/JSqlParser/issues/1004 * * overwrite chaining - methods of abstract parents/interfaces for returning concrete type https://github.com/JSQLParser/JSqlParser/issues/1004 * * add with prefix for fluent setters. https://github.com/JSQLParser/JSqlParser/issues/1004 * add getters * * add with prefix for fluent setters. (revert to chaining setters, do not break current api) https://github.com/JSQLParser/JSqlParser/issues/1004 * * add with prefix for fluent setters. (revert to chaining setters, do not break current api) https://github.com/JSQLParser/JSqlParser/issues/1004 * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * remove create() methods - they do not add enough value to be justified * * use new methods within testcases * add some constructors * fix and add "with" / "add" methods * * use new methods within testcases * * use new methods within testcases * add some constructors * * renamed constant * use new methods within testcases * use new methods within testcases * use new methods within testcases * use new methods within testcases * * use new methods within testcases * add some with-methods * add getter/setter named after the field without abbrivation * * use new methods within testcases * remove empty implicit constructor * return the deparsed Statement - object * compare object tree * compare object tree * * fix ObjectTreeToStringStyle * compare object tree * remove casts not needed * * use new methods within testcases * add some "set" "with" "add" methods missing * * use new methods within testcases * add empty constructors and override with-/add-methods returning concrete type * * add ReflectionModelTest * * use new methods within testcases * fix checkstyle errors * license header * remove test-classes from ReflectionModelTest * remove visitoradapter-classes from ReflectionModelTest * remove duplicate import declaration (checkstyle error) * * fix RandomUtils to support used java.sql.* types * fix RandomUtils to support enums * fix RandomUtils to map objects by its interfaces and super-classes * filter method "setASTNode" - do not test setters (cannot randomly create a SimpleNode) * add javadoc, stating that this is a marker interface https://github.com/JSQLParser/JSqlParser/pull/1014#discussion_r454761902 * revert formatting change https://github.com/JSQLParser/JSqlParser/pull/1014#discussion_r454762463 * change to EXEC_TYPE.EXECUTE just so the assertion didn't change https://github.com/JSQLParser/JSqlParser/pull/1014#discussion_r454763565 * try to revert format changes https://github.com/JSQLParser/JSqlParser/pull/1014#discussion_r454800430 * try to revert format changes https://github.com/JSQLParser/JSqlParser/pull/1014#discussion_r454800430 * remove brackets on @Override() -> @Override * add with-methods to new fields --- pom.xml | 6 + src/main/java/net/sf/jsqlparser/Model.java | 18 ++ .../net/sf/jsqlparser/expression/Alias.java | 31 +++ .../expression/AnalyticExpression.java | 71 +++++ .../expression/ArrayExpression.java | 22 ++ .../expression/BinaryExpression.java | 43 ++- .../jsqlparser/expression/CaseExpression.java | 40 ++- .../jsqlparser/expression/CastExpression.java | 19 ++ .../expression/CollateExpression.java | 18 ++ .../expression/DateTimeLiteralExpression.java | 10 + .../sf/jsqlparser/expression/DateValue.java | 20 +- .../sf/jsqlparser/expression/DoubleValue.java | 9 + .../sf/jsqlparser/expression/Expression.java | 4 +- .../expression/ExtractExpression.java | 14 + .../sf/jsqlparser/expression/Function.java | 44 +++ .../sf/jsqlparser/expression/HexValue.java | 21 +- .../expression/IntervalExpression.java | 19 ++ .../expression/JdbcNamedParameter.java | 5 + .../jsqlparser/expression/JdbcParameter.java | 10 + .../jsqlparser/expression/JsonExpression.java | 5 + .../jsqlparser/expression/KeepExpression.java | 34 ++- .../sf/jsqlparser/expression/LongValue.java | 17 +- .../expression/MySQLGroupConcat.java | 36 +++ .../jsqlparser/expression/MySQLIndexHint.java | 12 + .../expression/NextValExpression.java | 4 + .../jsqlparser/expression/NotExpression.java | 18 ++ .../sf/jsqlparser/expression/NumericBind.java | 5 + .../OracleHierarchicalExpression.java | 28 ++ .../sf/jsqlparser/expression/OracleHint.java | 9 + .../jsqlparser/expression/OrderByClause.java | 24 +- .../sf/jsqlparser/expression/Parenthesis.java | 9 + .../expression/PartitionByClause.java | 5 + .../jsqlparser/expression/RowConstructor.java | 10 + .../jsqlparser/expression/SQLServerHints.java | 10 + .../expression/SignedExpression.java | 18 ++ .../sf/jsqlparser/expression/StringValue.java | 17 +- .../expression/TimeKeyExpression.java | 9 + .../sf/jsqlparser/expression/TimeValue.java | 9 + .../jsqlparser/expression/TimestampValue.java | 10 + .../jsqlparser/expression/UserVariable.java | 18 ++ .../expression/ValueListExpression.java | 4 + .../sf/jsqlparser/expression/WhenClause.java | 21 +- .../jsqlparser/expression/WindowElement.java | 16 ++ .../jsqlparser/expression/WindowOffset.java | 15 + .../sf/jsqlparser/expression/WindowRange.java | 10 + .../operators/arithmetic/Addition.java | 11 + .../operators/arithmetic/BitwiseAnd.java | 11 + .../arithmetic/BitwiseLeftShift.java | 11 + .../operators/arithmetic/BitwiseOr.java | 11 + .../arithmetic/BitwiseRightShift.java | 11 + .../operators/arithmetic/BitwiseXor.java | 11 + .../operators/arithmetic/Concat.java | 11 + .../operators/arithmetic/Division.java | 11 + .../operators/arithmetic/IntegerDivision.java | 11 + .../operators/arithmetic/Modulo.java | 11 + .../operators/arithmetic/Multiplication.java | 11 + .../operators/arithmetic/Subtraction.java | 11 + .../operators/conditional/AndExpression.java | 27 +- .../operators/conditional/OrExpression.java | 15 + .../operators/relational/Between.java | 32 +++ .../relational/ComparisonOperator.java | 28 ++ .../operators/relational/EqualsTo.java | 27 ++ .../relational/ExistsExpression.java | 14 + .../operators/relational/ExpressionList.java | 30 +- .../operators/relational/FullTextSearch.java | 36 ++- .../operators/relational/GreaterThan.java | 21 ++ .../relational/GreaterThanEquals.java | 21 ++ .../operators/relational/InExpression.java | 65 ++++- .../relational/IsBooleanExpression.java | 19 ++ .../relational/IsNullExpression.java | 19 ++ .../operators/relational/JsonOperator.java | 11 + .../operators/relational/LikeExpression.java | 26 ++ .../operators/relational/Matches.java | 21 ++ .../operators/relational/MinorThan.java | 21 ++ .../operators/relational/MinorThanEquals.java | 21 ++ .../relational/MultiExpressionList.java | 52 ++-- .../relational/NamedExpressionList.java | 38 +++ .../operators/relational/NotEqualsTo.java | 27 ++ .../OldOracleJoinBinaryExpression.java | 22 +- .../relational/RegExpMatchOperator.java | 11 + .../relational/RegExpMySQLOperator.java | 11 + .../relational/SimilarToExpression.java | 21 ++ .../SupportsOldOracleJoinSyntax.java | 4 + .../java/net/sf/jsqlparser/schema/Column.java | 58 ++-- .../net/sf/jsqlparser/schema/Database.java | 10 + .../net/sf/jsqlparser/schema/Sequence.java | 50 +++- .../java/net/sf/jsqlparser/schema/Server.java | 12 + .../java/net/sf/jsqlparser/schema/Table.java | 77 +++++- .../net/sf/jsqlparser/statement/Block.java | 5 + .../statement/CreateFunctionalStatement.java | 178 +++++++----- .../statement/DeclareStatement.java | 106 +++++++- .../statement/DescribeStatement.java | 9 + .../statement/ExplainStatement.java | 11 +- .../statement/ReferentialAction.java | 12 +- .../sf/jsqlparser/statement/SetStatement.java | 18 ++ .../statement/ShowColumnsStatement.java | 9 + .../jsqlparser/statement/ShowStatement.java | 9 + .../sf/jsqlparser/statement/Statement.java | 4 +- .../sf/jsqlparser/statement/Statements.java | 21 ++ .../sf/jsqlparser/statement/UseStatement.java | 9 + .../sf/jsqlparser/statement/alter/Alter.java | 29 ++ .../statement/alter/AlterExpression.java | 218 ++++++++++++++- .../statement/alter/DeferrableConstraint.java | 9 + .../statement/alter/EnableConstraint.java | 9 + .../statement/alter/ValidateConstraint.java | 9 + .../alter/sequence/AlterSequence.java | 5 + .../jsqlparser/statement/comment/Comment.java | 15 + .../create/function/CreateFunction.java | 69 +++-- .../statement/create/index/CreateIndex.java | 16 +- .../create/procedure/CreateProcedure.java | 69 +++-- .../statement/create/schema/CreateSchema.java | 30 ++ .../create/sequence/CreateSequence.java | 5 + .../create/table/CheckConstraint.java | 63 +++++ .../statement/create/table/ColDataType.java | 58 +++- .../create/table/ColumnDefinition.java | 40 ++- .../statement/create/table/CreateTable.java | 92 ++++++- .../create/table/ExcludeConstraint.java | 56 ++++ .../create/table/ForeignKeyIndex.java | 88 +++++- .../statement/create/table/Index.java | 91 ++++++- .../create/table/NamedConstraint.java | 50 +++- .../statement/create/table/RowMovement.java | 5 + .../statement/create/view/AlterView.java | 40 +++ .../statement/create/view/CreateView.java | 51 ++++ .../jsqlparser/statement/delete/Delete.java | 79 +++++- .../sf/jsqlparser/statement/drop/Drop.java | 37 ++- .../jsqlparser/statement/execute/Execute.java | 21 +- .../sf/jsqlparser/statement/grant/Grant.java | 51 +++- .../jsqlparser/statement/insert/Insert.java | 179 +++++++++++- .../sf/jsqlparser/statement/merge/Merge.java | 44 +++ .../statement/merge/MergeInsert.java | 38 +++ .../statement/merge/MergeUpdate.java | 56 ++++ .../jsqlparser/statement/replace/Replace.java | 63 ++++- .../statement/select/AllColumns.java | 4 +- .../statement/select/AllTableColumns.java | 5 + .../jsqlparser/statement/select/Distinct.java | 26 ++ .../statement/select/ExpressionListItem.java | 10 + .../sf/jsqlparser/statement/select/Fetch.java | 15 + .../sf/jsqlparser/statement/select/First.java | 20 ++ .../jsqlparser/statement/select/FromItem.java | 18 +- .../statement/select/FunctionItem.java | 13 +- .../statement/select/GroupByElement.java | 37 +++ .../sf/jsqlparser/statement/select/Join.java | 100 ++++++- .../statement/select/KSQLJoinWindow.java | 30 ++ .../statement/select/KSQLWindow.java | 21 ++ .../statement/select/LateralSubSelect.java | 23 ++ .../sf/jsqlparser/statement/select/Limit.java | 28 ++ .../jsqlparser/statement/select/Offset.java | 14 + .../statement/select/OptimizeFor.java | 5 + .../statement/select/OrderByElement.java | 20 ++ .../statement/select/ParenthesisFromItem.java | 21 +- .../sf/jsqlparser/statement/select/Pivot.java | 80 +++++- .../jsqlparser/statement/select/PivotXml.java | 85 +++++- .../statement/select/PlainSelect.java | 238 ++++++++++++++-- .../jsqlparser/statement/select/Select.java | 31 ++- .../statement/select/SelectBody.java | 4 +- .../select/SelectExpressionItem.java | 14 + .../statement/select/SetOperationList.java | 95 +++++++ .../sf/jsqlparser/statement/select/Skip.java | 15 + .../statement/select/SpecialSubSelect.java | 17 ++ .../jsqlparser/statement/select/SubJoin.java | 49 +++- .../statement/select/SubSelect.java | 51 ++++ .../statement/select/TableFunction.java | 26 ++ .../sf/jsqlparser/statement/select/Top.java | 9 + .../jsqlparser/statement/select/UnPivot.java | 5 + .../jsqlparser/statement/select/UnionOp.java | 10 + .../statement/select/ValuesList.java | 51 +++- .../sf/jsqlparser/statement/select/Wait.java | 5 + .../jsqlparser/statement/select/WithItem.java | 40 +++ .../statement/truncate/Truncate.java | 10 + .../jsqlparser/statement/update/Update.java | 159 ++++++++++- .../jsqlparser/statement/upsert/Upsert.java | 90 +++++- .../statement/values/ValuesStatement.java | 31 ++- .../net/sf/jsqlparser/util/SelectUtils.java | 83 ++---- .../net/sf/jsqlparser/parser/JSqlParserCC.jjt | 256 ++++++++---------- .../ExpressionVisitorAdapterTest.java | 34 +-- .../mysql/MySqlSqlCalcFoundRowsTest.java | 22 +- .../arithmetic/ArithmethicTests.java | 93 +++++++ .../relational/LikeExpressionTest.java | 3 +- .../sf/jsqlparser/schema/SequenceTest.java | 16 +- .../net/sf/jsqlparser/schema/TableTest.java | 9 +- .../statement/DeclareStatementTest.java | 70 ++++- .../jsqlparser/statement/alter/AlterTest.java | 65 ++++- .../builder/JSQLParserFluentModelTests.java | 76 ++++++ .../builder/ReflectionModelTest.java | 189 +++++++++++++ .../statement/comment/CommentTest.java | 10 + .../statement/create/AlterSequenceTest.java | 39 +++ .../statement/create/AlterViewTest.java | 36 ++- .../create/CreateFunctionalStatementTest.java | 23 +- .../statement/create/CreateSequenceTest.java | 30 +- .../statement/create/CreateTableTest.java | 101 ++++--- .../create/schema/CreateSchemaTest.java | 14 +- .../statement/delete/DeleteTest.java | 20 +- .../jsqlparser/statement/drop/DropTest.java | 49 +++- .../jsqlparser/statement/grant/GrantTest.java | 16 +- .../statement/insert/InsertTest.java | 86 ++++-- .../select/NestedBracketsPerformanceTest.java | 12 +- .../statement/select/SelectASTTest.java | 16 +- .../statement/select/SelectTest.java | 220 +++++++++------ .../statement/select/SpeedTest.java | 32 +-- .../statement/truncate/TruncateTest.java | 19 +- .../statement/upsert/UpsertTest.java | 33 +-- .../statement/values/ValuesTest.java | 19 +- .../net/sf/jsqlparser/test/TestUtils.java | 200 +++++++++++++- .../net/sf/jsqlparser/util/RandomUtils.java | 146 ++++++++++ .../jsqlparser/util/ReflectionTestUtils.java | 185 +++++++++++++ .../sf/jsqlparser/util/SelectUtilsTest.java | 4 +- .../util/TablesNamesFinderTest.java | 35 ++- .../util/deparser/ExecuteDeParserTest.java | 42 ++- 208 files changed, 6787 insertions(+), 893 deletions(-) create mode 100644 src/main/java/net/sf/jsqlparser/Model.java create mode 100644 src/test/java/net/sf/jsqlparser/expression/operators/arithmetic/ArithmethicTests.java create mode 100644 src/test/java/net/sf/jsqlparser/statement/builder/JSQLParserFluentModelTests.java create mode 100644 src/test/java/net/sf/jsqlparser/statement/builder/ReflectionModelTest.java create mode 100644 src/test/java/net/sf/jsqlparser/statement/create/AlterSequenceTest.java create mode 100644 src/test/java/net/sf/jsqlparser/util/RandomUtils.java create mode 100644 src/test/java/net/sf/jsqlparser/util/ReflectionTestUtils.java diff --git a/pom.xml b/pom.xml index 2f933ad487..c1b9effbc3 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,12 @@ 3.16.1 test + + org.apache.commons + commons-lang3 + 3.10 + test + diff --git a/src/main/java/net/sf/jsqlparser/Model.java b/src/main/java/net/sf/jsqlparser/Model.java new file mode 100644 index 0000000000..3b7378d148 --- /dev/null +++ b/src/main/java/net/sf/jsqlparser/Model.java @@ -0,0 +1,18 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser; + +/** + *

A marker interface for jsqlparser-model-classes.

+ *

The datastructure where the sql syntax is represented by a tree consists of {@link Model}'s

+ */ +public interface Model { + +} diff --git a/src/main/java/net/sf/jsqlparser/expression/Alias.java b/src/main/java/net/sf/jsqlparser/expression/Alias.java index 939f7136de..e6718f67ad 100644 --- a/src/main/java/net/sf/jsqlparser/expression/Alias.java +++ b/src/main/java/net/sf/jsqlparser/expression/Alias.java @@ -9,8 +9,12 @@ */ package net.sf.jsqlparser.expression; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Optional; import net.sf.jsqlparser.statement.create.table.ColDataType; public class Alias { @@ -73,6 +77,33 @@ public String toString() { return alias; } + public Alias withName(String name) { + this.setName(name); + return this; + } + + public Alias withUseAs(boolean useAs) { + this.setUseAs(useAs); + return this; + } + + public Alias withAliasColumns(List aliasColumns) { + this.setAliasColumns(aliasColumns); + return this; + } + + public Alias addAliasColumns(AliasColumn... aliasColumns) { + List collection = Optional.ofNullable(getAliasColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, aliasColumns); + return this.withAliasColumns(collection); + } + + public Alias addAliasColumns(Collection aliasColumns) { + List collection = Optional.ofNullable(getAliasColumns()).orElseGet(ArrayList::new); + collection.addAll(aliasColumns); + return this.withAliasColumns(collection); + } + public static class AliasColumn { public final String name; diff --git a/src/main/java/net/sf/jsqlparser/expression/AnalyticExpression.java b/src/main/java/net/sf/jsqlparser/expression/AnalyticExpression.java index ac1d6a9946..8e49bff3bb 100644 --- a/src/main/java/net/sf/jsqlparser/expression/AnalyticExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/AnalyticExpression.java @@ -237,4 +237,75 @@ public Expression getFilterExpression() { public void setFilterExpression(Expression filterExpression) { this.filterExpression = filterExpression; } + + public AnalyticExpression withName(String name) { + this.setName(name); + return this; + } + + public AnalyticExpression withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public AnalyticExpression withOffset(Expression offset) { + this.setOffset(offset); + return this; + } + + public AnalyticExpression withDefaultValue(Expression defaultValue) { + this.setDefaultValue(defaultValue); + return this; + } + + public AnalyticExpression withAllColumns(boolean allColumns) { + this.setAllColumns(allColumns); + return this; + } + + public AnalyticExpression withKeep(KeepExpression keep) { + this.setKeep(keep); + return this; + } + + public AnalyticExpression withType(AnalyticType type) { + this.setType(type); + return this; + } + + public AnalyticExpression withDistinct(boolean distinct) { + this.setDistinct(distinct); + return this; + } + + public AnalyticExpression withIgnoreNulls(boolean ignoreNulls) { + this.setIgnoreNulls(ignoreNulls); + return this; + } + + public AnalyticExpression withFilterExpression(Expression filterExpression) { + this.setFilterExpression(filterExpression); + return this; + } + + public AnalyticExpression withWindowElement(WindowElement windowElement) { + this.setWindowElement(windowElement); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } + + public E getOffset(Class type) { + return type.cast(getOffset()); + } + + public E getDefaultValue(Class type) { + return type.cast(getDefaultValue()); + } + + public E getFilterExpression(Class type) { + return type.cast(getFilterExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/ArrayExpression.java b/src/main/java/net/sf/jsqlparser/expression/ArrayExpression.java index 05ebfa9513..50ee820345 100644 --- a/src/main/java/net/sf/jsqlparser/expression/ArrayExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/ArrayExpression.java @@ -16,6 +16,10 @@ public class ArrayExpression extends ASTNodeAccessImpl implements Expression { private Expression objExpression; private Expression indexExpression; + public ArrayExpression() { + // empty constructor + } + public ArrayExpression(Expression objExpression, Expression indexExpression) { this.objExpression = objExpression; this.indexExpression = indexExpression; @@ -46,4 +50,22 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return objExpression.toString() + "[" + indexExpression.toString() + "]"; } + + public ArrayExpression withObjExpression(Expression objExpression) { + this.setObjExpression(objExpression); + return this; + } + + public ArrayExpression withIndexExpression(Expression indexExpression) { + this.setIndexExpression(indexExpression); + return this; + } + + public E getObjExpression(Class type) { + return type.cast(getObjExpression()); + } + + public E getIndexExpression(Class type) { + return type.cast(getIndexExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/BinaryExpression.java b/src/main/java/net/sf/jsqlparser/expression/BinaryExpression.java index 1a7b932e77..cf87acfb3c 100644 --- a/src/main/java/net/sf/jsqlparser/expression/BinaryExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/BinaryExpression.java @@ -19,7 +19,7 @@ public abstract class BinaryExpression extends ASTNodeAccessImpl implements Expr private Expression leftExpression; private Expression rightExpression; -// private boolean not = false; + // private boolean not = false; public BinaryExpression() { } @@ -32,31 +32,48 @@ public Expression getRightExpression() { return rightExpression; } + public BinaryExpression withLeftExpression(Expression expression) { + setLeftExpression(expression); + return this; + } + public void setLeftExpression(Expression expression) { leftExpression = expression; } + public BinaryExpression withRightExpression(Expression expression) { + setRightExpression(expression); + return this; + } + public void setRightExpression(Expression expression) { rightExpression = expression; } -// public void setNot() { -// not = true; -// } -// -// public void removeNot() { -// not = false; -// } -// -// public boolean isNot() { -// return not; -// } + // public void setNot() { + // not = true; + // } + // + // public void removeNot() { + // not = false; + // } + // + // public boolean isNot() { + // return not; + // } @Override public String toString() { - return //(not ? "NOT " : "") + + return // (not ? "NOT " : "") + getLeftExpression() + " " + getStringExpression() + " " + getRightExpression(); } public abstract String getStringExpression(); + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } + + public E getRightExpression(Class type) { + return type.cast(getRightExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/CaseExpression.java b/src/main/java/net/sf/jsqlparser/expression/CaseExpression.java index 63c1faaa4d..08fddcc53b 100644 --- a/src/main/java/net/sf/jsqlparser/expression/CaseExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/CaseExpression.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.expression; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; import net.sf.jsqlparser.statement.select.PlainSelect; @@ -91,4 +94,39 @@ public String toString() { + PlainSelect.getStringList(whenClauses, false, false) + " " + ((elseExpression != null) ? "ELSE " + elseExpression + " " : "") + "END"; } + + public CaseExpression withSwitchExpression(Expression switchExpression) { + this.setSwitchExpression(switchExpression); + return this; + } + + public CaseExpression withWhenClauses(List whenClauses) { + this.setWhenClauses(whenClauses); + return this; + } + + public CaseExpression withElseExpression(Expression elseExpression) { + this.setElseExpression(elseExpression); + return this; + } + + public CaseExpression addWhenClauses(WhenClause... whenClauses) { + List collection = Optional.ofNullable(getWhenClauses()).orElseGet(ArrayList::new); + Collections.addAll(collection, whenClauses); + return this.withWhenClauses(collection); + } + + public CaseExpression addWhenClauses(Collection whenClauses) { + List collection = Optional.ofNullable(getWhenClauses()).orElseGet(ArrayList::new); + collection.addAll(whenClauses); + return this.withWhenClauses(collection); + } + + public E getSwitchExpression(Class type) { + return type.cast(getSwitchExpression()); + } + + public E getElseExpression(Class type) { + return type.cast(getElseExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/CastExpression.java b/src/main/java/net/sf/jsqlparser/expression/CastExpression.java index 3031a20b0a..e5f12f7d83 100644 --- a/src/main/java/net/sf/jsqlparser/expression/CastExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/CastExpression.java @@ -55,4 +55,23 @@ public String toString() { return leftExpression + "::" + type.toString(); } } + + public CastExpression withType(ColDataType type) { + this.setType(type); + return this; + } + + public CastExpression withUseCastKeyword(boolean useCastKeyword) { + this.setUseCastKeyword(useCastKeyword); + return this; + } + + public CastExpression withLeftExpression(Expression leftExpression) { + this.setLeftExpression(leftExpression); + return this; + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/CollateExpression.java b/src/main/java/net/sf/jsqlparser/expression/CollateExpression.java index 5638bcf7f7..07c2b8616f 100644 --- a/src/main/java/net/sf/jsqlparser/expression/CollateExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/CollateExpression.java @@ -16,6 +16,10 @@ public class CollateExpression extends ASTNodeAccessImpl implements Expression { private Expression leftExpression; private String collate; + public CollateExpression() { + // empty constructor + } + public CollateExpression(Expression leftExpression, String collate) { this.leftExpression = leftExpression; this.collate = collate; @@ -46,4 +50,18 @@ public void setCollate(String collate) { public String toString() { return leftExpression.toString() + " COLLATE " + collate; } + + public CollateExpression withLeftExpression(Expression leftExpression) { + this.setLeftExpression(leftExpression); + return this; + } + + public CollateExpression withCollate(String collate) { + this.setCollate(collate); + return this; + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/DateTimeLiteralExpression.java b/src/main/java/net/sf/jsqlparser/expression/DateTimeLiteralExpression.java index 8af8b1c18c..1e4a6ae369 100644 --- a/src/main/java/net/sf/jsqlparser/expression/DateTimeLiteralExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/DateTimeLiteralExpression.java @@ -42,6 +42,16 @@ public String toString() { return type.name() + " " + value; } + public DateTimeLiteralExpression withValue(String value) { + this.setValue(value); + return this; + } + + public DateTimeLiteralExpression withType(DateTime type) { + this.setType(type); + return this; + } + public static enum DateTime { DATE, TIME, TIMESTAMP; } diff --git a/src/main/java/net/sf/jsqlparser/expression/DateValue.java b/src/main/java/net/sf/jsqlparser/expression/DateValue.java index c83e39e8c6..1e863b78b0 100644 --- a/src/main/java/net/sf/jsqlparser/expression/DateValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/DateValue.java @@ -20,8 +20,21 @@ public class DateValue extends ASTNodeAccessImpl implements Expression { private Date value; + public DateValue() { + // empty constructor + } + + public DateValue(Date value) { + this.value = value; + } + + /** + * A Date in the form {d 'yyyy-mm-dd'} + * + * @param value + */ public DateValue(String value) { - this.value = Date.valueOf(value.substring(1, value.length() - 1)); + this(Date.valueOf(value.substring(1, value.length() - 1))); } @Override @@ -41,4 +54,9 @@ public void setValue(Date d) { public String toString() { return "{d '" + value.toString() + "'}"; } + + public DateValue withValue(Date value) { + this.setValue(value); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/DoubleValue.java b/src/main/java/net/sf/jsqlparser/expression/DoubleValue.java index e882b1a786..43e072dcf1 100644 --- a/src/main/java/net/sf/jsqlparser/expression/DoubleValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/DoubleValue.java @@ -19,6 +19,10 @@ public class DoubleValue extends ASTNodeAccessImpl implements Expression { private double value; private String stringValue; + public DoubleValue() { + // empty constructor + } + public DoubleValue(final String value) { String val = value; if (val.charAt(0) == '+') { @@ -45,4 +49,9 @@ public void setValue(double d) { public String toString() { return stringValue; } + + public DoubleValue withValue(double value) { + this.setValue(value); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/Expression.java b/src/main/java/net/sf/jsqlparser/expression/Expression.java index dec9bbf49a..daeb2da834 100644 --- a/src/main/java/net/sf/jsqlparser/expression/Expression.java +++ b/src/main/java/net/sf/jsqlparser/expression/Expression.java @@ -9,9 +9,11 @@ */ package net.sf.jsqlparser.expression; +import net.sf.jsqlparser.Model; import net.sf.jsqlparser.parser.ASTNodeAccess; -public interface Expression extends ASTNodeAccess { +public interface Expression extends ASTNodeAccess, Model { void accept(ExpressionVisitor expressionVisitor); + } diff --git a/src/main/java/net/sf/jsqlparser/expression/ExtractExpression.java b/src/main/java/net/sf/jsqlparser/expression/ExtractExpression.java index b3c07a0eb7..aeb01814e2 100644 --- a/src/main/java/net/sf/jsqlparser/expression/ExtractExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/ExtractExpression.java @@ -47,4 +47,18 @@ public void setExpression(Expression expression) { public String toString() { return "EXTRACT(" + name + " FROM " + expression + ')'; } + + public ExtractExpression withName(String name) { + this.setName(name); + return this; + } + + public ExtractExpression withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/Function.java b/src/main/java/net/sf/jsqlparser/expression/Function.java index 45258b3c28..6e7daceace 100644 --- a/src/main/java/net/sf/jsqlparser/expression/Function.java +++ b/src/main/java/net/sf/jsqlparser/expression/Function.java @@ -190,4 +190,48 @@ public String toString() { return ans; } + + public Function withAttribute(Expression attribute) { + this.setAttribute(attribute); + return this; + } + + public Function withAttributeName(String attributeName) { + this.setAttributeName(attributeName); + return this; + } + + public Function withKeep(KeepExpression keep) { + this.setKeep(keep); + return this; + } + + public Function withIgnoreNulls(boolean ignoreNulls) { + this.setIgnoreNulls(ignoreNulls); + return this; + } + + public Function withParameters(ExpressionList parameters) { + this.setParameters(parameters); + return this; + } + + public Function withNamedParameters(NamedExpressionList namedParameters) { + this.setNamedParameters(namedParameters); + return this; + } + + public Function withAllColumns(boolean allColumns) { + this.setAllColumns(allColumns); + return this; + } + + public Function withDistinct(boolean distinct) { + this.setDistinct(distinct); + return this; + } + + public E getAttribute(Class type) { + return type.cast(getAttribute()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/HexValue.java b/src/main/java/net/sf/jsqlparser/expression/HexValue.java index 2bc3b421f5..a5a334a2a8 100644 --- a/src/main/java/net/sf/jsqlparser/expression/HexValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/HexValue.java @@ -13,11 +13,15 @@ public class HexValue extends ASTNodeAccessImpl implements Expression { - private String stringValue; + private String value; + + public HexValue() { + // empty constructor + } public HexValue(final String value) { String val = value; - this.stringValue = val; + this.value = val; } @Override @@ -26,15 +30,20 @@ public void accept(ExpressionVisitor expressionVisitor) { } public String getValue() { - return stringValue; + return value; + } + + public void setValue(String value) { + this.value = value; } - public void setValue(String d) { - stringValue = d; + public HexValue withValue(String value) { + this.setValue(value); + return this; } @Override public String toString() { - return stringValue; + return value; } } diff --git a/src/main/java/net/sf/jsqlparser/expression/IntervalExpression.java b/src/main/java/net/sf/jsqlparser/expression/IntervalExpression.java index 3f82409a75..a374785f94 100644 --- a/src/main/java/net/sf/jsqlparser/expression/IntervalExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/IntervalExpression.java @@ -62,4 +62,23 @@ public String toString() { public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + public IntervalExpression withParameter(String parameter) { + this.setParameter(parameter); + return this; + } + + public IntervalExpression withIntervalType(String intervalType) { + this.setIntervalType(intervalType); + return this; + } + + public IntervalExpression withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/JdbcNamedParameter.java b/src/main/java/net/sf/jsqlparser/expression/JdbcNamedParameter.java index 0c66dd46c7..42cc781310 100644 --- a/src/main/java/net/sf/jsqlparser/expression/JdbcNamedParameter.java +++ b/src/main/java/net/sf/jsqlparser/expression/JdbcNamedParameter.java @@ -39,4 +39,9 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return ":" + name; } + + public JdbcNamedParameter withName(String name) { + this.setName(name); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/JdbcParameter.java b/src/main/java/net/sf/jsqlparser/expression/JdbcParameter.java index d2dc0be53a..d72bb8df8a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/JdbcParameter.java +++ b/src/main/java/net/sf/jsqlparser/expression/JdbcParameter.java @@ -52,4 +52,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return useFixedIndex ? "?" + index : "?"; } + + public JdbcParameter withIndex(Integer index) { + this.setIndex(index); + return this; + } + + public JdbcParameter withUseFixedIndex(boolean useFixedIndex) { + this.setUseFixedIndex(useFixedIndex); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/JsonExpression.java b/src/main/java/net/sf/jsqlparser/expression/JsonExpression.java index 7eed1cf12b..472e793a8a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/JsonExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/JsonExpression.java @@ -64,4 +64,9 @@ public String toString() { } return b.toString(); } + + public JsonExpression withColumn(Column column) { + this.setColumn(column); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/KeepExpression.java b/src/main/java/net/sf/jsqlparser/expression/KeepExpression.java index 51fb5b8bfb..2712a0e468 100644 --- a/src/main/java/net/sf/jsqlparser/expression/KeepExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/KeepExpression.java @@ -9,11 +9,14 @@ */ package net.sf.jsqlparser.expression; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; import net.sf.jsqlparser.statement.select.OrderByElement; -import java.util.List; - public class KeepExpression extends ASTNodeAccessImpl implements Expression { private String name; @@ -74,4 +77,31 @@ private void toStringOrderByElements(StringBuilder b) { } } } + + public KeepExpression withName(String name) { + this.setName(name); + return this; + } + + public KeepExpression withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public KeepExpression withFirst(boolean first) { + this.setFirst(first); + return this; + } + + public KeepExpression addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public KeepExpression addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/LongValue.java b/src/main/java/net/sf/jsqlparser/expression/LongValue.java index 253c73a0b2..f023210dd3 100644 --- a/src/main/java/net/sf/jsqlparser/expression/LongValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/LongValue.java @@ -9,9 +9,8 @@ */ package net.sf.jsqlparser.expression; -import net.sf.jsqlparser.parser.ASTNodeAccessImpl; - import java.math.BigInteger; +import net.sf.jsqlparser.parser.ASTNodeAccessImpl; /** * Every number without a point or an exponential format is a LongValue. @@ -20,6 +19,10 @@ public class LongValue extends ASTNodeAccessImpl implements Expression { private String stringValue; + public LongValue() { + // empty constructor + } + public LongValue(final String value) { String val = value; if (val.charAt(0) == '+') { @@ -49,6 +52,11 @@ public void setValue(long d) { stringValue = String.valueOf(d); } + public LongValue withValue(long d) { + setValue(d); + return this; + } + public String getStringValue() { return stringValue; } @@ -61,4 +69,9 @@ public void setStringValue(String string) { public String toString() { return getStringValue(); } + + public LongValue withStringValue(String stringValue) { + this.setStringValue(stringValue); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/MySQLGroupConcat.java b/src/main/java/net/sf/jsqlparser/expression/MySQLGroupConcat.java index 68f110711b..ee347ffa92 100644 --- a/src/main/java/net/sf/jsqlparser/expression/MySQLGroupConcat.java +++ b/src/main/java/net/sf/jsqlparser/expression/MySQLGroupConcat.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.expression; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; import net.sf.jsqlparser.statement.select.OrderByElement; @@ -82,4 +86,36 @@ public String toString() { b.append(")"); return b.toString(); } + + public MySQLGroupConcat withExpressionList(ExpressionList expressionList) { + this.setExpressionList(expressionList); + return this; + } + + public MySQLGroupConcat withDistinct(boolean distinct) { + this.setDistinct(distinct); + return this; + } + + public MySQLGroupConcat withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public MySQLGroupConcat withSeparator(String separator) { + this.setSeparator(separator); + return this; + } + + public MySQLGroupConcat addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public MySQLGroupConcat addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java b/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java index cef60c5081..fc3745774a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java +++ b/src/main/java/net/sf/jsqlparser/expression/MySQLIndexHint.java @@ -23,6 +23,18 @@ public MySQLIndexHint(String action, String indexQualifier, List indexNa this.indexNames = indexNames; } + public String getAction() { + return action; + } + + public String getIndexQualifier() { + return indexQualifier; + } + + public List getIndexNames() { + return indexNames; + } + @Override public String toString() { // use|ignore|force key|index (index1,...,indexN) diff --git a/src/main/java/net/sf/jsqlparser/expression/NextValExpression.java b/src/main/java/net/sf/jsqlparser/expression/NextValExpression.java index 50e30553fd..97098a83c9 100644 --- a/src/main/java/net/sf/jsqlparser/expression/NextValExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/NextValExpression.java @@ -20,6 +20,10 @@ public NextValExpression(List nameList) { this.nameList = nameList; } + public List getNameList() { + return nameList; + } + public String getName() { StringBuilder b = new StringBuilder(); for (String name : nameList) { diff --git a/src/main/java/net/sf/jsqlparser/expression/NotExpression.java b/src/main/java/net/sf/jsqlparser/expression/NotExpression.java index 62d8846d00..d61ae2bb9a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/NotExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/NotExpression.java @@ -20,6 +20,10 @@ public class NotExpression extends ASTNodeAccessImpl implements Expression { private boolean exclamationMark = false; + public NotExpression() { + // empty constructor + } + public NotExpression(Expression expression) { this(expression, false); } @@ -54,4 +58,18 @@ public boolean isExclamationMark() { public void setExclamationMark(boolean exclamationMark) { this.exclamationMark = exclamationMark; } + + public NotExpression withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public NotExpression withExclamationMark(boolean exclamationMark) { + this.setExclamationMark(exclamationMark); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/NumericBind.java b/src/main/java/net/sf/jsqlparser/expression/NumericBind.java index 106b221490..8f5ac40880 100644 --- a/src/main/java/net/sf/jsqlparser/expression/NumericBind.java +++ b/src/main/java/net/sf/jsqlparser/expression/NumericBind.java @@ -32,4 +32,9 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return ":" + bindId; } + + public NumericBind withBindId(int bindId) { + this.setBindId(bindId); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/OracleHierarchicalExpression.java b/src/main/java/net/sf/jsqlparser/expression/OracleHierarchicalExpression.java index 9c3b715c7f..a3644e4419 100644 --- a/src/main/java/net/sf/jsqlparser/expression/OracleHierarchicalExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/OracleHierarchicalExpression.java @@ -79,4 +79,32 @@ public String toString() { } return b.toString(); } + + public OracleHierarchicalExpression withStartExpression(Expression startExpression) { + this.setStartExpression(startExpression); + return this; + } + + public OracleHierarchicalExpression withConnectExpression(Expression connectExpression) { + this.setConnectExpression(connectExpression); + return this; + } + + public OracleHierarchicalExpression withNoCycle(boolean noCycle) { + this.setNoCycle(noCycle); + return this; + } + + public OracleHierarchicalExpression withConnectFirst(boolean connectFirst) { + this.setConnectFirst(connectFirst); + return this; + } + + public E getStartExpression(Class type) { + return type.cast(getStartExpression()); + } + + public E getConnectExpression(Class type) { + return type.cast(getConnectExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/OracleHint.java b/src/main/java/net/sf/jsqlparser/expression/OracleHint.java index 54ef90e47d..cbfe0632dc 100644 --- a/src/main/java/net/sf/jsqlparser/expression/OracleHint.java +++ b/src/main/java/net/sf/jsqlparser/expression/OracleHint.java @@ -75,4 +75,13 @@ public String toString() { } } + public OracleHint withValue(String value) { + this.setValue(value); + return this; + } + + public OracleHint withSingleLine(boolean singleLine) { + this.setSingleLine(singleLine); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/OrderByClause.java b/src/main/java/net/sf/jsqlparser/expression/OrderByClause.java index c76a9c6003..4e142f5605 100644 --- a/src/main/java/net/sf/jsqlparser/expression/OrderByClause.java +++ b/src/main/java/net/sf/jsqlparser/expression/OrderByClause.java @@ -9,9 +9,12 @@ */ package net.sf.jsqlparser.expression; -import net.sf.jsqlparser.statement.select.OrderByElement; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; +import net.sf.jsqlparser.statement.select.OrderByElement; public class OrderByClause { private List orderByElements; @@ -35,4 +38,21 @@ void toStringOrderByElements(StringBuilder b) { } } } + + public OrderByClause withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public OrderByClause addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public OrderByClause addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/Parenthesis.java b/src/main/java/net/sf/jsqlparser/expression/Parenthesis.java index 12bd6f3f53..c83e273e36 100644 --- a/src/main/java/net/sf/jsqlparser/expression/Parenthesis.java +++ b/src/main/java/net/sf/jsqlparser/expression/Parenthesis.java @@ -42,4 +42,13 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return "(" + expression + ")"; } + + public Parenthesis withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/PartitionByClause.java b/src/main/java/net/sf/jsqlparser/expression/PartitionByClause.java index 57844ed6d4..32bff70873 100644 --- a/src/main/java/net/sf/jsqlparser/expression/PartitionByClause.java +++ b/src/main/java/net/sf/jsqlparser/expression/PartitionByClause.java @@ -41,4 +41,9 @@ void toStringPartitionBy(StringBuilder b) { public boolean isBrackets() { return brackets; } + + public PartitionByClause withPartitionExpressionList(ExpressionList partitionExpressionList) { + this.setPartitionExpressionList(partitionExpressionList); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/RowConstructor.java b/src/main/java/net/sf/jsqlparser/expression/RowConstructor.java index 16144f248d..fb499dee1b 100644 --- a/src/main/java/net/sf/jsqlparser/expression/RowConstructor.java +++ b/src/main/java/net/sf/jsqlparser/expression/RowConstructor.java @@ -45,4 +45,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return (name != null ? name : "") + exprList.toString(); } + + public RowConstructor withExprList(ExpressionList exprList) { + this.setExprList(exprList); + return this; + } + + public RowConstructor withName(String name) { + this.setName(name); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/SQLServerHints.java b/src/main/java/net/sf/jsqlparser/expression/SQLServerHints.java index 3a676c210f..28f497616e 100644 --- a/src/main/java/net/sf/jsqlparser/expression/SQLServerHints.java +++ b/src/main/java/net/sf/jsqlparser/expression/SQLServerHints.java @@ -54,4 +54,14 @@ public String toString() { + String.join(", ", hints) + ")"; } + + public SQLServerHints withNoLock(Boolean noLock) { + this.setNoLock(noLock); + return this; + } + + public SQLServerHints withIndexName(String indexName) { + this.setIndexName(indexName); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java b/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java index ad8d3e1b6d..dabc2f9c57 100644 --- a/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/SignedExpression.java @@ -19,6 +19,10 @@ public class SignedExpression extends ASTNodeAccessImpl implements Expression { private char sign; private Expression expression; + public SignedExpression() { + // empty constructor + } + public SignedExpression(char sign, Expression expression) { setSign(sign); setExpression(expression); @@ -52,4 +56,18 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return getSign() + expression.toString(); } + + public SignedExpression withSign(char sign) { + this.setSign(sign); + return this; + } + + public SignedExpression withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/StringValue.java b/src/main/java/net/sf/jsqlparser/expression/StringValue.java index 25deae03a0..d7b0c49121 100644 --- a/src/main/java/net/sf/jsqlparser/expression/StringValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/StringValue.java @@ -23,6 +23,10 @@ public final class StringValue extends ASTNodeAccessImpl implements Expression { public static final List ALLOWED_PREFIXES = Arrays.asList("N", "U", "E", "R", "B", "RB", "_utf8"); + public StringValue() { + // empty constructor + } + public StringValue(String escapedValue) { // removing "'" at the start and at the end if (escapedValue.startsWith("'") && escapedValue.endsWith("'")) { @@ -32,7 +36,8 @@ public StringValue(String escapedValue) { if (escapedValue.length() > 2) { for (String p : ALLOWED_PREFIXES) { - if (escapedValue.length() > p.length() && escapedValue.substring(0, p.length()).equalsIgnoreCase(p) && escapedValue.charAt(p.length()) == '\'') { + if (escapedValue.length() > p.length() && escapedValue.substring(0, p.length()).equalsIgnoreCase(p) + && escapedValue.charAt(p.length()) == '\'') { this.prefix = p; value = escapedValue.substring(p.length() + 1, escapedValue.length() - 1); return; @@ -80,4 +85,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return (prefix != null ? prefix : "") + "'" + value + "'"; } + + public StringValue withPrefix(String prefix) { + this.setPrefix(prefix); + return this; + } + + public StringValue withValue(String value) { + this.setValue(value); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/TimeKeyExpression.java b/src/main/java/net/sf/jsqlparser/expression/TimeKeyExpression.java index b82b885641..f2c4cfa65b 100644 --- a/src/main/java/net/sf/jsqlparser/expression/TimeKeyExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/TimeKeyExpression.java @@ -15,6 +15,10 @@ public class TimeKeyExpression extends ASTNodeAccessImpl implements Expression { private String stringValue; + public TimeKeyExpression() { + // empty constructor + } + public TimeKeyExpression(final String value) { this.stringValue = value; } @@ -36,4 +40,9 @@ public void setStringValue(String string) { public String toString() { return getStringValue(); } + + public TimeKeyExpression withStringValue(String stringValue) { + this.setStringValue(stringValue); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/TimeValue.java b/src/main/java/net/sf/jsqlparser/expression/TimeValue.java index cadd953982..1009451476 100644 --- a/src/main/java/net/sf/jsqlparser/expression/TimeValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/TimeValue.java @@ -20,6 +20,10 @@ public class TimeValue extends ASTNodeAccessImpl implements Expression { private Time value; + public TimeValue() { + // empty constructor + } + public TimeValue(String value) { this.value = Time.valueOf(value.substring(1, value.length() - 1)); } @@ -41,4 +45,9 @@ public void setValue(Time d) { public String toString() { return "{t '" + value + "'}"; } + + public TimeValue withValue(Time value) { + this.setValue(value); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/TimestampValue.java b/src/main/java/net/sf/jsqlparser/expression/TimestampValue.java index b37c19a265..dc18995e6e 100644 --- a/src/main/java/net/sf/jsqlparser/expression/TimestampValue.java +++ b/src/main/java/net/sf/jsqlparser/expression/TimestampValue.java @@ -20,6 +20,11 @@ public class TimestampValue extends ASTNodeAccessImpl implements Expression { private Timestamp value; private char quotation = '\''; + + public TimestampValue() { + // empty constructor + } + public TimestampValue(String value) { if (value == null) { throw new java.lang.IllegalArgumentException("null string"); @@ -49,4 +54,9 @@ public void setValue(Timestamp d) { public String toString() { return "{ts '" + value + "'}"; } + + public TimestampValue withValue(Timestamp value) { + this.setValue(value); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/UserVariable.java b/src/main/java/net/sf/jsqlparser/expression/UserVariable.java index 9209881393..f7abde5f8b 100644 --- a/src/main/java/net/sf/jsqlparser/expression/UserVariable.java +++ b/src/main/java/net/sf/jsqlparser/expression/UserVariable.java @@ -19,6 +19,14 @@ public class UserVariable extends ASTNodeAccessImpl implements Expression { private String name; private boolean doubleAdd = false; + public UserVariable() { + // empty constructor + } + + public UserVariable(String name) { + this.name = name; + } + public String getName() { return name; } @@ -44,4 +52,14 @@ public void setDoubleAdd(boolean doubleAdd) { public String toString() { return "@" + (doubleAdd ? "@" : "") + name; } + + public UserVariable withName(String name) { + this.setName(name); + return this; + } + + public UserVariable withDoubleAdd(boolean doubleAdd) { + this.setDoubleAdd(doubleAdd); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/ValueListExpression.java b/src/main/java/net/sf/jsqlparser/expression/ValueListExpression.java index 1886eeb963..5023f4caa5 100644 --- a/src/main/java/net/sf/jsqlparser/expression/ValueListExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/ValueListExpression.java @@ -40,4 +40,8 @@ public String toString() { return expressionList.toString(); } + public ValueListExpression withExpressionList(ExpressionList expressionList) { + this.setExpressionList(expressionList); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/WhenClause.java b/src/main/java/net/sf/jsqlparser/expression/WhenClause.java index ed5915379d..2d4de0b293 100644 --- a/src/main/java/net/sf/jsqlparser/expression/WhenClause.java +++ b/src/main/java/net/sf/jsqlparser/expression/WhenClause.java @@ -12,7 +12,8 @@ import net.sf.jsqlparser.parser.ASTNodeAccessImpl; /** - * A clause of following syntax: WHEN condition THEN expression. Which is part of a CaseExpression. + * A clause of following syntax: WHEN condition THEN expression. Which is part + * of a CaseExpression. */ public class WhenClause extends ASTNodeAccessImpl implements Expression { @@ -50,4 +51,22 @@ public void setWhenExpression(Expression whenExpression) { public String toString() { return "WHEN " + whenExpression + " THEN " + thenExpression; } + + public WhenClause withWhenExpression(Expression whenExpression) { + this.setWhenExpression(whenExpression); + return this; + } + + public WhenClause withThenExpression(Expression thenExpression) { + this.setThenExpression(thenExpression); + return this; + } + + public E getThenExpression(Class type) { + return type.cast(getThenExpression()); + } + + public E getWhenExpression(Class type) { + return type.cast(getWhenExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/WindowElement.java b/src/main/java/net/sf/jsqlparser/expression/WindowElement.java index 0d49303946..7270de37ae 100644 --- a/src/main/java/net/sf/jsqlparser/expression/WindowElement.java +++ b/src/main/java/net/sf/jsqlparser/expression/WindowElement.java @@ -57,4 +57,20 @@ public String toString() { return buffer.toString(); } + + public WindowElement withType(Type type) { + this.setType(type); + return this; + } + + public WindowElement withOffset(WindowOffset offset) { + this.setOffset(offset); + return this; + } + + public WindowElement withRange(WindowRange range) { + this.setRange(range); + return this; + } + } diff --git a/src/main/java/net/sf/jsqlparser/expression/WindowOffset.java b/src/main/java/net/sf/jsqlparser/expression/WindowOffset.java index b7c7efb9b1..ee7ab5cfeb 100644 --- a/src/main/java/net/sf/jsqlparser/expression/WindowOffset.java +++ b/src/main/java/net/sf/jsqlparser/expression/WindowOffset.java @@ -66,4 +66,19 @@ public String toString() { } return buffer.toString(); } + + public WindowOffset withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public WindowOffset withType(Type type) { + this.setType(type); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } + } diff --git a/src/main/java/net/sf/jsqlparser/expression/WindowRange.java b/src/main/java/net/sf/jsqlparser/expression/WindowRange.java index 3698f82f11..6176c0dbb9 100644 --- a/src/main/java/net/sf/jsqlparser/expression/WindowRange.java +++ b/src/main/java/net/sf/jsqlparser/expression/WindowRange.java @@ -39,4 +39,14 @@ public String toString() { buffer.append(end); return buffer.toString(); } + + public WindowRange withStart(WindowOffset start) { + this.setStart(start); + return this; + } + + public WindowRange withEnd(WindowOffset end) { + this.setEnd(end); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Addition.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Addition.java index eae793e577..cc1d9620ef 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Addition.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Addition.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Addition extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "+"; } + + @Override + public Addition withLeftExpression(Expression arg0) { + return (Addition) super.withLeftExpression(arg0); + } + + @Override + public Addition withRightExpression(Expression arg0) { + return (Addition) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseAnd.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseAnd.java index d09a639a7e..54e031bf55 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseAnd.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseAnd.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class BitwiseAnd extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "&"; } + + @Override + public BitwiseAnd withLeftExpression(Expression arg0) { + return (BitwiseAnd) super.withLeftExpression(arg0); + } + + @Override + public BitwiseAnd withRightExpression(Expression arg0) { + return (BitwiseAnd) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseLeftShift.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseLeftShift.java index 9e370b8cfd..ddd529f2e1 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseLeftShift.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseLeftShift.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class BitwiseLeftShift extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "<<"; } + + @Override + public BitwiseLeftShift withLeftExpression(Expression arg0) { + return (BitwiseLeftShift) super.withLeftExpression(arg0); + } + + @Override + public BitwiseLeftShift withRightExpression(Expression arg0) { + return (BitwiseLeftShift) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseOr.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseOr.java index 71018b32f5..f381bb8c94 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseOr.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseOr.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class BitwiseOr extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "|"; } + + @Override + public BitwiseOr withLeftExpression(Expression arg0) { + return (BitwiseOr) super.withLeftExpression(arg0); + } + + @Override + public BitwiseOr withRightExpression(Expression arg0) { + return (BitwiseOr) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseRightShift.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseRightShift.java index 5166d5c7b5..f697cfd06f 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseRightShift.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseRightShift.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class BitwiseRightShift extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return ">>"; } + + @Override + public BitwiseRightShift withLeftExpression(Expression arg0) { + return (BitwiseRightShift) super.withLeftExpression(arg0); + } + + @Override + public BitwiseRightShift withRightExpression(Expression arg0) { + return (BitwiseRightShift) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseXor.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseXor.java index 8fed7afdd9..d543ee42b0 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseXor.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/BitwiseXor.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class BitwiseXor extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "^"; } + + @Override + public BitwiseXor withLeftExpression(Expression arg0) { + return (BitwiseXor) super.withLeftExpression(arg0); + } + + @Override + public BitwiseXor withRightExpression(Expression arg0) { + return (BitwiseXor) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Concat.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Concat.java index b2ede36534..50ad8cf7b2 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Concat.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Concat.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Concat extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "||"; } + + @Override + public Concat withLeftExpression(Expression arg0) { + return (Concat) super.withLeftExpression(arg0); + } + + @Override + public Concat withRightExpression(Expression arg0) { + return (Concat) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Division.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Division.java index d6097216b0..c980d87c37 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Division.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Division.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Division extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "/"; } + + @Override + public Division withLeftExpression(Expression arg0) { + return (Division) super.withLeftExpression(arg0); + } + + @Override + public Division withRightExpression(Expression arg0) { + return (Division) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/IntegerDivision.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/IntegerDivision.java index c2fa939fe0..f9ac96fb64 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/IntegerDivision.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/IntegerDivision.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class IntegerDivision extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "DIV"; } + + @Override + public IntegerDivision withLeftExpression(Expression arg0) { + return (IntegerDivision) super.withLeftExpression(arg0); + } + + @Override + public IntegerDivision withRightExpression(Expression arg0) { + return (IntegerDivision) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Modulo.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Modulo.java index f6fb98ba76..ff0ad6eb47 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Modulo.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Modulo.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; /** @@ -29,4 +30,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "%"; } + + @Override + public Modulo withLeftExpression(Expression arg0) { + return (Modulo) super.withLeftExpression(arg0); + } + + @Override + public Modulo withRightExpression(Expression arg0) { + return (Modulo) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Multiplication.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Multiplication.java index dcc193c584..db66fb1d48 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Multiplication.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Multiplication.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Multiplication extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "*"; } + + @Override + public Multiplication withLeftExpression(Expression arg0) { + return (Multiplication) super.withLeftExpression(arg0); + } + + @Override + public Multiplication withRightExpression(Expression arg0) { + return (Multiplication) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Subtraction.java b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Subtraction.java index 2ebc55bfdc..87615f6c1e 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Subtraction.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/arithmetic/Subtraction.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.arithmetic; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Subtraction extends BinaryExpression { @@ -23,4 +24,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "-"; } + + @Override + public Subtraction withLeftExpression(Expression arg0) { + return (Subtraction) super.withLeftExpression(arg0); + } + + @Override + public Subtraction withRightExpression(Expression arg0) { + return (Subtraction) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/conditional/AndExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/conditional/AndExpression.java index 1aca703f20..38152158b7 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/conditional/AndExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/conditional/AndExpression.java @@ -15,16 +15,20 @@ public class AndExpression extends BinaryExpression { private boolean useOperator = false; - + + public AndExpression() { + // nothing + } + public AndExpression(Expression leftExpression, Expression rightExpression) { setLeftExpression(leftExpression); setRightExpression(rightExpression); } - + public void setUseOperator(boolean useOperator) { this.useOperator = useOperator; } - + public boolean isUseOperator() { return useOperator; } @@ -36,6 +40,21 @@ public void accept(ExpressionVisitor expressionVisitor) { @Override public String getStringExpression() { - return useOperator?"&&":"AND"; + return useOperator ? "&&" : "AND"; + } + + public AndExpression withUseOperator(boolean useOperator) { + this.setUseOperator(useOperator); + return this; + } + + @Override + public AndExpression withLeftExpression(Expression arg0) { + return (AndExpression) super.withLeftExpression(arg0); + } + + @Override + public AndExpression withRightExpression(Expression arg0) { + return (AndExpression) super.withRightExpression(arg0); } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/conditional/OrExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/conditional/OrExpression.java index 35bd21f38a..11503b475a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/conditional/OrExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/conditional/OrExpression.java @@ -15,11 +15,25 @@ public class OrExpression extends BinaryExpression { + public OrExpression() { + // nothing + } + public OrExpression(Expression leftExpression, Expression rightExpression) { setLeftExpression(leftExpression); setRightExpression(rightExpression); } + @Override + public OrExpression withLeftExpression(Expression expression) { + return (OrExpression) super.withLeftExpression(expression); + } + + @Override + public OrExpression withRightExpression(Expression expression) { + return (OrExpression) super.withRightExpression(expression); + } + @Override public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); @@ -29,4 +43,5 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "OR"; } + } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/Between.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/Between.java index 58d8851631..e220a1dcb4 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/Between.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/Between.java @@ -65,4 +65,36 @@ public String toString() { return leftExpression + " " + (not ? "NOT " : "") + "BETWEEN " + betweenExpressionStart + " AND " + betweenExpressionEnd; } + + public Between withLeftExpression(Expression leftExpression) { + this.setLeftExpression(leftExpression); + return this; + } + + public Between withNot(boolean not) { + this.setNot(not); + return this; + } + + public Between withBetweenExpressionStart(Expression betweenExpressionStart) { + this.setBetweenExpressionStart(betweenExpressionStart); + return this; + } + + public Between withBetweenExpressionEnd(Expression betweenExpressionEnd) { + this.setBetweenExpressionEnd(betweenExpressionEnd); + return this; + } + + public E getBetweenExpressionEnd(Class type) { + return type.cast(getBetweenExpressionEnd()); + } + + public E getBetweenExpressionStart(Class type) { + return type.cast(getBetweenExpressionStart()); + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ComparisonOperator.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ComparisonOperator.java index dba5439670..d15081101f 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ComparisonOperator.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ComparisonOperator.java @@ -9,6 +9,8 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; + public abstract class ComparisonOperator extends OldOracleJoinBinaryExpression { private final String operator; @@ -17,8 +19,34 @@ public ComparisonOperator(String operator) { this.operator = operator; } + public ComparisonOperator(String operator, Expression left, Expression right) { + this(operator); + setLeftExpression(left); + setRightExpression(right); + } + @Override public String getStringExpression() { return operator; } + + @Override + public ComparisonOperator withLeftExpression(Expression arg0) { + return (ComparisonOperator) super.withLeftExpression(arg0); + } + + @Override + public ComparisonOperator withRightExpression(Expression arg0) { + return (ComparisonOperator) super.withRightExpression(arg0); + } + + @Override + public ComparisonOperator withOldOracleJoinSyntax(int oldOracleJoinSyntax) { + return (ComparisonOperator) super.withOldOracleJoinSyntax(oldOracleJoinSyntax); + } + + @Override + public ComparisonOperator withOraclePriorPosition(int oraclePriorPosition) { + return (ComparisonOperator) super.withOraclePriorPosition(oraclePriorPosition); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java index b890860d13..e9e33ac607 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/EqualsTo.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class EqualsTo extends ComparisonOperator { @@ -17,8 +18,34 @@ public EqualsTo() { super("="); } + public EqualsTo(Expression left, Expression right) { + this(); + setLeftExpression(left); + setRightExpression(right); + } + @Override public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public EqualsTo withLeftExpression(Expression expression) { + return (EqualsTo) super.withLeftExpression(expression); + } + + @Override + public EqualsTo withRightExpression(Expression expression) { + return (EqualsTo) super.withRightExpression(expression); + } + + @Override + public EqualsTo withOldOracleJoinSyntax(int arg0) { + return (EqualsTo) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public EqualsTo withOraclePriorPosition(int arg0) { + return (EqualsTo) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExistsExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExistsExpression.java index e0b30214fe..8fce8d04ed 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExistsExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExistsExpression.java @@ -47,4 +47,18 @@ public String getStringExpression() { public String toString() { return getStringExpression() + " " + rightExpression.toString(); } + + public ExistsExpression withRightExpression(Expression rightExpression) { + this.setRightExpression(rightExpression); + return this; + } + + public ExistsExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + public E getRightExpression(Class type) { + return type.cast(getRightExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExpressionList.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExpressionList.java index d1144cbd82..edf8404306 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExpressionList.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/ExpressionList.java @@ -9,9 +9,12 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.statement.select.PlainSelect; @@ -28,8 +31,8 @@ public ExpressionList() { public ExpressionList(List expressions) { this.expressions = expressions; } - - public ExpressionList(Expression ... expressions) { + + public ExpressionList(Expression... expressions) { this.expressions = Arrays.asList(expressions); } @@ -37,8 +40,19 @@ public List getExpressions() { return expressions; } - public void setExpressions(List list) { - expressions = list; + public ExpressionList addExpressions(Expression... elements) { + List list = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + Collections.addAll(list, elements); + return withExpressions(list); + } + + public ExpressionList withExpressions(List expressions) { + this.setExpressions(expressions); + return this; + } + + public void setExpressions(List expressions) { + this.expressions = expressions; } @Override @@ -50,4 +64,10 @@ public void accept(ItemsListVisitor itemsListVisitor) { public String toString() { return PlainSelect.getStringList(expressions, true, true); } + + public ExpressionList addExpressions(Collection expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + collection.addAll(expressions); + return this.withExpressions(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java index d011d48f0b..f54dd73c6f 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/FullTextSearch.java @@ -9,15 +9,18 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; import net.sf.jsqlparser.schema.Column; -import java.util.Iterator; -import java.util.List; - public class FullTextSearch extends ASTNodeAccessImpl implements Expression { private List _matchColumns; @@ -73,4 +76,31 @@ public String toString() { return "MATCH (" + columnsListCommaSeperated + ") AGAINST (" + this._againstValue + (this._searchModifier != null ? " " + this._searchModifier : "") + ")"; } + + public FullTextSearch withMatchColumns(List matchColumns) { + this.setMatchColumns(matchColumns); + return this; + } + + public FullTextSearch withAgainstValue(StringValue againstValue) { + this.setAgainstValue(againstValue); + return this; + } + + public FullTextSearch withSearchModifier(String searchModifier) { + this.setSearchModifier(searchModifier); + return this; + } + + public FullTextSearch addMatchColumns(Column... matchColumns) { + List collection = Optional.ofNullable(getMatchColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, matchColumns); + return this.withMatchColumns(collection); + } + + public FullTextSearch addMatchColumns(Collection matchColumns) { + List collection = Optional.ofNullable(getMatchColumns()).orElseGet(ArrayList::new); + collection.addAll(matchColumns); + return this.withMatchColumns(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThan.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThan.java index f8e4a9d69e..1a22e867b4 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThan.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThan.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class GreaterThan extends ComparisonOperator { @@ -21,4 +22,24 @@ public GreaterThan() { public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public GreaterThan withLeftExpression(Expression arg0) { + return (GreaterThan) super.withLeftExpression(arg0); + } + + @Override + public GreaterThan withRightExpression(Expression arg0) { + return (GreaterThan) super.withRightExpression(arg0); + } + + @Override + public GreaterThan withOldOracleJoinSyntax(int arg0) { + return (GreaterThan) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public GreaterThan withOraclePriorPosition(int arg0) { + return (GreaterThan) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThanEquals.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThanEquals.java index 0a232663cf..2ff66a1349 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThanEquals.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/GreaterThanEquals.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class GreaterThanEquals extends ComparisonOperator { @@ -25,4 +26,24 @@ public GreaterThanEquals(String operator) { public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public GreaterThanEquals withLeftExpression(Expression arg0) { + return (GreaterThanEquals) super.withLeftExpression(arg0); + } + + @Override + public GreaterThanEquals withRightExpression(Expression arg0) { + return (GreaterThanEquals) super.withRightExpression(arg0); + } + + @Override + public GreaterThanEquals withOldOracleJoinSyntax(int arg0) { + return (GreaterThanEquals) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public GreaterThanEquals withOraclePriorPosition(int arg0) { + return (GreaterThanEquals) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/InExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/InExpression.java index b8cfeb5d20..be65acc677 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/InExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/InExpression.java @@ -36,7 +36,8 @@ public InExpression(Expression leftExpression, ItemsList itemsList) { public void setOldOracleJoinSyntax(int oldOracleJoinSyntax) { this.oldOracleJoinSyntax = oldOracleJoinSyntax; if (oldOracleJoinSyntax < 0 || oldOracleJoinSyntax > 1) { - throw new IllegalArgumentException("unexpected join type for oracle found with IN (type=" + oldOracleJoinSyntax + ")"); + throw new IllegalArgumentException( + "unexpected join type for oracle found with IN (type=" + oldOracleJoinSyntax + ")"); } } @@ -53,10 +54,20 @@ public Expression getLeftExpression() { return leftExpression; } + public InExpression withRightItemsList(ItemsList list) { + this.setRightItemsList(list); + return this; + } + public final void setRightItemsList(ItemsList list) { rightItemsList = list; } + public InExpression withLeftExpression(Expression expression) { + this.setLeftExpression(expression); + return this; + } + public final void setLeftExpression(Expression expression) { leftExpression = expression; } @@ -115,10 +126,10 @@ public String toString() { statementBuilder.append(multiExpressionList); statementBuilder.append(")"); } else { - if (rightExpression == null ) { + if (rightExpression == null) { statementBuilder.append(rightItemsList); } else { - statementBuilder.append(rightExpression); + statementBuilder.append(rightExpression); } } @@ -144,4 +155,52 @@ public MultiExpressionList getMultiExpressionList() { public void setMultiExpressionList(MultiExpressionList multiExpressionList) { this.multiExpressionList = multiExpressionList; } + + public InExpression withLeftItemsList(ItemsList leftItemsList) { + this.setLeftItemsList(leftItemsList); + return this; + } + + public InExpression withRightExpression(Expression rightExpression) { + this.setRightExpression(rightExpression); + return this; + } + + public InExpression withMultiExpressionList(MultiExpressionList multiExpressionList) { + this.setMultiExpressionList(multiExpressionList); + return this; + } + + @Override + public InExpression withOldOracleJoinSyntax(int oldOracleJoinSyntax) { + this.setOldOracleJoinSyntax(oldOracleJoinSyntax); + return this; + } + + @Override + public InExpression withOraclePriorPosition(int priorPosition) { + this.setOraclePriorPosition(priorPosition); + return this; + } + + public InExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + public E getRightItemsList(Class type) { + return type.cast(getRightItemsList()); + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } + + public E getLeftItemsList(Class type) { + return type.cast(getLeftItemsList()); + } + + public E getRightExpression(Class type) { + return type.cast(getRightExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsBooleanExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsBooleanExpression.java index 96e10e91cd..68ce5eed4c 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsBooleanExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsBooleanExpression.java @@ -56,4 +56,23 @@ public String toString() { return leftExpression + " IS" + (not ? " NOT" : "") + " FALSE"; } } + + public IsBooleanExpression withIsTrue(boolean isTrue) { + this.setIsTrue(isTrue); + return this; + } + + public IsBooleanExpression withLeftExpression(Expression leftExpression) { + this.setLeftExpression(leftExpression); + return this; + } + + public IsBooleanExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNullExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNullExpression.java index 9a511171d4..eac3f2904a 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNullExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/IsNullExpression.java @@ -56,4 +56,23 @@ public String toString() { return leftExpression + " IS " + (not ? "NOT " : "") + "NULL"; } } + + public IsNullExpression withUseIsNull(boolean useIsNull) { + this.setUseIsNull(useIsNull); + return this; + } + + public IsNullExpression withLeftExpression(Expression leftExpression) { + this.setLeftExpression(leftExpression); + return this; + } + + public IsNullExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + public E getLeftExpression(Class type) { + return type.cast(getLeftExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/JsonOperator.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/JsonOperator.java index e10c71ea19..5525b1e054 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/JsonOperator.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/JsonOperator.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class JsonOperator extends BinaryExpression { @@ -29,4 +30,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return op; } + + @Override + public JsonOperator withLeftExpression(Expression arg0) { + return (JsonOperator) super.withLeftExpression(arg0); + } + + @Override + public JsonOperator withRightExpression(Expression arg0) { + return (JsonOperator) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java index 95513513fe..a920922931 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/LikeExpression.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class LikeExpression extends BinaryExpression { @@ -61,4 +62,29 @@ public boolean isCaseInsensitive() { public void setCaseInsensitive(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; } + + public LikeExpression withEscape(String escape) { + this.setEscape(escape); + return this; + } + + public LikeExpression withCaseInsensitive(boolean caseInsensitive) { + this.setCaseInsensitive(caseInsensitive); + return this; + } + + public LikeExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + @Override + public LikeExpression withLeftExpression(Expression arg0) { + return (LikeExpression) super.withLeftExpression(arg0); + } + + @Override + public LikeExpression withRightExpression(Expression arg0) { + return (LikeExpression) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/Matches.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/Matches.java index 4b3d305a2a..4c2e1cb4b8 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/Matches.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/Matches.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class Matches extends OldOracleJoinBinaryExpression { @@ -22,4 +23,24 @@ public void accept(ExpressionVisitor expressionVisitor) { public String getStringExpression() { return "@@"; } + + @Override + public Matches withLeftExpression(Expression arg0) { + return (Matches) super.withLeftExpression(arg0); + } + + @Override + public Matches withRightExpression(Expression arg0) { + return (Matches) super.withRightExpression(arg0); + } + + @Override + public Matches withOldOracleJoinSyntax(int oldOracleJoinSyntax) { + return (Matches) super.withOldOracleJoinSyntax(oldOracleJoinSyntax); + } + + @Override + public Matches withOraclePriorPosition(int oraclePriorPosition) { + return (Matches) super.withOraclePriorPosition(oraclePriorPosition); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThan.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThan.java index 182170f147..717e594933 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThan.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThan.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class MinorThan extends ComparisonOperator { @@ -21,4 +22,24 @@ public MinorThan() { public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public MinorThan withLeftExpression(Expression arg0) { + return (MinorThan) super.withLeftExpression(arg0); + } + + @Override + public MinorThan withRightExpression(Expression arg0) { + return (MinorThan) super.withRightExpression(arg0); + } + + @Override + public MinorThan withOldOracleJoinSyntax(int arg0) { + return (MinorThan) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public MinorThan withOraclePriorPosition(int arg0) { + return (MinorThan) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThanEquals.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThanEquals.java index 641fe23849..2bdc5eef1f 100755 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThanEquals.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MinorThanEquals.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class MinorThanEquals extends ComparisonOperator { @@ -25,4 +26,24 @@ public MinorThanEquals(String operator) { public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public MinorThanEquals withLeftExpression(Expression arg0) { + return (MinorThanEquals) super.withLeftExpression(arg0); + } + + @Override + public MinorThanEquals withRightExpression(Expression arg0) { + return (MinorThanEquals) super.withRightExpression(arg0); + } + + @Override + public MinorThanEquals withOldOracleJoinSyntax(int arg0) { + return (MinorThanEquals) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public MinorThanEquals withOraclePriorPosition(int arg0) { + return (MinorThanEquals) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MultiExpressionList.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MultiExpressionList.java index 782fb3436d..2466a29810 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/MultiExpressionList.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/MultiExpressionList.java @@ -11,8 +11,11 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import net.sf.jsqlparser.expression.Expression; /** @@ -21,10 +24,10 @@ */ public class MultiExpressionList implements ItemsList { - private List exprList; + private List expressionLists; public MultiExpressionList() { - this.exprList = new ArrayList(); + this.expressionLists = new ArrayList<>(); } @Override @@ -32,35 +35,52 @@ public void accept(ItemsListVisitor itemsListVisitor) { itemsListVisitor.visit(this); } + @Deprecated public List getExprList() { - return exprList; + return getExpressionLists(); + } + + public List getExpressionLists() { + return expressionLists; + } + + public void setExpressionLists(List expressionLists) { + this.expressionLists = expressionLists; + } + + public MultiExpressionList withExpressionLists(List expressionLists) { + this.setExpressionLists(expressionLists); + return this; } public void addExpressionList(ExpressionList el) { - if (!exprList.isEmpty() - && exprList.get(0).getExpressions().size() != el.getExpressions().size()) { + if (!expressionLists.isEmpty() + && expressionLists.get(0).getExpressions().size() != el.getExpressions().size()) { throw new IllegalArgumentException("different count of parameters"); } - exprList.add(el); + expressionLists.add(el); } public void addExpressionList(List list) { addExpressionList(new ExpressionList(list)); } - public void addExpressionList(Expression expr) { + public void addExpressionList(Expression... expr) { addExpressionList(new ExpressionList(Arrays.asList(expr))); } + public MultiExpressionList addExpressionLists(ExpressionList... expr) { + Stream.of(expr).forEach(this::addExpressionList); + return this; + } + + public MultiExpressionList addExpressionLists(Collection expr) { + expr.stream().forEach(this::addExpressionList); + return this; + } + @Override public String toString() { - StringBuilder b = new StringBuilder(); - for (Iterator it = exprList.iterator(); it.hasNext();) { - b.append(it.next().toString()); - if (it.hasNext()) { - b.append(", "); - } - } - return b.toString(); + return expressionLists.stream().map(ExpressionList::toString).collect(Collectors.joining(", ")); } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/NamedExpressionList.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/NamedExpressionList.java index 3de97cc23e..8ee675640f 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/NamedExpressionList.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/NamedExpressionList.java @@ -9,8 +9,12 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; /** @@ -73,4 +77,38 @@ public String toString() { return ret.toString(); } + + public NamedExpressionList withExpressions(List expressions) { + this.setExpressions(expressions); + return this; + } + + public NamedExpressionList withNames(List names) { + this.setNames(names); + return this; + } + + public NamedExpressionList addExpressions(Expression... expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, expressions); + return this.withExpressions(collection); + } + + public NamedExpressionList addExpressions(Collection expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + collection.addAll(expressions); + return this.withExpressions(collection); + } + + public NamedExpressionList addNames(String... names) { + List collection = Optional.ofNullable(getNames()).orElseGet(ArrayList::new); + Collections.addAll(collection, names); + return this.withNames(collection); + } + + public NamedExpressionList addNames(Collection names) { + List collection = Optional.ofNullable(getNames()).orElseGet(ArrayList::new); + collection.addAll(names); + return this.withNames(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/NotEqualsTo.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/NotEqualsTo.java index 14749fd8a3..397a4fb848 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/NotEqualsTo.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/NotEqualsTo.java @@ -9,6 +9,7 @@ */ package net.sf.jsqlparser.expression.operators.relational; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class NotEqualsTo extends ComparisonOperator { @@ -21,8 +22,34 @@ public NotEqualsTo(String operator) { super(operator); } + public NotEqualsTo(Expression left, Expression right) { + this(); + setLeftExpression(left); + setRightExpression(right); + } + + @Override + public NotEqualsTo withLeftExpression(Expression expression) { + return (NotEqualsTo) super.withLeftExpression(expression); + } + + @Override + public NotEqualsTo withRightExpression(Expression expression) { + return (NotEqualsTo) super.withRightExpression(expression); + } + @Override public void accept(ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } + + @Override + public NotEqualsTo withOldOracleJoinSyntax(int arg0) { + return (NotEqualsTo) super.withOldOracleJoinSyntax(arg0); + } + + @Override + public NotEqualsTo withOraclePriorPosition(int arg0) { + return (NotEqualsTo) super.withOraclePriorPosition(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/OldOracleJoinBinaryExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/OldOracleJoinBinaryExpression.java index 114673d1c1..e607ee36c4 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/OldOracleJoinBinaryExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/OldOracleJoinBinaryExpression.java @@ -10,7 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; -import static net.sf.jsqlparser.expression.operators.relational.SupportsOldOracleJoinSyntax.ORACLE_PRIOR_START; +import net.sf.jsqlparser.expression.Expression; public abstract class OldOracleJoinBinaryExpression extends BinaryExpression implements SupportsOldOracleJoinSyntax { @@ -52,4 +52,24 @@ public int getOraclePriorPosition() { public void setOraclePriorPosition(int oraclePriorPosition) { this.oraclePriorPosition = oraclePriorPosition; } + + public OldOracleJoinBinaryExpression withOldOracleJoinSyntax(int oldOracleJoinSyntax) { + this.setOldOracleJoinSyntax(oldOracleJoinSyntax); + return this; + } + + public OldOracleJoinBinaryExpression withOraclePriorPosition(int oraclePriorPosition) { + this.setOraclePriorPosition(oraclePriorPosition); + return this; + } + + @Override + public OldOracleJoinBinaryExpression withLeftExpression(Expression arg0) { + return (OldOracleJoinBinaryExpression) super.withLeftExpression(arg0); + } + + @Override + public OldOracleJoinBinaryExpression withRightExpression(Expression arg0) { + return (OldOracleJoinBinaryExpression) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMatchOperator.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMatchOperator.java index ce1b4295a4..0a1d011179 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMatchOperator.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMatchOperator.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class RegExpMatchOperator extends BinaryExpression { @@ -48,4 +49,14 @@ public String getStringExpression() { } return null; } + + @Override + public RegExpMatchOperator withLeftExpression(Expression arg0) { + return (RegExpMatchOperator) super.withLeftExpression(arg0); + } + + @Override + public RegExpMatchOperator withRightExpression(Expression arg0) { + return (RegExpMatchOperator) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMySQLOperator.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMySQLOperator.java index 6f4761efe3..d729c61a5d 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMySQLOperator.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/RegExpMySQLOperator.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class RegExpMySQLOperator extends BinaryExpression { @@ -47,4 +48,14 @@ public String getStringExpression() { return (useRLike ? "RLIKE" : "REGEXP") + (operatorType == RegExpMatchOperatorType.MATCH_CASESENSITIVE ? " BINARY" : ""); } + + @Override + public RegExpMySQLOperator withLeftExpression(Expression arg0) { + return (RegExpMySQLOperator) super.withLeftExpression(arg0); + } + + @Override + public RegExpMySQLOperator withRightExpression(Expression arg0) { + return (RegExpMySQLOperator) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/SimilarToExpression.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/SimilarToExpression.java index 234d001135..ae460e42bb 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/SimilarToExpression.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/SimilarToExpression.java @@ -10,6 +10,7 @@ package net.sf.jsqlparser.expression.operators.relational; import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; public class SimilarToExpression extends BinaryExpression { @@ -52,4 +53,24 @@ public String getEscape() { public void setEscape(String escape) { this.escape = escape; } + + public SimilarToExpression withEscape(String escape) { + this.setEscape(escape); + return this; + } + + public SimilarToExpression withNot(boolean not) { + this.setNot(not); + return this; + } + + @Override + public SimilarToExpression withLeftExpression(Expression arg0) { + return (SimilarToExpression) super.withLeftExpression(arg0); + } + + @Override + public SimilarToExpression withRightExpression(Expression arg0) { + return (SimilarToExpression) super.withRightExpression(arg0); + } } diff --git a/src/main/java/net/sf/jsqlparser/expression/operators/relational/SupportsOldOracleJoinSyntax.java b/src/main/java/net/sf/jsqlparser/expression/operators/relational/SupportsOldOracleJoinSyntax.java index 05e9839c88..9b8777dcc4 100644 --- a/src/main/java/net/sf/jsqlparser/expression/operators/relational/SupportsOldOracleJoinSyntax.java +++ b/src/main/java/net/sf/jsqlparser/expression/operators/relational/SupportsOldOracleJoinSyntax.java @@ -22,7 +22,11 @@ public interface SupportsOldOracleJoinSyntax { void setOldOracleJoinSyntax(int oldOracleJoinSyntax); + SupportsOldOracleJoinSyntax withOldOracleJoinSyntax(int oldOracleJoinSyntax); + int getOraclePriorPosition(); void setOraclePriorPosition(int priorPosition); + + SupportsOldOracleJoinSyntax withOraclePriorPosition(int priorPosition); } diff --git a/src/main/java/net/sf/jsqlparser/schema/Column.java b/src/main/java/net/sf/jsqlparser/schema/Column.java index 3c2cec0b81..469e9aa8b5 100644 --- a/src/main/java/net/sf/jsqlparser/schema/Column.java +++ b/src/main/java/net/sf/jsqlparser/schema/Column.java @@ -10,7 +10,8 @@ package net.sf.jsqlparser.schema; import java.util.List; -import net.sf.jsqlparser.expression.*; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExpressionVisitor; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; /** @@ -30,8 +31,7 @@ public Column(Table table, String columnName) { } public Column(List nameParts) { - this(nameParts.size() > 1 - ? new Table(nameParts.subList(0, nameParts.size() - 1)) : null, + this(nameParts.size() > 1 ? new Table(nameParts.subList(0, nameParts.size() - 1)) : null, nameParts.get(nameParts.size() - 1)); } @@ -40,27 +40,27 @@ public Column(String columnName) { } /** - * Retrieve the information regarding the {@code Table} this {@code Column} does - * belong to, if any can be inferred. - *

- * The inference is based only on local information, and not on the whole SQL command. - * For example, consider the following query: - *

-     *  SELECT x FROM Foo
-     * 
- * Given the {@code Column} called {@code x}, this method would return {@code null}, - * and not the info about the table {@code Foo}. - * On the other hand, consider: - *
-     *  SELECT t.x FROM Foo t
-     * 
- * Here, we will get a {@code Table} object for a table called {@code t}. - * But because the inference is local, such object will not know that {@code t} is - * just an alias for {@code Foo}. - * - * @return an instance of {@link net.sf.jsqlparser.schema.Table} representing the - * table this column does belong to, if it can be inferred. Can be {@code null}. - */ + * Retrieve the information regarding the {@code Table} this {@code Column} does + * belong to, if any can be inferred. + *

+- * The inference is based only on local information, and not on the whole SQL command. +- * For example, consider the following query: +- *

+-     *  SELECT x FROM Foo
+-     * 
+- * Given the {@code Column} called {@code x}, this method would return {@code null}, +- * and not the info about the table {@code Foo}. +- * On the other hand, consider: +- *
+-     *  SELECT t.x FROM Foo t
+-     * 
+- * Here, we will get a {@code Table} object for a table called {@code t}. +- * But because the inference is local, such object will not know that {@code t} is +- * just an alias for {@code Foo}. + * +- * @return an instance of {@link net.sf.jsqlparser.schema.Table} representing the +- * table this column does belong to, if it can be inferred. Can be {@code null}. + */ public Table getTable() { return table; } @@ -110,4 +110,14 @@ public void accept(ExpressionVisitor expressionVisitor) { public String toString() { return getName(true); } + + public Column withTable(Table table) { + this.setTable(table); + return this; + } + + public Column withColumnName(String columnName) { + this.setColumnName(columnName); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/schema/Database.java b/src/main/java/net/sf/jsqlparser/schema/Database.java index 9ec4b53948..00f65f8e89 100644 --- a/src/main/java/net/sf/jsqlparser/schema/Database.java +++ b/src/main/java/net/sf/jsqlparser/schema/Database.java @@ -61,4 +61,14 @@ public String getFullyQualifiedName() { public String toString() { return getFullyQualifiedName(); } + + public Database withServer(Server server) { + this.setServer(server); + return this; + } + + public Database withDatabaseName(String databaseName) { + this.setDatabaseName(databaseName); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/schema/Sequence.java b/src/main/java/net/sf/jsqlparser/schema/Sequence.java index 343174a542..6572c68df9 100644 --- a/src/main/java/net/sf/jsqlparser/schema/Sequence.java +++ b/src/main/java/net/sf/jsqlparser/schema/Sequence.java @@ -9,11 +9,12 @@ */ package net.sf.jsqlparser.schema; -import net.sf.jsqlparser.parser.ASTNodeAccessImpl; - import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Optional; +import net.sf.jsqlparser.parser.ASTNodeAccessImpl; /** * Represents the database type for a {@code SEQUENCE} @@ -55,6 +56,11 @@ public void setDatabase(Database database) { } } + public Sequence withDatabase(Database database) { + setDatabase(database); + return this; + } + public String getSchemaName() { return getIndex(SCHEMA_IDX); } @@ -63,6 +69,11 @@ public void setSchemaName(String string) { setIndex(SCHEMA_IDX, string); } + public Sequence withSchemaName(String string) { + setSchemaName(string); + return this; + } + public String getName() { return getIndex(NAME_IDX); } @@ -71,6 +82,11 @@ public void setName(String string) { setIndex(NAME_IDX, string); } + public Sequence withName(String string) { + setName(string); + return this; + } + private void setIndex(int idx, String value) { int size = partItems.size(); for (int i = 0; i < idx - size + 1; i++) { @@ -116,6 +132,23 @@ public String toString() { return sql.toString(); } + public Sequence withParameters(List parameters) { + this.setParameters(parameters); + return this; + } + + public Sequence addParameters(Parameter... parameters) { + List collection = Optional.ofNullable(getParameters()).orElseGet(ArrayList::new); + Collections.addAll(collection, parameters); + return this.withParameters(collection); + } + + public Sequence addParameters(Collection parameters) { + List collection = Optional.ofNullable(getParameters()).orElseGet(ArrayList::new); + collection.addAll(parameters); + return this.withParameters(collection); + } + /** * The available parameters to a sequence */ @@ -160,21 +193,26 @@ public void setValue(Long value) { public String formatParameter() { switch (option) { case INCREMENT_BY: - return withValue("INCREMENT BY"); + return prefix("INCREMENT BY"); case START_WITH: - return withValue("START WITH"); + return prefix("START WITH"); case MAXVALUE: case MINVALUE: case CACHE: - return withValue(option.name()); + return prefix(option.name()); default: // fallthrough just return option name return option.name(); } } - private String withValue(String prefix) { + private String prefix(String prefix) { return prefix + " " + value; } + + public Parameter withValue(Long value) { + this.setValue(value); + return this; + } } } diff --git a/src/main/java/net/sf/jsqlparser/schema/Server.java b/src/main/java/net/sf/jsqlparser/schema/Server.java index ea983b601b..3dca6cd2c9 100644 --- a/src/main/java/net/sf/jsqlparser/schema/Server.java +++ b/src/main/java/net/sf/jsqlparser/schema/Server.java @@ -17,7 +17,9 @@ public final class Server implements MultiPartName { compile("\\[([^\\]]+?)(?:\\\\([^\\]]+))?\\]"); private String serverName; + private String instanceName; + private String simpleName; public Server(String serverAndInstanceName) { @@ -71,4 +73,14 @@ public String getFullyQualifiedName() { public String toString() { return getFullyQualifiedName(); } + + public Server withServerName(String serverName) { + this.setServerName(serverName); + return this; + } + + public Server withInstanceName(String instanceName) { + this.setInstanceName(instanceName); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/schema/Table.java b/src/main/java/net/sf/jsqlparser/schema/Table.java index 97fde8b19c..515cd9f87b 100644 --- a/src/main/java/net/sf/jsqlparser/schema/Table.java +++ b/src/main/java/net/sf/jsqlparser/schema/Table.java @@ -12,29 +12,42 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import net.sf.jsqlparser.expression.*; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.MySQLIndexHint; +import net.sf.jsqlparser.expression.SQLServerHints; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; -import net.sf.jsqlparser.statement.select.*; +import net.sf.jsqlparser.statement.select.FromItem; +import net.sf.jsqlparser.statement.select.FromItemVisitor; +import net.sf.jsqlparser.statement.select.IntoTableVisitor; +import net.sf.jsqlparser.statement.select.Pivot; +import net.sf.jsqlparser.statement.select.UnPivot; /** * A table. It can have an alias and the schema name it belongs to. */ public class Table extends ASTNodeAccessImpl implements FromItem, MultiPartName { -// private Database database; -// private String schemaName; -// private String name; + // private Database database; + // private String schemaName; + // private String name; private static final int NAME_IDX = 0; + private static final int SCHEMA_IDX = 1; + private static final int DATABASE_IDX = 2; + private static final int SERVER_IDX = 3; private List partItems = new ArrayList<>(); private Alias alias; + private Pivot pivot; + private UnPivot unpivot; + private MySQLIndexHint mysqlHints; + private SQLServerHints sqlServerHints; public Table() { @@ -64,6 +77,11 @@ public Database getDatabase() { return new Database(getIndex(DATABASE_IDX)); } + public Table withDatabase(Database database) { + setDatabase(database); + return this; + } + public void setDatabase(Database database) { setIndex(DATABASE_IDX, database.getDatabaseName()); if (database.getServer() != null) { @@ -75,16 +93,26 @@ public String getSchemaName() { return getIndex(SCHEMA_IDX); } - public void setSchemaName(String string) { - setIndex(SCHEMA_IDX, string); + public Table withSchemaName(String schemaName) { + setSchemaName(schemaName); + return this; + } + + public void setSchemaName(String schemaName) { + setIndex(SCHEMA_IDX, schemaName); } public String getName() { return getIndex(NAME_IDX); } - public void setName(String string) { - setIndex(NAME_IDX, string); + public Table withName(String name) { + this.setName(name); + return this; + } + + public void setName(String name) { + setIndex(NAME_IDX, name); } @Override @@ -169,6 +197,11 @@ public MySQLIndexHint getIndexHint() { return mysqlHints; } + public Table withHint(MySQLIndexHint hint) { + setHint(hint); + return this; + } + public void setHint(MySQLIndexHint hint) { this.mysqlHints = hint; } @@ -183,11 +216,29 @@ public void setSqlServerHints(SQLServerHints sqlServerHints) { @Override public String toString() { - return getFullyQualifiedName() - + ((alias != null) ? alias.toString() : "") - + ((pivot != null) ? " " + pivot : "") - + ((unpivot != null) ? " " + unpivot : "") + return getFullyQualifiedName() + ((alias != null) ? alias.toString() : "") + + ((pivot != null) ? " " + pivot : "") + ((unpivot != null) ? " " + unpivot : "") + ((mysqlHints != null) ? mysqlHints.toString() : "") + ((sqlServerHints != null) ? sqlServerHints.toString() : ""); } + + @Override + public Table withUnPivot(UnPivot unpivot) { + return (Table) FromItem.super.withUnPivot(unpivot); + } + + @Override + public Table withAlias(Alias alias) { + return (Table) FromItem.super.withAlias(alias); + } + + @Override + public Table withPivot(Pivot pivot) { + return (Table) FromItem.super.withPivot(pivot); + } + + public Table withSqlServerHints(SQLServerHints sqlServerHints) { + this.setSqlServerHints(sqlServerHints); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/Block.java b/src/main/java/net/sf/jsqlparser/statement/Block.java index 8d41cc7455..6ee6055183 100644 --- a/src/main/java/net/sf/jsqlparser/statement/Block.java +++ b/src/main/java/net/sf/jsqlparser/statement/Block.java @@ -30,4 +30,9 @@ public void accept(StatementVisitor statementVisitor) { public String toString() { return "BEGIN\n" + (statements != null ? statements.toString() : "") + "END"; } + + public Block withStatements(Statements statements) { + this.setStatements(statements); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/CreateFunctionalStatement.java b/src/main/java/net/sf/jsqlparser/statement/CreateFunctionalStatement.java index 2e8eadd4ae..cc3b960247 100644 --- a/src/main/java/net/sf/jsqlparser/statement/CreateFunctionalStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/CreateFunctionalStatement.java @@ -1,75 +1,103 @@ -/*- - * #%L - * JSQLParser library - * %% - * Copyright (C) 2004 - 2020 JSQLParser - * %% - * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 - * #L% - */ -package net.sf.jsqlparser.statement; - -import java.util.List; - -/** - * A base for the declaration of function like statements - */ -public abstract class CreateFunctionalStatement implements Statement { - - private String kind; - private List functionDeclarationParts; - - protected CreateFunctionalStatement(String kind, List functionDeclarationParts) { - this.kind = kind; - this.functionDeclarationParts = functionDeclarationParts; - } - - /** - * @return the declaration parts after {@code CREATE FUNCTION|PROCEDURE} - */ - public List getFunctionDeclarationParts() { - return functionDeclarationParts; - } - - /** - * @return the kind of functional statement - */ - public String getKind() { - return kind; - } - - /** - * @return a whitespace appended String with the declaration parts with some minimal formatting. - */ - public String formatDeclaration() { - StringBuilder declaration = new StringBuilder(); - - int currIndex = 0; - while (currIndex < functionDeclarationParts.size()) { - String token = functionDeclarationParts.get(currIndex); - declaration.append(token); - - // if the next token is a ; don't put a space - if (currIndex + 1 < functionDeclarationParts.size()) { - // peek ahead just to format nicely - String nextToken = functionDeclarationParts.get(currIndex+1); - if (!nextToken.equals(";")) { - declaration.append(" "); - } - } - currIndex++; - } - - return declaration.toString(); - } - - @Override - public void accept(StatementVisitor statementVisitor) { - statementVisitor.visit(this); - } - - @Override - public String toString() { - return "CREATE " + kind + " " + formatDeclaration(); - } -} +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * A base for the declaration of function like statements + */ +public abstract class CreateFunctionalStatement implements Statement { + + private String kind; + + private List functionDeclarationParts; + + protected CreateFunctionalStatement(String kind) { + this.kind = kind; + } + + protected CreateFunctionalStatement(String kind, List functionDeclarationParts) { + this.kind = kind; + this.functionDeclarationParts = functionDeclarationParts; + } + + public void setFunctionDeclarationParts(List functionDeclarationParts) { + this.functionDeclarationParts = functionDeclarationParts; + } + + /** + * @return the declaration parts after {@code CREATE FUNCTION|PROCEDURE} + */ + public List getFunctionDeclarationParts() { + return functionDeclarationParts; + } + + /** + * @return the kind of functional statement + */ + public String getKind() { + return kind; + } + + /** + * @return a whitespace appended String with the declaration parts with some + * minimal formatting. + */ + public String formatDeclaration() { + StringBuilder declaration = new StringBuilder(); + int currIndex = 0; + while (currIndex < functionDeclarationParts.size()) { + String token = functionDeclarationParts.get(currIndex); + declaration.append(token); + // if the next token is a ; don't put a space + if (currIndex + 1 < functionDeclarationParts.size()) { + // peek ahead just to format nicely + String nextToken = functionDeclarationParts.get(currIndex + 1); + if (!nextToken.equals(";")) { + declaration.append(" "); + } + } + currIndex++; + } + return declaration.toString(); + } + + @Override + public void accept(StatementVisitor statementVisitor) { + statementVisitor.visit(this); + } + + @Override + public String toString() { + return "CREATE " + kind + " " + formatDeclaration(); + } + + public CreateFunctionalStatement withFunctionDeclarationParts(List functionDeclarationParts) { + this.setFunctionDeclarationParts(functionDeclarationParts); + return this; + } + + public CreateFunctionalStatement addFunctionDeclarationParts(String... functionDeclarationParts) { + List collection = Optional.ofNullable(getFunctionDeclarationParts()).orElseGet(ArrayList::new); + Collections.addAll(collection, functionDeclarationParts); + return this.withFunctionDeclarationParts(collection); + } + + public CreateFunctionalStatement addFunctionDeclarationParts(Collection functionDeclarationParts) { + List collection = Optional.ofNullable(getFunctionDeclarationParts()).orElseGet(ArrayList::new); + collection.addAll(functionDeclarationParts); + return this.withFunctionDeclarationParts(collection); + } +} diff --git a/src/main/java/net/sf/jsqlparser/statement/DeclareStatement.java b/src/main/java/net/sf/jsqlparser/statement/DeclareStatement.java index da84c419a1..4d3f51bf01 100644 --- a/src/main/java/net/sf/jsqlparser/statement/DeclareStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/DeclareStatement.java @@ -10,7 +10,10 @@ package net.sf.jsqlparser.statement; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.UserVariable; import net.sf.jsqlparser.statement.create.table.ColDataType; @@ -19,10 +22,10 @@ public final class DeclareStatement implements Statement { private UserVariable userVariable = null; - private DeclareType type = DeclareType.TYPE; + private DeclareType declareType = DeclareType.TYPE; private String typeName; private List typeDefExprList = new ArrayList<>(); - private List colDefs = new ArrayList<>(); + private List columnDefinitions = new ArrayList<>(); public DeclareStatement() { } @@ -35,32 +38,73 @@ public UserVariable getUserVariable() { return userVariable; } + /** + * @return the {@link DeclareType} + * @deprecated use {@link #getDeclareType()} + */ + @Deprecated public DeclareType getType() { - return type; + return getDeclareType(); + } + + /** + * @return the {@link DeclareType} + */ + public DeclareType getDeclareType() { + return declareType; } public String getTypeName() { return typeName; } - public void setDeclareType(DeclareType type) { - this.type = type; + public void setDeclareType(DeclareType declareType) { + this.declareType = declareType; } public void addType(ColDataType colDataType, Expression defaultExpr) { - typeDefExprList.add(new TypeDefExpr(colDataType, defaultExpr)); + addTypeDefExprList(new TypeDefExpr(colDataType, defaultExpr)); } public void addType(UserVariable userVariable, ColDataType colDataType, Expression defaultExpr) { - typeDefExprList.add(new TypeDefExpr(userVariable, colDataType, defaultExpr)); + addTypeDefExprList(new TypeDefExpr(userVariable, colDataType, defaultExpr)); + } + + public DeclareStatement addTypeDefExprList(TypeDefExpr... typeDefExpressions) { + List collection = Optional.ofNullable(getTypeDefExprList()).orElseGet(ArrayList::new); + Collections.addAll(collection, typeDefExpressions); + return this.withTypeDefExprList(collection); + } + + public DeclareStatement addTypeDefExprList(Collection typeDefExpressions) { + List collection = Optional.ofNullable(getTypeDefExprList()).orElseGet(ArrayList::new); + collection.addAll(typeDefExpressions); + return this.withTypeDefExprList(collection); + } + + public DeclareStatement withTypeDefExprList(List typeDefExpressions) { + setTypeDefExprList(typeDefExpressions); + return this; + } + + public void setTypeDefExprList(List expr) { + this.typeDefExprList = expr; + } + + public List getTypeDefExprList() { + return this.typeDefExprList ; } public void addColumnDefinition(ColumnDefinition colDef) { - colDefs.add(colDef); + columnDefinitions.add(colDef); + } + + public void setColumnDefinitions(List columnDefinitions) { + this.columnDefinitions = columnDefinitions; } public List getColumnDefinitions() { - return colDefs; + return columnDefinitions; } public List getTypeDefinitions() { @@ -74,18 +118,18 @@ public void setTypeName(String typeName) { @Override public String toString() { StringBuilder b = new StringBuilder("DECLARE "); - if (type == DeclareType.AS) { + if (declareType == DeclareType.AS) { b.append(userVariable.toString()); b.append(" AS ").append(typeName); } else { - if (type == DeclareType.TABLE) { + if (declareType == DeclareType.TABLE) { b.append(userVariable.toString()); b.append(" TABLE ("); - for (int i = 0; i < colDefs.size(); i++) { + for (int i = 0; i < columnDefinitions.size(); i++) { if (i > 0) { b.append(", "); } - b.append(colDefs.get(i).toString()); + b.append(columnDefinitions.get(i).toString()); } b.append(")"); } else { @@ -108,11 +152,43 @@ public String toString() { } @Override - public void accept(StatementVisitor statementVisitor - ) { + public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + public DeclareStatement withUserVariable(UserVariable userVariable) { + this.setUserVariable(userVariable); + return this; + } + + public DeclareStatement withTypeName(String typeName) { + this.setTypeName(typeName); + return this; + } + + public DeclareStatement withDeclareType(DeclareType declareType) { + this.setDeclareType(declareType); + return this; + } + + public DeclareStatement withColumnDefinitions(List columnDefinitions) { + this.setColumnDefinitions(columnDefinitions); + return this; + } + + public DeclareStatement addColumnDefinitions(ColumnDefinition... statements) { + List collection = Optional.ofNullable(getColumnDefinitions()).orElseGet(ArrayList::new); + Collections.addAll(collection, statements); + return this.withColumnDefinitions(collection); + } + + + public DeclareStatement addColumnDefinitions(Collection columnDefinitions) { + List collection = Optional.ofNullable(getColumnDefinitions()).orElseGet(ArrayList::new); + collection.addAll(columnDefinitions); + return this.withColumnDefinitions(collection); + } + public static class TypeDefExpr { public final UserVariable userVariable; diff --git a/src/main/java/net/sf/jsqlparser/statement/DescribeStatement.java b/src/main/java/net/sf/jsqlparser/statement/DescribeStatement.java index 26bf26dcd2..09d84c2e74 100644 --- a/src/main/java/net/sf/jsqlparser/statement/DescribeStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/DescribeStatement.java @@ -15,6 +15,10 @@ public class DescribeStatement implements Statement { private Table table; + public DescribeStatement() { + // empty constructor + } + public DescribeStatement(Table table) { this.table = table; } @@ -36,4 +40,9 @@ public String toString() { public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + + public DescribeStatement withTable(Table table) { + this.setTable(table); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/ExplainStatement.java b/src/main/java/net/sf/jsqlparser/statement/ExplainStatement.java index 91b74a9e82..6ede0e03cd 100644 --- a/src/main/java/net/sf/jsqlparser/statement/ExplainStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/ExplainStatement.java @@ -22,6 +22,10 @@ public class ExplainStatement implements Statement { private Select select; private LinkedHashMap options; + public ExplainStatement() { + // empty constructor + } + public ExplainStatement(Select select) { this.select = select; } @@ -53,7 +57,7 @@ public void addOption(Option option) { */ public Option getOption(OptionType optionType) { if (options == null) { - return null; + return null; } return options.get(optionType); } @@ -108,5 +112,10 @@ public void setValue(String value) { public String formatOption() { return type.name() + (value != null ? (" " + value) : ""); } + + public Option withValue(String value) { + this.setValue(value); + return this; + } } } diff --git a/src/main/java/net/sf/jsqlparser/statement/ReferentialAction.java b/src/main/java/net/sf/jsqlparser/statement/ReferentialAction.java index a712de0994..f707e910b4 100644 --- a/src/main/java/net/sf/jsqlparser/statement/ReferentialAction.java +++ b/src/main/java/net/sf/jsqlparser/statement/ReferentialAction.java @@ -31,6 +31,11 @@ public void setType(Type type) { this.type = type; } + public ReferentialAction withType(Type type) { + setType(type); + return this; + } + public Action getAction() { return action; } @@ -39,6 +44,11 @@ public void setAction(Action action) { this.action = action; } + public ReferentialAction withAction(Action action) { + setAction(action); + return this; + } + @Override public int hashCode() { final int prime = 31; @@ -91,7 +101,7 @@ private Action(String action) { this.action = action; } - private String action; + private final String action; /** * @param action diff --git a/src/main/java/net/sf/jsqlparser/statement/SetStatement.java b/src/main/java/net/sf/jsqlparser/statement/SetStatement.java index 8350f007a2..5110defabe 100644 --- a/src/main/java/net/sf/jsqlparser/statement/SetStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/SetStatement.java @@ -17,6 +17,10 @@ public final class SetStatement implements Statement { private final List values = new ArrayList<>(); + public SetStatement() { + // empty constructor + } + public SetStatement(String name, Expression expression) { add(name, expression, true); } @@ -41,11 +45,21 @@ public boolean isUseEqual() { return isUseEqual(0); } + public SetStatement withUseEqual(int idx, boolean useEqual) { + this.setUseEqual(idx, useEqual); + return this; + } + public SetStatement setUseEqual(int idx, boolean useEqual) { values.get(idx).useEqual = useEqual; return this; } + public SetStatement withUseEqual(boolean useEqual) { + this.setUseEqual(useEqual); + return this; + } + public SetStatement setUseEqual(boolean useEqual) { return setUseEqual(0, useEqual); } @@ -105,6 +119,10 @@ public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + public E getExpression(Class type) { + return type.cast(getExpression()); + } + static class NameExpr { private String name; diff --git a/src/main/java/net/sf/jsqlparser/statement/ShowColumnsStatement.java b/src/main/java/net/sf/jsqlparser/statement/ShowColumnsStatement.java index 71f9822ef7..8915d81fd7 100644 --- a/src/main/java/net/sf/jsqlparser/statement/ShowColumnsStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/ShowColumnsStatement.java @@ -13,6 +13,10 @@ public class ShowColumnsStatement implements Statement { private String tableName; + public ShowColumnsStatement() { + // empty constructor + } + public ShowColumnsStatement(String tableName) { this.tableName = tableName; } @@ -34,4 +38,9 @@ public String toString() { public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + + public ShowColumnsStatement withTableName(String tableName) { + this.setTableName(tableName); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/ShowStatement.java b/src/main/java/net/sf/jsqlparser/statement/ShowStatement.java index 9e3bd62a13..f6bc845185 100644 --- a/src/main/java/net/sf/jsqlparser/statement/ShowStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/ShowStatement.java @@ -13,6 +13,10 @@ public class ShowStatement implements Statement { private String name; + public ShowStatement() { + // empty constructor + } + public ShowStatement(String name) { this.name = name; } @@ -34,4 +38,9 @@ public String toString() { public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + + public ShowStatement withName(String name) { + this.setName(name); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/Statement.java b/src/main/java/net/sf/jsqlparser/statement/Statement.java index e90f8746b5..d3f2ddda49 100644 --- a/src/main/java/net/sf/jsqlparser/statement/Statement.java +++ b/src/main/java/net/sf/jsqlparser/statement/Statement.java @@ -9,7 +9,9 @@ */ package net.sf.jsqlparser.statement; -public interface Statement { +import net.sf.jsqlparser.Model; + +public interface Statement extends Model { void accept(StatementVisitor statementVisitor); } diff --git a/src/main/java/net/sf/jsqlparser/statement/Statements.java b/src/main/java/net/sf/jsqlparser/statement/Statements.java index a0f7989c3c..261ae0e840 100644 --- a/src/main/java/net/sf/jsqlparser/statement/Statements.java +++ b/src/main/java/net/sf/jsqlparser/statement/Statements.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; public class Statements { @@ -35,4 +39,21 @@ public String toString() { } return b.toString(); } + + public Statements withStatements(List statements) { + this.setStatements(statements); + return this; + } + + public Statements addStatements(Statement... statements) { + List collection = Optional.ofNullable(getStatements()).orElseGet(ArrayList::new); + Collections.addAll(collection, statements); + return this.withStatements(collection); + } + + public Statements addStatements(Collection statements) { + List collection = Optional.ofNullable(getStatements()).orElseGet(ArrayList::new); + collection.addAll(statements); + return this.withStatements(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/UseStatement.java b/src/main/java/net/sf/jsqlparser/statement/UseStatement.java index 37d5e15057..4022bd2da2 100644 --- a/src/main/java/net/sf/jsqlparser/statement/UseStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/UseStatement.java @@ -13,6 +13,10 @@ public class UseStatement implements Statement { private String name; + public UseStatement() { + // empty constructor + } + public UseStatement(String name) { this.name = name; } @@ -34,4 +38,9 @@ public String toString() { public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } + + public UseStatement withName(String name) { + this.setName(name); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/Alter.java b/src/main/java/net/sf/jsqlparser/statement/alter/Alter.java index f93406a912..e5adc1ea33 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/Alter.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/Alter.java @@ -10,8 +10,11 @@ package net.sf.jsqlparser.statement.alter; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -84,4 +87,30 @@ public String toString() { return b.toString(); } + public Alter withTable(Table table) { + this.setTable(table); + return this; + } + + public Alter withUseOnly(boolean useOnly) { + this.setUseOnly(useOnly); + return this; + } + + public Alter withAlterExpressions(List alterExpressions) { + this.setAlterExpressions(alterExpressions); + return this; + } + + public Alter addAlterExpressions(AlterExpression... alterExpressions) { + List collection = Optional.ofNullable(getAlterExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, alterExpressions); + return this.withAlterExpressions(collection); + } + + public Alter addAlterExpressions(Collection alterExpressions) { + List collection = Optional.ofNullable(getAlterExpressions()).orElseGet(ArrayList::new); + collection.addAll(alterExpressions); + return this.withAlterExpressions(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/AlterExpression.java b/src/main/java/net/sf/jsqlparser/statement/alter/AlterExpression.java index 2845ac11d5..0d0feb4d7c 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/AlterExpression.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/AlterExpression.java @@ -11,8 +11,12 @@ import java.util.ArrayList; import java.util.Arrays; + +import java.util.Collection; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import net.sf.jsqlparser.statement.ReferentialAction; @@ -85,6 +89,11 @@ public void setReferentialAction(Type type, Action action) { setReferentialAction(type, action, true); } + public AlterExpression withReferentialAction(Type type, Action action) { + setReferentialAction(type, action); + return this; + } + /** * @param type */ @@ -223,11 +232,21 @@ public void setColumnName(String columnName) { this.columnName = columnName; } + @Deprecated public String getColOldName() { - return columnOldName; + return getColumnOldName(); } + @Deprecated public void setColOldName(String columnOldName) { + setColumnOldName(columnOldName); + } + + public String getColumnOldName() { + return columnOldName; + } + + public void setColumnOldName(String columnOldName) { this.columnOldName = columnOldName; } @@ -407,10 +426,175 @@ public String toString() { return b.toString(); } - public final static class ColumnDataType extends ColumnDefinition { + public AlterExpression withOperation(AlterOperation operation) { + this.setOperation(operation); + return this; + } + + public AlterExpression withOptionalSpecifier(String optionalSpecifier) { + this.setOptionalSpecifier(optionalSpecifier); + return this; + } + + public AlterExpression withColumnName(String columnName) { + this.setColumnName(columnName); + return this; + } + + public AlterExpression withPkColumns(List pkColumns) { + this.setPkColumns(pkColumns); + return this; + } + + public AlterExpression withUkColumns(List ukColumns) { + this.setUkColumns(ukColumns); + return this; + } + + public AlterExpression withUkName(String ukName) { + this.setUkName(ukName); + return this; + } + + public AlterExpression withIndex(Index index) { + this.setIndex(index); + return this; + } + + public AlterExpression withConstraintName(String constraintName) { + this.setConstraintName(constraintName); + return this; + } + + public AlterExpression constraintIfExists(boolean constraintIfExists) { + this.setConstraintIfExists(constraintIfExists); + return this; + } + + public AlterExpression withOnDeleteRestrict(boolean onDeleteRestrict) { + this.setOnDeleteRestrict(onDeleteRestrict); + return this; + } + + public AlterExpression withOnDeleteSetNull(boolean onDeleteSetNull) { + this.setOnDeleteSetNull(onDeleteSetNull); + return this; + } + + public AlterExpression withOnDeleteCascade(boolean onDeleteCascade) { + this.setOnDeleteCascade(onDeleteCascade); + return this; + } + + public AlterExpression withFkColumns(List fkColumns) { + this.setFkColumns(fkColumns); + return this; + } + + public AlterExpression withFkSourceTable(String fkSourceTable) { + this.setFkSourceTable(fkSourceTable); + return this; + } + + public AlterExpression withFkSourceColumns(List fkSourceColumns) { + this.setFkSourceColumns(fkSourceColumns); + return this; + } + + public AlterExpression withUk(boolean uk) { + this.setUk(uk); + return this; + } + + public AlterExpression withUseEqual(boolean useEqual) { + this.setUseEqual(useEqual); + return this; + } + + public AlterExpression withConstraints(List constraints) { + this.setConstraints(constraints); + return this; + } + + public AlterExpression withCommentText(String commentText) { + this.setCommentText(commentText); + return this; + } + + public AlterExpression withColumnOldName(String columnOldName) { + setColumnOldName(columnOldName); + return this; + } + + public AlterExpression addPkColumns(String... pkColumns) { + List collection = Optional.ofNullable(getPkColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, pkColumns); + return this.withPkColumns(collection); + } + + public AlterExpression addPkColumns(Collection pkColumns) { + List collection = Optional.ofNullable(getPkColumns()).orElseGet(ArrayList::new); + collection.addAll(pkColumns); + return this.withPkColumns(collection); + } + + public AlterExpression addUkColumns(String... ukColumns) { + List collection = Optional.ofNullable(getUkColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, ukColumns); + return this.withUkColumns(collection); + } + + public AlterExpression addUkColumns(Collection ukColumns) { + List collection = Optional.ofNullable(getUkColumns()).orElseGet(ArrayList::new); + collection.addAll(ukColumns); + return this.withUkColumns(collection); + } + + public AlterExpression addFkColumns(String... fkColumns) { + List collection = Optional.ofNullable(getFkColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, fkColumns); + return this.withFkColumns(collection); + } + + public AlterExpression addFkColumns(Collection fkColumns) { + List collection = Optional.ofNullable(getFkColumns()).orElseGet(ArrayList::new); + collection.addAll(fkColumns); + return this.withFkColumns(collection); + } + + public AlterExpression addFkSourceColumns(String... fkSourceColumns) { + List collection = Optional.ofNullable(getFkSourceColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, fkSourceColumns); + return this.withFkSourceColumns(collection); + } + + public AlterExpression addFkSourceColumns(Collection fkSourceColumns) { + List collection = Optional.ofNullable(getFkSourceColumns()).orElseGet(ArrayList::new); + collection.addAll(fkSourceColumns); + return this.withFkSourceColumns(collection); + } + + public AlterExpression addConstraints(ConstraintState... constraints) { + List collection = Optional.ofNullable(getConstraints()).orElseGet(ArrayList::new); + Collections.addAll(collection, constraints); + return this.withConstraints(collection); + } + + public AlterExpression addConstraints(Collection constraints) { + List collection = Optional.ofNullable(getConstraints()).orElseGet(ArrayList::new); + collection.addAll(constraints); + return this.withConstraints(collection); + } + + public static final class ColumnDataType extends ColumnDefinition { private final boolean withType; + public ColumnDataType(boolean withType) { + super(); + this.withType = withType; + } + public ColumnDataType(String columnName, boolean withType, ColDataType colDataType, List columnSpecs) { super(columnName, colDataType, columnSpecs); this.withType = withType; @@ -420,6 +604,32 @@ public ColumnDataType(String columnName, boolean withType, ColDataType colDataTy public String toString() { return getColumnName() + (withType ? " TYPE " : " ") + toStringDataTypeAndSpec(); } + + @Override + public ColumnDataType withColDataType(ColDataType colDataType) { + return (ColumnDataType) super.withColDataType(colDataType); + } + + @Override + public ColumnDataType withColumnName(String columnName) { + return (ColumnDataType) super.withColumnName(columnName); + } + + @Override + public ColumnDataType addColumnSpecs(String... columnSpecs) { + return (ColumnDataType) super.addColumnSpecs(columnSpecs); + } + + @Override + public ColumnDataType addColumnSpecs(Collection columnSpecs) { + return (ColumnDataType) super.addColumnSpecs(columnSpecs); + } + + @Override + public ColumnDataType withColumnSpecs(List columnSpecs) { + return (ColumnDataType) super.withColumnSpecs(columnSpecs); + } + } public final static class ColumnDropNotNull { @@ -427,6 +637,10 @@ public final static class ColumnDropNotNull { private final String columnName; private final boolean withNot; + public ColumnDropNotNull(String columnName) { + this(columnName, false); + } + public ColumnDropNotNull(String columnName, boolean withNot) { this.columnName = columnName; this.withNot = withNot; diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/DeferrableConstraint.java b/src/main/java/net/sf/jsqlparser/statement/alter/DeferrableConstraint.java index 15bba4a115..ee8b7503b9 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/DeferrableConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/DeferrableConstraint.java @@ -13,6 +13,10 @@ public class DeferrableConstraint implements ConstraintState { private boolean not; + public DeferrableConstraint() { + // empty constructor + } + public DeferrableConstraint(boolean not) { this.not = not; } @@ -34,4 +38,9 @@ public String toString() { b.append("DEFERRABLE"); return b.toString(); } + + public DeferrableConstraint withNot(boolean not) { + this.setNot(not); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/EnableConstraint.java b/src/main/java/net/sf/jsqlparser/statement/alter/EnableConstraint.java index 9573a1b6b0..48a319eba2 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/EnableConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/EnableConstraint.java @@ -13,6 +13,10 @@ public class EnableConstraint implements ConstraintState { private boolean disable; + public EnableConstraint() { + // empty constructor + } + public EnableConstraint(boolean disable) { this.disable = disable; } @@ -29,4 +33,9 @@ public void setDisable(boolean disable) { public String toString() { return disable ? "DISABLE" : "ENABLE"; } + + public EnableConstraint withDisable(boolean disable) { + this.setDisable(disable); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/ValidateConstraint.java b/src/main/java/net/sf/jsqlparser/statement/alter/ValidateConstraint.java index 36d000a9c2..93f58bed45 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/ValidateConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/ValidateConstraint.java @@ -13,6 +13,10 @@ public class ValidateConstraint implements ConstraintState { private boolean not; + public ValidateConstraint() { + // empty constructor + } + public ValidateConstraint(boolean not) { this.not = not; } @@ -29,4 +33,9 @@ public void setNot(boolean not) { public String toString() { return not ? "NOVALIDATE" : "VALIDATE"; } + + public ValidateConstraint withNot(boolean not) { + this.setNot(not); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/alter/sequence/AlterSequence.java b/src/main/java/net/sf/jsqlparser/statement/alter/sequence/AlterSequence.java index af9e818ebc..cd994717bd 100644 --- a/src/main/java/net/sf/jsqlparser/statement/alter/sequence/AlterSequence.java +++ b/src/main/java/net/sf/jsqlparser/statement/alter/sequence/AlterSequence.java @@ -39,4 +39,9 @@ public String toString() { sql = "ALTER SEQUENCE " + sequence; return sql; } + + public AlterSequence withSequence(Sequence sequence) { + this.setSequence(sequence); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/comment/Comment.java b/src/main/java/net/sf/jsqlparser/statement/comment/Comment.java index cc2c736df7..23942a8899 100755 --- a/src/main/java/net/sf/jsqlparser/statement/comment/Comment.java +++ b/src/main/java/net/sf/jsqlparser/statement/comment/Comment.java @@ -72,4 +72,19 @@ public String toString() { sql += "IS " + comment; return sql; } + + public Comment withTable(Table table) { + this.setTable(table); + return this; + } + + public Comment withColumn(Column column) { + this.setColumn(column); + return this; + } + + public Comment withComment(StringValue comment) { + this.setComment(comment); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/function/CreateFunction.java b/src/main/java/net/sf/jsqlparser/statement/create/function/CreateFunction.java index 95db9d8056..e05525ad4c 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/function/CreateFunction.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/function/CreateFunction.java @@ -1,24 +1,45 @@ -/*- - * #%L - * JSQLParser library - * %% - * Copyright (C) 2004 - 2020 JSQLParser - * %% - * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 - * #L% - */ -package net.sf.jsqlparser.statement.create.function; - -import net.sf.jsqlparser.statement.CreateFunctionalStatement; - -import java.util.List; - -/** - * A {@code CREATE PROCEDURE} statement - */ -public class CreateFunction extends CreateFunctionalStatement { - - public CreateFunction(List functionDeclarationParts) { - super("FUNCTION", functionDeclarationParts); - } -} +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.create.function; + +import java.util.Collection; +import java.util.List; + +import net.sf.jsqlparser.statement.CreateFunctionalStatement; + +/** + * A {@code CREATE PROCEDURE} statement + */ +public class CreateFunction extends CreateFunctionalStatement { + + public CreateFunction() { + super("FUNCTION"); + } + + public CreateFunction(List functionDeclarationParts) { + super("FUNCTION", functionDeclarationParts); + } + + @Override + public CreateFunction withFunctionDeclarationParts(List functionDeclarationParts) { + return (CreateFunction) super.withFunctionDeclarationParts(functionDeclarationParts); + } + + @Override + public CreateFunction addFunctionDeclarationParts(String... functionDeclarationParts) { + return (CreateFunction) super.addFunctionDeclarationParts(functionDeclarationParts); + } + + @Override + public CreateFunction addFunctionDeclarationParts(Collection functionDeclarationParts) { + return (CreateFunction) super.addFunctionDeclarationParts(functionDeclarationParts); + } + +} diff --git a/src/main/java/net/sf/jsqlparser/statement/create/index/CreateIndex.java b/src/main/java/net/sf/jsqlparser/statement/create/index/CreateIndex.java index b16ad112ed..806eda9a68 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/index/CreateIndex.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/index/CreateIndex.java @@ -76,7 +76,7 @@ public String toString() { buffer.append(" ("); buffer.append( - index.getColumnWithParams().stream() + index.getColumns().stream() .map(cp -> cp.columnName + (cp.getParams() != null ? " " + String.join(" ", cp.getParams()) : "")).collect(joining(", ")) ); @@ -92,4 +92,18 @@ public String toString() { return buffer.toString(); } + public CreateIndex withTable(Table table) { + this.setTable(table); + return this; + } + + public CreateIndex withIndex(Index index) { + this.setIndex(index); + return this; + } + + public CreateIndex withTailParameters(List tailParameters) { + this.setTailParameters(tailParameters); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/procedure/CreateProcedure.java b/src/main/java/net/sf/jsqlparser/statement/create/procedure/CreateProcedure.java index 4b29e1b522..7ce777b6ad 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/procedure/CreateProcedure.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/procedure/CreateProcedure.java @@ -1,25 +1,44 @@ -/*- - * #%L - * JSQLParser library - * %% - * Copyright (C) 2004 - 2020 JSQLParser - * %% - * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 - * #L% - */ -package net.sf.jsqlparser.statement.create.procedure; - -import net.sf.jsqlparser.statement.CreateFunctionalStatement; - -import java.util.List; - -/** - * A {@code CREATE PROCEDURE} statement - */ -public class CreateProcedure extends CreateFunctionalStatement { - - public CreateProcedure(List functionDeclarationParts) { - super("PROCEDURE", functionDeclarationParts); - } - -} +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.create.procedure; + +import java.util.Collection; +import java.util.List; +import net.sf.jsqlparser.statement.CreateFunctionalStatement; + +/** + * A {@code CREATE PROCEDURE} statement + */ +public class CreateProcedure extends CreateFunctionalStatement { + + public CreateProcedure() { + super("PROCEDURE"); + } + + public CreateProcedure(List functionDeclarationParts) { + super("PROCEDURE", functionDeclarationParts); + } + + @Override + public CreateProcedure withFunctionDeclarationParts(List functionDeclarationParts) { + return (CreateProcedure) super.withFunctionDeclarationParts(functionDeclarationParts); + } + + @Override + public CreateProcedure addFunctionDeclarationParts(String... functionDeclarationParts) { + return (CreateProcedure) super.addFunctionDeclarationParts(functionDeclarationParts); + } + + @Override + public CreateProcedure addFunctionDeclarationParts(Collection functionDeclarationParts) { + return (CreateProcedure) super.addFunctionDeclarationParts(functionDeclarationParts); + } + +} diff --git a/src/main/java/net/sf/jsqlparser/statement/create/schema/CreateSchema.java b/src/main/java/net/sf/jsqlparser/statement/create/schema/CreateSchema.java index 3284105f35..7832f291ef 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/schema/CreateSchema.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/schema/CreateSchema.java @@ -10,7 +10,10 @@ package net.sf.jsqlparser.statement.create.schema; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -116,4 +119,31 @@ public String toString() { } return sql; } + + public CreateSchema withAuthorization(String authorization) { + this.setAuthorization(authorization); + return this; + } + + public CreateSchema withSchemaName(String schemaName) { + this.setSchemaName(schemaName); + return this; + } + + public CreateSchema withSchemaPath(List schemaPath) { + this.setSchemaPath(schemaPath); + return this; + } + + public CreateSchema addSchemaPath(String... schemaPath) { + List collection = Optional.ofNullable(getSchemaPath()).orElseGet(ArrayList::new); + Collections.addAll(collection, schemaPath); + return this.withSchemaPath(collection); + } + + public CreateSchema addSchemaPath(Collection schemaPath) { + List collection = Optional.ofNullable(getSchemaPath()).orElseGet(ArrayList::new); + collection.addAll(schemaPath); + return this.withSchemaPath(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/sequence/CreateSequence.java b/src/main/java/net/sf/jsqlparser/statement/create/sequence/CreateSequence.java index 5e8e506d7a..ba21a04b12 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/sequence/CreateSequence.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/sequence/CreateSequence.java @@ -39,4 +39,9 @@ public String toString() { sql = "CREATE SEQUENCE " + sequence; return sql; } + + public CreateSequence withSequence(Sequence sequence) { + this.setSequence(sequence); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/CheckConstraint.java b/src/main/java/net/sf/jsqlparser/statement/create/table/CheckConstraint.java index 30dfbc4246..21a3e53840 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/CheckConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/CheckConstraint.java @@ -9,12 +9,15 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.Collection; +import java.util.List; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Table; public class CheckConstraint extends NamedConstraint { private Table table; + private Expression expression; public Table getTable() { @@ -37,4 +40,64 @@ public void setExpression(Expression expression) { public String toString() { return "CONSTRAINT " + getName() + " CHECK (" + expression + ")"; } + + public CheckConstraint withTable(Table table) { + this.setTable(table); + return this; + } + + public CheckConstraint withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } + + @Override + public CheckConstraint withType(String type) { + return (CheckConstraint) super.withType(type); + } + + @Override + public CheckConstraint withUsing(String using) { + return (CheckConstraint) super.withUsing(using); + } + + @Override + public CheckConstraint withName(List name) { + return (CheckConstraint) super.withName(name); + } + + @Override + public CheckConstraint withName(String name) { + return (CheckConstraint) super.withName(name); + } + + @Override + public CheckConstraint withColumnsNames(List list) { + return (CheckConstraint) super.withColumnsNames(list); + } + + @Override + public CheckConstraint withColumns(List columns) { + return (CheckConstraint) super.withColumns(columns); + } + + @Override + public CheckConstraint addColumns(ColumnParams... functionDeclarationParts) { + return (CheckConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public CheckConstraint addColumns(Collection functionDeclarationParts) { + return (CheckConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public CheckConstraint withIndexSpec(List idxSpec) { + return (CheckConstraint) super.withIndexSpec(idxSpec); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/ColDataType.java b/src/main/java/net/sf/jsqlparser/statement/create/table/ColDataType.java index de41489615..c55b75105d 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/ColDataType.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/ColDataType.java @@ -10,8 +10,10 @@ package net.sf.jsqlparser.statement.create.table; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.statement.select.PlainSelect; public class ColDataType { @@ -21,6 +23,14 @@ public class ColDataType { private String characterSet; private List arrayData = new ArrayList(); + public ColDataType() { + // empty constructor + } + + public ColDataType(String dataType) { + this.dataType = dataType; + } + public List getArgumentsStringList() { return argumentsStringList; } @@ -65,8 +75,52 @@ public String toString() { } return dataType + (argumentsStringList != null ? " " + PlainSelect. - getStringList(argumentsStringList, true, true) : "") + getStringList(argumentsStringList, true, true) : "") + arraySpec.toString() + (characterSet != null ? " CHARACTER SET " + characterSet : ""); } + + public ColDataType withDataType(String dataType) { + this.setDataType(dataType); + return this; + } + + public ColDataType withArgumentsStringList(List argumentsStringList) { + this.setArgumentsStringList(argumentsStringList); + return this; + } + + public ColDataType withCharacterSet(String characterSet) { + this.setCharacterSet(characterSet); + return this; + } + + public ColDataType withArrayData(List arrayData) { + this.setArrayData(arrayData); + return this; + } + + public ColDataType addArgumentsStringList(String... argumentsStringList) { + List collection = Optional.ofNullable(getArgumentsStringList()).orElseGet(ArrayList::new); + Collections.addAll(collection, argumentsStringList); + return this.withArgumentsStringList(collection); + } + + public ColDataType addArgumentsStringList(Collection argumentsStringList) { + List collection = Optional.ofNullable(getArgumentsStringList()).orElseGet(ArrayList::new); + collection.addAll(argumentsStringList); + return this.withArgumentsStringList(collection); + } + + public ColDataType addArrayData(Integer... arrayData) { + List collection = Optional.ofNullable(getArrayData()).orElseGet(ArrayList::new); + Collections.addAll(collection, arrayData); + return this.withArrayData(collection); + } + + public ColDataType addArrayData(Collection arrayData) { + List collection = Optional.ofNullable(getArrayData()).orElseGet(ArrayList::new); + collection.addAll(arrayData); + return this.withArrayData(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/ColumnDefinition.java b/src/main/java/net/sf/jsqlparser/statement/create/table/ColumnDefinition.java index 6c2d2675f1..6c06eac49b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/ColumnDefinition.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/ColumnDefinition.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.statement.select.PlainSelect; /** @@ -25,9 +28,13 @@ public class ColumnDefinition { public ColumnDefinition() { } - public ColumnDefinition(String columnName, ColDataType colDataType, List columnSpecs) { + public ColumnDefinition(String columnName, ColDataType colDataType) { this.columnName = columnName; this.colDataType = colDataType; + } + + public ColumnDefinition(String columnName, ColDataType colDataType, List columnSpecs) { + this(columnName, colDataType); this.columnSpecs = columnSpecs; } @@ -59,9 +66,36 @@ public void setColumnName(String string) { public String toString() { return columnName + " " + toStringDataTypeAndSpec(); } - + public String toStringDataTypeAndSpec() { return colDataType + ((columnSpecs != null && !columnSpecs.isEmpty())? " " + PlainSelect. getStringList(columnSpecs, false, false) : ""); } + + public ColumnDefinition withColumnName(String columnName) { + this.setColumnName(columnName); + return this; + } + + public ColumnDefinition withColDataType(ColDataType colDataType) { + this.setColDataType(colDataType); + return this; + } + + public ColumnDefinition withColumnSpecs(List columnSpecs) { + this.setColumnSpecs(columnSpecs); + return this; + } + + public ColumnDefinition addColumnSpecs(String... columnSpecs) { + List collection = Optional.ofNullable(getColumnSpecs()).orElseGet(ArrayList::new); + Collections.addAll(collection, columnSpecs); + return this.withColumnSpecs(collection); + } + + public ColumnDefinition addColumnSpecs(Collection columnSpecs) { + List collection = Optional.ofNullable(getColumnSpecs()).orElseGet(ArrayList::new); + collection.addAll(columnSpecs); + return this.withColumnSpecs(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/CreateTable.java b/src/main/java/net/sf/jsqlparser/statement/create/table/CreateTable.java index 109dbe6935..e8a0c76142 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/CreateTable.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/CreateTable.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -65,12 +68,12 @@ public void setColumnDefinitions(List list) { /** * A list of options (as simple strings) of this table definition, as ("TYPE", "=", "MYISAM") */ - public List getTableOptionsStrings() { + public List getTableOptionsStrings() { return tableOptionsStrings; } - public void setTableOptionsStrings(List list) { - tableOptionsStrings = list; + public void setTableOptionsStrings(List tableOptionsStrings) { + this.tableOptionsStrings = tableOptionsStrings; } public List getCreateOptionsStrings() { @@ -159,4 +162,85 @@ public String toString() { } return sql; } + + public CreateTable withTable(Table table) { + this.setTable(table); + return this; + } + + public CreateTable withUnlogged(boolean unlogged) { + this.setUnlogged(unlogged); + return this; + } + + public CreateTable withCreateOptionsStrings(List createOptionsStrings) { + this.setCreateOptionsStrings(createOptionsStrings); + return this; + } + + public CreateTable withSelectParenthesis(boolean selectParenthesis) { + this.setSelectParenthesis(selectParenthesis); + return this; + } + + public CreateTable withIfNotExists(boolean ifNotExists) { + this.setIfNotExists(ifNotExists); + return this; + } + + public CreateTable withRowMovement(RowMovement rowMovement) { + this.setRowMovement(rowMovement); + return this; + } + + public CreateTable withTableOptionsStrings(List tableOptionsStrings) { + this.setTableOptionsStrings(tableOptionsStrings); + return this; + } + + public CreateTable withColumnDefinitions(List columnDefinitions) { + this.setColumnDefinitions(columnDefinitions); + return this; + } + + public CreateTable withIndexes(List indexes) { + this.setIndexes(indexes); + return this; + } + + public CreateTable addCreateOptionsStrings(String... createOptionsStrings) { + List collection = Optional.ofNullable(getCreateOptionsStrings()).orElseGet(ArrayList::new); + Collections.addAll(collection, createOptionsStrings); + return this.withCreateOptionsStrings(collection); + } + + public CreateTable addCreateOptionsStrings(Collection createOptionsStrings) { + List collection = Optional.ofNullable(getCreateOptionsStrings()).orElseGet(ArrayList::new); + collection.addAll(createOptionsStrings); + return this.withCreateOptionsStrings(collection); + } + + public CreateTable addColumnDefinitions(ColumnDefinition... columnDefinitions) { + List collection = Optional.ofNullable(getColumnDefinitions()).orElseGet(ArrayList::new); + Collections.addAll(collection, columnDefinitions); + return this.withColumnDefinitions(collection); + } + + public CreateTable addColumnDefinitions(Collection columnDefinitions) { + List collection = Optional.ofNullable(getColumnDefinitions()).orElseGet(ArrayList::new); + collection.addAll(columnDefinitions); + return this.withColumnDefinitions(collection); + } + + public CreateTable addIndexes(Index... indexes) { + List collection = Optional.ofNullable(getIndexes()).orElseGet(ArrayList::new); + Collections.addAll(collection, indexes); + return this.withIndexes(collection); + } + + public CreateTable addIndexes(Collection indexes) { + List collection = Optional.ofNullable(getIndexes()).orElseGet(ArrayList::new); + collection.addAll(indexes); + return this.withIndexes(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/ExcludeConstraint.java b/src/main/java/net/sf/jsqlparser/statement/create/table/ExcludeConstraint.java index 0cc4c9d734..cbae5035aa 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/ExcludeConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/ExcludeConstraint.java @@ -9,6 +9,8 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.Collection; +import java.util.List; import net.sf.jsqlparser.expression.Expression; public class ExcludeConstraint extends Index { @@ -32,4 +34,58 @@ public String toString() { return exclusionStatement.toString(); } + public ExcludeConstraint withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } + + @Override + public ExcludeConstraint withName(List name) { + return (ExcludeConstraint) super.withName(name); + } + + @Override + public ExcludeConstraint withType(String type) { + return (ExcludeConstraint) super.withType(type); + } + + @Override + public ExcludeConstraint withUsing(String using) { + return (ExcludeConstraint) super.withUsing(using); + } + + @Override + public ExcludeConstraint withColumnsNames(List list) { + return (ExcludeConstraint) super.withColumnsNames(list); + } + + @Override + public ExcludeConstraint withColumns(List columns) { + return (ExcludeConstraint) super.withColumns(columns); + } + + @Override + public ExcludeConstraint addColumns(ColumnParams... functionDeclarationParts) { + return (ExcludeConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public ExcludeConstraint addColumns(Collection functionDeclarationParts) { + return (ExcludeConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public ExcludeConstraint withIndexSpec(List idxSpec) { + return (ExcludeConstraint) super.withIndexSpec(idxSpec); + } + + @Override + public ExcludeConstraint withName(String name) { + return (ExcludeConstraint) super.withName(name); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/ForeignKeyIndex.java b/src/main/java/net/sf/jsqlparser/statement/create/table/ForeignKeyIndex.java index a8aceb769a..3ece350bea 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/ForeignKeyIndex.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/ForeignKeyIndex.java @@ -9,10 +9,13 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import java.util.Set; - import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.ReferentialAction; import net.sf.jsqlparser.statement.ReferentialAction.Action; @@ -49,6 +52,11 @@ public void setReferentialAction(Type type, Action action) { setReferentialAction(type, action, true); } + public ForeignKeyIndex withReferentialAction(Type type, Action action) { + setReferentialAction(type, action); + return this; + } + /** * @param type */ @@ -114,4 +122,82 @@ public String toString() { referentialActions.forEach(b::append); return b.toString(); } + + public ForeignKeyIndex withTable(Table table) { + this.setTable(table); + return this; + } + + public ForeignKeyIndex withReferencedColumnNames(List referencedColumnNames) { + this.setReferencedColumnNames(referencedColumnNames); + return this; + } + + public ForeignKeyIndex withOnDeleteReferenceOption(String onDeleteReferenceOption) { + this.setOnDeleteReferenceOption(onDeleteReferenceOption); + return this; + } + + public ForeignKeyIndex withOnUpdateReferenceOption(String onUpdateReferenceOption) { + this.setOnUpdateReferenceOption(onUpdateReferenceOption); + return this; + } + + public ForeignKeyIndex addReferencedColumnNames(String... referencedColumnNames) { + List collection = Optional.ofNullable(getReferencedColumnNames()).orElseGet(ArrayList::new); + Collections.addAll(collection, referencedColumnNames); + return this.withReferencedColumnNames(collection); + } + + public ForeignKeyIndex addReferencedColumnNames(Collection referencedColumnNames) { + List collection = Optional.ofNullable(getReferencedColumnNames()).orElseGet(ArrayList::new); + collection.addAll(referencedColumnNames); + return this.withReferencedColumnNames(collection); + } + + @Override + public ForeignKeyIndex withType(String type) { + return (ForeignKeyIndex) super.withType(type); + } + + @Override + public ForeignKeyIndex withUsing(String using) { + return (ForeignKeyIndex) super.withUsing(using); + } + + @Override + public ForeignKeyIndex withName(List name) { + return (ForeignKeyIndex) super.withName(name); + } + + @Override + public ForeignKeyIndex withName(String name) { + return (ForeignKeyIndex) super.withName(name); + } + + @Override + public ForeignKeyIndex withColumnsNames(List list) { + return (ForeignKeyIndex) super.withColumnsNames(list); + } + + @Override + public ForeignKeyIndex withColumns(List columns) { + return (ForeignKeyIndex) super.withColumns(columns); + } + + @Override + public ForeignKeyIndex addColumns(ColumnParams... functionDeclarationParts) { + return (ForeignKeyIndex) super.addColumns(functionDeclarationParts); + } + + @Override + public ForeignKeyIndex addColumns(Collection functionDeclarationParts) { + return (ForeignKeyIndex) super.addColumns(functionDeclarationParts); + } + + @Override + public ForeignKeyIndex withIndexSpec(List idxSpec) { + return (ForeignKeyIndex) super.withIndexSpec(idxSpec); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/Index.java b/src/main/java/net/sf/jsqlparser/statement/create/table/Index.java index 7c24544817..dc1bbe8979 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/Index.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/Index.java @@ -9,11 +9,12 @@ */ package net.sf.jsqlparser.statement.create.table; +import static java.util.stream.Collectors.toList; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; -import static java.util.stream.Collectors.toList; - +import java.util.Optional; import net.sf.jsqlparser.statement.select.PlainSelect; public class Index { @@ -29,15 +30,46 @@ public List getColumnsNames() { .map(col -> col.columnName) .collect(toList()); } - + + @Deprecated public List getColumnWithParams() { + return getColumns(); + } + + @Deprecated + public void setColumnNamesWithParams(List list) { + setColumns(list); + } + + public List getColumns() { return columns; } + public void setColumns(List columns) { + this.columns = columns; + } + + public Index withColumns(List columns) { + setColumns(columns); + return this; + } + + public Index addColumns(ColumnParams... functionDeclarationParts) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, functionDeclarationParts); + return this.withColumns(collection); + } + + public Index addColumns(Collection functionDeclarationParts) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(functionDeclarationParts); + return this.withColumns(collection); + } + public String getName() { - return name.isEmpty()?null:String.join(".", name); + return name.isEmpty() ? null : String.join(".", name); } - + public List getNameParts() { return Collections.unmodifiableList(name); } @@ -52,24 +84,25 @@ public String getType() { * Please note that: * Oracle - the type might be BITMAP, indicating a bitmap kind of index * MySQL - the type might be FULLTEXT or SPATIAL - */ + */ public void setUsing(String string) { using = string; } public void setColumnsNames(List list) { - columns = list.stream().map(col -> new ColumnParams(col, null)).collect(toList()); + columns = list.stream().map(ColumnParams::new).collect(toList()); } - - public void setColumnNamesWithParams(List list) { - this.columns = list; + + public Index withColumnsNames(List list) { + setColumnsNames(list); + return this; } public void setName(String name) { this.name.clear(); this.name.add(name); } - + public void setName(List name) { this.name.clear(); this.name.addAll(name); @@ -91,17 +124,47 @@ public void setIndexSpec(List idxSpec) { this.idxSpec = idxSpec; } + public Index withIndexSpec(List idxSpec) { + setIndexSpec(idxSpec); + return this; + } + @Override public String toString() { String idxSpecText = PlainSelect.getStringList(idxSpec, false, false); return type + (!name.isEmpty() ? " " + getName() : "") + " " + PlainSelect. getStringList(columns, true, true) + (!"".equals(idxSpecText) ? " " + idxSpecText : ""); } - + + public Index withType(String type) { + this.setType(type); + return this; + } + + public Index withUsing(String using) { + this.setUsing(using); + return this; + } + + public Index withName(List name) { + this.setName(name); + return this; + } + + public Index withName(String name) { + this.setName(name); + return this; + } + public static class ColumnParams { public final String columnName; public final List params; + public ColumnParams(String columnName) { + this.columnName = columnName; + this.params = null; + } + public ColumnParams(String columnName, List params) { this.columnName = columnName; this.params = params; @@ -114,10 +177,10 @@ public String getColumnName() { public List getParams() { return params; } - + @Override public String toString() { - return columnName + (params!=null?" " + String.join(" ", params):""); + return columnName + (params != null ? " " + String.join(" ", params) : ""); } } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/NamedConstraint.java b/src/main/java/net/sf/jsqlparser/statement/create/table/NamedConstraint.java index 55cb4a21bb..8f188ebc89 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/NamedConstraint.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/NamedConstraint.java @@ -9,6 +9,8 @@ */ package net.sf.jsqlparser.statement.create.table; +import java.util.Collection; +import java.util.List; import net.sf.jsqlparser.statement.select.PlainSelect; public class NamedConstraint extends Index { @@ -18,6 +20,52 @@ public String toString() { String idxSpecText = PlainSelect.getStringList(getIndexSpec(), false, false); return (getName() != null ? "CONSTRAINT " + getName() + " " : "") + getType() + " " + PlainSelect.getStringList(getColumnsNames(), true, true) + (!"". - equals(idxSpecText) ? " " + idxSpecText : ""); + equals(idxSpecText) ? " " + idxSpecText : ""); } + + @Override + public NamedConstraint withName(List name) { + return (NamedConstraint) super.withName(name); + } + + @Override + public NamedConstraint withName(String name) { + return (NamedConstraint) super.withName(name); + } + + @Override + public NamedConstraint withType(String type) { + return (NamedConstraint) super.withType(type); + } + + @Override + public NamedConstraint withUsing(String using) { + return (NamedConstraint) super.withUsing(using); + } + + @Override + public NamedConstraint withColumnsNames(List list) { + return (NamedConstraint) super.withColumnsNames(list); + } + + @Override + public NamedConstraint withColumns(List columns) { + return (NamedConstraint) super.withColumns(columns); + } + + @Override + public NamedConstraint addColumns(ColumnParams... functionDeclarationParts) { + return (NamedConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public NamedConstraint addColumns(Collection functionDeclarationParts) { + return (NamedConstraint) super.addColumns(functionDeclarationParts); + } + + @Override + public NamedConstraint withIndexSpec(List idxSpec) { + return (NamedConstraint) super.withIndexSpec(idxSpec); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/table/RowMovement.java b/src/main/java/net/sf/jsqlparser/statement/create/table/RowMovement.java index 77ee482aa6..4cb56685fc 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/table/RowMovement.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/table/RowMovement.java @@ -23,4 +23,9 @@ public RowMovementMode getMode() { public void setMode(RowMovementMode mode) { this.mode = mode; } + + public RowMovement withMode(RowMovementMode mode) { + this.setMode(mode); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/view/AlterView.java b/src/main/java/net/sf/jsqlparser/statement/create/view/AlterView.java index 2e9af61048..a436d6c984 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/view/AlterView.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/view/AlterView.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.create.view; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -76,4 +80,40 @@ public String toString() { sql.append(" AS ").append(selectBody); return sql.toString(); } + + public AlterView withView(Table view) { + this.setView(view); + return this; + } + + public AlterView withSelectBody(SelectBody selectBody) { + this.setSelectBody(selectBody); + return this; + } + + public AlterView withUseReplace(boolean useReplace) { + this.setUseReplace(useReplace); + return this; + } + + public AlterView withColumnNames(List columnNames) { + this.setColumnNames(columnNames); + return this; + } + + public AlterView addColumnNames(String... columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + Collections.addAll(collection, columnNames); + return this.withColumnNames(collection); + } + + public AlterView addColumnNames(Collection columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + collection.addAll(columnNames); + return this.withColumnNames(collection); + } + + public E getSelectBody(Class type) { + return type.cast(getSelectBody()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/create/view/CreateView.java b/src/main/java/net/sf/jsqlparser/statement/create/view/CreateView.java index f4143fff5e..95dd85129b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/create/view/CreateView.java +++ b/src/main/java/net/sf/jsqlparser/statement/create/view/CreateView.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.create.view; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -132,4 +136,51 @@ public String toString() { } return sql.toString(); } + + public CreateView withView(Table view) { + this.setView(view); + return this; + } + + public CreateView withSelect(Select select) { + this.setSelect(select); + return this; + } + + public CreateView withOrReplace(boolean orReplace) { + this.setOrReplace(orReplace); + return this; + } + + public CreateView withColumnNames(List columnNames) { + this.setColumnNames(columnNames); + return this; + } + + public CreateView withMaterialized(boolean materialized) { + this.setMaterialized(materialized); + return this; + } + + public CreateView withForce(ForceOption force) { + this.setForce(force); + return this; + } + + public CreateView withWithReadOnly(boolean withReadOnly) { + this.setWithReadOnly(withReadOnly); + return this; + } + + public CreateView addColumnNames(String... columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + Collections.addAll(collection, columnNames); + return this.withColumnNames(collection); + } + + public CreateView addColumnNames(Collection columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + collection.addAll(columnNames); + return this.withColumnNames(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/delete/Delete.java b/src/main/java/net/sf/jsqlparser/statement/delete/Delete.java index 3e59b2e7c3..5c9dbfc6a3 100644 --- a/src/main/java/net/sf/jsqlparser/statement/delete/Delete.java +++ b/src/main/java/net/sf/jsqlparser/statement/delete/Delete.java @@ -9,6 +9,12 @@ */ package net.sf.jsqlparser.statement.delete; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import static java.util.stream.Collectors.joining; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; @@ -18,9 +24,6 @@ import net.sf.jsqlparser.statement.select.OrderByElement; import net.sf.jsqlparser.statement.select.PlainSelect; -import java.util.List; -import static java.util.stream.Collectors.joining; - public class Delete implements Statement { private Table table; @@ -120,4 +123,74 @@ public String toString() { } return b.toString(); } + + public Delete withTables(List tables) { + this.setTables(tables); + return this; + } + + public Delete withJoins(List joins) { + this.setJoins(joins); + return this; + } + + public Delete withLimit(Limit limit) { + this.setLimit(limit); + return this; + } + + public Delete withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public Delete withTable(Table table) { + this.setTable(table); + return this; + } + + public Delete withWhere(Expression where) { + this.setWhere(where); + return this; + } + + public Delete addTables(Table... tables) { + List
collection = Optional.ofNullable(getTables()).orElseGet(ArrayList::new); + Collections.addAll(collection, tables); + return this.withTables(collection); + } + + public Delete addTables(Collection tables) { + List
collection = Optional.ofNullable(getTables()).orElseGet(ArrayList::new); + collection.addAll(tables); + return this.withTables(collection); + } + + public Delete addJoins(Join... joins) { + List collection = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + Collections.addAll(collection, joins); + return this.withJoins(collection); + } + + public Delete addJoins(Collection joins) { + List collection = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + collection.addAll(joins); + return this.withJoins(collection); + } + + public Delete addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public Delete addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } + + public E getWhere(Class type) { + return type.cast(getWhere()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/drop/Drop.java b/src/main/java/net/sf/jsqlparser/statement/drop/Drop.java index 177f6398de..33dbd3bf33 100644 --- a/src/main/java/net/sf/jsqlparser/statement/drop/Drop.java +++ b/src/main/java/net/sf/jsqlparser/statement/drop/Drop.java @@ -9,9 +9,12 @@ */ package net.sf.jsqlparser.statement.drop; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.schema.Table; - import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; import net.sf.jsqlparser.statement.select.PlainSelect; @@ -71,4 +74,36 @@ public String toString() { return sql; } + + public Drop withIfExists(boolean ifExists) { + this.setIfExists(ifExists); + return this; + } + + public Drop withType(String type) { + this.setType(type); + return this; + } + + public Drop withName(Table name) { + this.setName(name); + return this; + } + + public Drop withParameters(List parameters) { + this.setParameters(parameters); + return this; + } + + public Drop addParameters(String... parameters) { + List collection = Optional.ofNullable(getParameters()).orElseGet(ArrayList::new); + Collections.addAll(collection, parameters); + return this.withParameters(collection); + } + + public Drop addParameters(Collection parameters) { + List collection = Optional.ofNullable(getParameters()).orElseGet(ArrayList::new); + collection.addAll(parameters); + return this.withParameters(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/execute/Execute.java b/src/main/java/net/sf/jsqlparser/statement/execute/Execute.java index 75422b0c7f..f37046892b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/execute/Execute.java +++ b/src/main/java/net/sf/jsqlparser/statement/execute/Execute.java @@ -76,10 +76,29 @@ public String toString() { + PlainSelect.getStringList(exprList.getExpressions(), true, parenthesis) : ""); } + public Execute withExecType(EXEC_TYPE execType) { + this.setExecType(execType); + return this; + } + + public Execute withName(String name) { + this.setName(name); + return this; + } + + public Execute withExprList(ExpressionList exprList) { + this.setExprList(exprList); + return this; + } + + public Execute withParenthesis(boolean parenthesis) { + this.setParenthesis(parenthesis); + return this; + } + public static enum EXEC_TYPE { EXECUTE, EXEC, CALL } - } diff --git a/src/main/java/net/sf/jsqlparser/statement/grant/Grant.java b/src/main/java/net/sf/jsqlparser/statement/grant/Grant.java index 3e96033c7f..3655ce9179 100644 --- a/src/main/java/net/sf/jsqlparser/statement/grant/Grant.java +++ b/src/main/java/net/sf/jsqlparser/statement/grant/Grant.java @@ -9,11 +9,14 @@ */ package net.sf.jsqlparser.statement.grant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; -import java.util.List; - public class Grant implements Statement { private String role; @@ -84,4 +87,48 @@ public String toString() { } return buffer.toString(); } + + public Grant withRole(String role) { + this.setRole(role); + return this; + } + + public Grant withPrivileges(List privileges) { + this.setPrivileges(privileges); + return this; + } + + public Grant withObjectName(String objectName) { + this.setObjectName(objectName); + return this; + } + + public Grant withUsers(List users) { + this.setUsers(users); + return this; + } + + public Grant addPrivileges(String... privileges) { + List collection = Optional.ofNullable(getPrivileges()).orElseGet(ArrayList::new); + Collections.addAll(collection, privileges); + return this.withPrivileges(collection); + } + + public Grant addPrivileges(Collection privileges) { + List collection = Optional.ofNullable(getPrivileges()).orElseGet(ArrayList::new); + collection.addAll(privileges); + return this.withPrivileges(collection); + } + + public Grant addUsers(String... users) { + List collection = Optional.ofNullable(getUsers()).orElseGet(ArrayList::new); + Collections.addAll(collection, users); + return this.withUsers(collection); + } + + public Grant addUsers(Collection users) { + List collection = Optional.ofNullable(getUsers()).orElseGet(ArrayList::new); + collection.addAll(users); + return this.withUsers(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/insert/Insert.java b/src/main/java/net/sf/jsqlparser/statement/insert/Insert.java index 14db121927..4e596b145a 100644 --- a/src/main/java/net/sf/jsqlparser/statement/insert/Insert.java +++ b/src/main/java/net/sf/jsqlparser/statement/insert/Insert.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.insert; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.schema.Column; @@ -156,27 +159,27 @@ public boolean isModifierIgnore() { public void setModifierIgnore(boolean modifierIgnore) { this.modifierIgnore = modifierIgnore; } - + public void setUseSet(boolean useSet) { this.useSet = useSet; } - + public boolean isUseSet() { return useSet; } - + public void setSetColumns(List setColumns) { this.setColumns = setColumns; } - + public List getSetColumns() { return setColumns; } - + public void setSetExpressionList(List setExpressionList) { this.setExpressionList = setExpressionList; } - + public List getSetExpressionList() { return setExpressionList; } @@ -247,5 +250,165 @@ public String toString() { return sql.toString(); } - + + public Insert withUseValues(boolean useValues) { + this.setUseValues(useValues); + return this; + } + + public Insert withSelect(Select select) { + this.setSelect(select); + return this; + } + + public Insert withUseSelectBrackets(boolean useSelectBrackets) { + this.setUseSelectBrackets(useSelectBrackets); + return this; + } + + public Insert withUseDuplicate(boolean useDuplicate) { + this.setUseDuplicate(useDuplicate); + return this; + } + + public Insert withDuplicateUpdateColumns(List duplicateUpdateColumns) { + this.setDuplicateUpdateColumns(duplicateUpdateColumns); + return this; + } + + public Insert withDuplicateUpdateExpressionList(List duplicateUpdateExpressionList) { + this.setDuplicateUpdateExpressionList(duplicateUpdateExpressionList); + return this; + } + + public Insert withModifierPriority(InsertModifierPriority modifierPriority) { + this.setModifierPriority(modifierPriority); + return this; + } + + public Insert withModifierIgnore(boolean modifierIgnore) { + this.setModifierIgnore(modifierIgnore); + return this; + } + + public Insert withReturningAllColumns(boolean returningAllColumns) { + this.setReturningAllColumns(returningAllColumns); + return this; + } + + public Insert withReturningExpressionList(List returningExpressionList) { + this.setReturningExpressionList(returningExpressionList); + return this; + } + + public Insert withUseSet(boolean useSet) { + this.setUseSet(useSet); + return this; + } + + public Insert withUseSetColumns(List setColumns) { + this.setSetColumns(setColumns); + return this; + } + + public Insert withSetExpressionList(List setExpressionList) { + this.setSetExpressionList(setExpressionList); + return this; + } + + public Insert withTable(Table table) { + this.setTable(table); + return this; + } + + public Insert withColumns(List columns) { + this.setColumns(columns); + return this; + } + + public Insert withSetColumns(List columns) { + this.setSetColumns(columns); + return this; + } + + public Insert withItemsList(ItemsList itemsList) { + this.setItemsList(itemsList); + return this; + } + + public Insert addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public Insert addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public Insert addDuplicateUpdateColumns(Column... duplicateUpdateColumns) { + List collection = Optional.ofNullable(getDuplicateUpdateColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, duplicateUpdateColumns); + return this.withDuplicateUpdateColumns(collection); + } + + public Insert addDuplicateUpdateColumns(Collection duplicateUpdateColumns) { + List collection = Optional.ofNullable(getDuplicateUpdateColumns()).orElseGet(ArrayList::new); + collection.addAll(duplicateUpdateColumns); + return this.withDuplicateUpdateColumns(collection); + } + + public Insert addDuplicateUpdateExpressionList(Expression... duplicateUpdateExpressionList) { + List collection = Optional.ofNullable(getDuplicateUpdateExpressionList()).orElseGet(ArrayList::new); + Collections.addAll(collection, duplicateUpdateExpressionList); + return this.withDuplicateUpdateExpressionList(collection); + } + + public Insert addDuplicateUpdateExpressionList(Collection duplicateUpdateExpressionList) { + List collection = Optional.ofNullable(getDuplicateUpdateExpressionList()).orElseGet(ArrayList::new); + collection.addAll(duplicateUpdateExpressionList); + return this.withDuplicateUpdateExpressionList(collection); + } + + public Insert addReturningExpressionList(SelectExpressionItem... returningExpressionList) { + List collection = Optional.ofNullable(getReturningExpressionList()).orElseGet(ArrayList::new); + Collections.addAll(collection, returningExpressionList); + return this.withReturningExpressionList(collection); + } + + public Insert addReturningExpressionList(Collection returningExpressionList) { + List collection = Optional.ofNullable(getReturningExpressionList()).orElseGet(ArrayList::new); + collection.addAll(returningExpressionList); + return this.withReturningExpressionList(collection); + } + + public Insert addSetColumns(Column... setColumns) { + List collection = Optional.ofNullable(getSetColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, setColumns); + return this.withSetColumns(collection); + } + + public Insert addSetColumns(Collection setColumns) { + List collection = Optional.ofNullable(getSetColumns()).orElseGet(ArrayList::new); + collection.addAll(setColumns); + return this.withSetColumns(collection); + } + + public Insert addSetExpressionList(Expression... setExpressionList) { + List collection = Optional.ofNullable(getSetExpressionList()).orElseGet(ArrayList::new); + Collections.addAll(collection, setExpressionList); + return this.withSetExpressionList(collection); + } + + public Insert addSetExpressionList(Collection setExpressionList) { + List collection = Optional.ofNullable(getSetExpressionList()).orElseGet(ArrayList::new); + collection.addAll(setExpressionList); + return this.withSetExpressionList(collection); + } + + public E getItemsList(Class type) { + return type.cast(getItemsList()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/merge/Merge.java b/src/main/java/net/sf/jsqlparser/statement/merge/Merge.java index f9c7bced0d..bd894ca38f 100644 --- a/src/main/java/net/sf/jsqlparser/statement/merge/Merge.java +++ b/src/main/java/net/sf/jsqlparser/statement/merge/Merge.java @@ -136,4 +136,48 @@ public String toString() { return b.toString(); } + + public Merge withUsingTable(Table usingTable) { + this.setUsingTable(usingTable); + return this; + } + + public Merge withUsingSelect(SubSelect usingSelect) { + this.setUsingSelect(usingSelect); + return this; + } + + public Merge withUsingAlias(Alias usingAlias) { + this.setUsingAlias(usingAlias); + return this; + } + + public Merge withOnCondition(Expression onCondition) { + this.setOnCondition(onCondition); + return this; + } + + public Merge withMergeUpdate(MergeUpdate mergeUpdate) { + this.setMergeUpdate(mergeUpdate); + return this; + } + + public Merge withInsertFirst(boolean insertFirst) { + this.setInsertFirst(insertFirst); + return this; + } + + public Merge withTable(Table table) { + this.setTable(table); + return this; + } + + public Merge withMergeInsert(MergeInsert mergeInsert) { + this.setMergeInsert(mergeInsert); + return this; + } + + public E getOnCondition(Class type) { + return type.cast(getOnCondition()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/merge/MergeInsert.java b/src/main/java/net/sf/jsqlparser/statement/merge/MergeInsert.java index 6f46a3574e..eb6c7cf5f4 100644 --- a/src/main/java/net/sf/jsqlparser/statement/merge/MergeInsert.java +++ b/src/main/java/net/sf/jsqlparser/statement/merge/MergeInsert.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.merge; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.statement.select.PlainSelect; @@ -41,4 +45,38 @@ public String toString() { + (columns.isEmpty() ? "" : PlainSelect.getStringList(columns, true, true)) + " VALUES " + PlainSelect.getStringList(values, true, true); } + + public MergeInsert withColumns(List columns) { + this.setColumns(columns); + return this; + } + + public MergeInsert withValues(List values) { + this.setValues(values); + return this; + } + + public MergeInsert addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public MergeInsert addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public MergeInsert addValues(Expression... values) { + List collection = Optional.ofNullable(getValues()).orElseGet(ArrayList::new); + Collections.addAll(collection, values); + return this.withValues(collection); + } + + public MergeInsert addValues(Collection values) { + List collection = Optional.ofNullable(getValues()).orElseGet(ArrayList::new); + collection.addAll(values); + return this.withValues(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/merge/MergeUpdate.java b/src/main/java/net/sf/jsqlparser/statement/merge/MergeUpdate.java index b81b446d73..c3e66da125 100644 --- a/src/main/java/net/sf/jsqlparser/statement/merge/MergeUpdate.java +++ b/src/main/java/net/sf/jsqlparser/statement/merge/MergeUpdate.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.merge; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Column; @@ -70,4 +74,56 @@ public String toString() { } return b.toString(); } + + public MergeUpdate withColumns(List columns) { + this.setColumns(columns); + return this; + } + + public MergeUpdate withValues(List values) { + this.setValues(values); + return this; + } + + public MergeUpdate withWhereCondition(Expression whereCondition) { + this.setWhereCondition(whereCondition); + return this; + } + + public MergeUpdate withDeleteWhereCondition(Expression deleteWhereCondition) { + this.setDeleteWhereCondition(deleteWhereCondition); + return this; + } + + public MergeUpdate addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public MergeUpdate addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public MergeUpdate addValues(Expression... values) { + List collection = Optional.ofNullable(getValues()).orElseGet(ArrayList::new); + Collections.addAll(collection, values); + return this.withValues(collection); + } + + public MergeUpdate addValues(Collection values) { + List collection = Optional.ofNullable(getValues()).orElseGet(ArrayList::new); + collection.addAll(values); + return this.withValues(collection); + } + + public E getWhereCondition(Class type) { + return type.cast(getWhereCondition()); + } + + public E getDeleteWhereCondition(Class type) { + return type.cast(getDeleteWhereCondition()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/replace/Replace.java b/src/main/java/net/sf/jsqlparser/statement/replace/Replace.java index 51252d3ed6..d51f378a49 100644 --- a/src/main/java/net/sf/jsqlparser/statement/replace/Replace.java +++ b/src/main/java/net/sf/jsqlparser/statement/replace/Replace.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.replace; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.schema.Column; @@ -121,4 +124,62 @@ public String toString() { return sql.toString(); } + + public Replace withUseValues(boolean useValues) { + this.setUseValues(useValues); + return this; + } + + public Replace withUseIntoTables(boolean useIntoTables) { + this.setUseIntoTables(useIntoTables); + return this; + } + + public Replace withTable(Table table) { + this.setTable(table); + return this; + } + + public Replace withColumns(List columns) { + this.setColumns(columns); + return this; + } + + public Replace withItemsList(ItemsList itemsList) { + this.setItemsList(itemsList); + return this; + } + + public Replace withExpressions(List expressions) { + this.setExpressions(expressions); + return this; + } + + public Replace addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public Replace addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public Replace addExpressions(Expression... expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, expressions); + return this.withExpressions(collection); + } + + public Replace addExpressions(Collection expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + collection.addAll(expressions); + return this.withExpressions(collection); + } + + public E getItemsList(Class type) { + return type.cast(getItemsList()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/AllColumns.java b/src/main/java/net/sf/jsqlparser/statement/select/AllColumns.java index b01828b32a..4b23c69484 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/AllColumns.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/AllColumns.java @@ -13,9 +13,6 @@ public class AllColumns extends ASTNodeAccessImpl implements SelectItem { - public AllColumns() { - } - @Override public void accept(SelectItemVisitor selectItemVisitor) { selectItemVisitor.visit(this); @@ -25,4 +22,5 @@ public void accept(SelectItemVisitor selectItemVisitor) { public String toString() { return "*"; } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/AllTableColumns.java b/src/main/java/net/sf/jsqlparser/statement/select/AllTableColumns.java index e1b7d3d541..3f19892a0b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/AllTableColumns.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/AllTableColumns.java @@ -40,4 +40,9 @@ public void accept(SelectItemVisitor selectItemVisitor) { public String toString() { return table + ".*"; } + + public AllTableColumns withTable(Table table) { + this.setTable(table); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Distinct.java b/src/main/java/net/sf/jsqlparser/statement/select/Distinct.java index 9b2f6c83b6..8cc89d5fd7 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Distinct.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Distinct.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; public class Distinct { @@ -49,4 +53,26 @@ public String toString() { return sql; } + + public Distinct withOnSelectItems(List onSelectItems) { + this.setOnSelectItems(onSelectItems); + return this; + } + + public Distinct withUseUnique(boolean useUnique) { + this.setUseUnique(useUnique); + return this; + } + + public Distinct addOnSelectItems(SelectItem... onSelectItems) { + List collection = Optional.ofNullable(getOnSelectItems()).orElseGet(ArrayList::new); + Collections.addAll(collection, onSelectItems); + return this.withOnSelectItems(collection); + } + + public Distinct addOnSelectItems(Collection onSelectItems) { + List collection = Optional.ofNullable(getOnSelectItems()).orElseGet(ArrayList::new); + collection.addAll(onSelectItems); + return this.withOnSelectItems(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/ExpressionListItem.java b/src/main/java/net/sf/jsqlparser/statement/select/ExpressionListItem.java index 7ae1d1a905..2bbe4dea96 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/ExpressionListItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/ExpressionListItem.java @@ -37,4 +37,14 @@ public void setAlias(Alias alias) { public String toString() { return expressionList + ((alias != null) ? alias.toString() : ""); } + + public ExpressionListItem withExpressionList(ExpressionList expressionList) { + this.setExpressionList(expressionList); + return this; + } + + public ExpressionListItem withAlias(Alias alias) { + this.setAlias(alias); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Fetch.java b/src/main/java/net/sf/jsqlparser/statement/select/Fetch.java index 3a7f34a5c6..9f625a1622 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Fetch.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Fetch.java @@ -56,4 +56,19 @@ public String toString() { + (fetchJdbcParameter!=null ? fetchJdbcParameter.toString() : Long.toString(rowCount)) + " " + fetchParam + " ONLY"; } + + public Fetch withRowCount(long rowCount) { + this.setRowCount(rowCount); + return this; + } + + public Fetch withFetchJdbcParameter(JdbcParameter fetchJdbcParameter) { + this.setFetchJdbcParameter(fetchJdbcParameter); + return this; + } + + public Fetch withFetchParam(String fetchParam) { + this.setFetchParam(fetchParam); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/First.java b/src/main/java/net/sf/jsqlparser/statement/select/First.java index dfac655b65..4ef0a3e8b7 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/First.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/First.java @@ -69,4 +69,24 @@ public String toString() { return result; } + + public First withKeyword(Keyword keyword) { + this.setKeyword(keyword); + return this; + } + + public First withRowCount(Long rowCount) { + this.setRowCount(rowCount); + return this; + } + + public First withJdbcParameter(JdbcParameter jdbcParameter) { + this.setJdbcParameter(jdbcParameter); + return this; + } + + public First withVariable(String variable) { + this.setVariable(variable); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/FromItem.java b/src/main/java/net/sf/jsqlparser/statement/select/FromItem.java index b191750b83..b43d7b33b8 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/FromItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/FromItem.java @@ -9,22 +9,38 @@ */ package net.sf.jsqlparser.statement.select; +import net.sf.jsqlparser.Model; import net.sf.jsqlparser.expression.Alias; -public interface FromItem { +public interface FromItem extends Model { void accept(FromItemVisitor fromItemVisitor); Alias getAlias(); + default FromItem withAlias(Alias alias) { + setAlias(alias); + return this; + } + void setAlias(Alias alias); Pivot getPivot(); + default FromItem withPivot(Pivot pivot) { + setPivot(pivot); + return this; + } + void setPivot(Pivot pivot); UnPivot getUnPivot(); + default FromItem withUnPivot(UnPivot unpivot) { + setUnPivot(unpivot); + return this; + } + void setUnPivot(UnPivot unpivot); } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/FunctionItem.java b/src/main/java/net/sf/jsqlparser/statement/select/FunctionItem.java index 50c920f707..63ea3fbb8a 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/FunctionItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/FunctionItem.java @@ -9,10 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import net.sf.jsqlparser.Model; import net.sf.jsqlparser.expression.Alias; import net.sf.jsqlparser.expression.Function; -public class FunctionItem { +public class FunctionItem implements Model { private Function function; private Alias alias; @@ -37,4 +38,14 @@ public void setFunction(Function function) { public String toString() { return function + ((alias != null) ? alias.toString() : ""); } + + public FunctionItem withFunction(Function function) { + this.setFunction(function); + return this; + } + + public FunctionItem withAlias(Alias alias) { + this.setAlias(alias); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/GroupByElement.java b/src/main/java/net/sf/jsqlparser/statement/select/GroupByElement.java index f57a06ed3c..43c104482f 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/GroupByElement.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/GroupByElement.java @@ -10,7 +10,10 @@ package net.sf.jsqlparser.statement.select; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; @@ -79,4 +82,38 @@ public String toString() { return b.toString(); } + + public GroupByElement withGroupByExpressions(List groupByExpressions) { + this.setGroupByExpressions(groupByExpressions); + return this; + } + + public GroupByElement withGroupingSets(List groupingSets) { + this.setGroupingSets(groupingSets); + return this; + } + + public GroupByElement addGroupByExpressions(Expression... groupByExpressions) { + List collection = Optional.ofNullable(getGroupByExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, groupByExpressions); + return this.withGroupByExpressions(collection); + } + + public GroupByElement addGroupByExpressions(Collection groupByExpressions) { + List collection = Optional.ofNullable(getGroupByExpressions()).orElseGet(ArrayList::new); + collection.addAll(groupByExpressions); + return this.withGroupByExpressions(collection); + } + + public GroupByElement addGroupingSets(Object... groupingSets) { + List collection = Optional.ofNullable(getGroupingSets()).orElseGet(ArrayList::new); + Collections.addAll(collection, groupingSets); + return this.withGroupingSets(collection); + } + + public GroupByElement addGroupingSets(Collection groupingSets) { + List collection = Optional.ofNullable(getGroupingSets()).orElseGet(ArrayList::new); + collection.addAll(groupingSets); + return this.withGroupingSets(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Join.java b/src/main/java/net/sf/jsqlparser/statement/select/Join.java index 98e4a89b3c..4a79fdc0a0 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Join.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Join.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.parser.ASTNodeAccessImpl; import net.sf.jsqlparser.schema.Column; @@ -37,6 +40,11 @@ public boolean isSimple() { return simple; } + public Join withSimple(boolean b) { + this.setSimple(b); + return this; + } + public void setSimple(boolean b) { simple = b; } @@ -45,6 +53,11 @@ public boolean isInner() { return inner; } + public Join withInner(boolean b) { + this.setInner(b); + return this; + } + public void setInner(boolean b) { inner = b; } @@ -53,6 +66,11 @@ public boolean isStraight() { return straight; } + public Join withStraight(boolean b) { + this.setStraight(b); + return this; + } + public void setStraight(boolean b) { straight = b; } @@ -66,6 +84,11 @@ public boolean isOuter() { return outer; } + public Join withOuter(boolean b) { + this.setOuter(b); + return this; + } + public void setOuter(boolean b) { outer = b; } @@ -74,6 +97,11 @@ public boolean isApply() { return apply; } + public Join withApply(boolean apply) { + this.setApply(apply); + return this; + } + public void setApply(boolean apply) { this.apply = apply; } @@ -87,6 +115,11 @@ public boolean isSemi() { return semi; } + public Join withSemi(boolean b) { + this.setSemi(b); + return this; + } + public void setSemi(boolean b) { semi = b; } @@ -100,6 +133,11 @@ public boolean isLeft() { return left; } + public Join withLeft(boolean b) { + this.setLeft(b); + return this; + } + public void setLeft(boolean b) { left = b; } @@ -113,6 +151,11 @@ public boolean isRight() { return right; } + public Join withRight(boolean b) { + this.setRight(b); + return this; + } + public void setRight(boolean b) { right = b; } @@ -126,6 +169,11 @@ public boolean isNatural() { return natural; } + public Join withNatural(boolean b) { + this.setNatural(b); + return this; + } + public void setNatural(boolean b) { natural = b; } @@ -139,6 +187,11 @@ public boolean isFull() { return full; } + public Join withFull(boolean b) { + this.setFull(b); + return this; + } + public void setFull(boolean b) { full = b; } @@ -147,6 +200,11 @@ public boolean isCross() { return cross; } + public Join withCross(boolean cross) { + this.setCross(cross); + return this; + } + public void setCross(boolean cross) { this.cross = cross; } @@ -158,6 +216,11 @@ public FromItem getRightItem() { return rightItem; } + public Join withRightItem(FromItem item) { + this.setRightItem(item); + return this; + } + public void setRightItem(FromItem item) { rightItem = item; } @@ -169,6 +232,11 @@ public Expression getOnExpression() { return onExpression; } + public Join withOnExpression(Expression expression) { + this.setOnExpression(expression); + return this; + } + public void setOnExpression(Expression expression) { onExpression = expression; } @@ -180,6 +248,11 @@ public List getUsingColumns() { return usingColumns; } + public Join withUsingColumns(List list) { + this.setUsingColumns(list); + return this; + } + public void setUsingColumns(List list) { usingColumns = list; } @@ -195,6 +268,11 @@ public KSQLJoinWindow getJoinWindow() { return joinWindow; } + public Join withJoinWindow(KSQLJoinWindow joinWindow) { + this.setJoinWindow(joinWindow); + return this; + } + public void setJoinWindow(KSQLJoinWindow joinWindow) { this.joinWindow = joinWindow; } @@ -242,4 +320,24 @@ public String toString() { } } + + public Join addUsingColumns(Column... usingColumns) { + List collection = Optional.ofNullable(getUsingColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, usingColumns); + return this.withUsingColumns(collection); + } + + public Join addUsingColumns(Collection usingColumns) { + List collection = Optional.ofNullable(getUsingColumns()).orElseGet(ArrayList::new); + collection.addAll(usingColumns); + return this.withUsingColumns(collection); + } + + public E getRightItem(Class type) { + return type.cast(getRightItem()); + } + + public E getOnExpression(Class type) { + return type.cast(getOnExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/KSQLJoinWindow.java b/src/main/java/net/sf/jsqlparser/statement/select/KSQLJoinWindow.java index 871dc02824..e473a16a6a 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/KSQLJoinWindow.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/KSQLJoinWindow.java @@ -110,4 +110,34 @@ public String toString() { } return "(" + duration + " " + timeUnit + ")"; } + + public KSQLJoinWindow withDuration(long duration) { + this.setDuration(duration); + return this; + } + + public KSQLJoinWindow withTimeUnit(TimeUnit timeUnit) { + this.setTimeUnit(timeUnit); + return this; + } + + public KSQLJoinWindow withBeforeDuration(long beforeDuration) { + this.setBeforeDuration(beforeDuration); + return this; + } + + public KSQLJoinWindow withBeforeTimeUnit(TimeUnit beforeTimeUnit) { + this.setBeforeTimeUnit(beforeTimeUnit); + return this; + } + + public KSQLJoinWindow withAfterDuration(long afterDuration) { + this.setAfterDuration(afterDuration); + return this; + } + + public KSQLJoinWindow withAfterTimeUnit(TimeUnit afterTimeUnit) { + this.setAfterTimeUnit(afterTimeUnit); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/KSQLWindow.java b/src/main/java/net/sf/jsqlparser/statement/select/KSQLWindow.java index 620cb1424c..133bd3bdf5 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/KSQLWindow.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/KSQLWindow.java @@ -130,4 +130,25 @@ public String toString() { return "TUMBLING (" + "SIZE " + sizeDuration + " " + sizeTimeUnit + ")"; } } + + public KSQLWindow withSizeDuration(long sizeDuration) { + this.setSizeDuration(sizeDuration); + return this; + } + + public KSQLWindow withSizeTimeUnit(TimeUnit sizeTimeUnit) { + this.setSizeTimeUnit(sizeTimeUnit); + return this; + } + + public KSQLWindow withAdvanceDuration(long advanceDuration) { + this.setAdvanceDuration(advanceDuration); + return this; + } + + public KSQLWindow withAdvanceTimeUnit(TimeUnit advanceTimeUnit) { + this.setAdvanceTimeUnit(advanceTimeUnit); + return this; + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/LateralSubSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/LateralSubSelect.java index fb9bde2620..8c2feb093a 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/LateralSubSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/LateralSubSelect.java @@ -9,6 +9,8 @@ */ package net.sf.jsqlparser.statement.select; +import net.sf.jsqlparser.expression.Alias; + /** * lateral sub select * @author tobens @@ -23,4 +25,25 @@ public LateralSubSelect() { public void accept(FromItemVisitor fromItemVisitor) { fromItemVisitor.visit(this); } + + @Override + public LateralSubSelect withPivot(Pivot pivot) { + return (LateralSubSelect) super.withPivot(pivot); + } + + @Override + public LateralSubSelect withAlias(Alias alias) { + return (LateralSubSelect) super.withAlias(alias); + } + + @Override + public LateralSubSelect withSubSelect(SubSelect subSelect) { + return (LateralSubSelect) super.withSubSelect(subSelect); + } + + @Override + public LateralSubSelect withUnPivot(UnPivot unpivot) { + return (LateralSubSelect) super.withUnPivot(unpivot); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Limit.java b/src/main/java/net/sf/jsqlparser/statement/select/Limit.java index 3ddd975b3a..80384abeff 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Limit.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Limit.java @@ -71,4 +71,32 @@ public String toString() { return retVal; } + + public Limit withRowCount(Expression rowCount) { + this.setRowCount(rowCount); + return this; + } + + public Limit withOffset(Expression offset) { + this.setOffset(offset); + return this; + } + + public Limit withLimitAll(boolean limitAll) { + this.setLimitAll(limitAll); + return this; + } + + public Limit withLimitNull(boolean limitNull) { + this.setLimitNull(limitNull); + return this; + } + + public E getOffset(Class type) { + return type.cast(getOffset()); + } + + public E getRowCount(Class type) { + return type.cast(getRowCount()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Offset.java b/src/main/java/net/sf/jsqlparser/statement/select/Offset.java index 310226c0fa..0f4c01648f 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Offset.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Offset.java @@ -51,4 +51,18 @@ public void setOffsetJdbcParameter(JdbcNamedParameter jdbc) { public String toString() { return " OFFSET " + (offsetJdbcParameter!=null ? offsetJdbcParameter.toString() : offset) + (offsetParam != null ? " " + offsetParam : ""); } + + public Offset withOffset(long offset) { + this.setOffset(offset); + return this; + } + + public Offset withOffsetParam(String offsetParam) { + this.setOffsetParam(offsetParam); + return this; + } + + public E getOffsetJdbcParameter(Class type) { + return type.cast(getOffsetJdbcParameter()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/OptimizeFor.java b/src/main/java/net/sf/jsqlparser/statement/select/OptimizeFor.java index d10d11612e..9c8bbb6d21 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/OptimizeFor.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/OptimizeFor.java @@ -32,4 +32,9 @@ public void setRowCount(long l) { public String toString() { return " OPTIMIZE FOR " + rowCount + " ROWS"; } + + public OptimizeFor withRowCount(long rowCount) { + this.setRowCount(rowCount); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/OrderByElement.java b/src/main/java/net/sf/jsqlparser/statement/select/OrderByElement.java index 60a953a87f..c7e376267d 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/OrderByElement.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/OrderByElement.java @@ -77,4 +77,24 @@ public String toString() { } return b.toString(); } + + public OrderByElement withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public OrderByElement withAsc(boolean asc) { + this.setAsc(asc); + return this; + } + + public OrderByElement withNullOrdering(NullOrdering nullOrdering) { + this.setNullOrdering(nullOrdering); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/ParenthesisFromItem.java b/src/main/java/net/sf/jsqlparser/statement/select/ParenthesisFromItem.java index 8ed4eeabaf..4617ba5634 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/ParenthesisFromItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/ParenthesisFromItem.java @@ -9,12 +9,12 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.expression.*; +import net.sf.jsqlparser.expression.Alias; public class ParenthesisFromItem implements FromItem { private FromItem fromItem; - + private Alias alias; public ParenthesisFromItem() { @@ -39,7 +39,7 @@ public void accept(FromItemVisitor fromItemVisitor) { @Override public String toString() { - return "(" + fromItem + ")" + (alias!=null?alias.toString():""); + return "(" + fromItem + ")" + (alias != null ? alias.toString() : ""); } @Override @@ -71,4 +71,19 @@ public UnPivot getUnPivot() { public void setUnPivot(UnPivot unpivot) { throw new UnsupportedOperationException("Not supported yet."); } + + public ParenthesisFromItem withFromItem(FromItem fromItem) { + this.setFromItem(fromItem); + return this; + } + + @Override + public ParenthesisFromItem withAlias(Alias alias) { + this.setAlias(alias); + return this; + } + + public E getFromItem(Class type) { + return type.cast(getFromItem()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Pivot.java b/src/main/java/net/sf/jsqlparser/statement/select/Pivot.java index 191ca0b142..f3318ee5fc 100755 --- a/src/main/java/net/sf/jsqlparser/statement/select/Pivot.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Pivot.java @@ -9,10 +9,13 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.schema.Column; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.schema.Column; public class Pivot { @@ -79,4 +82,77 @@ public String toString() { + " IN " + PlainSelect.getStringList(getInItems(), true, true) + ")" + (alias!=null?alias.toString():""); } + + public Pivot withFunctionItems(List functionItems) { + this.setFunctionItems(functionItems); + return this; + } + + public Pivot withForColumns(List forColumns) { + this.setForColumns(forColumns); + return this; + } + + public Pivot withSingleInItems(List singleInItems) { + this.setSingleInItems(singleInItems); + return this; + } + + public Pivot withMultiInItems(List multiInItems) { + this.setMultiInItems(multiInItems); + return this; + } + + public Pivot withAlias(Alias alias) { + this.setAlias(alias); + return this; + } + + public Pivot addFunctionItems(FunctionItem... functionItems) { + List collection = Optional.ofNullable(getFunctionItems()).orElseGet(ArrayList::new); + Collections.addAll(collection, functionItems); + return this.withFunctionItems(collection); + } + + public Pivot addFunctionItems(Collection functionItems) { + List collection = Optional.ofNullable(getFunctionItems()).orElseGet(ArrayList::new); + collection.addAll(functionItems); + return this.withFunctionItems(collection); + } + + public Pivot addForColumns(Column... forColumns) { + List collection = Optional.ofNullable(getForColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, forColumns); + return this.withForColumns(collection); + } + + public Pivot addForColumns(Collection forColumns) { + List collection = Optional.ofNullable(getForColumns()).orElseGet(ArrayList::new); + collection.addAll(forColumns); + return this.withForColumns(collection); + } + + public Pivot addSingleInItems(SelectExpressionItem... singleInItems) { + List collection = Optional.ofNullable(getSingleInItems()).orElseGet(ArrayList::new); + Collections.addAll(collection, singleInItems); + return this.withSingleInItems(collection); + } + + public Pivot addSingleInItems(Collection singleInItems) { + List collection = Optional.ofNullable(getSingleInItems()).orElseGet(ArrayList::new); + collection.addAll(singleInItems); + return this.withSingleInItems(collection); + } + + public Pivot addMultiInItems(ExpressionListItem... multiInItems) { + List collection = Optional.ofNullable(getMultiInItems()).orElseGet(ArrayList::new); + Collections.addAll(collection, multiInItems); + return this.withMultiInItems(collection); + } + + public Pivot addMultiInItems(Collection multiInItems) { + List collection = Optional.ofNullable(getMultiInItems()).orElseGet(ArrayList::new); + collection.addAll(multiInItems); + return this.withMultiInItems(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PivotXml.java b/src/main/java/net/sf/jsqlparser/statement/select/PivotXml.java index 51c1bde98f..fb9ad7ca4d 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PivotXml.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PivotXml.java @@ -9,10 +9,12 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.schema.Column; - +import java.util.Collection; import java.util.List; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.schema.Column; + public class PivotXml extends Pivot { private SelectBody inSelect; @@ -51,4 +53,83 @@ public String toString() { + " IN (" + in + "))"; } + public PivotXml withInSelect(SelectBody inSelect) { + this.setInSelect(inSelect); + return this; + } + + public PivotXml withInAny(boolean inAny) { + this.setInAny(inAny); + return this; + } + + public E getInSelect(Class type) { + return type.cast(getInSelect()); + } + + @Override + public PivotXml withAlias(Alias alias) { + return (PivotXml) super.withAlias(alias); + } + + @Override + public PivotXml withFunctionItems(List functionItems) { + return (PivotXml) super.withFunctionItems(functionItems); + } + + @Override + public PivotXml withForColumns(List forColumns) { + return (PivotXml) super.withForColumns(forColumns); + } + + @Override + public PivotXml withSingleInItems(List singleInItems) { + return (PivotXml) super.withSingleInItems(singleInItems); + } + + @Override + public PivotXml withMultiInItems(List multiInItems) { + return (PivotXml) super.withMultiInItems(multiInItems); + } + + @Override + public PivotXml addFunctionItems(Collection functionItems) { + return (PivotXml) super.addFunctionItems(functionItems); + } + + @Override + public PivotXml addFunctionItems(FunctionItem... functionItems) { + return (PivotXml) super.addFunctionItems(functionItems); + } + + @Override + public PivotXml addForColumns(Collection forColumns) { + return (PivotXml) super.addForColumns(forColumns); + } + + @Override + public PivotXml addForColumns(Column... forColumns) { + return (PivotXml) super.addForColumns(forColumns); + } + + @Override + public PivotXml addSingleInItems(Collection singleInItems) { + return (PivotXml) super.addSingleInItems(singleInItems); + } + + @Override + public PivotXml addSingleInItems(SelectExpressionItem... singleInItems) { + return (PivotXml) super.addSingleInItems(singleInItems); + } + + @Override + public PivotXml addMultiInItems(ExpressionListItem... multiInItems) { + return (PivotXml) super.addMultiInItems(multiInItems); + } + + @Override + public PivotXml addMultiInItems(Collection multiInItems) { + return (PivotXml) super.addMultiInItems(multiInItems); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java index bc86874e58..58f13f7c05 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/PlainSelect.java @@ -10,9 +10,11 @@ package net.sf.jsqlparser.statement.select; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.OracleHierarchicalExpression; import net.sf.jsqlparser.expression.OracleHint; @@ -75,6 +77,11 @@ public Expression getWhere() { return where; } + public PlainSelect withFromItem(FromItem item) { + this.setFromItem(item); + return this; + } + public void setFromItem(FromItem item) { fromItem = item; } @@ -83,15 +90,19 @@ public void setIntoTables(List
intoTables) { this.intoTables = intoTables; } + public PlainSelect withSelectItems(List list) { + this.setSelectItems(list); + return this; + } + public void setSelectItems(List list) { selectItems = list; } - public void addSelectItems(SelectItem... items) { - if (selectItems == null) { - selectItems = new ArrayList(); - } - Collections.addAll(selectItems, items); + public PlainSelect addSelectItems(SelectItem... items) { + List list = Optional.ofNullable(getSelectItems()).orElseGet(ArrayList::new); + Collections.addAll(list, items); + return withSelectItems(list); } public void setWhere(Expression where) { @@ -107,6 +118,17 @@ public List getJoins() { return joins; } + public PlainSelect addJoins(Join... joins) { + List list = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + Collections.addAll(list, joins); + return withJoins(list); + } + + public PlainSelect withJoins(List joins) { + this.setJoins(joins); + return this; + } + public void setJoins(List list) { joins = list; } @@ -205,8 +227,8 @@ public void setHaving(Expression expression) { } /** - * A list of {@link Expression}s of the GROUP BY clause. It is null in case there is no GROUP BY - * clause + * A list of {@link Expression}s of the GROUP BY clause. It is null in case + * there is no GROUP BY clause * * @return a list of {@link Expression}s */ @@ -218,11 +240,10 @@ public void setGroupByElement(GroupByElement groupBy) { this.groupBy = groupBy; } - public void addGroupByColumnReference(Expression expr) { - if (groupBy == null) { - groupBy = new GroupByElement(); - } + public PlainSelect addGroupByColumnReference(Expression expr) { + groupBy = Optional.ofNullable(groupBy).orElseGet(GroupByElement::new); groupBy.addGroupByExpression(expr); + return this; } public OracleHierarchicalExpression getOracleHierarchical() { @@ -406,7 +427,7 @@ public String toString() { sql.append(optimizeFor); } } else { - //without from + // without from if (where != null) { sql.append(" WHERE ").append(where); } @@ -447,8 +468,8 @@ public static String getFormatedList(List list, String expression, boolean us } /** - * List the toString out put of the objects in the List comma separated. If the List is null or - * empty an empty string is returned. + * List the toString out put of the objects in the List comma separated. If the + * List is null or empty an empty string is returned. * * The same as getStringList(list, true, false) * @@ -461,17 +482,17 @@ public static String getStringList(List list) { } /** - * List the toString out put of the objects in the List that can be comma separated. If the List - * is null or empty an empty string is returned. + * List the toString out put of the objects in the List that can be comma + * separated. If the List is null or empty an empty string is returned. * - * @param list list of objects with toString methods - * @param useComma true if the list has to be comma separated + * @param list list of objects with toString methods + * @param useComma true if the list has to be comma separated * @param useBrackets true if the list has to be enclosed in brackets * @return comma separated list of the elements in the list */ public static String getStringList(List list, boolean useComma, boolean useBrackets) { StringBuilder ans = new StringBuilder(); -// String ans = ""; + // String ans = ""; String comma = ","; if (!useComma) { comma = ""; @@ -479,23 +500,33 @@ public static String getStringList(List list, boolean useComma, boolean useBr if (list != null) { if (useBrackets) { ans.append("("); -// ans += "("; + // ans += "("; } for (int i = 0; i < list.size(); i++) { ans.append(list.get(i)).append((i < list.size() - 1) ? comma + " " : ""); -// ans += "" + list.get(i) + ((i < list.size() - 1) ? comma + " " : ""); + // ans += "" + list.get(i) + ((i < list.size() - 1) ? comma + " " : ""); } if (useBrackets) { ans.append(")"); -// ans += ")"; + // ans += ")"; } } return ans.toString(); } + public PlainSelect withMySqlSqlCalcFoundRows(boolean mySqlCalcFoundRows) { + this.setMySqlSqlCalcFoundRows(mySqlCalcFoundRows); + return this; + } + + public PlainSelect withMySqlSqlNoCache(boolean sqlNoCacheFlagSet) { + this.setMySqlSqlNoCache(sqlNoCacheFlagSet); + return this; + } + public void setMySqlSqlCalcFoundRows(boolean mySqlCalcFoundRows) { this.mySqlSqlCalcFoundRows = mySqlCalcFoundRows; } @@ -519,4 +550,167 @@ public void setNoWait(boolean noWait) { public boolean isNoWait() { return this.noWait; } + + public PlainSelect withDistinct(Distinct distinct) { + this.setDistinct(distinct); + return this; + } + + public PlainSelect withIntoTables(List
intoTables) { + this.setIntoTables(intoTables); + return this; + } + + public PlainSelect withWhere(Expression where) { + this.setWhere(where); + return this; + } + + public PlainSelect withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public PlainSelect withLimit(Limit limit) { + this.setLimit(limit); + return this; + } + + public PlainSelect withOffset(Offset offset) { + this.setOffset(offset); + return this; + } + + public PlainSelect withFetch(Fetch fetch) { + this.setFetch(fetch); + return this; + } + + public PlainSelect withOptimizeFor(OptimizeFor optimizeFor) { + this.setOptimizeFor(optimizeFor); + return this; + } + + public PlainSelect withSkip(Skip skip) { + this.setSkip(skip); + return this; + } + + public PlainSelect withMySqlHintStraightJoin(boolean mySqlHintStraightJoin) { + this.setMySqlHintStraightJoin(mySqlHintStraightJoin); + return this; + } + + public PlainSelect withFirst(First first) { + this.setFirst(first); + return this; + } + + public PlainSelect withTop(Top top) { + this.setTop(top); + return this; + } + + public PlainSelect withOracleHierarchical(OracleHierarchicalExpression oracleHierarchical) { + this.setOracleHierarchical(oracleHierarchical); + return this; + } + + public PlainSelect withOracleHint(OracleHint oracleHint) { + this.setOracleHint(oracleHint); + return this; + } + + public PlainSelect withOracleSiblings(boolean oracleSiblings) { + this.setOracleSiblings(oracleSiblings); + return this; + } + + public PlainSelect withForUpdate(boolean forUpdate) { + this.setForUpdate(forUpdate); + return this; + } + + public PlainSelect withForUpdateTable(Table forUpdateTable) { + this.setForUpdateTable(forUpdateTable); + return this; + } + + public PlainSelect withUseBrackets(boolean useBrackets) { + this.setUseBrackets(useBrackets); + return this; + } + + public PlainSelect withForXmlPath(String forXmlPath) { + this.setForXmlPath(forXmlPath); + return this; + } + + public PlainSelect withKsqlWindow(KSQLWindow ksqlWindow) { + this.setKsqlWindow(ksqlWindow); + return this; + } + + public PlainSelect withNoWait(boolean noWait) { + this.setNoWait(noWait); + return this; + } + + public PlainSelect withHaving(Expression having) { + this.setHaving(having); + return this; + } + + public PlainSelect withWait(Wait wait) { + this.setWait(wait); + return this; + } + + public PlainSelect addSelectItems(Collection selectItems) { + List collection = Optional.ofNullable(getSelectItems()).orElseGet(ArrayList::new); + collection.addAll(selectItems); + return this.withSelectItems(collection); + } + + public PlainSelect addIntoTables(Table... intoTables) { + List
collection = Optional.ofNullable(getIntoTables()).orElseGet(ArrayList::new); + Collections.addAll(collection, intoTables); + return this.withIntoTables(collection); + } + + public PlainSelect addIntoTables(Collection intoTables) { + List
collection = Optional.ofNullable(getIntoTables()).orElseGet(ArrayList::new); + collection.addAll(intoTables); + return this.withIntoTables(collection); + } + + public PlainSelect addJoins(Collection joins) { + List collection = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + collection.addAll(joins); + return this.withJoins(collection); + } + + public PlainSelect addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public PlainSelect addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } + + public E getFromItem(Class type) { + return type.cast(getFromItem()); + } + + public E getWhere(Class type) { + return type.cast(getWhere()); + } + + public E getHaving(Class type) { + return type.cast(getHaving()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Select.java b/src/main/java/net/sf/jsqlparser/statement/select/Select.java index 7a28e1cddd..b30a95c1e1 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Select.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Select.java @@ -9,9 +9,12 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -29,6 +32,11 @@ public SelectBody getSelectBody() { return selectBody; } + public Select withSelectBody(SelectBody body) { + setSelectBody(body); + return this; + } + public void setSelectBody(SelectBody body) { selectBody = body; } @@ -58,4 +66,25 @@ public List getWithItemsList() { public void setWithItemsList(List withItemsList) { this.withItemsList = withItemsList; } + + public Select withWithItemsList(List withItemsList) { + this.setWithItemsList(withItemsList); + return this; + } + + public E getSelectBody(Class type) { + return type.cast(getSelectBody()); + } + + public Select addWithItemsList(WithItem... withItemsList) { + List collection = Optional.ofNullable(getWithItemsList()).orElseGet(ArrayList::new); + Collections.addAll(collection, withItemsList); + return this.withWithItemsList(collection); + } + + public Select addWithItemsList(Collection withItemsList) { + List collection = Optional.ofNullable(getWithItemsList()).orElseGet(ArrayList::new); + collection.addAll(withItemsList); + return this.withWithItemsList(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SelectBody.java b/src/main/java/net/sf/jsqlparser/statement/select/SelectBody.java index bbe9c54514..8c9815d01e 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SelectBody.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SelectBody.java @@ -9,7 +9,9 @@ */ package net.sf.jsqlparser.statement.select; -public interface SelectBody { +import net.sf.jsqlparser.Model; + +public interface SelectBody extends Model { void accept(SelectVisitor selectVisitor); } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SelectExpressionItem.java b/src/main/java/net/sf/jsqlparser/statement/select/SelectExpressionItem.java index d7be09c63b..a0b8fde6dc 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SelectExpressionItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SelectExpressionItem.java @@ -50,4 +50,18 @@ public void accept(SelectItemVisitor selectItemVisitor) { public String toString() { return expression + ((alias != null) ? alias.toString() : ""); } + + public SelectExpressionItem withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public SelectExpressionItem withAlias(Alias alias) { + this.setAlias(alias); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SetOperationList.java b/src/main/java/net/sf/jsqlparser/statement/select/SetOperationList.java index 7a96b22765..6737634bc5 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SetOperationList.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SetOperationList.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; public class SetOperationList implements SelectBody { @@ -34,6 +38,14 @@ public List getSelects() { return selects; } + public void setSelects(List selects) { + this.selects = selects; + } + + public void setOperations(List operations) { + this.operations = operations; + } + public List getOperations() { return operations; } @@ -114,6 +126,89 @@ public String toString() { return buffer.toString(); } + public SetOperationList withOperations(List operationList) { + setOperations(operationList); + return this; + } + + public SetOperationList withSelects(List selects) { + setSelects(selects); + return this; + } + + public SetOperationList withBrackets(List brackets) { + this.setBrackets(brackets); + return this; + } + + public SetOperationList withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public SetOperationList withLimit(Limit limit) { + this.setLimit(limit); + return this; + } + + public SetOperationList withOffset(Offset offset) { + this.setOffset(offset); + return this; + } + + public SetOperationList withFetch(Fetch fetch) { + this.setFetch(fetch); + return this; + } + + public SetOperationList addSelects(SelectBody... selects) { + List collection = Optional.ofNullable(getSelects()).orElseGet(ArrayList::new); + Collections.addAll(collection, selects); + return this.withSelects(collection); + } + + public SetOperationList addSelects(Collection selects) { + List collection = Optional.ofNullable(getSelects()).orElseGet(ArrayList::new); + collection.addAll(selects); + return this.withSelects(collection); + } + + public SetOperationList addOperations(SetOperation... operationList) { + List collection = Optional.ofNullable(getOperations()).orElseGet(ArrayList::new); + Collections.addAll(collection, operationList); + return this.withOperations(collection); + } + + public SetOperationList addOperations(Collection operationList) { + List collection = Optional.ofNullable(getOperations()).orElseGet(ArrayList::new); + collection.addAll(operationList); + return this.withOperations(collection); + } + + public SetOperationList addBrackets(Boolean... brackets) { + List collection = Optional.ofNullable(getBrackets()).orElseGet(ArrayList::new); + Collections.addAll(collection, brackets); + return this.withBrackets(collection); + } + + public SetOperationList addBrackets(Collection brackets) { + List collection = Optional.ofNullable(getBrackets()).orElseGet(ArrayList::new); + collection.addAll(brackets); + return this.withBrackets(collection); + } + + public SetOperationList addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public SetOperationList addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } + public enum SetOperationType { INTERSECT, diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Skip.java b/src/main/java/net/sf/jsqlparser/statement/select/Skip.java index 13a6b838ee..f7af8f1f4b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Skip.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Skip.java @@ -55,4 +55,19 @@ public String toString() { return result; } + + public Skip withRowCount(Long rowCount) { + this.setRowCount(rowCount); + return this; + } + + public Skip withJdbcParameter(JdbcParameter jdbcParameter) { + this.setJdbcParameter(jdbcParameter); + return this; + } + + public Skip withVariable(String variable) { + this.setVariable(variable); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SpecialSubSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/SpecialSubSelect.java index 0d67959dc7..5622f3ecbb 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SpecialSubSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SpecialSubSelect.java @@ -76,4 +76,21 @@ public String toString() { + ((pivot != null) ? " " + pivot : "") + ((unpivot != null) ? " " + unpivot : ""); } + + public SpecialSubSelect withSubSelect(SubSelect subSelect) { + this.setSubSelect(subSelect); + return this; + } + + @Override + public SpecialSubSelect withAlias(Alias alias) { + this.setAlias(alias); + return this; + } + + @Override + public SpecialSubSelect withPivot(Pivot pivot) { + this.setPivot(pivot); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SubJoin.java b/src/main/java/net/sf/jsqlparser/statement/select/SubJoin.java index 24ceb2c17a..115a966d21 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SubJoin.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SubJoin.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Alias; public class SubJoin implements FromItem { @@ -29,6 +33,11 @@ public FromItem getLeft() { return left; } + public SubJoin left(FromItem l) { + setLeft(l); + return this; + } + public void setLeft(FromItem l) { left = l; } @@ -83,8 +92,44 @@ public String toString() { } } - sb.append(")").append((alias != null) ? (" " + alias.toString()) : "").append((pivot != null) ? " " + pivot : "") - .append((unpivot != null) ? " " + unpivot : ""); + sb.append(")").append((alias != null) ? (" " + alias.toString()) : "") + .append((pivot != null) ? " " + pivot : "").append((unpivot != null) ? " " + unpivot : ""); return sb.toString(); } + + @Override + public SubJoin withAlias(Alias alias) { + return (SubJoin) FromItem.super.withAlias(alias); + } + + @Override + public SubJoin withPivot(Pivot pivot) { + return (SubJoin) FromItem.super.withPivot(pivot); + } + + @Override + public SubJoin withUnPivot(UnPivot unpivot) { + return (SubJoin) FromItem.super.withUnPivot(unpivot); + } + + public SubJoin withJoinList(List joinList) { + this.setJoinList(joinList); + return this; + } + + public SubJoin addJoinList(Join... joinList) { + List collection = Optional.ofNullable(getJoinList()).orElseGet(ArrayList::new); + Collections.addAll(collection, joinList); + return this.withJoinList(collection); + } + + public SubJoin addJoinList(Collection joinList) { + List collection = Optional.ofNullable(getJoinList()).orElseGet(ArrayList::new); + collection.addAll(joinList); + return this.withJoinList(collection); + } + + public E getLeft(Class type) { + return type.cast(getLeft()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/SubSelect.java b/src/main/java/net/sf/jsqlparser/statement/select/SubSelect.java index 2078abfeb8..107b922ace 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/SubSelect.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/SubSelect.java @@ -9,8 +9,12 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Alias; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.ExpressionVisitor; @@ -131,4 +135,51 @@ public String toString() { return retval.toString(); } + + @Override + public SubSelect withAlias(Alias alias) { + this.setAlias(alias); + return this; + } + + public SubSelect withUseBrackets(boolean useBrackets) { + this.setUseBrackets(useBrackets); + return this; + } + + public SubSelect withItemsList(List withItemsList) { + this.setWithItemsList(withItemsList); + return this; + } + + public SubSelect withSelectBody(SelectBody selectBody) { + this.setSelectBody(selectBody); + return this; + } + + @Override + public SubSelect withPivot(Pivot pivot) { + return (SubSelect) FromItem.super.withPivot(pivot); + } + + @Override + public SubSelect withUnPivot(UnPivot unpivot) { + return (SubSelect) FromItem.super.withUnPivot(unpivot); + } + + public SubSelect addWithItemsList(WithItem... withItemsList) { + List collection = Optional.ofNullable(getWithItemsList()).orElseGet(ArrayList::new); + Collections.addAll(collection, withItemsList); + return this.withItemsList(collection); + } + + public SubSelect addWithItemsList(Collection withItemsList) { + List collection = Optional.ofNullable(getWithItemsList()).orElseGet(ArrayList::new); + collection.addAll(withItemsList); + return this.withItemsList(collection); + } + + public E getSelectBody(Class type) { + return type.cast(getSelectBody()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/TableFunction.java b/src/main/java/net/sf/jsqlparser/statement/select/TableFunction.java index 2b4085c8c8..a64a0c1b9e 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/TableFunction.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/TableFunction.java @@ -9,6 +9,9 @@ */ package net.sf.jsqlparser.statement.select; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.Function; + public class TableFunction extends FunctionItem implements FromItem { @Override @@ -23,6 +26,7 @@ public Pivot getPivot() { @Override public void setPivot(Pivot pivot) { + } @Override @@ -32,5 +36,27 @@ public UnPivot getUnPivot() { @Override public void setUnPivot(UnPivot unpivot) { + + } + + @Override + public TableFunction withAlias(Alias alias) { + return (TableFunction) FromItem.super.withAlias(alias); + } + + @Override + public TableFunction withFunction(Function function) { + return (TableFunction) super.withFunction(function); + } + + @Override + public TableFunction withPivot(Pivot pivot) { + return (TableFunction) FromItem.super.withPivot(pivot); } + + @Override + public TableFunction withUnPivot(UnPivot unpivot) { + return (TableFunction) FromItem.super.withUnPivot(unpivot); + } + } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Top.java b/src/main/java/net/sf/jsqlparser/statement/select/Top.java index f2f3ac521c..c783772adc 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Top.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Top.java @@ -61,4 +61,13 @@ public String toString() { return result; } + + public Top withExpression(Expression expression) { + this.setExpression(expression); + return this; + } + + public E getExpression(Class type) { + return type.cast(getExpression()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/UnPivot.java b/src/main/java/net/sf/jsqlparser/statement/select/UnPivot.java index 5af759d5e9..a4c0e105d3 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/UnPivot.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/UnPivot.java @@ -71,4 +71,9 @@ public String toString() { + " FOR " + PlainSelect.getStringList(unpivotForClause, true, unpivotForClause != null && unpivotForClause.size() > 1) + " IN " + PlainSelect.getStringList(unpivotInClause, true, true) + ")"; } + + public UnPivot withIncludeNulls(boolean includeNulls) { + this.setIncludeNulls(includeNulls); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/UnionOp.java b/src/main/java/net/sf/jsqlparser/statement/select/UnionOp.java index a9dd91e818..68271bcd6f 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/UnionOp.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/UnionOp.java @@ -46,4 +46,14 @@ public String toString() { } return super.toString() + allDistinct; } + + public UnionOp withDistinct(boolean distinct) { + this.setDistinct(distinct); + return this; + } + + public UnionOp withAll(boolean all) { + this.setAll(all); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/ValuesList.java b/src/main/java/net/sf/jsqlparser/statement/select/ValuesList.java index c8b0a7772a..9b5ca1fda7 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/ValuesList.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/ValuesList.java @@ -9,12 +9,15 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.expression.operators.relational.ExpressionList; -import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; public class ValuesList implements FromItem { @@ -116,4 +119,46 @@ public List getColumnNames() { public void setColumnNames(List columnNames) { this.columnNames = columnNames; } + + @Override + public ValuesList withAlias(Alias alias) { + return (ValuesList) FromItem.super.withAlias(alias); + } + + @Override + public ValuesList withPivot(Pivot pivot) { + return (ValuesList) FromItem.super.withPivot(pivot); + } + + @Override + public ValuesList withUnPivot(UnPivot unpivot) { + return (ValuesList) FromItem.super.withUnPivot(unpivot); + } + + public ValuesList withMultiExpressionList(MultiExpressionList multiExpressionList) { + this.setMultiExpressionList(multiExpressionList); + return this; + } + + public ValuesList withNoBrackets(boolean noBrackets) { + this.setNoBrackets(noBrackets); + return this; + } + + public ValuesList withColumnNames(List columnNames) { + this.setColumnNames(columnNames); + return this; + } + + public ValuesList addColumnNames(String... columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + Collections.addAll(collection, columnNames); + return this.withColumnNames(collection); + } + + public ValuesList addColumnNames(Collection columnNames) { + List collection = Optional.ofNullable(getColumnNames()).orElseGet(ArrayList::new); + collection.addAll(columnNames); + return this.withColumnNames(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/Wait.java b/src/main/java/net/sf/jsqlparser/statement/select/Wait.java index 984ee318a2..5045449a3f 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/Wait.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/Wait.java @@ -31,4 +31,9 @@ public void setTimeout(long timeout) { public String toString() { return " WAIT " + timeout; } + + public Wait withTimeout(long timeout) { + this.setTimeout(timeout); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/select/WithItem.java b/src/main/java/net/sf/jsqlparser/statement/select/WithItem.java index 6bba0498bc..8da329304b 100644 --- a/src/main/java/net/sf/jsqlparser/statement/select/WithItem.java +++ b/src/main/java/net/sf/jsqlparser/statement/select/WithItem.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.select; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; public class WithItem implements SelectBody { @@ -66,4 +70,40 @@ public String toString() { public void accept(SelectVisitor visitor) { visitor.visit(this); } + + public WithItem withName(String name) { + this.setName(name); + return this; + } + + public WithItem withWithItemList(List withItemList) { + this.setWithItemList(withItemList); + return this; + } + + public WithItem withSelectBody(SelectBody selectBody) { + this.setSelectBody(selectBody); + return this; + } + + public WithItem withRecursive(boolean recursive) { + this.setRecursive(recursive); + return this; + } + + public WithItem addWithItemList(SelectItem... withItemList) { + List collection = Optional.ofNullable(getWithItemList()).orElseGet(ArrayList::new); + Collections.addAll(collection, withItemList); + return this.withWithItemList(collection); + } + + public WithItem addWithItemList(Collection withItemList) { + List collection = Optional.ofNullable(getWithItemList()).orElseGet(ArrayList::new); + collection.addAll(withItemList); + return this.withWithItemList(collection); + } + + public E getSelectBody(Class type) { + return type.cast(getSelectBody()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/truncate/Truncate.java b/src/main/java/net/sf/jsqlparser/statement/truncate/Truncate.java index 94a7c95ae9..67d064249c 100644 --- a/src/main/java/net/sf/jsqlparser/statement/truncate/Truncate.java +++ b/src/main/java/net/sf/jsqlparser/statement/truncate/Truncate.java @@ -46,4 +46,14 @@ public String toString() { } return "TRUNCATE TABLE " + table; } + + public Truncate withTable(Table table) { + this.setTable(table); + return this; + } + + public Truncate withCascade(boolean cascade) { + this.setCascade(cascade); + return this; + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/update/Update.java b/src/main/java/net/sf/jsqlparser/statement/update/Update.java index 592db5d18d..8b3ece703c 100644 --- a/src/main/java/net/sf/jsqlparser/statement/update/Update.java +++ b/src/main/java/net/sf/jsqlparser/statement/update/Update.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.update; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; @@ -18,10 +21,10 @@ import net.sf.jsqlparser.statement.StatementVisitor; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.Limit; +import net.sf.jsqlparser.statement.select.OrderByElement; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; -import net.sf.jsqlparser.statement.select.OrderByElement; -import net.sf.jsqlparser.statement.select.Limit; import net.sf.jsqlparser.statement.select.SelectExpressionItem; public class Update implements Statement { @@ -231,4 +234,154 @@ public String toString() { return b.toString(); } + + public Update withTable(Table table) { + this.setTable(table); + return this; + } + + public Update withFromItem(FromItem fromItem) { + this.setFromItem(fromItem); + return this; + } + + public Update withJoins(List joins) { + this.setJoins(joins); + return this; + } + + public Update withStartJoins(List startJoins) { + this.setStartJoins(startJoins); + return this; + } + + public Update withSelect(Select select) { + this.setSelect(select); + return this; + } + + public Update withUseColumnsBrackets(boolean useColumnsBrackets) { + this.setUseColumnsBrackets(useColumnsBrackets); + return this; + } + + public Update withUseSelect(boolean useSelect) { + this.setUseSelect(useSelect); + return this; + } + + public Update withOrderByElements(List orderByElements) { + this.setOrderByElements(orderByElements); + return this; + } + + public Update withLimit(Limit limit) { + this.setLimit(limit); + return this; + } + + public Update withReturningAllColumns(boolean returningAllColumns) { + this.setReturningAllColumns(returningAllColumns); + return this; + } + + public Update withReturningExpressionList(List returningExpressionList) { + this.setReturningExpressionList(returningExpressionList); + return this; + } + + public Update withWhere(Expression where) { + this.setWhere(where); + return this; + } + + public Update withColumns(List columns) { + this.setColumns(columns); + return this; + } + + public Update withExpressions(List expressions) { + this.setExpressions(expressions); + return this; + } + + public Update addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public Update addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public Update addExpressions(Expression... expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, expressions); + return this.withExpressions(collection); + } + + public Update addExpressions(Collection expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + collection.addAll(expressions); + return this.withExpressions(collection); + } + + public Update addJoins(Join... joins) { + List collection = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + Collections.addAll(collection, joins); + return this.withJoins(collection); + } + + public Update addJoins(Collection joins) { + List collection = Optional.ofNullable(getJoins()).orElseGet(ArrayList::new); + collection.addAll(joins); + return this.withJoins(collection); + } + + public Update addStartJoins(Join... startJoins) { + List collection = Optional.ofNullable(getStartJoins()).orElseGet(ArrayList::new); + Collections.addAll(collection, startJoins); + return this.withStartJoins(collection); + } + + public Update addStartJoins(Collection startJoins) { + List collection = Optional.ofNullable(getStartJoins()).orElseGet(ArrayList::new); + collection.addAll(startJoins); + return this.withStartJoins(collection); + } + + public Update addOrderByElements(OrderByElement... orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + Collections.addAll(collection, orderByElements); + return this.withOrderByElements(collection); + } + + public Update addOrderByElements(Collection orderByElements) { + List collection = Optional.ofNullable(getOrderByElements()).orElseGet(ArrayList::new); + collection.addAll(orderByElements); + return this.withOrderByElements(collection); + } + + public Update addReturningExpressionList(SelectExpressionItem... returningExpressionList) { + List collection = Optional.ofNullable(getReturningExpressionList()).orElseGet(ArrayList::new); + Collections.addAll(collection, returningExpressionList); + return this.withReturningExpressionList(collection); + } + + public Update addReturningExpressionList(Collection returningExpressionList) { + List collection = Optional.ofNullable(getReturningExpressionList()).orElseGet(ArrayList::new); + collection.addAll(returningExpressionList); + return this.withReturningExpressionList(collection); + } + + public E getWhere(Class type) { + return type.cast(getWhere()); + } + + public E getFromItem(Class type) { + return type.cast(getFromItem()); + } } diff --git a/src/main/java/net/sf/jsqlparser/statement/upsert/Upsert.java b/src/main/java/net/sf/jsqlparser/statement/upsert/Upsert.java index f8f7d2e0b5..31d5343741 100644 --- a/src/main/java/net/sf/jsqlparser/statement/upsert/Upsert.java +++ b/src/main/java/net/sf/jsqlparser/statement/upsert/Upsert.java @@ -9,8 +9,11 @@ */ package net.sf.jsqlparser.statement.upsert; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; - +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.schema.Column; @@ -150,5 +153,88 @@ public String toString() { return sb.toString(); } -} + public Upsert withUseValues(boolean useValues) { + this.setUseValues(useValues); + return this; + } + + public Upsert withSelect(Select select) { + this.setSelect(select); + return this; + } + + public Upsert withUseSelectBrackets(boolean useSelectBrackets) { + this.setUseSelectBrackets(useSelectBrackets); + return this; + } + + public Upsert withUseDuplicate(boolean useDuplicate) { + this.setUseDuplicate(useDuplicate); + return this; + } + + public Upsert withDuplicateUpdateColumns(List duplicateUpdateColumns) { + this.setDuplicateUpdateColumns(duplicateUpdateColumns); + return this; + } + + public Upsert withDuplicateUpdateExpressionList(List duplicateUpdateExpressionList) { + this.setDuplicateUpdateExpressionList(duplicateUpdateExpressionList); + return this; + } + + public Upsert withTable(Table table) { + this.setTable(table); + return this; + } + + public Upsert withColumns(List columns) { + this.setColumns(columns); + return this; + } + public Upsert withItemsList(ItemsList itemsList) { + this.setItemsList(itemsList); + return this; + } + + public Upsert addColumns(Column... columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, columns); + return this.withColumns(collection); + } + + public Upsert addColumns(Collection columns) { + List collection = Optional.ofNullable(getColumns()).orElseGet(ArrayList::new); + collection.addAll(columns); + return this.withColumns(collection); + } + + public Upsert addDuplicateUpdateColumns(Column... duplicateUpdateColumns) { + List collection = Optional.ofNullable(getDuplicateUpdateColumns()).orElseGet(ArrayList::new); + Collections.addAll(collection, duplicateUpdateColumns); + return this.withDuplicateUpdateColumns(collection); + } + + public Upsert addDuplicateUpdateColumns(Collection duplicateUpdateColumns) { + List collection = Optional.ofNullable(getDuplicateUpdateColumns()).orElseGet(ArrayList::new); + collection.addAll(duplicateUpdateColumns); + return this.withDuplicateUpdateColumns(collection); + } + + public Upsert addDuplicateUpdateExpressionList(Expression... duplicateUpdateExpressionList) { + List collection = Optional.ofNullable(getDuplicateUpdateExpressionList()).orElseGet(ArrayList::new); + Collections.addAll(collection, duplicateUpdateExpressionList); + return this.withDuplicateUpdateExpressionList(collection); + } + + public Upsert addDuplicateUpdateExpressionList(Collection duplicateUpdateExpressionList) { + List collection = Optional.ofNullable(getDuplicateUpdateExpressionList()).orElseGet(ArrayList::new); + collection.addAll(duplicateUpdateExpressionList); + return this.withDuplicateUpdateExpressionList(collection); + } + + public E getItemsList(Class type) { + return type.cast(getItemsList()); + } +} diff --git a/src/main/java/net/sf/jsqlparser/statement/values/ValuesStatement.java b/src/main/java/net/sf/jsqlparser/statement/values/ValuesStatement.java index 4d34792ab1..9be0893938 100644 --- a/src/main/java/net/sf/jsqlparser/statement/values/ValuesStatement.java +++ b/src/main/java/net/sf/jsqlparser/statement/values/ValuesStatement.java @@ -9,7 +9,11 @@ */ package net.sf.jsqlparser.statement.values; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Optional; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; @@ -20,7 +24,11 @@ public class ValuesStatement implements Statement, SelectBody { private List expressions; - + + public ValuesStatement() { + // empty constructor + } + public ValuesStatement(List expressions) { this.expressions = expressions; } @@ -34,8 +42,8 @@ public List getExpressions() { return expressions; } - public void setExpressions(List list) { - expressions = list; + public void setExpressions(List expressions) { + this.expressions = expressions; } @Override @@ -50,4 +58,21 @@ public String toString() { public void accept(SelectVisitor selectVisitor) { selectVisitor.visit(this); } + + public ValuesStatement withExpressions(List expressions) { + this.setExpressions(expressions); + return this; + } + + public ValuesStatement addExpressions(Expression... expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + Collections.addAll(collection, expressions); + return this.withExpressions(collection); + } + + public ValuesStatement addExpressions(Collection expressions) { + List collection = Optional.ofNullable(getExpressions()).orElseGet(ArrayList::new); + collection.addAll(expressions); + return this.withExpressions(collection); + } } diff --git a/src/main/java/net/sf/jsqlparser/util/SelectUtils.java b/src/main/java/net/sf/jsqlparser/util/SelectUtils.java index 744cd1b399..5e1efc6d12 100644 --- a/src/main/java/net/sf/jsqlparser/util/SelectUtils.java +++ b/src/main/java/net/sf/jsqlparser/util/SelectUtils.java @@ -9,8 +9,6 @@ */ package net.sf.jsqlparser.util; -import java.util.ArrayList; -import java.util.List; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.parser.CCJSqlParserUtil; @@ -21,10 +19,6 @@ import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectExpressionItem; import net.sf.jsqlparser.statement.select.SelectItem; -import net.sf.jsqlparser.statement.select.SelectVisitor; -import net.sf.jsqlparser.statement.select.SetOperationList; -import net.sf.jsqlparser.statement.select.WithItem; -import net.sf.jsqlparser.statement.values.ValuesStatement; public final class SelectUtils { @@ -50,12 +44,8 @@ public static Select buildSelectFromTableAndExpressions(Table table, String... e } public static Select buildSelectFromTableAndSelectItems(Table table, SelectItem... selectItems) { - Select select = new Select(); - PlainSelect body = new PlainSelect(); - body.addSelectItems(selectItems); - body.setFromItem(table); - select.setSelectBody(body); - return select; + PlainSelect body = new PlainSelect().addSelectItems(selectItems).withFromItem(table); + return new Select().withSelectBody(body); } /** @@ -75,28 +65,11 @@ public static Select buildSelectFromTable(Table table) { * @param expr */ public static void addExpression(Select select, final Expression expr) { - select.getSelectBody().accept(new SelectVisitor() { - - @Override - public void visit(PlainSelect plainSelect) { - plainSelect.getSelectItems().add(new SelectExpressionItem(expr)); - } - - @Override - public void visit(SetOperationList setOpList) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - - @Override - public void visit(WithItem withItem) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - - @Override - public void visit(ValuesStatement aThis) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - }); + if (select.getSelectBody() instanceof PlainSelect) { + select.getSelectBody(PlainSelect.class).getSelectItems().add(new SelectExpressionItem(expr)); + } else { + throw new UnsupportedOperationException(NOT_SUPPORTED_YET); + } } /** @@ -110,19 +83,12 @@ public void visit(ValuesStatement aThis) { */ public static Join addJoin(Select select, final Table table, final Expression onExpression) { if (select.getSelectBody() instanceof PlainSelect) { - PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); - List joins = plainSelect.getJoins(); - if (joins == null) { - joins = new ArrayList(); - plainSelect.setJoins(joins); - } - Join join = new Join(); - join.setRightItem(table); - join.setOnExpression(onExpression); - joins.add(join); + Join join = new Join().withRightItem(table).withOnExpression(onExpression); + select.getSelectBody(PlainSelect.class).addJoins(join); return join; + } else { + throw new UnsupportedOperationException(NOT_SUPPORTED_YET); } - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); } /** @@ -132,27 +98,10 @@ public static Join addJoin(Select select, final Table table, final Expression on * @param expr */ public static void addGroupBy(Select select, final Expression expr) { - select.getSelectBody().accept(new SelectVisitor() { - - @Override - public void visit(PlainSelect plainSelect) { - plainSelect.addGroupByColumnReference(expr); - } - - @Override - public void visit(SetOperationList setOpList) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - - @Override - public void visit(WithItem withItem) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - - @Override - public void visit(ValuesStatement aThis) { - throw new UnsupportedOperationException(NOT_SUPPORTED_YET); - } - }); + if (select.getSelectBody() instanceof PlainSelect) { + select.getSelectBody(PlainSelect.class).addGroupByColumnReference(expr); + } else { + throw new UnsupportedOperationException(NOT_SUPPORTED_YET); + } } } diff --git a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt index 9246c2d3ad..9b1f4b37f7 100644 --- a/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt +++ b/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt @@ -533,8 +533,8 @@ Statement SingleStatement() : Block Block() #Block : { Statements stmts = new Statements(); - List list = new ArrayList(); - Statement stm; + List list = new ArrayList(); + Statement stm; Block block = new Block(); } { @@ -547,9 +547,9 @@ Block Block() #Block : { if (errorRecovery) { parseErrors.add(e); error_skipto(ST_SEMICOLON); - } - else + } else { throw e; + } } { stmts.setStatements(list); @@ -561,10 +561,11 @@ Block Block() #Block : { } } -Statements Statements() #Statements : -{ Statements stmts = new Statements(); - List list = new ArrayList(); - Statement stm; } +Statements Statements() #Statements : { + Statements stmts = new Statements(); + List list = new ArrayList(); + Statement stm; +} { ()* try { @@ -575,13 +576,12 @@ Statements Statements() #Statements : if (errorRecovery) { parseErrors.add(e); error_skipto(ST_SEMICOLON); - } - else + } else { throw e; + } } { - stmts.setStatements(list); - return stmts; + return stmts.withStatements(list); } } @@ -606,20 +606,26 @@ DeclareStatement Declare(): { userVariable = UserVariable() ( ( "(" colDef = ColumnDefinition() - { stmt.setUserVariable(userVariable); - stmt.setDeclareType(DeclareType.TABLE); - stmt.addColumnDefinition(colDef); } + { + stmt.withUserVariable(userVariable) + .withDeclareType(DeclareType.TABLE) + .addColumnDefinition(colDef); + } ("," colDef = ColumnDefinition() { stmt.addColumnDefinition(colDef); })* ")" ) | typeName = RelObjectName() - { stmt.setUserVariable(userVariable); - stmt.setDeclareType(DeclareType.AS); - stmt.setTypeName(typeName); } + { + stmt.withUserVariable(userVariable) + .withDeclareType(DeclareType.AS) + .withTypeName(typeName); + } | (colDataType = ColDataType() ["=" defaultExpr = Expression()] - { stmt.setDeclareType(DeclareType.TYPE); - stmt.addType(userVariable, colDataType, defaultExpr); } + { + stmt.withDeclareType(DeclareType.TYPE) + .addType(userVariable, colDataType, defaultExpr); + } ("," userVariable = UserVariable() colDataType = ColDataType() { defaultExpr = null; } ["=" defaultExpr = Expression()] { stmt.addType(userVariable, colDataType, defaultExpr); } )* ) @@ -639,7 +645,7 @@ SetStatement Set(): { } { name = RelObjectNameExt() ["=" { useEqual=true; } ] value=SimpleExpression() - { set = new SetStatement(name,value).setUseEqual(useEqual); } + { set = new SetStatement(name,value).withUseEqual(useEqual); } ( { useEqual=false; } "," name = RelObjectNameExt() ["=" { useEqual=true; } ] value=SimpleExpression() { set.add(name, value, useEqual); } )* @@ -892,16 +898,15 @@ Update Update(): ] { - update.setColumns(columns); - update.setExpressions(expList); - update.setTable(table); - update.setStartJoins(startJoins); - update.setFromItem(fromItem); - update.setJoins(joins); - update.setSelect(select); - update.setUseColumnsBrackets(useColumnsBrackets); - update.setReturningExpressionList(returning); - return update; + return update.withColumns(columns) + .withExpressions(expList) + .withTable(table) + .withStartJoins(startJoins) + .withFromItem(fromItem) + .withJoins(joins) + .withSelect(select) + .withUseColumnsBrackets(useColumnsBrackets) + .withReturningExpressionList(returning); } } @@ -956,10 +961,10 @@ Replace Replace(): ) ) { - if (columns.size() > 0) - replace.setColumns(columns); - replace.setTable(table); - return replace; + if (!columns.isEmpty()) { + replace.withColumns(columns); + } + return replace.withTable(table); } } @@ -1080,22 +1085,22 @@ Insert Insert(): ] { - insert.setItemsList(itemsList); - insert.setUseSelectBrackets(useSelectBrackets); - insert.setSelect(select); - insert.setTable(table); - if (columns.size() > 0) + if (!columns.isEmpty()) { insert.setColumns(columns); - insert.setUseDuplicate(useDuplicate); - insert.setDuplicateUpdateColumns(duplicateUpdateColumns); - insert.setDuplicateUpdateExpressionList(duplicateUpdateExpressionList); - insert.setReturningExpressionList(returning); - insert.setModifierPriority(modifierPriority); - insert.setModifierIgnore(modifierIgnore); - insert.setUseSet(useSet); - insert.setSetColumns(setColumns); - insert.setSetExpressionList(setExpressionList); - return insert; + } + return insert.withItemsList(itemsList) + .withUseSelectBrackets(useSelectBrackets) + .withSelect(select) + .withTable(table) + .withUseDuplicate(useDuplicate) + .withDuplicateUpdateColumns(duplicateUpdateColumns) + .withDuplicateUpdateExpressionList(duplicateUpdateExpressionList) + .withReturningExpressionList(returning) + .withModifierPriority(modifierPriority) + .withModifierIgnore(modifierIgnore) + .withUseSet(useSet) + .withUseSetColumns(setColumns) + .withSetExpressionList(setExpressionList); } } @@ -1163,17 +1168,16 @@ Upsert Upsert(): duplicateUpdateExpressionList.add(exp); } )*] { - upsert.setItemsList(itemsList); - upsert.setUseSelectBrackets(useSelectBrackets); - upsert.setSelect(select); - upsert.setTable(table); - if (columns.size() > 0) { + if (columns.size() > 0) { upsert.setColumns(columns); } - upsert.setUseDuplicate(useDuplicate); - upsert.setDuplicateUpdateColumns(duplicateUpdateColumns); - upsert.setDuplicateUpdateExpressionList(duplicateUpdateExpressionList); - return upsert; + return upsert.withItemsList(itemsList) + .withUseSelectBrackets(useSelectBrackets) + .withSelect(select) + .withTable(table) + .withUseDuplicate(useDuplicate) + .withDuplicateUpdateColumns(duplicateUpdateColumns) + .withDuplicateUpdateExpressionList(duplicateUpdateExpressionList); } } @@ -1197,11 +1201,10 @@ Delete Delete(): [orderByElements = OrderByElements() { delete.setOrderByElements(orderByElements); } ] [limit=PlainLimit() {delete.setLimit(limit); } ] { - delete.setTables(tables); - if (joins != null && joins.size() > 0) + if (joins != null && joins.size() > 0) { delete.setJoins(joins); - delete.setTable(table); - return delete; + } + return delete.withTables(tables).withTable(table); } } @@ -1225,7 +1228,7 @@ Statement Merge() : { [ ( LOOKAHEAD(2) update = MergeUpdateClause() { merge.setMergeUpdate(update); } [ insert = MergeInsertClause() { merge.setMergeInsert(insert); } ] - | insert = MergeInsertClause() { merge.setMergeInsert(insert); merge.setInsertFirst(true); } + | insert = MergeInsertClause() { merge.withMergeInsert(insert).withInsertFirst(true); } [ update = MergeUpdateClause() { merge.setMergeUpdate(update); } ] ) ] @@ -1253,7 +1256,7 @@ MergeUpdate MergeUpdateClause() : { { columns.add(col); expList.add(exp); } ("," col = Column() "=" exp = SimpleExpression() { columns.add(col); expList.add(exp); } )* - { mu.setColumns(columns); mu.setValues(expList); } + { mu.withColumns(columns).withValues(expList); } [ condition = Expression() { mu.setWhereCondition(condition); }] [ condition = Expression() { mu.setDeleteWhereCondition(condition); } ] @@ -1273,9 +1276,7 @@ MergeInsert MergeInsertClause() : { ["(" col=Column() { columns.add(col); } ("," col=Column() { columns.add(col); } )* ")"] "(" exp=SimpleExpression() { expList.add(exp); } ("," exp=SimpleExpression() { expList.add(exp); } )* ")" { - mi.setColumns(columns); - mi.setValues(expList); - return mi; + return mi.withColumns(columns).withValues(expList); } } @@ -1425,9 +1426,7 @@ Select Select(): { [ with=WithList() { } ] selectBody = SelectBody() { - select.setWithItemsList(with); - select.setSelectBody(selectBody); - return select; + return select.withWithItemsList(with).withSelectBody(selectBody); } } @@ -1742,11 +1741,11 @@ String Identifier(): { return tk.image; } } -FunctionItem FunctionItem(): + FunctionItem FunctionItem(): { Alias alias = null; Function function; - FunctionItem functionItem; + FunctionItem functionItem; } { function=Function() { functionItem = new FunctionItem(); functionItem.setFunction(function); } @@ -1771,7 +1770,7 @@ List PivotForColumns(): List PivotFunctionItems(): { - List functionItems = new ArrayList(); + List< FunctionItem> functionItems = new ArrayList< FunctionItem>(); FunctionItem item; } { @@ -2056,7 +2055,7 @@ List JoinsList(): { return joinsList; } } -List SubJoinsList(): +List SubJoinsList(): { List joinsList = new ArrayList(); Join join = null; @@ -2102,7 +2101,7 @@ Join JoinerExpression() #JoinerExpression: LOOKAHEAD(2) ([ "(" joinWindow = JoinWindow() ")" {join.setJoinWindow(joinWindow);}] ( onExpression=Expression() { join.setOnExpression(onExpression); }) | - ( "(" tableColumn=Column() { columns = new ArrayList(); columns.add(tableColumn); } + ( "(" tableColumn=Column() { columns = new ArrayList(); columns.add(tableColumn); } ("," tableColumn=Column() { columns.add(tableColumn); } )* ")" { join.setUsingColumns(columns); } )) ] @@ -2651,7 +2650,7 @@ Expression RegularCondition() #RegularCondition: [ "(" "+" ")" { oracleJoin=EqualsTo.ORACLE_JOIN_LEFT; } ] { - BinaryExpression regCond = (BinaryExpression) result; + BinaryExpression regCond = (BinaryExpression) result; regCond.setLeftExpression(leftExpression); regCond.setRightExpression(rightExpression); @@ -3096,7 +3095,7 @@ Expression BitwiseAndOr(): rightExpression=AdditiveExpression() { - BinaryExpression binExp = (BinaryExpression) result; + BinaryExpression binExp = (BinaryExpression) result; binExp.setLeftExpression(leftExpression); binExp.setRightExpression(rightExpression); leftExpression = result; @@ -3120,7 +3119,7 @@ Expression AdditiveExpression(): rightExpression=MultiplicativeExpression() { - BinaryExpression binExp = (BinaryExpression) result; + BinaryExpression binExp = (BinaryExpression) result; binExp.setLeftExpression(leftExpression); binExp.setRightExpression(rightExpression); leftExpression = result; @@ -3151,7 +3150,7 @@ Expression MultiplicativeExpression(): rightExpression=BitwiseXor() { - BinaryExpression binExp = (BinaryExpression) result; + BinaryExpression binExp = (BinaryExpression) result; binExp.setLeftExpression(leftExpression); binExp.setRightExpression(rightExpression); leftExpression = result; @@ -3811,7 +3810,9 @@ TableFunction TableFunction(): TableFunction functionItem; } { - function=Function() { functionItem = new TableFunction(); functionItem.setFunction(function); } + function=Function() { + functionItem = new TableFunction().withFunction(function); + } [LOOKAHEAD(2) alias=Alias() { functionItem.setAlias(alias); }] { return functionItem; } } @@ -3897,7 +3898,7 @@ CreateIndex CreateIndex(): [ tailParameter = CreateParameter() {} ] { - index.setColumnNamesWithParams(colNames); + index.setColumns(colNames); createIndex.setIndex(index); createIndex.setTable(table); createIndex.setTailParameters(tailParameter); @@ -3986,8 +3987,8 @@ CreateTable CreateTable(): { CreateTable createTable = new CreateTable(); Table table = null; - List columnDefinitions = new ArrayList(); - List columnSpecs = null; + List columnDefinitions = new ArrayList(); + List columnSpecs = null; List tableOptions = new ArrayList(); List createOptions = new ArrayList(); String columnName; @@ -3998,7 +3999,7 @@ CreateTable CreateTable(): ColDataType colDataType = null; String stringList = null; ColumnDefinition coldef = null; - List indexes = new ArrayList(); + List indexes = new ArrayList(); List colNames = null; List colNames2 = null; Index index = null; @@ -4042,10 +4043,7 @@ CreateTable CreateTable(): /* colNames=ColumnsNamesList() */ colNames = ColumnNamesWithParamsList() { - index = new Index(); - index.setType(tk.image); - index.setName(sk3); - index.setColumnNamesWithParams(colNames); + index = new Index().withType(tk.image).withName(sk3).withColumns(colNames); indexes.add(index); } ) @@ -4063,8 +4061,7 @@ CreateTable CreateTable(): colNames = ColumnNamesWithParamsList() ( parameter=CreateParameter() { idxSpec.addAll(parameter); } )* { - index.setColumnNamesWithParams(colNames); - index.setIndexSpec(idxSpec); + index.withColumns(colNames).withIndexSpec(idxSpec); indexes.add(index); } ) @@ -4076,11 +4073,11 @@ CreateTable CreateTable(): colNames = ColumnNamesWithParamsList() ( parameter=CreateParameter() { idxSpec.addAll(parameter); } )* { - index = new Index(); - index.setType((tk!=null?tk.image + " ":"") + (tk3!=null?tk3.image + " ":"") + tk2.image); - index.setName(sk3); - index.setColumnNamesWithParams(colNames); - index.setIndexSpec(idxSpec); + index = new Index() + .withType((tk!=null?tk.image + " ":"") + (tk3!=null?tk3.image + " ":"") + tk2.image) + .withName(sk3) + .withColumns(colNames) + .withIndexSpec(idxSpec); indexes.add(index); } ) @@ -4094,8 +4091,7 @@ CreateTable CreateTable(): /* colNames=ColumnsNamesList() */ colNames = ColumnNamesWithParamsList() { - fkIndex.setType(tk.image + " " + tk2.image); - fkIndex.setColumnNamesWithParams(colNames); + fkIndex.withType(tk.image + " " + tk2.image).withColumns(colNames); } fkTable=Table() colNames2=ColumnsNamesList() { @@ -4115,9 +4111,7 @@ CreateTable CreateTable(): [ sk3 = RelObjectName()] {Expression exp = null;} ("(" exp = Expression() ")")* { - checkCs = new CheckConstraint(); - checkCs.setName(sk3); - checkCs.setExpression(exp); + checkCs = new CheckConstraint().withName(sk3).withExpression(exp); indexes.add(checkCs); } ) @@ -4138,7 +4132,7 @@ CreateTable CreateTable(): colDataType = ColDataType() { - columnSpecs = new ArrayList(); + columnSpecs = new ArrayList(); } ( parameter=CreateParameter() { columnSpecs.addAll(parameter); } )* @@ -4186,7 +4180,7 @@ ColDataType ColDataType(): ColDataType colDataType = new ColDataType(); Token tk = null; Token tk2 = null; - ArrayList argumentsStringList = new ArrayList(); + List argumentsStringList = new ArrayList(); List array = new ArrayList(); } { @@ -4500,7 +4494,7 @@ AlterExpression.ColumnDataType AlterExpressionColumnDataType(): { columnName = RelObjectName() ( { withType = true; } )? - dataType = ColDataType() { columnSpecs = new ArrayList(); } + dataType = ColDataType() { columnSpecs = new ArrayList(); } ( parameter = CreateParameter() { columnSpecs.addAll(parameter); } )* { return new AlterExpression.ColumnDataType(columnName, withType, dataType, columnSpecs); @@ -4597,10 +4591,7 @@ AlterExpression AlterExpression(): sk3 = RelObjectName() columnNames = ColumnsNamesList() { - index = new Index(); - index.setType(tk.image); - index.setName(sk3); - index.setColumnsNames(columnNames); + index = new Index().withType(tk.image).withName(sk3).withColumnsNames(columnNames); alterExp.setIndex(index); } constraints=AlterExpressionConstraintState() { alterExp.setConstraints(constraints); } @@ -4641,16 +4632,15 @@ AlterExpression AlterExpression(): ( ( tk= tk2= columnNames=ColumnsNamesList() { - fkIndex = new ForeignKeyIndex(); - fkIndex.setName(sk3); - fkIndex.setType(tk.image + " " + tk2.image); - fkIndex.setColumnsNames(columnNames); + fkIndex = new ForeignKeyIndex() + .withName(sk3) + .withType(tk.image + " " + tk2.image) + .withColumnsNames(columnNames); columnNames = null; } fkTable=Table() [ columnNames=ColumnsNamesList() ] { - fkIndex.setTable(fkTable); - fkIndex.setReferencedColumnNames(columnNames); + fkIndex.withTable(fkTable).withReferencedColumnNames(columnNames); alterExp.setIndex(fkIndex); } @@ -4666,10 +4656,10 @@ AlterExpression AlterExpression(): ( tk= tk2= columnNames=ColumnsNamesList() { - index = new NamedConstraint(); - index.setName(sk3); - index.setType(tk.image + " " + tk2.image); - index.setColumnsNames(columnNames); + index = new NamedConstraint() + .withName(sk3) + .withType(tk.image + " " + tk2.image) + .withColumnsNames(columnNames); alterExp.setIndex(index); } constraints=AlterExpressionConstraintState() { alterExp.setConstraints(constraints); } @@ -4678,9 +4668,7 @@ AlterExpression AlterExpression(): | ( {Expression exp = null;} ("(" exp = Expression() ")")* { - CheckConstraint checkCs = new CheckConstraint(); - checkCs.setName(sk3); - checkCs.setExpression(exp); + CheckConstraint checkCs = new CheckConstraint().withName(sk3).withExpression(exp); alterExp.setIndex(checkCs); } ) @@ -4689,10 +4677,10 @@ AlterExpression AlterExpression(): tk= (tk2= { alterExp.setUk(true); } | tk2=)? columnNames=ColumnsNamesList() { - index = new NamedConstraint(); - index.setName(sk3); - index.setType(tk.image + (tk2!=null?" " + tk2.image:"")); - index.setColumnsNames(columnNames); + index = new NamedConstraint() + .withName(sk3) + .withType(tk.image + (tk2!=null?" " + tk2.image:"")) + .withColumnsNames(columnNames); alterExp.setIndex(index); } constraints=AlterExpressionConstraintState() { alterExp.setConstraints(constraints); } @@ -4703,10 +4691,10 @@ AlterExpression AlterExpression(): tk= columnNames=ColumnsNamesList() { - index = new NamedConstraint(); - index.setName(sk3); - index.setType(tk.image); - index.setColumnsNames(columnNames); + index = new NamedConstraint() + .withName(sk3) + .withType(tk.image) + .withColumnsNames(columnNames); alterExp.setIndex(index); } constraints=AlterExpressionConstraintState() { alterExp.setConstraints(constraints); } @@ -4716,8 +4704,7 @@ AlterExpression AlterExpression(): | ( sk3=RelObjectName() tk= { - alterExp.setColumnName(sk3); - alterExp.setCommentText(tk.image); + alterExp.withColumnName(sk3).withCommentText(tk.image); } ) ) @@ -4733,8 +4720,7 @@ AlterExpression AlterExpression(): ( (tk= | tk=) alterExpressionColumnDataType = AlterExpressionColumnDataType() { - alterExp.setColOldName(tk.image); - alterExp.addColDataType(alterExpressionColumnDataType); + alterExp.withColumnOldName(tk.image).addColDataType(alterExpressionColumnDataType); } ) ) @@ -4756,9 +4742,7 @@ AlterExpression AlterExpression(): ( tk= (tk2= | tk2=) { - index = new Index(); - index.setType(tk.image); - index.setName(tk2.image); + index = new Index().withType(tk.image).withName(tk2.image); alterExp.setIndex(index); } ) diff --git a/src/test/java/net/sf/jsqlparser/expression/ExpressionVisitorAdapterTest.java b/src/test/java/net/sf/jsqlparser/expression/ExpressionVisitorAdapterTest.java index 7c78b66944..5257af1d1e 100644 --- a/src/test/java/net/sf/jsqlparser/expression/ExpressionVisitorAdapterTest.java +++ b/src/test/java/net/sf/jsqlparser/expression/ExpressionVisitorAdapterTest.java @@ -11,6 +11,16 @@ import java.util.ArrayList; import java.util.List; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.operators.relational.InExpression; import net.sf.jsqlparser.expression.operators.relational.ItemsList; @@ -19,16 +29,6 @@ import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectVisitorAdapter; -import org.junit.After; -import org.junit.AfterClass; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; /** * @@ -57,9 +57,9 @@ public void tearDown() { @Test public void testInExpressionProblem() throws JSQLParserException { - final List exprList = new ArrayList(); + final List exprList = new ArrayList<>(); Select select = (Select) CCJSqlParserUtil.parse("select * from foo where x in (?,?,?)"); - PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); + PlainSelect plainSelect = select.getSelectBody(PlainSelect.class); Expression where = plainSelect.getWhere(); where.accept(new ExpressionVisitorAdapter() { @@ -79,7 +79,7 @@ public void visit(InExpression expr) { @Test public void testInExpression() throws JSQLParserException { - final List exprList = new ArrayList(); + final List exprList = new ArrayList<>(); Select select = (Select) CCJSqlParserUtil. parse("select * from foo where (a,b) in (select a,b from foo2)"); PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); @@ -179,28 +179,28 @@ public void testSubSelectExpressionProblem() throws JSQLParserException { fail(); } } - + @Test public void testCaseWithoutElse() throws JSQLParserException { Expression expr = CCJSqlParserUtil.parseExpression("CASE WHEN 1 then 0 END"); ExpressionVisitorAdapter adapter = new ExpressionVisitorAdapter(); expr.accept(adapter); } - + @Test public void testCaseWithoutElse2() throws JSQLParserException { Expression expr = CCJSqlParserUtil.parseExpression("CASE WHEN 1 then 0 ELSE -1 END"); ExpressionVisitorAdapter adapter = new ExpressionVisitorAdapter(); expr.accept(adapter); } - + @Test public void testCaseWithoutElse3() throws JSQLParserException { Expression expr = CCJSqlParserUtil.parseExpression("CASE 3+4 WHEN 1 then 0 END"); ExpressionVisitorAdapter adapter = new ExpressionVisitorAdapter(); expr.accept(adapter); } - + @Test public void testAnalyticFunctionWithoutExpression502() throws JSQLParserException { Expression expr = CCJSqlParserUtil.parseExpression("row_number() over (order by c)"); diff --git a/src/test/java/net/sf/jsqlparser/expression/mysql/MySqlSqlCalcFoundRowsTest.java b/src/test/java/net/sf/jsqlparser/expression/mysql/MySqlSqlCalcFoundRowsTest.java index fd32a667f0..728cde8063 100644 --- a/src/test/java/net/sf/jsqlparser/expression/mysql/MySqlSqlCalcFoundRowsTest.java +++ b/src/test/java/net/sf/jsqlparser/expression/mysql/MySqlSqlCalcFoundRowsTest.java @@ -9,18 +9,22 @@ */ package net.sf.jsqlparser.expression.mysql; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertEqualsObjectTree; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import java.util.Arrays; +import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitorAdapter; +import net.sf.jsqlparser.statement.select.AllColumns; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectVisitorAdapter; -import org.junit.Test; - -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author sam @@ -38,8 +42,12 @@ public void testPossibleParsingWithSqlCalcFoundRowsHint() throws JSQLParserExcep accept(CCJSqlParserUtil.parse(generalSql), ref); assertFalse(ref.sqlCalcFoundRows); - assertSqlCanBeParsedAndDeparsed(sqlCalcFoundRowsContainingSql); + Statement parsed = assertSqlCanBeParsedAndDeparsed(sqlCalcFoundRowsContainingSql); assertSqlCanBeParsedAndDeparsed(generalSql); + Select created = new Select().withSelectBody(new PlainSelect().addSelectItems(Arrays.asList(new AllColumns())) + .withMySqlSqlCalcFoundRows(true).withFromItem(new Table("TABLE"))); + assertDeparse(created, sqlCalcFoundRowsContainingSql); + assertEqualsObjectTree(parsed, created); } private void accept(Statement statement, final MySqlSqlCalcFoundRowRef ref) { @@ -53,7 +61,7 @@ public void visit(PlainSelect plainSelect) { } }); } - + }); } } diff --git a/src/test/java/net/sf/jsqlparser/expression/operators/arithmetic/ArithmethicTests.java b/src/test/java/net/sf/jsqlparser/expression/operators/arithmetic/ArithmethicTests.java new file mode 100644 index 0000000000..3f7cdb6b40 --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/expression/operators/arithmetic/ArithmethicTests.java @@ -0,0 +1,93 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.expression.operators.arithmetic; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.schema.Column; + +public class ArithmethicTests { + + @Test + public void testAddition () { + assertEquals("1 + a", + new Addition().withLeftExpression(new LongValue(1)).withRightExpression(new Column("a")).toString()); + } + + @Test + public void testBitwiseAnd() { + assertEquals("a & b", + new BitwiseAnd().withLeftExpression(new Column("a")).withRightExpression(new Column("b")).toString()); + } + + @Test + public void testBitwiseLeftShift() { + assertEquals("a << b", new BitwiseLeftShift().withLeftExpression(new Column("a")) + .withRightExpression(new Column("b")).toString()); + } + + @Test + public void testBitwiseOr() { + assertEquals("a | b", + new BitwiseOr().withLeftExpression(new Column("a")).withRightExpression(new Column("b")).toString()); + } + + @Test + public void testBitwiseRightShift() { + assertEquals("a >> b", + new BitwiseRightShift().withLeftExpression(new Column("a")).withRightExpression(new Column("b")) + .toString()); + } + + @Test + public void testBitwiseXor() { + assertEquals("a ^ b", + new BitwiseXor().withLeftExpression(new Column("a")).withRightExpression(new Column("b")).toString()); + } + + @Test + public void testConcat() { + assertEquals("a || b", + new Concat().withLeftExpression(new Column("a")).withRightExpression(new Column("b")).toString()); + } + + @Test + public void testDivision() { + assertEquals("a / b", + new Division().withLeftExpression(new Column("a")).withRightExpression(new Column("b")).toString()); + } + + @Test + public void testIntegerDivision() { + assertEquals("4 DIV 2", new IntegerDivision().withLeftExpression(new LongValue(4)) + .withRightExpression(new LongValue(2)).toString()); + } + + @Test + public void testModulo() { + assertEquals("3 % 2", + new Modulo().withLeftExpression(new LongValue(3)).withRightExpression(new LongValue(2)).toString()); + } + + @Test + public void testMultiplication() { + assertEquals("5 * 2", + new Multiplication().withLeftExpression(new LongValue(5)).withRightExpression(new LongValue(2)) + .toString()); + } + + @Test + public void testSubtraction() { + assertEquals("5 - 3", new Subtraction().withLeftExpression(new LongValue(5)) + .withRightExpression(new LongValue(3)).toString()); + } + +} diff --git a/src/test/java/net/sf/jsqlparser/expression/operators/relational/LikeExpressionTest.java b/src/test/java/net/sf/jsqlparser/expression/operators/relational/LikeExpressionTest.java index 0ae55966ff..595ac1a8ed 100644 --- a/src/test/java/net/sf/jsqlparser/expression/operators/relational/LikeExpressionTest.java +++ b/src/test/java/net/sf/jsqlparser/expression/operators/relational/LikeExpressionTest.java @@ -23,7 +23,6 @@ public class LikeExpressionTest { public void testLikeNotIssue660() { LikeExpression instance = new LikeExpression(); assertFalse(instance.isNot()); - instance.setNot(true); - assertTrue(instance.isNot()); + assertTrue(instance.withNot(true).isNot()); } } diff --git a/src/test/java/net/sf/jsqlparser/schema/SequenceTest.java b/src/test/java/net/sf/jsqlparser/schema/SequenceTest.java index 40b6497cc5..4d58e93bd7 100644 --- a/src/test/java/net/sf/jsqlparser/schema/SequenceTest.java +++ b/src/test/java/net/sf/jsqlparser/schema/SequenceTest.java @@ -9,16 +9,15 @@ */ package net.sf.jsqlparser.schema; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + public class SequenceTest { @Test public void testSetName() { - Sequence sequence = new Sequence(); - sequence.setName("foo"); + Sequence sequence = new Sequence().withName("foo"); assertThat(sequence.getName()).isEqualTo("foo"); assertThat(sequence.getFullyQualifiedName()).isEqualTo("foo"); @@ -26,9 +25,7 @@ public void testSetName() { @Test public void testSetSchemaName() { - Sequence sequence = new Sequence(); - sequence.setName("foo"); - sequence.setSchemaName("bar"); + Sequence sequence = new Sequence().withName("foo").withSchemaName("bar"); assertThat(sequence.getSchemaName()).isEqualTo("bar"); assertThat(sequence.getFullyQualifiedName()).isEqualTo("bar.foo"); @@ -36,10 +33,7 @@ public void testSetSchemaName() { @Test public void testSetDatabase() { - Sequence sequence = new Sequence(); - sequence.setName("foo"); - sequence.setSchemaName("bar"); - sequence.setDatabase(new Database("default")); + Sequence sequence = new Sequence().withName("foo").withSchemaName("bar").withDatabase(new Database("default")); assertThat(sequence.getDatabase().getDatabaseName()).isEqualTo("default"); assertThat(sequence.getFullyQualifiedName()).isEqualTo("default.bar.foo"); diff --git a/src/test/java/net/sf/jsqlparser/schema/TableTest.java b/src/test/java/net/sf/jsqlparser/schema/TableTest.java index 975eca8dc2..583ac8fa9f 100644 --- a/src/test/java/net/sf/jsqlparser/schema/TableTest.java +++ b/src/test/java/net/sf/jsqlparser/schema/TableTest.java @@ -9,14 +9,15 @@ */ package net.sf.jsqlparser.schema; +import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; + import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.util.deparser.ExpressionDeParser; import net.sf.jsqlparser.util.deparser.SelectDeParser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; import org.junit.Test; /** @@ -27,9 +28,7 @@ public class TableTest { @Test public void tableIndexException() { - Table table = new Table(); - table.setName("bla"); - table.setDatabase(new Database(new Server("server", "instance"), "db")); + Table table = new Table().withName("bla").withDatabase(new Database(new Server("server", "instance"), "db")); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/DeclareStatementTest.java b/src/test/java/net/sf/jsqlparser/statement/DeclareStatementTest.java index 3ca78c894a..ea48a87b78 100644 --- a/src/test/java/net/sf/jsqlparser/statement/DeclareStatementTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/DeclareStatementTest.java @@ -9,44 +9,94 @@ */ package net.sf.jsqlparser.statement; -import net.sf.jsqlparser.JSQLParserException; +import static net.sf.jsqlparser.test.TestUtils.asList; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertEqualsObjectTree; import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import java.util.ArrayList; import org.junit.Test; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.UserVariable; +import net.sf.jsqlparser.statement.DeclareStatement.TypeDefExpr; +import net.sf.jsqlparser.statement.create.table.ColDataType; +import net.sf.jsqlparser.statement.create.table.ColumnDefinition; /** * * @author tw */ public class DeclareStatementTest { - + public DeclareStatementTest() { } @Test public void testDeclareType() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DECLARE @find nvarchar (30)"); + String statement = "DECLARE @find nvarchar (30)"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + DeclareStatement created = new DeclareStatement() + .addTypeDefExprList( + new TypeDefExpr(new UserVariable().withName("find"), + new ColDataType().withDataType("nvarchar").addArgumentsStringList("30"), null)) + .withDeclareType(DeclareType.TYPE); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } - + @Test public void testDeclareTypeWithDefault() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DECLARE @find varchar (30) = 'Man%'"); + String statement = "DECLARE @find varchar (30) = 'Man%'"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + DeclareStatement created = new DeclareStatement() + .addTypeDefExprList(new TypeDefExpr(new UserVariable().withName("find"), + new ColDataType().withDataType("varchar").addArgumentsStringList("30"), + new StringValue().withValue("Man%"))) + .withDeclareType(DeclareType.TYPE); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test public void testDeclareTypeList() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DECLARE @group nvarchar (50), @sales money"); + String statement = "DECLARE @group nvarchar (50), @sales money"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + DeclareStatement created = new DeclareStatement().addTypeDefExprList(asList( // + new TypeDefExpr( + new UserVariable().withName("group"), + new ColDataType().withDataType("nvarchar").addArgumentsStringList("50"), + null), + new TypeDefExpr(new UserVariable().withName("sales"), + new ColDataType().withDataType("money"), null))) + .withDeclareType(DeclareType.TYPE); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } - + @Test public void testDeclareTypeList2() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("DECLARE @group nvarchar (50), @sales varchar (50)"); } - + @Test public void testDeclareTable() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DECLARE @MyTableVar TABLE (EmpID int NOT NULL, OldVacationHours int, NewVacationHours int, ModifiedDate datetime)"); + String statement = "DECLARE @MyTableVar TABLE (EmpID int NOT NULL, OldVacationHours int, NewVacationHours int, ModifiedDate datetime)"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + DeclareStatement created = new DeclareStatement().withUserVariable(new UserVariable("MyTableVar")) + .withColumnDefinitions(new ArrayList<>()) + .addColumnDefinitions( + new ColumnDefinition("EmpID", new ColDataType().withDataType("int"), + asList("NOT", "NULL")), + new ColumnDefinition("OldVacationHours", new ColDataType("int"))) + .addColumnDefinitions( + asList( + new ColumnDefinition("NewVacationHours", new ColDataType("int")), + new ColumnDefinition("ModifiedDate", new ColDataType("datetime")))) + .withDeclareType(DeclareType.TABLE); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } - + @Test public void testDeclareAs() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("DECLARE @LocationTVP AS LocationTableType"); diff --git a/src/test/java/net/sf/jsqlparser/statement/alter/AlterTest.java b/src/test/java/net/sf/jsqlparser/statement/alter/AlterTest.java index 197c4a6207..fcefb2da63 100644 --- a/src/test/java/net/sf/jsqlparser/statement/alter/AlterTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/alter/AlterTest.java @@ -10,22 +10,31 @@ package net.sf.jsqlparser.statement.alter; import static net.sf.jsqlparser.test.TestUtils.*; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; +import java.util.Collections; import java.util.List; import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.ReferentialAction; import net.sf.jsqlparser.statement.ReferentialAction.Action; import net.sf.jsqlparser.statement.ReferentialAction.Type; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.alter.AlterExpression.ColumnDataType; +import net.sf.jsqlparser.statement.create.index.CreateIndex; +import net.sf.jsqlparser.statement.create.table.CheckConstraint; +import net.sf.jsqlparser.statement.create.table.Index; +import net.sf.jsqlparser.statement.create.table.NamedConstraint; +import net.sf.jsqlparser.statement.create.table.Index.ColumnParams; import net.sf.jsqlparser.statement.create.table.ForeignKeyIndex; import org.junit.Test; @@ -197,7 +206,16 @@ public void testAlterTableFK() throws JSQLParserException { @Test public void testAlterTableCheckConstraint() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("ALTER TABLE `Author` ADD CONSTRAINT name_not_empty CHECK (`NAME` <> '')"); + String statement = "ALTER TABLE `Author` ADD CONSTRAINT name_not_empty CHECK (`NAME` <> '')"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Alter created = new Alter().withTable(new Table("`Author`")) + .addAlterExpressions(Collections.singleton( + new AlterExpression().withOperation(AlterOperation.ADD).withIndex(new CheckConstraint() + .withName("name_not_empty") + .withExpression(new NotEqualsTo().withLeftExpression(new Column("`NAME`")) + .withRightExpression(new StringValue()))))); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test @@ -274,7 +292,7 @@ public void testAlterTableModifyColumn2() throws JSQLParserException { @Test public void testAlterTableAlterColumn() throws JSQLParserException { // http://www.postgresqltutorial.com/postgresql-change-column-type/ - assertSqlCanBeParsedAndDeparsed("ALTER TABLE table_name ALTER COLUMN column_name_1 TYPE TIMESTAMP, ALTER COLUMN column_name_2 TYPE BOOLEAN"); + assertSqlCanBeParsedAndDeparsed("ALTER TABLE table_name ALTER COLUMN column_name_1 TYPE TIMESTAMP, ALTER COLUMN column_name_2 TYPE BOOLEAN"); } @Test @@ -392,12 +410,28 @@ public void testIssue259() throws JSQLParserException { @Test public void testIssue633_2() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE INDEX idx_american_football_action_plays_1 ON american_football_action_plays USING btree (play_type)"); + String statement = "CREATE INDEX idx_american_football_action_plays_1 ON american_football_action_plays USING btree (play_type)"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + CreateIndex created = new CreateIndex() + .withTable(new Table("american_football_action_plays")) + .withIndex( + new Index().withName("idx_american_football_action_plays_1") + .addColumns(new ColumnParams("play_type", null)).withUsing("btree") + ); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test public void testAlterOnlyIssue928() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("ALTER TABLE ONLY categories ADD CONSTRAINT pk_categories PRIMARY KEY (category_id)"); + String statement = "ALTER TABLE ONLY categories ADD CONSTRAINT pk_categories PRIMARY KEY (category_id)"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Alter created = new Alter().withUseOnly(true).withTable(new Table("categories")).addAlterExpressions( + new AlterExpression().withOperation(AlterOperation.ADD).withIndex(new NamedConstraint() + .withName(Arrays.asList("pk_categories")).withType("PRIMARY KEY") + .addColumns(new ColumnParams("category_id")))); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test @@ -426,7 +460,7 @@ public void testAlterTableForeignKeyIssue981() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed( "ALTER TABLE atconfigpro " + "ADD CONSTRAINT atconfigpro_atconfignow_id_foreign FOREIGN KEY (atconfignow_id) REFERENCES atconfignow(id) ON DELETE CASCADE, " + - "ADD CONSTRAINT atconfigpro_attariff_id_foreign FOREIGN KEY (attariff_id) REFERENCES attariff(id) ON DELETE CASCADE"); + "ADD CONSTRAINT atconfigpro_attariff_id_foreign FOREIGN KEY (attariff_id) REFERENCES attariff(id) ON DELETE CASCADE"); } @Test @@ -438,14 +472,25 @@ public void testAlterTableForeignKeyIssue981_2() throws JSQLParserException { @Test public void testAlterTableTableCommentIssue984() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed( - "ALTER TABLE texto_fichero COMMENT 'This is a sample comment'"); + String statement = "ALTER TABLE texto_fichero COMMENT 'This is a sample comment'"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Alter created = new Alter().withTable(new Table("texto_fichero")) + .addAlterExpressions(new AlterExpression().withOperation(AlterOperation.COMMENT) + .withCommentText("'This is a sample comment'")); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test public void testAlterTableColumnCommentIssue984() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed( - "ALTER TABLE texto_fichero MODIFY id COMMENT 'some comment'"); + String statement = "ALTER TABLE texto_fichero MODIFY id COMMENT 'some comment'"; + Statement parsed = assertSqlCanBeParsedAndDeparsed( + statement); + Alter created = new Alter().withTable(new Table("texto_fichero")) + .addAlterExpressions(new AlterExpression().withOperation(AlterOperation.MODIFY).withColumnName("id") + .withCommentText("'some comment'")); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/builder/JSQLParserFluentModelTests.java b/src/test/java/net/sf/jsqlparser/statement/builder/JSQLParserFluentModelTests.java new file mode 100644 index 0000000000..ce0b3579fe --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/statement/builder/JSQLParserFluentModelTests.java @@ -0,0 +1,76 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.builder; + +import static net.sf.jsqlparser.test.TestUtils.*; + +import java.util.List; +import org.junit.Test; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Alias; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.JdbcParameter; +import net.sf.jsqlparser.expression.Parenthesis; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; +import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.Join; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.test.TestUtils; + +public class JSQLParserFluentModelTests { + + @Test + public void testParseAndBuild() throws JSQLParserException { + String statement = "SELECT * FROM tab1 AS t1 " // + + "JOIN tab2 t2 ON t1.ref = t2.id WHERE (t1.col1 = ? OR t1.col2 = ?) AND t1.col3 IN ('A')"; + + Statement parsed = TestUtils.assertSqlCanBeParsedAndDeparsed(statement); + + Table t1 = new Table("tab1").withAlias(new Alias("t1").withUseAs(true)); + Table t2 = new Table("tab2").withAlias(new Alias("t2", false)); + + AndExpression where = new AndExpression().withLeftExpression( + new Parenthesis(new OrExpression().withLeftExpression( + new EqualsTo() + .withLeftExpression(new Column(asList("t1", "col1"))) + .withRightExpression(new JdbcParameter().withIndex(1))) + .withRightExpression(new EqualsTo( + new Column(asList("t1", "col2")), + new JdbcParameter().withIndex( + 2))) + )).withRightExpression( + new InExpression() + .withLeftExpression(new Column(asList("t1", "col3"))) + .withRightItemsList(new ExpressionList().addExpressions(new StringValue("A")))); + Select select = new Select().withSelectBody(new PlainSelect().addSelectItems(new AllColumns()).withFromItem(t1) + .addJoins(new Join().withRightItem(t2) + .withOnExpression( + new EqualsTo(new Column(asList("t1", "ref")), new Column(asList("t2", "id"))))) + .withWhere(where)); + + ExpressionList list = select.getSelectBody(PlainSelect.class).getWhere(AndExpression.class) + .getRightExpression(InExpression.class).getRightItemsList(ExpressionList.class); + List elist = list.getExpressions(); + list.setExpressions(elist); + + assertDeparse(select, statement); + assertEqualsObjectTree(parsed, select); + } + +} diff --git a/src/test/java/net/sf/jsqlparser/statement/builder/ReflectionModelTest.java b/src/test/java/net/sf/jsqlparser/statement/builder/ReflectionModelTest.java new file mode 100644 index 0000000000..ffb412a5fc --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/statement/builder/ReflectionModelTest.java @@ -0,0 +1,189 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.builder; + +import static net.sf.jsqlparser.test.TestUtils.*; +import java.util.List; +import org.junit.Test; +import net.sf.jsqlparser.expression.AnyType; +import net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperatorType; +import net.sf.jsqlparser.schema.Sequence.ParameterType; +import net.sf.jsqlparser.statement.ExplainStatement.OptionType; +import net.sf.jsqlparser.statement.create.table.ColDataType; +import net.sf.jsqlparser.statement.select.SubSelect; +import net.sf.jsqlparser.util.ReflectionTestUtils; + +/** + * Testing of setters, getters, with-/add-methods by calling them with random + * parameter-values + *
    + *
  • testing, whether return-value is the specific type (not the parent) + *
  • testing, whether calling the methods do not throw any exceptions + *
+ * + * @author gitmotte + */ +public class ReflectionModelTest { + + private static final List MODEL_OBJECTS = asList(new net.sf.jsqlparser.expression.Alias("a"), + new net.sf.jsqlparser.expression.Alias.AliasColumn("a", new ColDataType("varchar")), + new net.sf.jsqlparser.expression.AllComparisonExpression(new SubSelect()), + new net.sf.jsqlparser.expression.AnalyticExpression(), + new net.sf.jsqlparser.expression.AnyComparisonExpression(AnyType.ANY, new SubSelect()), + new net.sf.jsqlparser.expression.ArrayExpression(), + new net.sf.jsqlparser.expression.CaseExpression(), new net.sf.jsqlparser.expression.CastExpression(), + new net.sf.jsqlparser.expression.CollateExpression(), + new net.sf.jsqlparser.expression.DateTimeLiteralExpression(), + new net.sf.jsqlparser.expression.DateValue(), new net.sf.jsqlparser.expression.DoubleValue(), + new net.sf.jsqlparser.expression.ExtractExpression(), new net.sf.jsqlparser.expression.Function(), + new net.sf.jsqlparser.expression.HexValue(), new net.sf.jsqlparser.expression.IntervalExpression(), + new net.sf.jsqlparser.expression.JdbcNamedParameter(), new net.sf.jsqlparser.expression.JdbcParameter(), + new net.sf.jsqlparser.expression.JsonExpression(), new net.sf.jsqlparser.expression.KeepExpression(), + new net.sf.jsqlparser.expression.LongValue(), + new net.sf.jsqlparser.expression.MySQLGroupConcat(), + new net.sf.jsqlparser.expression.MySQLIndexHint("action", "indexQualifier", + asList("idx_name", "idx_name_col")), + new net.sf.jsqlparser.expression.NextValExpression(asList("sequence")), + new net.sf.jsqlparser.expression.NotExpression(), + new net.sf.jsqlparser.expression.NullValue(), new net.sf.jsqlparser.expression.NumericBind(), + new net.sf.jsqlparser.expression.OracleHierarchicalExpression(), + new net.sf.jsqlparser.expression.OracleHint(), new net.sf.jsqlparser.expression.OrderByClause(), + new net.sf.jsqlparser.expression.Parenthesis(), new net.sf.jsqlparser.expression.PartitionByClause(), + new net.sf.jsqlparser.expression.RowConstructor(), new net.sf.jsqlparser.expression.SQLServerHints(), + new net.sf.jsqlparser.expression.SignedExpression(), new net.sf.jsqlparser.expression.StringValue(), + new net.sf.jsqlparser.expression.TimeKeyExpression(), new net.sf.jsqlparser.expression.TimeValue(), + new net.sf.jsqlparser.expression.TimestampValue(), new net.sf.jsqlparser.expression.UserVariable(), + new net.sf.jsqlparser.expression.ValueListExpression(), new net.sf.jsqlparser.expression.WhenClause(), + new net.sf.jsqlparser.expression.WindowElement(), + new net.sf.jsqlparser.expression.WindowOffset(), + new net.sf.jsqlparser.expression.WindowRange(), + new net.sf.jsqlparser.expression.operators.arithmetic.Addition(), + new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd(), + new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseLeftShift(), + new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr(), + new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseRightShift(), + new net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor(), + new net.sf.jsqlparser.expression.operators.arithmetic.Concat(), + new net.sf.jsqlparser.expression.operators.arithmetic.Division(), + new net.sf.jsqlparser.expression.operators.arithmetic.IntegerDivision(), + new net.sf.jsqlparser.expression.operators.arithmetic.Modulo(), + new net.sf.jsqlparser.expression.operators.arithmetic.Multiplication(), + new net.sf.jsqlparser.expression.operators.arithmetic.Subtraction(), + new net.sf.jsqlparser.expression.operators.conditional.AndExpression(), + new net.sf.jsqlparser.expression.operators.conditional.OrExpression(), + new net.sf.jsqlparser.expression.operators.relational.Between(), + new net.sf.jsqlparser.expression.operators.relational.EqualsTo(), + new net.sf.jsqlparser.expression.operators.relational.ExistsExpression(), + new net.sf.jsqlparser.expression.operators.relational.ExpressionList(), + new net.sf.jsqlparser.expression.operators.relational.FullTextSearch(), + new net.sf.jsqlparser.expression.operators.relational.GreaterThan(), + new net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals(), + new net.sf.jsqlparser.expression.operators.relational.InExpression(), + new net.sf.jsqlparser.expression.operators.relational.IsBooleanExpression(), + new net.sf.jsqlparser.expression.operators.relational.IsNullExpression(), + new net.sf.jsqlparser.expression.operators.relational.JsonOperator("@>"), + new net.sf.jsqlparser.expression.operators.relational.LikeExpression(), + new net.sf.jsqlparser.expression.operators.relational.Matches(), + new net.sf.jsqlparser.expression.operators.relational.MinorThan(), + new net.sf.jsqlparser.expression.operators.relational.MinorThanEquals(), + new net.sf.jsqlparser.expression.operators.relational.MultiExpressionList(), + new net.sf.jsqlparser.expression.operators.relational.NamedExpressionList(), + new net.sf.jsqlparser.expression.operators.relational.NotEqualsTo(), + new net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperator( + RegExpMatchOperatorType.MATCH_CASEINSENSITIVE), + new net.sf.jsqlparser.expression.operators.relational.RegExpMySQLOperator( + RegExpMatchOperatorType.NOT_MATCH_CASESENSITIVE), + new net.sf.jsqlparser.expression.operators.relational.SimilarToExpression(), + new net.sf.jsqlparser.schema.Column(), + new net.sf.jsqlparser.schema.Database("db"), + new net.sf.jsqlparser.schema.Sequence(), + new net.sf.jsqlparser.schema.Sequence.Parameter(ParameterType.KEEP), + new net.sf.jsqlparser.schema.Server("srv"), + new net.sf.jsqlparser.schema.Table(), new net.sf.jsqlparser.statement.Block(), + new net.sf.jsqlparser.statement.Commit(), + new net.sf.jsqlparser.statement.DeclareStatement(), + new net.sf.jsqlparser.statement.DescribeStatement(), + new net.sf.jsqlparser.statement.ExplainStatement(), + new net.sf.jsqlparser.statement.ExplainStatement.Option(OptionType.COSTS), + new net.sf.jsqlparser.statement.SetStatement("name", null), + new net.sf.jsqlparser.statement.ShowColumnsStatement(), + new net.sf.jsqlparser.statement.ShowStatement(), new net.sf.jsqlparser.statement.Statements(), + new net.sf.jsqlparser.statement.UseStatement(), + new net.sf.jsqlparser.statement.alter.Alter(), + new net.sf.jsqlparser.statement.alter.AlterExpression(), + new net.sf.jsqlparser.statement.alter.AlterExpression.ColumnDataType(false), + new net.sf.jsqlparser.statement.alter.AlterExpression.ColumnDropNotNull("name"), + new net.sf.jsqlparser.statement.merge.MergeInsert(), + new net.sf.jsqlparser.statement.alter.DeferrableConstraint(), + new net.sf.jsqlparser.statement.alter.EnableConstraint(), + new net.sf.jsqlparser.statement.alter.ValidateConstraint(), + new net.sf.jsqlparser.statement.alter.sequence.AlterSequence(), + new net.sf.jsqlparser.statement.comment.Comment(), + new net.sf.jsqlparser.statement.create.function.CreateFunction(), + new net.sf.jsqlparser.statement.create.index.CreateIndex(), + new net.sf.jsqlparser.statement.create.procedure.CreateProcedure(), + new net.sf.jsqlparser.statement.create.schema.CreateSchema(), + new net.sf.jsqlparser.statement.create.sequence.CreateSequence(), + new net.sf.jsqlparser.statement.create.table.CheckConstraint(), + new net.sf.jsqlparser.statement.create.table.ColDataType(), + new net.sf.jsqlparser.statement.create.table.ColumnDefinition(), + new net.sf.jsqlparser.statement.create.table.CreateTable(), + new net.sf.jsqlparser.statement.create.table.ExcludeConstraint(), + new net.sf.jsqlparser.statement.create.table.ForeignKeyIndex(), + new net.sf.jsqlparser.statement.create.table.Index(), + new net.sf.jsqlparser.statement.create.table.Index.ColumnParams("p"), + new net.sf.jsqlparser.statement.create.table.NamedConstraint(), + new net.sf.jsqlparser.statement.create.table.RowMovement(), + new net.sf.jsqlparser.statement.create.view.AlterView(), + new net.sf.jsqlparser.statement.create.view.CreateView(), + new net.sf.jsqlparser.statement.delete.Delete(), + new net.sf.jsqlparser.statement.drop.Drop(), + new net.sf.jsqlparser.statement.execute.Execute(), new net.sf.jsqlparser.statement.grant.Grant(), + new net.sf.jsqlparser.statement.insert.Insert(), new net.sf.jsqlparser.statement.merge.Merge(), + new net.sf.jsqlparser.statement.merge.MergeUpdate(), new net.sf.jsqlparser.statement.replace.Replace(), + new net.sf.jsqlparser.statement.select.AllColumns(), + new net.sf.jsqlparser.statement.select.AllTableColumns(), + new net.sf.jsqlparser.statement.select.Distinct(), new net.sf.jsqlparser.statement.select.ExceptOp(), + new net.sf.jsqlparser.statement.select.ExpressionListItem(), + new net.sf.jsqlparser.statement.select.Fetch(), new net.sf.jsqlparser.statement.select.First(), + new net.sf.jsqlparser.statement.select.FunctionItem(), + new net.sf.jsqlparser.statement.select.GroupByElement(), + new net.sf.jsqlparser.statement.select.IntersectOp(), + new net.sf.jsqlparser.statement.select.Join(), new net.sf.jsqlparser.statement.select.KSQLJoinWindow(), + new net.sf.jsqlparser.statement.select.KSQLWindow(), + new net.sf.jsqlparser.statement.select.LateralSubSelect(), + new net.sf.jsqlparser.statement.select.Limit(), + new net.sf.jsqlparser.statement.select.MinusOp(), + new net.sf.jsqlparser.statement.select.Offset(), new net.sf.jsqlparser.statement.select.OptimizeFor(2L), + new net.sf.jsqlparser.statement.select.OrderByElement(), + new net.sf.jsqlparser.statement.select.ParenthesisFromItem(), + new net.sf.jsqlparser.statement.select.Pivot(), + new net.sf.jsqlparser.statement.select.PivotXml(), new net.sf.jsqlparser.statement.select.PlainSelect(), + new net.sf.jsqlparser.statement.select.Select(), + new net.sf.jsqlparser.statement.select.SelectExpressionItem(), + new net.sf.jsqlparser.statement.select.SetOperationList(), + new net.sf.jsqlparser.statement.select.Skip(), + new net.sf.jsqlparser.statement.select.SubJoin(), + new net.sf.jsqlparser.statement.select.SubSelect(), + new net.sf.jsqlparser.statement.select.TableFunction(), new net.sf.jsqlparser.statement.select.Top(), + new net.sf.jsqlparser.statement.select.UnPivot(), new net.sf.jsqlparser.statement.select.UnionOp(), + new net.sf.jsqlparser.statement.select.ValuesList(), new net.sf.jsqlparser.statement.select.Wait(), + new net.sf.jsqlparser.statement.select.WithItem(), + new net.sf.jsqlparser.statement.truncate.Truncate(), + new net.sf.jsqlparser.statement.update.Update(), new net.sf.jsqlparser.statement.upsert.Upsert(), + new net.sf.jsqlparser.statement.values.ValuesStatement(), + new net.sf.jsqlparser.statement.DeclareStatement.TypeDefExpr(new ColDataType("varchar"), null)); + + @Test + public void testModels() { + ReflectionTestUtils.testGetterSetterChaining(MODEL_OBJECTS, m -> !"setASTNode".equals(m.getName())); + } + +} diff --git a/src/test/java/net/sf/jsqlparser/statement/comment/CommentTest.java b/src/test/java/net/sf/jsqlparser/statement/comment/CommentTest.java index 81e1e5e596..8fa4271399 100755 --- a/src/test/java/net/sf/jsqlparser/statement/comment/CommentTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/comment/CommentTest.java @@ -17,6 +17,7 @@ import java.io.StringReader; import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; @@ -49,6 +50,11 @@ public void testCommentTable2() throws JSQLParserException { public void testCommentTableDeparse() throws JSQLParserException { String statement = "COMMENT ON TABLE table1 IS 'comment1'"; assertSqlCanBeParsedAndDeparsed(statement); + + Comment c = new Comment().withTable(new Table("table1")).withComment(new StringValue("comment1")); + assertEquals("table1", c.getTable().getName()); + assertEquals("comment1", c.getComment().getValue()); + assertDeparse(c, statement, false); } @Test @@ -60,6 +66,10 @@ public void testCommentColumn() throws JSQLParserException { assertEquals("column1", column.getColumnName()); assertEquals("comment1", comment.getComment().getValue()); assertEquals(statement, "" + comment); + + Comment c = new Comment().withColumn(new Column(new Table("table1"), "column1")) + .withComment(new StringValue("comment1")); + assertDeparse(c, statement, false); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/create/AlterSequenceTest.java b/src/test/java/net/sf/jsqlparser/statement/create/AlterSequenceTest.java new file mode 100644 index 0000000000..82bf0ac79d --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/statement/create/AlterSequenceTest.java @@ -0,0 +1,39 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.statement.create; + +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertEqualsObjectTree; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; + +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.schema.Sequence; +import net.sf.jsqlparser.schema.Sequence.Parameter; +import net.sf.jsqlparser.schema.Sequence.ParameterType; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.alter.sequence.AlterSequence; +import org.junit.Test; + +public class AlterSequenceTest { + + + @Test + public void testCreateSequence_withIncrement() throws JSQLParserException{ + String statement = "ALTER SEQUENCE my_seq CACHE 100"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + AlterSequence created = new AlterSequence().withSequence( + new Sequence().withName("my_seq") + .addParameters(new Parameter(ParameterType.CACHE).withValue(100L))); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); + } + + +} diff --git a/src/test/java/net/sf/jsqlparser/statement/create/AlterViewTest.java b/src/test/java/net/sf/jsqlparser/statement/create/AlterViewTest.java index 3e706ef748..947973e4c3 100644 --- a/src/test/java/net/sf/jsqlparser/statement/create/AlterViewTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/create/AlterViewTest.java @@ -9,21 +9,45 @@ */ package net.sf.jsqlparser.statement.create; -import net.sf.jsqlparser.JSQLParserException; -import static net.sf.jsqlparser.test.TestUtils.*; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertEqualsObjectTree; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import java.util.Collections; import org.junit.Test; +import static org.junit.Assert.assertTrue; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.create.view.AlterView; +import net.sf.jsqlparser.statement.select.AllColumns; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.SelectExpressionItem; public class AlterViewTest { @Test public void testAlterView() throws JSQLParserException { - String stmt = "ALTER VIEW myview AS SELECT * FROM mytab"; - assertSqlCanBeParsedAndDeparsed(stmt); + String statement = "ALTER VIEW myview AS SELECT * FROM mytab"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + AlterView created = new AlterView().withView(new Table("myview")).withSelectBody(new PlainSelect() + .addSelectItems(Collections.singleton(new AllColumns())).withFromItem(new Table("mytab"))); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test public void testReplaceView() throws JSQLParserException { - String stmt = "REPLACE VIEW myview AS SELECT * FROM mytab"; - assertSqlCanBeParsedAndDeparsed(stmt); + String statement = "REPLACE VIEW myview(a, b) AS SELECT a, b FROM mytab"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + AlterView alterView = new AlterView().withUseReplace(true).addColumnNames("a").addColumnNames(Collections.singleton("b")) + .withView(new Table("myview")) + .withSelectBody(new PlainSelect() + .addSelectItems(new SelectExpressionItem(new Column("a")), + new SelectExpressionItem(new Column("b"))) + .withFromItem(new Table("mytab"))); + assertTrue(alterView.getSelectBody(PlainSelect.class) instanceof PlainSelect); + assertDeparse(alterView, statement); + assertEqualsObjectTree(parsed, alterView); } } diff --git a/src/test/java/net/sf/jsqlparser/statement/create/CreateFunctionalStatementTest.java b/src/test/java/net/sf/jsqlparser/statement/create/CreateFunctionalStatementTest.java index 6d330a81e3..87959dc7df 100644 --- a/src/test/java/net/sf/jsqlparser/statement/create/CreateFunctionalStatementTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/create/CreateFunctionalStatementTest.java @@ -9,14 +9,15 @@ */ package net.sf.jsqlparser.statement.create; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import static org.assertj.core.api.Assertions.assertThat; +import java.util.Arrays; +import org.junit.Test; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.create.function.CreateFunction; import net.sf.jsqlparser.statement.create.procedure.CreateProcedure; -import org.junit.Test; - -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import static org.assertj.core.api.Assertions.assertThat; /** * Tests the behavior of {@link net.sf.jsqlparser.statement.CreateFunctionalStatement funtion statements} @@ -25,7 +26,12 @@ public class CreateFunctionalStatementTest { @Test public void createFunctionMinimal() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE FUNCTION foo RETURN 5 END;"); + String statement = "CREATE FUNCTION foo RETURN 5; END;"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse( + new CreateFunction().addFunctionDeclarationParts("foo") + .addFunctionDeclarationParts(Arrays.asList("RETURN 5;", "END;")), + statement); } @Test @@ -46,7 +52,12 @@ public void createFunctionLong() throws JSQLParserException { @Test public void createProcedureMinimal() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE PROCEDURE foo AS BEGIN END;"); + String statement = "CREATE PROCEDURE foo AS BEGIN END;"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse( + new CreateProcedure().addFunctionDeclarationParts("foo", "AS") + .addFunctionDeclarationParts(Arrays.asList("BEGIN", "END;")), + statement); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/create/CreateSequenceTest.java b/src/test/java/net/sf/jsqlparser/statement/create/CreateSequenceTest.java index 63de64350e..0c41b73040 100644 --- a/src/test/java/net/sf/jsqlparser/statement/create/CreateSequenceTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/create/CreateSequenceTest.java @@ -9,21 +9,33 @@ */ package net.sf.jsqlparser.statement.create; +import static net.sf.jsqlparser.test.TestUtils.*; + + import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.schema.Database; +import net.sf.jsqlparser.schema.Sequence; +import net.sf.jsqlparser.schema.Sequence.Parameter; +import net.sf.jsqlparser.schema.Sequence.ParameterType; +import net.sf.jsqlparser.statement.create.sequence.CreateSequence; import org.junit.Test; -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; - public class CreateSequenceTest { @Test public void testCreateSequence_noParams() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE SEQUENCE my_seq"); + String statement = "CREATE SEQUENCE my_seq"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateSequence().withSequence(new Sequence().withName("my_seq")), statement); } @Test public void testCreateSequence_withIncrement() throws JSQLParserException{ - assertSqlCanBeParsedAndDeparsed("CREATE SEQUENCE my_seq INCREMENT BY 1"); + String statement = "CREATE SEQUENCE db.schema.my_seq INCREMENT BY 1"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateSequence().withSequence( + new Sequence().withDatabase(new Database("db")).withSchemaName("schema").withName("my_seq") + .addParameters(new Parameter(ParameterType.INCREMENT_BY).withValue(1L))), statement); } @Test @@ -108,7 +120,15 @@ public void testCreateSequence_withGlobal() throws JSQLParserException { public void testCreateSequence_preservesParamOrder() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("CREATE SEQUENCE my_sec INCREMENT BY 2 START WITH 10"); assertSqlCanBeParsedAndDeparsed("CREATE SEQUENCE my_sec START WITH 2 INCREMENT BY 5 NOCACHE"); - assertSqlCanBeParsedAndDeparsed("CREATE SEQUENCE my_sec START WITH 2 INCREMENT BY 5 CACHE 200 CYCLE"); + String statement = "CREATE SEQUENCE my_sec START WITH 2 INCREMENT BY 5 CACHE 200 CYCLE"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateSequence().withSequence(new Sequence().withName("my_sec") + .addParameters(asList( + new Parameter(ParameterType.START_WITH).withValue(2L), + new Parameter(ParameterType.INCREMENT_BY).withValue(5L), + new Parameter(ParameterType.CACHE).withValue(200L), + new Parameter(ParameterType.CYCLE)))), + statement); } } diff --git a/src/test/java/net/sf/jsqlparser/statement/create/CreateTableTest.java b/src/test/java/net/sf/jsqlparser/statement/create/CreateTableTest.java index 921b769044..20940fe9d6 100644 --- a/src/test/java/net/sf/jsqlparser/statement/create/CreateTableTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/create/CreateTableTest.java @@ -9,30 +9,36 @@ */ package net.sf.jsqlparser.statement.create; -import net.sf.jsqlparser.JSQLParserException; -import net.sf.jsqlparser.parser.CCJSqlParserManager; -import net.sf.jsqlparser.parser.CCJSqlParserUtil; -import net.sf.jsqlparser.statement.create.table.ColumnDefinition; -import net.sf.jsqlparser.statement.create.table.CreateTable; -import net.sf.jsqlparser.statement.create.table.Index; -import net.sf.jsqlparser.statement.create.table.RowMovementMode; -import net.sf.jsqlparser.test.TestException; -import org.assertj.core.api.Assertions; -import org.junit.Test; - +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StringReader; import java.util.ArrayList; +import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; - -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import org.assertj.core.api.Assertions; +import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.operators.relational.GreaterThan; +import net.sf.jsqlparser.parser.CCJSqlParserManager; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.create.table.ColDataType; +import net.sf.jsqlparser.statement.create.table.ColumnDefinition; +import net.sf.jsqlparser.statement.create.table.CreateTable; +import net.sf.jsqlparser.statement.create.table.ExcludeConstraint; +import net.sf.jsqlparser.statement.create.table.Index; +import net.sf.jsqlparser.statement.create.table.RowMovementMode; +import net.sf.jsqlparser.test.TestException; public class CreateTableTest { @@ -69,12 +75,12 @@ public void testCreateTable() throws JSQLParserException { CreateTable createTable = (CreateTable) parserManager.parse(new StringReader(statement)); assertEquals(2, createTable.getColumnDefinitions().size()); assertFalse(createTable.isUnlogged()); - assertEquals("mycol", ((ColumnDefinition) createTable.getColumnDefinitions().get(0)). + assertEquals("mycol", createTable.getColumnDefinitions().get(0). getColumnName()); - assertEquals("mycol2", ((ColumnDefinition) createTable.getColumnDefinitions().get(1)). + assertEquals("mycol2", createTable.getColumnDefinitions().get(1). getColumnName()); - assertEquals("PRIMARY KEY", ((Index) createTable.getIndexes().get(0)).getType()); - assertEquals("mycol", ((Index) createTable.getIndexes().get(0)).getColumnsNames().get(1)); + assertEquals("PRIMARY KEY", createTable.getIndexes().get(0).getType()); + assertEquals("mycol", createTable.getIndexes().get(0).getColumnsNames().get(1)); assertEquals(statement, "" + createTable); } @@ -85,12 +91,12 @@ public void testCreateTableUnlogged() throws JSQLParserException { CreateTable createTable = (CreateTable) parserManager.parse(new StringReader(statement)); assertEquals(2, createTable.getColumnDefinitions().size()); assertTrue(createTable.isUnlogged()); - assertEquals("mycol", ((ColumnDefinition) createTable.getColumnDefinitions().get(0)). + assertEquals("mycol", createTable.getColumnDefinitions().get(0). getColumnName()); - assertEquals("mycol2", ((ColumnDefinition) createTable.getColumnDefinitions().get(1)). + assertEquals("mycol2", createTable.getColumnDefinitions().get(1). getColumnName()); - assertEquals("PRIMARY KEY", ((Index) createTable.getIndexes().get(0)).getType()); - assertEquals("mycol", ((Index) createTable.getIndexes().get(0)).getColumnsNames().get(1)); + assertEquals("PRIMARY KEY", createTable.getIndexes().get(0).getType()); + assertEquals("mycol", createTable.getIndexes().get(0).getColumnsNames().get(1)); assertEquals(statement, "" + createTable); } @@ -302,12 +308,21 @@ public void testColumnConstraintWith() throws JSQLParserException { @Test public void testExcludeWhereConstraint() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE TABLE foo (col1 integer, EXCLUDE WHERE (col1 > 100))"); + String statement = "CREATE TABLE foo (col1 integer, EXCLUDE WHERE (col1 > 100))"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateTable().withTable(new Table("foo")) + .addIndexes(new ExcludeConstraint().withExpression(new GreaterThan() + .withLeftExpression(new Column("col1")).withRightExpression(new LongValue(100)))) + .addColumnDefinitions(new ColumnDefinition("col1", new ColDataType("integer"))), statement); } @Test public void testTimestampWithoutTimezone() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE TABLE abc.tabc (transaction_date TIMESTAMP WITHOUT TIME ZONE)"); + String statement = "CREATE TABLE abc.tabc (transaction_date TIMESTAMP WITHOUT TIME ZONE)"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateTable().withTable(new Table(Arrays.asList("abc", "tabc"))).addColumnDefinitions( + new ColumnDefinition("transaction_date", new ColDataType("TIMESTAMP WITHOUT TIME ZONE"))), + statement); } @Test @@ -413,25 +428,21 @@ public void testRUBiSCreateList() throws Exception { } else { StringTokenizer tokenizer = new StringTokenizer(cols, " "); - List colsListList = new ArrayList(); + List colsListList = new ArrayList<>(); while (tokenizer.hasMoreTokens()) { colsListList.add(tokenizer.nextToken()); } - colsList = (String[]) colsListList.toArray(new String[colsListList.size()]); + colsList = colsListList.toArray(new String[colsListList.size()]); } - List colsFound = new ArrayList(); + List colsFound = new ArrayList<>(); if (createTable.getColumnDefinitions() != null) { - for (Iterator iter = createTable.getColumnDefinitions().iterator(); iter. - hasNext();) { - ColumnDefinition columnDefinition = (ColumnDefinition) iter.next(); + for (ColumnDefinition columnDefinition : createTable.getColumnDefinitions()) { String colName = columnDefinition.getColumnName(); boolean unique = false; if (createTable.getIndexes() != null) { - for (Iterator iterator = createTable.getIndexes().iterator(); iterator. - hasNext();) { - Index index = (Index) iterator.next(); + for (Index index : createTable.getIndexes()) { if (index.getType().equals("PRIMARY KEY") && index. getColumnsNames().size() == 1 && index.getColumnsNames().get(0).equals(colName)) { @@ -443,10 +454,9 @@ public void testRUBiSCreateList() throws Exception { if (!unique) { if (columnDefinition.getColumnSpecs() != null) { - for (Iterator iterator = columnDefinition.getColumnSpecs(). - iterator(); iterator - .hasNext();) { - String par = (String) iterator.next(); + for (Iterator iterator = columnDefinition.getColumnSpecs() + .iterator(); iterator.hasNext();) { + String par = iterator.next(); if (par.equals("UNIQUE")) { unique = true; } else if (par.equals("PRIMARY") && iterator.hasNext() @@ -489,7 +499,7 @@ private String getLine(BufferedReader in) throws Exception { if (line != null) { if ((line.length() != 0) && ((line.length() < 2) || (line.length() >= 2) - && !(line.charAt(0) == '/' && line.charAt(1) == '/'))) { + && !(line.charAt(0) == '/' && line.charAt(1) == '/'))) { break; } } else { @@ -546,7 +556,15 @@ public void testCreateTableIssue798_2() throws JSQLParserException { @Test public void testCreateTableIssue113() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE TABLE foo (reason character varying (255) DEFAULT 'Test' :: character varying NOT NULL)"); + String statement = "CREATE TABLE foo (reason character varying (255) DEFAULT 'Test' :: character varying NOT NULL)"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateTable().withTable(new Table().withName("foo")).withColumnDefinitions(Arrays.asList( + new ColumnDefinition().withColumnName("reason").withColDataType( + new ColDataType().withDataType("character varying") + .addArgumentsStringList(Arrays.asList("255"))) + .addColumnSpecs("DEFAULT 'Test' :: character varying", "NOT NULL"))), + statement); + } @Test @@ -586,7 +604,12 @@ public void testCreateTableIssue924_2() throws JSQLParserException { @Test public void testCreateTableIssue921() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE TABLE binary_test (c1 binary (10))"); + String statement = "CREATE TABLE binary_test (c1 binary (10))"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateTable().withTable(new Table().withName("binary_test")).addColumnDefinitions( + new ColumnDefinition("c1", new ColDataType().withDataType("binary").addArgumentsStringList("10"), + null)), + statement); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/create/schema/CreateSchemaTest.java b/src/test/java/net/sf/jsqlparser/statement/create/schema/CreateSchemaTest.java index b48f3fe94c..e469939633 100644 --- a/src/test/java/net/sf/jsqlparser/statement/create/schema/CreateSchemaTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/create/schema/CreateSchemaTest.java @@ -9,9 +9,10 @@ */ package net.sf.jsqlparser.statement.create.schema; -import net.sf.jsqlparser.JSQLParserException; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; import org.junit.Test; +import net.sf.jsqlparser.JSQLParserException; /** * @@ -20,6 +21,15 @@ public class CreateSchemaTest { @Test public void testSimpleCreateSchema() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("CREATE SCHEMA myschema"); + String statement = "CREATE SCHEMA myschema"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateSchema().withSchemaName("myschema"), statement); + } + + @Test + public void testSimpleCreateWithAuth() throws JSQLParserException { + String statement = "CREATE SCHEMA myschema AUTHORIZATION myauth"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new CreateSchema().withSchemaName("myschema").withAuthorization("myauth"), statement); } } diff --git a/src/test/java/net/sf/jsqlparser/statement/delete/DeleteTest.java b/src/test/java/net/sf/jsqlparser/statement/delete/DeleteTest.java index f17af8efa7..416bdd0a24 100644 --- a/src/test/java/net/sf/jsqlparser/statement/delete/DeleteTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/delete/DeleteTest.java @@ -11,13 +11,17 @@ import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import java.io.StringReader; +import static org.junit.Assert.assertEquals; -import org.junit.Test; +import java.io.StringReader; import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.parser.CCJSqlParserManager; -import static org.junit.Assert.assertEquals; +import net.sf.jsqlparser.schema.Column; +import org.junit.Test; public class DeleteTest { @@ -41,7 +45,13 @@ public void testDeleteWhereProblem1() throws JSQLParserException { @Test public void testDeleteWithLimit() throws JSQLParserException { String stmt = "DELETE FROM tablename WHERE a = 1 AND b = 1 LIMIT 5"; - assertSqlCanBeParsedAndDeparsed(stmt); + Delete parsed = (Delete) assertSqlCanBeParsedAndDeparsed(stmt); + AndExpression where = parsed.getWhere(AndExpression.class); + EqualsTo left = where.getLeftExpression(EqualsTo.class); + assertEquals("a", left.getLeftExpression(Column.class).getColumnName()); + EqualsTo right = where.getRightExpression(EqualsTo.class); + assertEquals("b", right.getLeftExpression(Column.class).getColumnName()); + assertEquals(5, parsed.getLimit().getRowCount(LongValue.class).getValue()); } @Test(expected = JSQLParserException.class) @@ -79,7 +89,7 @@ public void testDeleteFromTableUsingInnerJoinToAnotherTableWithAlias() throws JS String stmt = "DELETE gc FROM guide_category AS gc LEFT JOIN guide AS g ON g.id_guide = gc.id_guide WHERE g.title IS NULL LIMIT 5"; assertSqlCanBeParsedAndDeparsed(stmt); } - + @Test public void testDeleteMultiTableIssue878() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("DELETE table1, table2 FROM table1, table2"); diff --git a/src/test/java/net/sf/jsqlparser/statement/drop/DropTest.java b/src/test/java/net/sf/jsqlparser/statement/drop/DropTest.java index 4c0cdcf048..b558510d45 100644 --- a/src/test/java/net/sf/jsqlparser/statement/drop/DropTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/drop/DropTest.java @@ -9,12 +9,16 @@ */ package net.sf.jsqlparser.statement.drop; +import static net.sf.jsqlparser.test.TestUtils.*; + +import static org.junit.Assert.assertEquals; + import java.io.StringReader; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserManager; -import static net.sf.jsqlparser.test.TestUtils.*; -import static org.junit.Assert.assertEquals; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; import org.junit.Test; public class DropTest { @@ -24,17 +28,26 @@ public class DropTest { @Test public void testDrop() throws JSQLParserException { String statement = "DROP TABLE mytab"; - Drop drop = (Drop) parserManager.parse(new StringReader(statement)); - assertEquals("TABLE", drop.getType()); - assertEquals("mytab", drop.getName().getFullyQualifiedName()); - assertEquals(statement, "" + drop); + Drop parsed = (Drop) parserManager.parse(new StringReader(statement)); + assertEquals("TABLE", parsed.getType()); + assertEquals("mytab", parsed.getName().getFullyQualifiedName()); + assertEquals(statement, "" + parsed); + Drop created = new Drop().withType("TABLE").withName(new Table("mytab")); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); + } - statement = "DROP INDEX myindex CASCADE"; - drop = (Drop) parserManager.parse(new StringReader(statement)); - assertEquals("INDEX", drop.getType()); - assertEquals("myindex", drop.getName().getFullyQualifiedName()); - assertEquals("CASCADE", drop.getParameters().get(0)); - assertEquals(statement, "" + drop); + @Test + public void testDropIndex() throws JSQLParserException { + String statement = "DROP INDEX myindex CASCADE"; + Drop parsed = (Drop) parserManager.parse(new StringReader(statement)); + assertEquals("INDEX", parsed.getType()); + assertEquals("myindex", parsed.getName().getFullyQualifiedName()); + assertEquals("CASCADE", parsed.getParameters().get(0)); + assertEquals(statement, "" + parsed); + Drop created = new Drop().withType("INDEX").withName(new Table("myindex")).addParameters("CASCADE"); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test @@ -46,12 +59,20 @@ public void testDrop2() throws JSQLParserException { @Test public void testDropIfExists() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DROP TABLE IF EXISTS my_table"); + String statement = "DROP TABLE IF EXISTS my_table"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Drop created = new Drop().withType("TABLE").withIfExists(true).withName(new Table("my_table")); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test public void testDropRestrictIssue510() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("DROP TABLE TABLE2 RESTRICT"); + String statement = "DROP TABLE TABLE2 RESTRICT"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Drop created = new Drop().withType("TABLE").withName(new Table("TABLE2")).addParameters(asList("RESTRICT")); + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/grant/GrantTest.java b/src/test/java/net/sf/jsqlparser/statement/grant/GrantTest.java index cda882c598..8bb1b8a55c 100644 --- a/src/test/java/net/sf/jsqlparser/statement/grant/GrantTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/grant/GrantTest.java @@ -15,7 +15,7 @@ import java.io.StringReader; -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import static net.sf.jsqlparser.test.TestUtils.*; import static org.junit.Assert.assertEquals; public class GrantTest { @@ -36,6 +36,10 @@ public void testGrantPrivilege() throws JSQLParserException { assertEquals(statement, grant.toString()); assertEquals(null, grant.getRole()); + + Grant created = new Grant().addPrivileges("SELECT").withObjectName("t1").addUsers("u"); + assertDeparse(created, statement); + assertEqualsObjectTree(grant, created); } @Test @@ -53,6 +57,11 @@ public void testGrantPrivileges() throws JSQLParserException { assertEquals(statement, grant.toString()); assertEquals(null, grant.getRole()); + + Grant created = new Grant().addPrivileges(asList("SELECT", "INSERT")).withObjectName("t1") + .addUsers(asList("u", "u2")); + assertDeparse(created, statement); + assertEqualsObjectTree(grant, created); } @Test @@ -69,6 +78,11 @@ public void testGrantRole() throws JSQLParserException { assertEquals("role1", grant.getRole()); assertEquals(statement, grant.toString()); + + Grant created = new Grant().withRole("role1") + .addUsers(asList("u", "u2")); + assertDeparse(created, statement); + assertEqualsObjectTree(grant, created); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/insert/InsertTest.java b/src/test/java/net/sf/jsqlparser/statement/insert/InsertTest.java index e2f87eb02c..0c1ec490e0 100644 --- a/src/test/java/net/sf/jsqlparser/statement/insert/InsertTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/insert/InsertTest.java @@ -9,21 +9,31 @@ */ package net.sf.jsqlparser.statement.insert; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; import java.io.StringReader; +import java.util.Arrays; +import org.junit.Ignore; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.JdbcParameter; import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.select.AllColumns; import net.sf.jsqlparser.statement.select.PlainSelect; -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import static org.junit.Assert.*; -import org.junit.Ignore; -import org.junit.Test; +import net.sf.jsqlparser.statement.select.Select; public class InsertTest { @@ -35,28 +45,35 @@ public void testRegularInsert() throws JSQLParserException { Insert insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("mytable", insert.getTable().getName()); assertEquals(3, insert.getColumns().size()); - assertEquals("col1", ((Column) insert.getColumns().get(0)).getColumnName()); - assertEquals("col2", ((Column) insert.getColumns().get(1)).getColumnName()); - assertEquals("col3", ((Column) insert.getColumns().get(2)).getColumnName()); + assertEquals("col1", insert.getColumns().get(0).getColumnName()); + assertEquals("col2", insert.getColumns().get(1).getColumnName()); + assertEquals("col3", insert.getColumns().get(2).getColumnName()); assertEquals(3, ((ExpressionList) insert.getItemsList()).getExpressions().size()); assertTrue(((ExpressionList) insert.getItemsList()).getExpressions().get(0) instanceof JdbcParameter); assertEquals("sadfsd", ((StringValue) ((ExpressionList) insert.getItemsList()).getExpressions().get(1)). - getValue()); + getValue()); assertEquals(234, ((LongValue) ((ExpressionList) insert.getItemsList()).getExpressions(). get(2)).getValue()); assertEquals(statement, "" + insert); + assertDeparse(new Insert().withTable(new Table("mytable")) + .addColumns(Arrays.asList(new Column("col1"), new Column("col2"), new Column("col3"))) + .withItemsList(new ExpressionList(new JdbcParameter(), new StringValue("sadfsd"), + new LongValue().withValue(234))), + statement); + statement = "INSERT INTO myschema.mytable VALUES (?, ?, 2.3)"; insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("myschema.mytable", insert.getTable().getFullyQualifiedName()); - assertEquals(3, ((ExpressionList) insert.getItemsList()).getExpressions().size()); + assertEquals(3, insert.getItemsList(ExpressionList.class).getExpressions().size()); assertTrue(((ExpressionList) insert.getItemsList()).getExpressions().get(0) instanceof JdbcParameter); - assertEquals(2.3, ((DoubleValue) ((ExpressionList) insert.getItemsList()).getExpressions(). - get(2)).getValue(), - 0.0); + assertEquals(2.3, ((DoubleValue) insert.getItemsList(ExpressionList.class).getExpressions() + .get(2)).getValue(), 0.0); assertEquals(statement, "" + insert); + + } @Test @@ -65,11 +82,13 @@ public void testInsertWithKeywordValue() throws JSQLParserException { Insert insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("mytable", insert.getTable().getName()); assertEquals(1, insert.getColumns().size()); - assertEquals("col1", ((Column) insert.getColumns().get(0)).getColumnName()); + assertEquals("col1", insert.getColumns().get(0).getColumnName()); assertEquals("val1", ((StringValue) ((ExpressionList) insert.getItemsList()).getExpressions().get(0)). - getValue()); + getValue()); assertEquals("INSERT INTO mytable (col1) VALUES ('val1')", insert.toString()); + + } @Test @@ -78,9 +97,9 @@ public void testInsertFromSelect() throws JSQLParserException { Insert insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("mytable", insert.getTable().getName()); assertEquals(3, insert.getColumns().size()); - assertEquals("col1", ((Column) insert.getColumns().get(0)).getColumnName()); - assertEquals("col2", ((Column) insert.getColumns().get(1)).getColumnName()); - assertEquals("col3", ((Column) insert.getColumns().get(2)).getColumnName()); + assertEquals("col1", insert.getColumns().get(0).getColumnName()); + assertEquals("col2", insert.getColumns().get(1).getColumnName()); + assertEquals("col3", insert.getColumns().get(2).getColumnName()); assertNull(insert.getItemsList()); assertNotNull(insert.getSelect()); assertEquals("mytable2", @@ -89,6 +108,12 @@ public void testInsertFromSelect() throws JSQLParserException { // toString uses brakets String statementToString = "INSERT INTO mytable (col1, col2, col3) SELECT * FROM mytable2"; assertEquals(statementToString, "" + insert); + + assertDeparse(new Insert().withUseValues(false).withUseSelectBrackets(false).withTable(new Table("mytable")) + .addColumns(new Column("col1"), new Column("col2"), new Column("col3")) + .withSelect(new Select().withSelectBody( + new PlainSelect().addSelectItems(new AllColumns()).withFromItem(new Table("mytable2")))), + statement); } @Test @@ -97,8 +122,8 @@ public void testInsertFromSet() throws JSQLParserException { Insert insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("mytable", insert.getTable().getName()); assertEquals(2, insert.getSetColumns().size()); - assertEquals("col1", ((Column) insert.getSetColumns().get(0)).getColumnName()); - assertEquals("col2", ((Column) insert.getSetColumns().get(1)).getColumnName()); + assertEquals("col1", insert.getSetColumns().get(0).getColumnName()); + assertEquals("col2", insert.getSetColumns().get(1).getColumnName()); assertEquals(2, insert.getSetExpressionList().size()); assertEquals("12", insert.getSetExpressionList().get(0).toString()); assertEquals("name1 * name2", insert.getSetExpressionList().get(1).toString()); @@ -113,15 +138,15 @@ public void testInsertValuesWithDuplicateElimination() throws JSQLParserExceptio assertEquals("TEST", insert.getTable().getName()); assertEquals(2, insert.getColumns().size()); assertTrue(insert.isUseValues()); - assertEquals("ID", ((Column) insert.getColumns().get(0)).getColumnName()); - assertEquals("COUNTER", ((Column) insert.getColumns().get(1)).getColumnName()); + assertEquals("ID", insert.getColumns().get(0).getColumnName()); + assertEquals("COUNTER", insert.getColumns().get(1).getColumnName()); assertEquals(2, ((ExpressionList) insert.getItemsList()).getExpressions().size()); assertEquals(123, ((LongValue) ((ExpressionList) insert.getItemsList()).getExpressions(). get(0)).getValue()); assertEquals(0, ((LongValue) ((ExpressionList) insert.getItemsList()).getExpressions(). get(1)).getValue()); assertEquals(1, insert.getDuplicateUpdateColumns().size()); - assertEquals("COUNTER", ((Column) insert.getDuplicateUpdateColumns().get(0)).getColumnName()); + assertEquals("COUNTER", insert.getDuplicateUpdateColumns().get(0).getColumnName()); assertEquals(1, insert.getDuplicateUpdateExpressionList().size()); assertEquals("COUNTER + 1", insert.getDuplicateUpdateExpressionList().get(0).toString()); assertFalse(insert.isUseSelectBrackets()); @@ -136,12 +161,12 @@ public void testInsertFromSetWithDuplicateElimination() throws JSQLParserExcepti Insert insert = (Insert) parserManager.parse(new StringReader(statement)); assertEquals("mytable", insert.getTable().getName()); assertEquals(1, insert.getSetColumns().size()); - assertEquals("col1", ((Column) insert.getSetColumns().get(0)).getColumnName()); + assertEquals("col1", insert.getSetColumns().get(0).getColumnName()); assertEquals(1, insert.getSetExpressionList().size()); assertEquals("122", insert.getSetExpressionList().get(0).toString()); assertEquals(2, insert.getDuplicateUpdateColumns().size()); - assertEquals("col2", ((Column) insert.getDuplicateUpdateColumns().get(0)).getColumnName()); - assertEquals("col3", ((Column) insert.getDuplicateUpdateColumns().get(1)).getColumnName()); + assertEquals("col2", insert.getDuplicateUpdateColumns().get(0).getColumnName()); + assertEquals("col3", insert.getDuplicateUpdateColumns().get(1).getColumnName()); assertEquals(2, insert.getDuplicateUpdateExpressionList().size()); assertEquals("col2 + 1", insert.getDuplicateUpdateExpressionList().get(0).toString()); assertEquals("'saint'", insert.getDuplicateUpdateExpressionList().get(1).toString()); @@ -150,7 +175,14 @@ public void testInsertFromSetWithDuplicateElimination() throws JSQLParserExcepti @Test public void testInsertMultiRowValue() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("INSERT INTO mytable (col1, col2) VALUES (a, b), (d, e)"); + String statement = "INSERT INTO mytable (col1, col2) VALUES (a, b), (d, e)"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new Insert().withTable(new Table("mytable")) + .withColumns(Arrays.asList(new Column("col1"), new Column("col2"))) + .withItemsList(new MultiExpressionList().addExpressionLists( + new ExpressionList().addExpressions(Arrays.asList(new Column("a"), new Column("b"))), + new ExpressionList(new Column("d"), new Column("e")))), + statement); } @Test @@ -308,7 +340,7 @@ public void testNextValIssue773() throws JSQLParserException { public void testBackslashEscapingIssue827() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("INSERT INTO my_table (my_column_1, my_column_2) VALUES ('my_value_1\\\\', 'my_value_2')"); } - + @Test public void testDisableKeywordIssue945() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("INSERT INTO SOMESCHEMA.TEST (DISABLE, TESTCOLUMN) VALUES (1, 1)"); diff --git a/src/test/java/net/sf/jsqlparser/statement/select/NestedBracketsPerformanceTest.java b/src/test/java/net/sf/jsqlparser/statement/select/NestedBracketsPerformanceTest.java index b9d9cec69a..38b3c0e769 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/NestedBracketsPerformanceTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/NestedBracketsPerformanceTest.java @@ -9,12 +9,12 @@ */ package net.sf.jsqlparser.statement.select; -import net.sf.jsqlparser.JSQLParserException; import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import net.sf.jsqlparser.JSQLParserException; /** * @@ -22,6 +22,8 @@ */ public class NestedBracketsPerformanceTest { + private static final int ITERATIONS_20 = 20; + @Test public void testIssue766() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat(concat('1','2'),'3'),'4'),'5'),'6'),'7'),'8'),'9'),'10'),'11'),'12'),'13'),'14'),'15'),'16'),'17'),'18'),'19'),'20'),'21'),col1 FROM tbl t1", true); @@ -42,7 +44,7 @@ public void testIssue235() throws JSQLParserException { public void testIssue496() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("select isNull(charLen(TEST_ID,0)+ isNull(charLen(TEST_DVC,0)+ isNull(charLen(TEST_NO,0)+ isNull(charLen(ATEST_ID,0)+ isNull(charLen(TESTNO,0)+ isNull(charLen(TEST_CTNT,0)+ isNull(charLen(TEST_MESG_CTNT,0)+ isNull(charLen(TEST_DTM,0)+ isNull(charLen(TEST_DTT,0)+ isNull(charLen(TEST_ADTT,0)+ isNull(charLen(TEST_TCD,0)+ isNull(charLen(TEST_PD,0)+ isNull(charLen(TEST_VAL,0)+ isNull(charLen(TEST_YN,0)+ isNull(charLen(TEST_DTACM,0)+ isNull(charLen(TEST_MST,0) from test_info_m"); } - + @Test public void testIssue856() throws JSQLParserException { String sql = "SELECT " + buildRecursiveBracketExpression("if(month(today()) = 3, sum(\"Table5\".\"Month 002\"), $1)", "0", 5) + " FROM mytbl"; @@ -58,7 +60,7 @@ public void testIssue856() throws JSQLParserException { public void testIncreaseOfParseTime() throws JSQLParserException { long oldDurationTime = 1000; int countProblematic = 0; - for (int i = 0; i < 20; i++) { + for (int i = 0; i < ITERATIONS_20; i++) { String sql = "SELECT " + buildRecursiveBracketExpression("concat($1,'B')", "'A'", i) + " FROM mytbl"; long startTime = System.currentTimeMillis(); assertSqlCanBeParsedAndDeparsed(sql, true); diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectASTTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectASTTest.java index 3dd01df5a1..21cf2ecf7e 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SelectASTTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SelectASTTest.java @@ -36,13 +36,13 @@ public void testSelectASTColumn() throws JSQLParserException { PlainSelect ps = (PlainSelect) select.getSelectBody(); for (SelectItem item : ps.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; - Column c = (Column) sei.getExpression(); + Column c = sei.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().beginColumn - 1, '*'); } for (OrderByElement item : ps.getOrderByElements()) { - Column c = (Column) item.getExpression(); + Column c = item.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().beginColumn - 1, '#'); @@ -95,13 +95,13 @@ public void testSelectASTColumnLF() throws JSQLParserException { PlainSelect ps = (PlainSelect) select.getSelectBody(); for (SelectItem item : ps.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; - Column c = (Column) sei.getExpression(); + Column c = sei.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '*'); } for (OrderByElement item : ps.getOrderByElements()) { - Column c = (Column) item.getExpression(); + Column c = item.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '#'); @@ -118,13 +118,13 @@ public void testSelectASTCommentLF() throws JSQLParserException { PlainSelect ps = (PlainSelect) select.getSelectBody(); for (SelectItem item : ps.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; - Column c = (Column) sei.getExpression(); + Column c = sei.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '*'); } for (OrderByElement item : ps.getOrderByElements()) { - Column c = (Column) item.getExpression(); + Column c = item.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '#'); @@ -141,13 +141,13 @@ public void testSelectASTCommentCRLF() throws JSQLParserException { PlainSelect ps = (PlainSelect) select.getSelectBody(); for (SelectItem item : ps.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; - Column c = (Column) sei.getExpression(); + Column c = sei.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '*'); } for (OrderByElement item : ps.getOrderByElements()) { - Column c = (Column) item.getExpression(); + Column c = item.getExpression(Column.class); SimpleNode astNode = c.getASTNode(); assertNotNull(astNode); b.setCharAt(astNode.jjtGetFirstToken().absoluteBegin - 1, '#'); diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java index b0bbf31303..d5383dedc4 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java @@ -22,17 +22,53 @@ import static net.sf.jsqlparser.test.TestUtils.*; import org.apache.commons.io.IOUtils; import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.DoubleValue; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.IntervalExpression; +import net.sf.jsqlparser.expression.JdbcNamedParameter; +import net.sf.jsqlparser.expression.JdbcParameter; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.NotExpression; +import net.sf.jsqlparser.expression.SignedExpression; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.TimeValue; +import net.sf.jsqlparser.expression.TimestampValue; +import net.sf.jsqlparser.expression.operators.arithmetic.Addition; +import net.sf.jsqlparser.expression.operators.arithmetic.Multiplication; +import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.expression.operators.relational.EqualsTo; +import net.sf.jsqlparser.expression.operators.relational.GreaterThan; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +import net.sf.jsqlparser.parser.CCJSqlParserManager; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.schema.Database; +import net.sf.jsqlparser.schema.Server; +import net.sf.jsqlparser.schema.Table; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.StatementVisitorAdapter; +import net.sf.jsqlparser.statement.Statements; public class SelectTest { @@ -43,7 +79,7 @@ public class SelectTest { @Before public void setup() { -// System.out.println(name.getMethodName()); + // System.out.println(name.getMethodName()); } // From statement multipart @@ -52,6 +88,13 @@ public void testMultiPartTableNameWithServerNameAndDatabaseNameAndSchemaName() t final String statement = "SELECT columnName FROM [server-name\\server-instance].databaseName.schemaName.tableName"; assertSqlCanBeParsedAndDeparsed(statement, false, parser -> parser.withSquareBracketQuotation(true)); + assertDeparse(new Select().withSelectBody(new PlainSelect() + .addSelectItems(new SelectExpressionItem(new Column().withColumnName("columnName"))) + .withFromItem(new Table() + .withDatabase(new Database("databaseName").withServer( + new Server("[server-name\\server-instance]"))) + .withSchemaName("schemaName").withName("tableName"))), + statement); } @Test @@ -60,6 +103,13 @@ public void testMultiPartTableNameWithServerNameAndDatabaseName() throws Excepti assertSqlCanBeParsedAndDeparsed(statement, false, parser -> parser.withSquareBracketQuotation(true)); + assertDeparse(new Select().withSelectBody(new PlainSelect() + .addSelectItems(new SelectExpressionItem(new Column().withColumnName("columnName"))) + .withFromItem(new Table() + .withDatabase( + new Database("databaseName").withServer(new Server("[server-name\\server-instance]"))) + .withName("tableName"))), + statement); } @Test @@ -214,6 +264,12 @@ public void testAllColumnsFromTable() throws Exception { assertStatementCanBeDeparsedAs(select, statement); assertTrue(((PlainSelect) select.getSelectBody()).getSelectItems().get(0) instanceof AllTableColumns); + + Table t = new Table("tableName"); + assertDeparse( + new Select().withSelectBody( + new PlainSelect().addSelectItems(new AllTableColumns().withTable(t)).withFromItem(t)), + statement); } @Test @@ -241,9 +297,9 @@ public void testOperationsWithSigns() throws JSQLParserException { assertTrue(sub.getLeftExpression() instanceof LongValue); assertTrue(sub.getRightExpression() instanceof SignedExpression); - SignedExpression sexpr = (SignedExpression) sub.getRightExpression(); + SignedExpression sexpr = sub.getRightExpression(SignedExpression.class); assertEquals('-', sexpr.getSign()); - assertEquals("1", sexpr.getExpression().toString()); + assertEquals("1", sexpr.getExpression(LongValue.class).toString()); } @Test @@ -615,14 +671,12 @@ public void testTop() throws JSQLParserException { Select select = (Select) parserManager.parse(new StringReader(statement)); - assertEquals(3, ((LongValue) ((PlainSelect) select.getSelectBody()).getTop().getExpression()). - getValue()); + assertEquals(3, select.getSelectBody(PlainSelect.class).getTop().getExpression(LongValue.class).getValue()); assertStatementCanBeDeparsedAs(select, statement); statement = "select top 5 foo from bar"; select = (Select) parserManager.parse(new StringReader(statement)); - assertEquals(5, ((LongValue) ((PlainSelect) select.getSelectBody()).getTop().getExpression()). - getValue()); + assertEquals(5, select.getSelectBody(PlainSelect.class).getTop().getExpression(LongValue.class).getValue()); } @Test @@ -783,7 +837,7 @@ public void testSkipFirst() throws JSQLParserException { assertNotNull(skip.getJdbcParameter()); assertNotNull(skip.getJdbcParameter().getIndex()); assertTrue(skip.getJdbcParameter().isUseFixedIndex()); - assertEquals((int) 1, (int) skip.getJdbcParameter().getIndex()); + assertEquals(1, (int) skip.getJdbcParameter().getIndex()); assertNull(skip.getVariable()); final First first = selectBody.getFirst(); assertNull(first.getJdbcParameter()); @@ -895,7 +949,7 @@ public void testDistinct() throws JSQLParserException { assertEquals("myid", ((Column) ((SelectExpressionItem) plainSelect.getDistinct().getOnSelectItems(). get(0)).getExpression()) - .getColumnName()); + .getColumnName()); assertEquals("mycol", ((Column) ((SelectExpressionItem) plainSelect.getSelectItems().get(1)). getExpression()).getColumnName()); @@ -910,7 +964,7 @@ public void testDistinctTop() throws JSQLParserException { assertEquals("myid", ((Column) ((SelectExpressionItem) plainSelect.getSelectItems().get(0)). getExpression()) - .getColumnName()); + .getColumnName()); assertEquals("mycol", ((Column) ((SelectExpressionItem) plainSelect.getSelectItems().get(1)). getExpression()).getColumnName()); @@ -955,7 +1009,7 @@ public void testJoin() throws JSQLParserException { assertEquals("tab1.id", ((Column) ((EqualsTo) plainSelect.getJoins().get(0).getOnExpression()). getLeftExpression()) - .getFullyQualifiedName()); + .getFullyQualifiedName()); assertTrue(plainSelect.getJoins().get(0).isOuter()); assertStatementCanBeDeparsedAs(select, statement); @@ -1213,7 +1267,7 @@ public void testOrderBy() throws JSQLParserException { assertEquals(2, plainSelect.getOrderByElements().size()); assertEquals("tab1.a", ((Column) plainSelect.getOrderByElements().get(0).getExpression()) - .getFullyQualifiedName()); + .getFullyQualifiedName()); assertEquals("b", ((Column) plainSelect.getOrderByElements().get(1).getExpression()).getColumnName()); assertTrue(plainSelect.getOrderByElements().get(1).isAsc()); @@ -1251,7 +1305,7 @@ public void testTimestamp() throws JSQLParserException { PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); assertEquals("2004-04-30 04:05:34.56", ((TimestampValue) ((GreaterThan) plainSelect.getWhere()).getRightExpression()). - getValue().toString()); + getValue().toString()); assertStatementCanBeDeparsedAs(select, statement); } @@ -1387,7 +1441,7 @@ public void testNotLike() throws JSQLParserException { PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); assertEquals("test", ((StringValue) ((LikeExpression) plainSelect.getWhere()). getRightExpression()).getValue()); - assertEquals(true, (boolean) ((LikeExpression) plainSelect.getWhere()).isNot()); + assertEquals(true, ((LikeExpression) plainSelect.getWhere()).isNot()); } @Test @@ -1399,7 +1453,7 @@ public void testNotLikeWithNotBeforeExpression() throws JSQLParserException { NotExpression notExpr = (NotExpression) plainSelect.getWhere(); assertEquals("test", ((StringValue) ((LikeExpression) notExpr.getExpression()). getRightExpression()).getValue()); - assertEquals(false, (boolean) ((LikeExpression) notExpr.getExpression()).isNot()); + assertEquals(false, ((LikeExpression) notExpr.getExpression()).isNot()); } @Test @@ -2135,11 +2189,11 @@ public void testExtractFrom4() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed(stmt); } -// @Test -// public void testExtractFromIssue673() throws JSQLParserException { -// String stmt = "select EXTRACT(DAY FROM (SYSDATE - to_date('20180101', 'YYYYMMDD' ) ) DAY TO SECOND) from dual"; -// assertSqlCanBeParsedAndDeparsed(stmt); -// } + // @Test + // public void testExtractFromIssue673() throws JSQLParserException { + // String stmt = "select EXTRACT(DAY FROM (SYSDATE - to_date('20180101', 'YYYYMMDD' ) ) DAY TO SECOND) from dual"; + // assertSqlCanBeParsedAndDeparsed(stmt); + // } @Test public void testProblemFunction() throws JSQLParserException { String stmt = "SELECT test() FROM testtable"; @@ -2628,10 +2682,10 @@ public void testJsonExpression() throws JSQLParserException { //The following staments can be parsed but not deparsed for (String statement : new String[]{ - "SELECT doc->'site_name' FROM websites WHERE doc @> '{\"tags\":[{\"term\":\"paris\"}, {\"term\":\"food\"}]}'", - "SELECT * FROM sales where sale ->'items' @> '[{\"count\":0}]'", - "SELECT * FROM sales where sale ->'items' ? 'name'", - "SELECT * FROM sales where sale ->'items' -# 'name'" + "SELECT doc->'site_name' FROM websites WHERE doc @> '{\"tags\":[{\"term\":\"paris\"}, {\"term\":\"food\"}]}'", + "SELECT * FROM sales where sale ->'items' @> '[{\"count\":0}]'", + "SELECT * FROM sales where sale ->'items' ? 'name'", + "SELECT * FROM sales where sale ->'items' -# 'name'" }) { Select select = (Select) parserManager.parse(new StringReader(statement)); assertStatementCanBeDeparsedAs(select, statement, true); @@ -2848,7 +2902,7 @@ public void testOracleHint() throws JSQLParserException { + " b.application_id\n" + "FROM jl_br_journals j,\n" + " po_vendors p", true, "ORDERED INDEX (b, jl_br_balances_n1) USE_NL (j b) \n" - + " USE_NL (glcc glf) USE_MERGE (gp gsb)"); + + " USE_NL (glcc glf) USE_MERGE (gp gsb)"); assertOracleHintExists("SELECT /*+ROWID(emp)*/ /*+ THIS IS NOT HINT! ***/ * \n" + "FROM emp \n" + "WHERE rowid > 'AAAAtkAABAAAFNTAAA' AND empno = 155", false, "ROWID(emp)"); @@ -3031,15 +3085,15 @@ public void testCastToSigned() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT CAST(contact_id AS SIGNED) FROM contact WHERE contact_id = 20"); } -// @Test -// public void testWhereIssue240_notBoolean() { -// try { -// CCJSqlParserUtil.parse("SELECT count(*) FROM mytable WHERE 5"); -// fail("should not be parsed"); -// } catch (JSQLParserException ex) { -// //expected to fail -// } -// } + // @Test + // public void testWhereIssue240_notBoolean() { + // try { + // CCJSqlParserUtil.parse("SELECT count(*) FROM mytable WHERE 5"); + // fail("should not be parsed"); + // } catch (JSQLParserException ex) { + // //expected to fail + // } + // } @Test public void testWhereIssue240_true() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT count(*) FROM mytable WHERE true"); @@ -3137,10 +3191,10 @@ public void testProblemSqlIssue330() throws JSQLParserException { public void testProblemSqlIssue330_2() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT CAST('90 days' AS interval)"); } -// won't fix due to lookahead impact on parser -// @Test public void testKeywordOrderAsColumnnameIssue333() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("SELECT choice.response_choice_id AS uuid, choice.digit AS digit, choice.text_response AS textResponse, choice.voice_prompt AS voicePrompt, choice.action AS action, choice.contribution AS contribution, choice.order_num AS order, choice.description AS description, choice.is_join_conference AS joinConference, choice.voice_prompt_language_code AS voicePromptLanguageCode, choice.text_response_language_code AS textResponseLanguageCode, choice.description_language_code AS descriptionLanguageCode, choice.rec_phrase AS recordingPhrase FROM response_choices choice WHERE choice.presentation_id = ? ORDER BY choice.order_num", true); -// } + // won't fix due to lookahead impact on parser + // @Test public void testKeywordOrderAsColumnnameIssue333() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("SELECT choice.response_choice_id AS uuid, choice.digit AS digit, choice.text_response AS textResponse, choice.voice_prompt AS voicePrompt, choice.action AS action, choice.contribution AS contribution, choice.order_num AS order, choice.description AS description, choice.is_join_conference AS joinConference, choice.voice_prompt_language_code AS voicePromptLanguageCode, choice.text_response_language_code AS textResponseLanguageCode, choice.description_language_code AS descriptionLanguageCode, choice.rec_phrase AS recordingPhrase FROM response_choices choice WHERE choice.presentation_id = ? ORDER BY choice.order_num", true); + // } @Test public void testProblemKeywordCommitIssue341() throws JSQLParserException { @@ -3172,14 +3226,14 @@ public void testProblemIssue375Simplified2() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("select * from (pg_catalog.pg_class c inner join pg_catalog.pg_namespace n on n.oid = c.relnamespace and c.relname = 'business' and n.nspname = 'public') inner join pg_catalog.pg_attribute a on (not a.attisdropped) and a.attnum > 0 and a.attrelid = c.oid", true); } -// @Test public void testProblemIssue377() throws Exception { -// try { -// assertSqlCanBeParsedAndDeparsed("select 'yelp'::name as pktable_cat, n2.nspname as pktable_schem, c2.relname as pktable_name, a2.attname as pkcolumn_name, 'yelp'::name as fktable_cat, n1.nspname as fktable_schem, c1.relname as fktable_name, a1.attname as fkcolumn_name, i::int2 as key_seq, case ref.confupdtype when 'c' then 0::int2 when 'n' then 2::int2 when 'd' then 4::int2 when 'r' then 1::int2 else 3::int2 end as update_rule, case ref.confdeltype when 'c' then 0::int2 when 'n' then 2::int2 when 'd' then 4::int2 when 'r' then 1::int2 else 3::int2 end as delete_rule, ref.conname as fk_name, cn.conname as pk_name, case when ref.condeferrable then case when ref.condeferred then 5::int2 else 6::int2 end else 7::int2 end as deferrablity from ((((((( (select cn.oid, conrelid, conkey, confrelid, confkey, generate_series(array_lower(conkey, 1), array_upper(conkey, 1)) as i, confupdtype, confdeltype, conname, condeferrable, condeferred from pg_catalog.pg_constraint cn, pg_catalog.pg_class c, pg_catalog.pg_namespace n where contype = 'f' and conrelid = c.oid and relname = 'business' and n.oid = c.relnamespace and n.nspname = 'public' ) ref inner join pg_catalog.pg_class c1 on c1.oid = ref.conrelid) inner join pg_catalog.pg_namespace n1 on n1.oid = c1.relnamespace) inner join pg_catalog.pg_attribute a1 on a1.attrelid = c1.oid and a1.attnum = conkey[i]) inner join pg_catalog.pg_class c2 on c2.oid = ref.confrelid) inner join pg_catalog.pg_namespace n2 on n2.oid = c2.relnamespace) inner join pg_catalog.pg_attribute a2 on a2.attrelid = c2.oid and a2.attnum = confkey[i]) left outer join pg_catalog.pg_constraint cn on cn.conrelid = ref.confrelid and cn.contype = 'p') order by ref.oid, ref.i", true); -// } catch (Exception ex) { -// ex.printStackTrace(); -// throw ex; -// } -// } + // @Test public void testProblemIssue377() throws Exception { + // try { + // assertSqlCanBeParsedAndDeparsed("select 'yelp'::name as pktable_cat, n2.nspname as pktable_schem, c2.relname as pktable_name, a2.attname as pkcolumn_name, 'yelp'::name as fktable_cat, n1.nspname as fktable_schem, c1.relname as fktable_name, a1.attname as fkcolumn_name, i::int2 as key_seq, case ref.confupdtype when 'c' then 0::int2 when 'n' then 2::int2 when 'd' then 4::int2 when 'r' then 1::int2 else 3::int2 end as update_rule, case ref.confdeltype when 'c' then 0::int2 when 'n' then 2::int2 when 'd' then 4::int2 when 'r' then 1::int2 else 3::int2 end as delete_rule, ref.conname as fk_name, cn.conname as pk_name, case when ref.condeferrable then case when ref.condeferred then 5::int2 else 6::int2 end else 7::int2 end as deferrablity from ((((((( (select cn.oid, conrelid, conkey, confrelid, confkey, generate_series(array_lower(conkey, 1), array_upper(conkey, 1)) as i, confupdtype, confdeltype, conname, condeferrable, condeferred from pg_catalog.pg_constraint cn, pg_catalog.pg_class c, pg_catalog.pg_namespace n where contype = 'f' and conrelid = c.oid and relname = 'business' and n.oid = c.relnamespace and n.nspname = 'public' ) ref inner join pg_catalog.pg_class c1 on c1.oid = ref.conrelid) inner join pg_catalog.pg_namespace n1 on n1.oid = c1.relnamespace) inner join pg_catalog.pg_attribute a1 on a1.attrelid = c1.oid and a1.attnum = conkey[i]) inner join pg_catalog.pg_class c2 on c2.oid = ref.confrelid) inner join pg_catalog.pg_namespace n2 on n2.oid = c2.relnamespace) inner join pg_catalog.pg_attribute a2 on a2.attrelid = c2.oid and a2.attnum = confkey[i]) left outer join pg_catalog.pg_constraint cn on cn.conrelid = ref.confrelid and cn.contype = 'p') order by ref.oid, ref.i", true); + // } catch (Exception ex) { + // ex.printStackTrace(); + // throw ex; + // } + // } @Test public void testProblemInNotInProblemIssue379() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT rank FROM DBObjects WHERE rank NOT IN (0, 1)"); @@ -3230,13 +3284,13 @@ public void testForUpdateNoWait() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT * FROM mytable FOR UPDATE NOWAIT"); } -// @Test public void testSubSelectFailsIssue394() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("select aa.* , t.* from accenter.all aa, (select a.* from pacioli.emc_plan a) t"); -// } -// -// @Test public void testSubSelectFailsIssue394_2() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("select * from all"); -// } + // @Test public void testSubSelectFailsIssue394() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("select aa.* , t.* from accenter.all aa, (select a.* from pacioli.emc_plan a) t"); + // } + // + // @Test public void testSubSelectFailsIssue394_2() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("select * from all"); + // } @Test public void testMysqlIndexHints() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT column FROM testtable AS t0 USE INDEX (index1)"); @@ -3433,9 +3487,9 @@ public void testJoinerExpressionIssue596() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT * FROM a JOIN (b JOIN c ON b.id = c.id) ON a.id = c.id"); } -// @Test public void testJoinerExpressionIssue596_2() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("SELECT * FROM a JOIN b JOIN c ON b.id = c.id ON a.id = c.id"); -// } + // @Test public void testJoinerExpressionIssue596_2() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("SELECT * FROM a JOIN b JOIN c ON b.id = c.id ON a.id = c.id"); + // } @Test public void testProblemSqlIssue603() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT CASE WHEN MAX(CAST(a.jobNum AS INTEGER)) IS NULL THEN '1000' ELSE MAX(CAST(a.jobNum AS INTEGER)) + 1 END FROM user_employee a"); @@ -3524,8 +3578,8 @@ public void testMultiPartNamesForFunctionsIssue944() throws JSQLParserException assertSqlCanBeParsedAndDeparsed("SELECT pg_catalog.now()"); } -// Teradata allows SEL to be used in place of SELECT -// Deparse to the non-contracted form + // Teradata allows SEL to be used in place of SELECT + // Deparse to the non-contracted form @Test public void testSelContraction() throws JSQLParserException { final String statementSrc = "SEL name, age FROM person"; @@ -3634,10 +3688,10 @@ public void testForXmlPath() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT '|' + person_name FROM person JOIN person_group ON person.person_id = person_group.person_id WHERE person_group.group_id = 1 FOR XML PATH('')"); } -// @Test -// public void testForXmlPath2() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("SELECT ( STUFF( (SELECT '|' + person_name FROM person JOIN person_group ON person.person_id = person_group.person_id WHERE person_group.group_id = 1 FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,'')) AS person_name"); -// } + // @Test + // public void testForXmlPath2() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("SELECT ( STUFF( (SELECT '|' + person_name FROM person JOIN person_group ON person.person_id = person_group.person_id WHERE person_group.group_id = 1 FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,'')) AS person_name"); + // } @Test public void testChainedunctions() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT func('').func2('') AS foo FROM some_tables"); @@ -3648,10 +3702,10 @@ public void testCollateExprIssue164() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT u.name COLLATE Latin1_General_CI_AS AS User FROM users u"); } -// @Test -// public void testIntervalExpression() throws JSQLParserException { -// assertSqlCanBeParsedAndDeparsed("SELECT count(emails.id) FROM emails WHERE (emails.date_entered + 30 DAYS) > CURRENT_DATE"); -// } + // @Test + // public void testIntervalExpression() throws JSQLParserException { + // assertSqlCanBeParsedAndDeparsed("SELECT count(emails.id) FROM emails WHERE (emails.date_entered + 30 DAYS) > CURRENT_DATE"); + // } @Test public void testNotVariant() throws JSQLParserException { assertSqlCanBeParsedAndDeparsed("SELECT ! (1 + 1)"); @@ -3812,7 +3866,7 @@ public void visit(Select select) { @Override public void visit(PlainSelect plainSelect) { SelectExpressionItem typedExpression - = (SelectExpressionItem) plainSelect.getSelectItems().get(0); + = (SelectExpressionItem) plainSelect.getSelectItems().get(0); assertNotNull(typedExpression); assertNull(typedExpression.getAlias()); StringValue value = (StringValue) typedExpression.getExpression(); @@ -4065,13 +4119,13 @@ public void testWrongParseTreeIssue89() throws JSQLParserException { SetOperationList unionQueries = (SetOperationList) unionQuery.getSelectBody(); assertThat(unionQueries.getSelects()) - .extracting(select -> (PlainSelect) select).allSatisfy(ps -> assertNull(ps.getOrderByElements())); + .extracting(select -> (PlainSelect) select).allSatisfy(ps -> assertNull(ps.getOrderByElements())); assertThat(unionQueries.getOrderByElements()) - .isNotNull() - .hasSize(1) - .extracting(item -> item.toString()) - .contains("col"); + .isNotNull() + .hasSize(1) + .extracting(item -> item.toString()) + .contains("col"); } @Test @@ -4112,6 +4166,7 @@ public void testTableFunctionInExprIssue923() throws JSQLParserException { // .replace("@Prompt", "MyFunc"); // assertSqlCanBeParsedAndDeparsed(stmt, true); // } + @Test public void testTableFunctionInExprIssue923_3() throws JSQLParserException, IOException { String stmt = IOUtils.toString( @@ -4156,7 +4211,16 @@ public void testKeyWordView() throws JSQLParserException { @Test public void testPreserveAndOperator() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("SELECT * FROM mytable WHERE 1 = 2 && 2 = 3"); + String statement = "SELECT * FROM mytable WHERE 1 = 2 && 2 = 3"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse( + new Select().withSelectBody(new PlainSelect() + .addSelectItems(Collections.singleton(new AllColumns())) + .withFromItem(new Table("mytable")).withWhere( + new AndExpression().withUseOperator(true) + .withLeftExpression(new EqualsTo(new LongValue(1), new LongValue(2))) + .withRightExpression(new EqualsTo(new LongValue(2), new LongValue(3))))), + statement); } @Test diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SpeedTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SpeedTest.java index 116a2ee754..dd896daa1a 100644 --- a/src/test/java/net/sf/jsqlparser/statement/select/SpeedTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/select/SpeedTest.java @@ -16,18 +16,17 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; - +import org.junit.Test; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.statement.Statement; -import net.sf.jsqlparser.test.TestException; import net.sf.jsqlparser.statement.simpleparsing.CCJSqlParserManagerTest; +import net.sf.jsqlparser.test.TestException; import net.sf.jsqlparser.util.TablesNamesFinder; -import org.junit.Test; public class SpeedTest { - private final static int NUM_REPS = 500; + private final static int NUM_REPS_500 = 500; private final CCJSqlParserManager parserManager = new CCJSqlParserManager(); @Test @@ -36,7 +35,7 @@ public void testSpeed() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(SpeedTest.class. getResourceAsStream("/simple_parsing.txt"))); CCJSqlParserManagerTest d; - ArrayList statementsList = new ArrayList(); + List statementsList = new ArrayList<>(); while (true) { String statement = CCJSqlParserManagerTest.getStatement(in); @@ -90,21 +89,21 @@ public void testSpeed() throws Exception { int numTests = 0; // it seems that the very first parsing takes a while, so I put it aside Statement parsedStm = parserManager. - parse(new StringReader(statement = (String) statementsList.get(0))); + parse(new StringReader(statement = statementsList.get(0))); TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); - ArrayList parsedSelects = new ArrayList(NUM_REPS * statementsList.size()); + List iter = parsedSelects.iterator(); + while (iter.hasNext()) { + Select select = iter.next(); if (select != null) { numTests++; - List tableListRetr = tablesNamesFinder.getTableList(select); + List tableListRetr = tablesNamesFinder.getTableList(select); } } elapsedTime = System.currentTimeMillis() - time; statementsPerSecond = numTests * 1000 / elapsedTime; System.out. - println(numTests + " select scans for table name executed in " + elapsedTime + " milliseconds"); + println(numTests + " select scans for table name executed in " + elapsedTime + " milliseconds"); System.out.println(" (" + statementsPerSecond + " select scans for table name per second, " + df.format(1.0 / statementsPerSecond) + " seconds per select scans for table name)"); diff --git a/src/test/java/net/sf/jsqlparser/statement/truncate/TruncateTest.java b/src/test/java/net/sf/jsqlparser/statement/truncate/TruncateTest.java index e558f07f07..37a31ae989 100644 --- a/src/test/java/net/sf/jsqlparser/statement/truncate/TruncateTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/truncate/TruncateTest.java @@ -9,13 +9,16 @@ */ package net.sf.jsqlparser.statement.truncate; -import java.io.StringReader; +import static net.sf.jsqlparser.test.TestUtils.assertDeparse; +import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; -import static net.sf.jsqlparser.test.TestUtils.*; -import net.sf.jsqlparser.*; +import static org.junit.Assert.assertEquals; +import java.io.StringReader; + +import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserManager; -import static org.junit.Assert.assertEquals; +import net.sf.jsqlparser.schema.Table; import org.junit.Test; public class TruncateTest { @@ -43,12 +46,16 @@ public void testTruncate() throws Exception { @Test public void testTruncateDeparse() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("TRUNCATE TABLE foo"); + String statement = "TRUNCATE TABLE foo"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new Truncate().withTable(new Table("foo")), statement); } @Test public void testTruncateCascadeDeparse() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("TRUNCATE TABLE foo CASCADE"); + String statement = "TRUNCATE TABLE foo CASCADE"; + assertSqlCanBeParsedAndDeparsed(statement); + assertDeparse(new Truncate().withTable(new Table("foo")).withCascade(true), statement); } } diff --git a/src/test/java/net/sf/jsqlparser/statement/upsert/UpsertTest.java b/src/test/java/net/sf/jsqlparser/statement/upsert/UpsertTest.java index 55f2a02412..e4ce699bfa 100644 --- a/src/test/java/net/sf/jsqlparser/statement/upsert/UpsertTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/upsert/UpsertTest.java @@ -21,7 +21,6 @@ import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.parser.CCJSqlParserManager; -import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.PlainSelect; @@ -36,14 +35,12 @@ public void testUpsert() throws JSQLParserException { assertEquals("TEST", upsert.getTable().getName()); assertTrue(upsert.isUseValues()); assertEquals(2, upsert.getColumns().size()); - assertEquals("NAME", ((Column) upsert.getColumns().get(0)).getColumnName()); - assertEquals("ID", ((Column) upsert.getColumns().get(1)).getColumnName()); + assertEquals("NAME", upsert.getColumns().get(0).getColumnName()); + assertEquals("ID", upsert.getColumns().get(1).getColumnName()); assertEquals(2, ((ExpressionList) upsert.getItemsList()).getExpressions().size()); assertEquals("foo", - ((StringValue) ((ExpressionList) upsert.getItemsList()).getExpressions().get(0)). - getValue()); - assertEquals(123, ((LongValue) ((ExpressionList) upsert.getItemsList()).getExpressions(). - get(1)).getValue()); + ((StringValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(0)).getValue()); + assertEquals(123, ((LongValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(1)).getValue()); assertFalse(upsert.isUseSelectBrackets()); assertFalse(upsert.isUseDuplicate()); assertEquals(statement, "" + upsert); @@ -56,15 +53,13 @@ public void testUpsertDuplicate() throws JSQLParserException { assertEquals("TEST", upsert.getTable().getName()); assertEquals(2, upsert.getColumns().size()); assertTrue(upsert.isUseValues()); - assertEquals("ID", ((Column) upsert.getColumns().get(0)).getColumnName()); - assertEquals("COUNTER", ((Column) upsert.getColumns().get(1)).getColumnName()); + assertEquals("ID", upsert.getColumns().get(0).getColumnName()); + assertEquals("COUNTER", upsert.getColumns().get(1).getColumnName()); assertEquals(2, ((ExpressionList) upsert.getItemsList()).getExpressions().size()); - assertEquals(123, ((LongValue) ((ExpressionList) upsert.getItemsList()).getExpressions(). - get(0)).getValue()); - assertEquals(0, ((LongValue) ((ExpressionList) upsert.getItemsList()).getExpressions(). - get(1)).getValue()); + assertEquals(123, ((LongValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(0)).getValue()); + assertEquals(0, ((LongValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(1)).getValue()); assertEquals(1, upsert.getDuplicateUpdateColumns().size()); - assertEquals("COUNTER", ((Column) upsert.getDuplicateUpdateColumns().get(0)).getColumnName()); + assertEquals("COUNTER", upsert.getDuplicateUpdateColumns().get(0).getColumnName()); assertEquals(1, upsert.getDuplicateUpdateExpressionList().size()); assertEquals("COUNTER + 1", upsert.getDuplicateUpdateExpressionList().get(0).toString()); assertFalse(upsert.isUseSelectBrackets()); @@ -79,8 +74,8 @@ public void testUpsertSelect() throws JSQLParserException { assertEquals("test.targetTable", upsert.getTable().getFullyQualifiedName()); assertEquals(2, upsert.getColumns().size()); assertFalse(upsert.isUseValues()); - assertEquals("col1", ((Column) upsert.getColumns().get(0)).getColumnName()); - assertEquals("col2", ((Column) upsert.getColumns().get(1)).getColumnName()); + assertEquals("col1", upsert.getColumns().get(0).getColumnName()); + assertEquals("col2", upsert.getColumns().get(1).getColumnName()); assertNull(upsert.getItemsList()); assertNotNull(upsert.getSelect()); assertEquals("test.sourceTable", @@ -97,11 +92,9 @@ public void testUpsertN() throws JSQLParserException { assertEquals(3, ((ExpressionList) upsert.getItemsList()).getExpressions().size()); assertTrue(upsert.isUseValues()); assertEquals("foo", - ((StringValue) ((ExpressionList) upsert.getItemsList()).getExpressions().get(0)). - getValue()); + ((StringValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(0)).getValue()); assertEquals("bar", - ((StringValue) ((ExpressionList) upsert.getItemsList()).getExpressions().get(1)). - getValue()); + ((StringValue) upsert.getItemsList(ExpressionList.class).getExpressions().get(1)).getValue()); assertEquals(3, ((LongValue) ((ExpressionList) upsert.getItemsList()).getExpressions(). get(2)).getValue()); assertFalse(upsert.isUseSelectBrackets()); diff --git a/src/test/java/net/sf/jsqlparser/statement/values/ValuesTest.java b/src/test/java/net/sf/jsqlparser/statement/values/ValuesTest.java index 36d9262a6a..c3725ac6b4 100644 --- a/src/test/java/net/sf/jsqlparser/statement/values/ValuesTest.java +++ b/src/test/java/net/sf/jsqlparser/statement/values/ValuesTest.java @@ -10,14 +10,29 @@ package net.sf.jsqlparser.statement.values; import net.sf.jsqlparser.JSQLParserException; -import static net.sf.jsqlparser.test.TestUtils.assertSqlCanBeParsedAndDeparsed; +import net.sf.jsqlparser.expression.LongValue; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SetOperationList; + +import static net.sf.jsqlparser.test.TestUtils.*; + import org.junit.Test; public class ValuesTest { @Test public void testDuplicateKey() throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed("VALUES (1, 2, 'test')"); + String statement = "VALUES (1, 2, 'test')"; + Statement parsed = assertSqlCanBeParsedAndDeparsed(statement); + Select created = new Select().withSelectBody(new SetOperationList() + .addBrackets(Boolean.FALSE).addSelects(new ValuesStatement().addExpressions(new LongValue(1)) + .addExpressions(asList(new LongValue(2), new StringValue("test"))))); + + assertDeparse(created, statement); + assertEqualsObjectTree(parsed, created); + System.out.println(toReflectionString(created)); } @Test diff --git a/src/test/java/net/sf/jsqlparser/test/TestUtils.java b/src/test/java/net/sf/jsqlparser/test/TestUtils.java index 5b8d0fad68..f94ad13606 100644 --- a/src/test/java/net/sf/jsqlparser/test/TestUtils.java +++ b/src/test/java/net/sf/jsqlparser/test/TestUtils.java @@ -9,13 +9,25 @@ */ package net.sf.jsqlparser.test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.function.Consumer; import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.OracleHint; import net.sf.jsqlparser.parser.CCJSqlParser; import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.parser.Node; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; @@ -23,9 +35,10 @@ import net.sf.jsqlparser.util.deparser.ExpressionDeParser; import net.sf.jsqlparser.util.deparser.SelectDeParser; import net.sf.jsqlparser.util.deparser.StatementDeParser; +import org.apache.commons.lang3.builder.MultilineRecursiveToStringStyle; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; import org.junit.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import org.junit.Test; /** @@ -37,8 +50,13 @@ public class TestUtils { private static final Pattern SQL_COMMENT_PATTERN = Pattern. compile("(--.*$)|(/\\*.*?\\*/)", Pattern.MULTILINE); - public static void assertSqlCanBeParsedAndDeparsed(String statement) throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed(statement, false); + /** + * @param statement + * @return the parsed {@link Statement} + * @throws JSQLParserException + */ + public static Statement assertSqlCanBeParsedAndDeparsed(String statement) throws JSQLParserException { + return assertSqlCanBeParsedAndDeparsed(statement, false); } /** @@ -46,16 +64,30 @@ public static void assertSqlCanBeParsedAndDeparsed(String statement) throws JSQL * * @param statement * @param laxDeparsingCheck removes all linefeeds from the original and - * removes all double spaces. The check is caseinsensitive. + * removes all double spaces. The check is + * caseinsensitive. + * @return the parsed {@link Statement} * @throws JSQLParserException */ - public static void assertSqlCanBeParsedAndDeparsed(String statement, boolean laxDeparsingCheck) throws JSQLParserException { - assertSqlCanBeParsedAndDeparsed(statement, laxDeparsingCheck, null); + public static Statement assertSqlCanBeParsedAndDeparsed(String statement, boolean laxDeparsingCheck) + throws JSQLParserException { + return assertSqlCanBeParsedAndDeparsed(statement, laxDeparsingCheck, null); } - public static void assertSqlCanBeParsedAndDeparsed(String statement, boolean laxDeparsingCheck, Consumer consumer) throws JSQLParserException { + /** + * @param statement + * @param laxDeparsingCheck removes all linefeeds from the original and + * removes all double spaces. The check is + * caseinsensitive. + * @param consumer + * @return the parsed {@link Statement} + * @throws JSQLParserException + */ + public static Statement assertSqlCanBeParsedAndDeparsed(String statement, boolean laxDeparsingCheck, + Consumer consumer) throws JSQLParserException { Statement parsed = CCJSqlParserUtil.parse(statement, consumer); assertStatementCanBeDeparsedAs(parsed, statement, laxDeparsingCheck); + return parsed; } public static void assertStatementCanBeDeparsedAs(Statement parsed, String statement) { @@ -66,8 +98,158 @@ public static void assertStatementCanBeDeparsedAs(Statement parsed, String state assertEquals(buildSqlString(statement, laxDeparsingCheck), buildSqlString(parsed.toString(), laxDeparsingCheck)); + assertDeparse(parsed, statement, laxDeparsingCheck); + } + + /** + * Asserts that the {@link Statement} can be deparsed and deparsing results in + * given #statement + * + * @param stmt + * @param statement + */ + public static void assertDeparse(Statement stmt, String statement) { + assertDeparse(stmt, statement, false); + } + + /** + * Compares the object-tree of a given parsed model and a created one. + * + * @param parsed + * @param created + */ + public static void assertEqualsObjectTree(Statement parsed, Statement created) { + assertEquals(toReflectionString(parsed), toReflectionString(created)); + } + + /** + * @param stmt + * @return a {@link String} build by {@link ToStringBuilder} and + * {@link ObjectTreeToStringStyle#INSTANCE} + */ + public static String toReflectionString(Statement stmt) { + return toReflectionString(stmt, false); + } + + /** + * @param stmt + * @return a {@link String} build by {@link ToStringBuilder} and + * {@link ObjectTreeToStringStyle#INSTANCE} + */ + public static String toReflectionString(Statement stmt, boolean includingASTNode) { + ReflectionToStringBuilder strb = new ReflectionToStringBuilder(stmt, + includingASTNode ? ObjectTreeToStringStyle.INSTANCE_INCLUDING_AST : ObjectTreeToStringStyle.INSTANCE); + return strb.build(); + } + + /** + * Replacement of {@link Arrays#asList(Object...)} which returns + * java.util.Arrays$ArrayList not java.util.ArrayList, the internal model uses + * java.util.ArrayList by default, which supports modification + * + * @param + * @param obj + * @return a {@link ArrayList} of given items + */ + @SafeVarargs + public static List asList(T... obj) { + return Stream.of(obj).collect(Collectors.toCollection(ArrayList::new)); + } + + /** + *

+ * {@code ToStringStyle} that outputs on multiple lines without identity + * hashcode. + *

+ */ + private static final class ObjectTreeToStringStyle extends MultilineRecursiveToStringStyle { + + private static final long serialVersionUID = 1L; + + public static final ObjectTreeToStringStyle INSTANCE = new ObjectTreeToStringStyle(false); + public static final ObjectTreeToStringStyle INSTANCE_INCLUDING_AST = new ObjectTreeToStringStyle(true); + + private boolean includingASTNode; + + /** + *

+ * Constructor. + *

+ * + *

+ * Use the static constant rather than instantiating. + *

+ */ + private ObjectTreeToStringStyle(boolean includingASTNode) { + super(); + this.includingASTNode = includingASTNode; + this.setUseClassName(true); + this.setUseIdentityHashCode(false); + ToStringBuilder.setDefaultStyle(this); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final Object value, + final Boolean fullDetail) { + if (includingASTNode || !"node".equals(fieldName)) { + super.append(buffer, fieldName, value, fullDetail); + } + } + + /** + * empty {@link Collection}'s should be printed as null, otherwise + * the outcome cannot be compared + */ + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { + if (coll.isEmpty()) { + appendNullText(buffer, fieldName); + } else { + super.appendDetail(buffer, fieldName, coll); + } + } + + /** + * empty {@link Map}'s should be printed as null, otherwise the + * outcome cannot be compared + */ + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map coll) { + if (coll.isEmpty()) { + appendNullText(buffer, fieldName); + } else { + super.appendDetail(buffer, fieldName, coll); + } + } + + @Override + protected boolean accept(Class clazz) { + if (includingASTNode) { + return super.accept(clazz); + } else { + return isNotANode(clazz) && super.accept(clazz); + } + } + + public boolean isNotANode(Class clazz) { + return !Node.class.isAssignableFrom(clazz); + } + + } + + /** + * Asserts that the {@link Statement} can be deparsed and deparsing results in + * given #statement + * + * @param stmt + * @param statement + * @param laxDeparsingCheck removes all linefeeds from the original and + * removes all double spaces. The check is + * caseinsensitive. + */ + public static void assertDeparse(Statement stmt, String statement, boolean laxDeparsingCheck) { StatementDeParser deParser = new StatementDeParser(new StringBuilder()); - parsed.accept(deParser); + stmt.accept(deParser); assertEquals(buildSqlString(statement, laxDeparsingCheck), buildSqlString(deParser.getBuffer().toString(), laxDeparsingCheck)); } diff --git a/src/test/java/net/sf/jsqlparser/util/RandomUtils.java b/src/test/java/net/sf/jsqlparser/util/RandomUtils.java new file mode 100644 index 0000000000..b8b4eb08a6 --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/util/RandomUtils.java @@ -0,0 +1,146 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.util; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.apache.commons.lang3.RandomStringUtils; + +/** + * An utility to get a random value for any type given - see + * {@link #getRandomValueForType(Class)} + * + * @author gitmotte + * @see #pushObjects(List) + */ +public class RandomUtils { + + private static final Logger LOG = Logger.getLogger(RandomUtils.class.getName()); + private static final Random RANDOM = new Random(); + + private static final ThreadLocal, Object>> OBJECTS = new ThreadLocal<>(); + + /** + * register models (for use within method {@link #getRandomValueForType(Class)} + */ + public static void pushObjects(List obj) { + Map, Object> m = new HashMap<>(); + OBJECTS.set(m); + obj.stream().forEach(o -> { + m.put(o.getClass(), o); + for (Class iface : o.getClass().getInterfaces()) { + // register object with its implemented interfaces + // if we need an object for interface requested, an instance is available + m.put(iface, o); + } + Class cls = o.getClass(); + while ((cls = cls.getSuperclass()) != null) { + if (!Object.class.equals(cls)) { + // register object with its parent classes + // if we need an object for parent class requested, an instance is available + m.put(cls, o); + } + } + }); + + } + + /** + * @param + * @param type + * @return a random non-null value for given type or + * null if not supported. + */ + public static T getRandomValueForType(Class type) { + Object value = null; + if (Integer.class.equals(type) || int.class.equals(type)) { + value = RandomUtils.RANDOM.nextInt(); + } else if (Long.class.equals(type) || long.class.equals(type)) { + value = RandomUtils.RANDOM.nextLong(); + } else if (Boolean.class.equals(type) || boolean.class.equals(type)) { + value = RandomUtils.RANDOM.nextBoolean(); + } else if (Float.class.equals(type) || float.class.equals(type)) { + value = RandomUtils.RANDOM.nextFloat(); + } else if (Double.class.equals(type) || double.class.equals(type)) { + value = RandomUtils.RANDOM.nextDouble(); + } else if (Byte.class.equals(type) || byte.class.equals(type)) { + byte[] b = new byte[1]; + RandomUtils.RANDOM.nextBytes(b); + value = b[0]; + } else if (Short.class.equals(type) || short.class.equals(type)) { + value = (short) RandomUtils.RANDOM.nextInt(15); + } else if (char.class.equals(type)) { + value = RandomStringUtils.random(1).toCharArray()[0]; + } else if (Time.class.equals(type)) { + value = new Time(Math.abs(RandomUtils.RANDOM.nextLong())); + } else if (Timestamp.class.equals(type)) { + value = new Timestamp(Math.abs(RandomUtils.RANDOM.nextLong())); + } else if (Date.class.equals(type)) { + value = new Date(Math.abs(RandomUtils.RANDOM.nextLong())); + } else { + int size = RandomUtils.RANDOM.nextInt(10); + if (String.class.equals(type)) { + value = RandomStringUtils.random(size); + } else if (Collection.class.equals(type) || List.class.equals(type)) { + List c = new ArrayList<>(); + value = c; + } else if (Set.class.equals(type)) { + Set c = new HashSet<>(); + value = c; + } else if (type.isArray()) { + Object [] a = (Object[]) Array.newInstance(type.getComponentType(), size); + for (int i = 0; i < size; i++) { + a[i] = getRandomValueForType(type.getComponentType()); + } + value = a; + } else if (Map.class.equals(type)) { + Map c = new HashMap<>(); + value = c; + } else if (LocalDateTime.class.equals(type)) { + value = LocalDateTime.now(); + } else { + // try to get an object from test-objects + value = OBJECTS.get().get(type); + if (value == null) { + if (type.isEnum()) { + @SuppressWarnings("unchecked") + EnumSet enums = EnumSet.allOf(type.asSubclass(Enum.class)); + value = new ArrayList<>(enums).get(RandomUtils.RANDOM.nextInt(enums.size())); + } else { + try { + value = type.getConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { + // cannot get default instance with empty constructor + LOG.log(Level.WARNING, "cannot get default instance with reflection for type " + type); + } + } + } + } + } + return type.cast(value); + } + +} diff --git a/src/test/java/net/sf/jsqlparser/util/ReflectionTestUtils.java b/src/test/java/net/sf/jsqlparser/util/ReflectionTestUtils.java new file mode 100644 index 0000000000..69d7295955 --- /dev/null +++ b/src/test/java/net/sf/jsqlparser/util/ReflectionTestUtils.java @@ -0,0 +1,185 @@ +/*- + * #%L + * JSQLParser library + * %% + * Copyright (C) 2004 - 2020 JSQLParser + * %% + * Dual licensed under GNU LGPL 2.1 or Apache License 2.0 + * #L% + */ +package net.sf.jsqlparser.util; + +import static org.junit.Assume.assumeTrue; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.AssumptionViolatedException; + +/** + * @author gitmotte + */ +public class ReflectionTestUtils { + + public static final Predicate GETTER_METHODS = m -> !void.class.isAssignableFrom(m.getReturnType()) + && m.getParameterCount() == 0 + && (m.getName().startsWith("get") || m.getName().startsWith("is")); + + public static final Predicate SETTER_METHODS = m -> void.class.isAssignableFrom(m.getReturnType()) + && m.getParameterCount() == 1 + && m.getName().startsWith("set"); + + public static final Predicate CHAINING_METHODS = m -> m.getDeclaringClass() + .isAssignableFrom(m.getReturnType()) + // could be prefixed with "with" or not, does not matter + && m.getParameterCount() == 1; + + /** + * Testing of setters, getters, with-/add-methods by calling them with random + * parameter-values + *
    + *
  • testing, whether return-value is the specific type (not the parent) + *
  • testing, whether calling the methods do not throw any exceptions + *
+ * + * @param objs + * @param testMethodFilter - additional filter to skip some methods (by + * returning false). Default-Filters: + * {@link #notDeclaredInObjectClass(Method)}, + * {@link #GETTER_METHODS}, {@link #SETTER_METHODS}, + * {@link #CHAINING_METHODS} + */ + @SafeVarargs + public static void testGetterSetterChaining(List objs, Predicate... testMethodFilter) { + RandomUtils.pushObjects(objs); + objs.forEach(o -> { + testMethodInvocation(o, ReflectionTestUtils::anyReturnType, ReflectionTestUtils::reflectiveNonNullArgs, + ArrayUtils.insert(0, testMethodFilter, GETTER_METHODS, ReflectionTestUtils::notDeclaredInObjectClass)); + testMethodInvocation(o, ReflectionTestUtils::noReturnTypeValid, ReflectionTestUtils::reflectiveNonNullArgs, + ArrayUtils.insert(0, testMethodFilter, SETTER_METHODS, ReflectionTestUtils::notDeclaredInObjectClass)); + testMethodInvocation(o, ReflectionTestUtils::returnTypeThis, ReflectionTestUtils::reflectiveNonNullArgs, + ArrayUtils.insert(0, testMethodFilter, CHAINING_METHODS, ReflectionTestUtils::notDeclaredInObjectClass)); + }); + } + + private static boolean notDeclaredInObjectClass(Method m) { + return !Object.class.equals(m.getDeclaringClass()); + } + + private static Object[] reflectiveNonNullArgs(Method m) { + List params = new ArrayList<>(); + for (Parameter p : m.getParameters()) { + Class type = p.getType(); + Object value = RandomUtils.getRandomValueForType(type); + assumeTrue("cannot get random value for type " + type, value != null); + params.add(value); + } + return params.toArray(); + } + + /** + * @param returnValue + * @param m + * @return true, if the return-type is equals the method-declaring + * class + */ + private static boolean returnTypeThis(Object returnValue, Method m) { + return returnValue != null && m.getDeclaringClass().equals(returnValue.getClass()); + } + + /** + * @param returnValue + * @param m + * @return always true + */ + private static boolean anyReturnType(Object returnValue, Method m) { + return true; + } + + /** + * @param returnValue + * @param m + * @return true, if returnValue is null + */ + private static boolean noReturnTypeValid(Object returnValue, Method m) { + return returnValue == null; + } + + /** + * @param object + * @param argsFunction + * @param methodFilters + */ + @SafeVarargs + public static void testMethodInvocation( Object object, BiPredicate returnTypeCheck, + Function argsFunction, + Predicate... methodFilters) { + log(Level.INFO, "testing methods of class " + object.getClass()); + for (Method m : object.getClass().getMethods()) { + boolean testMethod = true; + for (Predicate f : methodFilters) { + if (!f.test(m)) { + log(Level.FINE, "skip method " + m.toGenericString()); + testMethod = false; + break; + } + } + if (testMethod) { + log(Level.INFO, "testing method " + m.toGenericString()); + try { + invoke(m, returnTypeCheck, argsFunction, object); + } catch (Exception e) { + assertFalse( + String.format("%s throws on invocation on object: %s", m.toGenericString(), + object.getClass()), + false); + } + } + } + } + + /** + * Invoke one method of given object with args provided by #argsFunction, and + * test it's return-value + * + * @param method + * @param returnValueCheck + * @param argsFunction + * @param object + * @throws IllegalAccessException + * @throws InvocationTargetException + */ + public static void invoke(Method method, BiPredicate returnValueCheck, + Function argsFunction, + Object object) + throws IllegalAccessException, InvocationTargetException { + try { + Object returnValue = method.invoke(object, argsFunction.apply(method)); + if (!void.class.isAssignableFrom(method.getReturnType())) { + assertTrue("unexpected return-value with type " + returnValue.getClass() + " for method " + + method.toGenericString(), returnValueCheck.test(returnValue, method)); + } + } catch (AssumptionViolatedException tae) { + log(Level.INFO, "skip methods " + method.toGenericString() + ", detail: " + tae.getMessage()); + } + } + + private static void log(Level level, String string) { + if (Logger.getAnonymousLogger().isLoggable(level)) { + System.out.println(string); + } + } + +} diff --git a/src/test/java/net/sf/jsqlparser/util/SelectUtilsTest.java b/src/test/java/net/sf/jsqlparser/util/SelectUtilsTest.java index 332fa94548..6adb388e50 100644 --- a/src/test/java/net/sf/jsqlparser/util/SelectUtilsTest.java +++ b/src/test/java/net/sf/jsqlparser/util/SelectUtilsTest.java @@ -99,8 +99,8 @@ public void testBuildSelectFromTableAndParsedExpression() throws JSQLParserExcep buildSelectFromTableAndExpressions(new Table("mytable"), "a+b", "test"); assertEquals("SELECT a + b, test FROM mytable", select.toString()); - assertTrue(((SelectExpressionItem) ((PlainSelect) select.getSelectBody()).getSelectItems(). - get(0)).getExpression() instanceof Addition); + assertTrue(((SelectExpressionItem) select.getSelectBody(PlainSelect.class) + .getSelectItems().get(0)).getExpression() instanceof Addition); } @Test diff --git a/src/test/java/net/sf/jsqlparser/util/TablesNamesFinderTest.java b/src/test/java/net/sf/jsqlparser/util/TablesNamesFinderTest.java index 853dcb44ec..6cc48d0123 100644 --- a/src/test/java/net/sf/jsqlparser/util/TablesNamesFinderTest.java +++ b/src/test/java/net/sf/jsqlparser/util/TablesNamesFinderTest.java @@ -23,6 +23,7 @@ import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.merge.Merge; +import net.sf.jsqlparser.statement.merge.MergeInsert; import net.sf.jsqlparser.statement.replace.Replace; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.simpleparsing.CCJSqlParserManagerTest; @@ -110,8 +111,8 @@ private void runTestOnResource(String resPath) throws Exception { List tableListRetr = tablesNamesFinder.getTableList(statement); assertEquals("stm num:" + numSt, tablesArray.length, tableListRetr.size()); - for (int i = 0; i < tablesArray.length; i++) { - assertTrue("stm num:" + numSt, tableListRetr.contains(tablesArray[i])); + for (String element : tablesArray) { + assertTrue("stm num:" + numSt, tableListRetr.contains(element)); } } catch (Exception e) { throw new TestException("error at stm num: " + numSt + " in file " + resPath, e); @@ -160,7 +161,7 @@ public void testGetTableListWithAlias() throws Exception { TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List tableList = tablesNamesFinder.getTableList(selectStatement); assertEquals(1, tableList.size()); - assertEquals("MY_TABLE1", (String) tableList.get(0)); + assertEquals("MY_TABLE1", tableList.get(0)); } @Test @@ -172,7 +173,7 @@ public void testGetTableListWithStmt() throws Exception { TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List tableList = tablesNamesFinder.getTableList(selectStatement); assertEquals(1, tableList.size()); - assertEquals("MY_TABLE1", (String) tableList.get(0)); + assertEquals("MY_TABLE1", tableList.get(0)); } @Test @@ -366,7 +367,7 @@ public void testInsertSubSelect() throws JSQLParserException { @Test public void testExpr() throws JSQLParserException { String sql = "mycol in (select col2 from mytable)"; - Expression expr = (Expression) CCJSqlParserUtil.parseCondExpression(sql); + Expression expr = CCJSqlParserUtil.parseCondExpression(sql); TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List tableList = tablesNamesFinder.getTableList(expr); assertEquals(1, tableList.size()); @@ -433,20 +434,26 @@ public void testGetTableListForMerge() throws Exception { String sql = "MERGE INTO employees e USING hr_records h ON (e.id = h.emp_id) WHEN MATCHED THEN UPDATE SET e.address = h.address WHEN NOT MATCHED THEN INSERT (id, address) VALUES (h.emp_id, h.address);"; TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); - List tableList = tablesNamesFinder.getTableList((Merge) CCJSqlParserUtil.parse(sql)); + Merge parsed = (Merge) CCJSqlParserUtil.parse(sql); + List tableList = tablesNamesFinder.getTableList(parsed); assertEquals(2, tableList.size()); - assertEquals("employees", (String) tableList.get(0)); - assertEquals("hr_records", (String) tableList.get(1)); + assertEquals("employees", tableList.get(0)); + assertEquals("hr_records", tableList.get(1)); + + Merge created = new Merge() + .withMergeInsert(new MergeInsert().addColumns(new Column("id"), new Column("address"))); + // TestUtils.assertEqualsObjectTree(parsed, created); + } @Test public void testGetTableListForMergeUsingQuery() throws Exception { String sql = "MERGE INTO employees e USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h ON (e.id = h.emp_id) WHEN MATCHED THEN UPDATE SET e.address = h.address WHEN NOT MATCHED THEN INSERT (id, address) VALUES (h.emp_id, h.address)"; TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); - List tableList = tablesNamesFinder.getTableList((Merge) CCJSqlParserUtil.parse(sql)); + List tableList = tablesNamesFinder.getTableList(CCJSqlParserUtil.parse(sql)); assertEquals(2, tableList.size()); - assertEquals("employees", (String) tableList.get(0)); - assertEquals("hr_records", (String) tableList.get(1)); + assertEquals("employees", tableList.get(0)); + assertEquals("hr_records", tableList.get(1)); } @Test @@ -582,7 +589,7 @@ public void testDescribe() throws JSQLParserException { @Test public void testBetween() throws JSQLParserException { String sql = "mycol BETWEEN (select col2 from mytable) AND (select col3 from mytable2)"; - Expression expr = (Expression) CCJSqlParserUtil.parseCondExpression(sql); + Expression expr = CCJSqlParserUtil.parseCondExpression(sql); TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List tableList = tablesNamesFinder.getTableList(expr); assertEquals(2, tableList.size()); @@ -607,7 +614,7 @@ public void testCreateSequence_throwsException() throws JSQLParserException { Statement stmt = CCJSqlParserUtil.parse(sql); TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); assertThatThrownBy(() -> tablesNamesFinder.getTableList(stmt)).isInstanceOf(UnsupportedOperationException.class) - .hasMessage("Finding tables from CreateSequence is not supported"); + .hasMessage("Finding tables from CreateSequence is not supported"); } @Test @@ -616,7 +623,7 @@ public void testAlterSequence_throwsException() throws JSQLParserException { Statement stmt = CCJSqlParserUtil.parse(sql); TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); assertThatThrownBy(() -> tablesNamesFinder.getTableList(stmt)).isInstanceOf(UnsupportedOperationException.class) - .hasMessage("Finding tables from AlterSequence is not supported"); + .hasMessage("Finding tables from AlterSequence is not supported"); } @Test diff --git a/src/test/java/net/sf/jsqlparser/util/deparser/ExecuteDeParserTest.java b/src/test/java/net/sf/jsqlparser/util/deparser/ExecuteDeParserTest.java index 23b88e0916..4a8e380b54 100644 --- a/src/test/java/net/sf/jsqlparser/util/deparser/ExecuteDeParserTest.java +++ b/src/test/java/net/sf/jsqlparser/util/deparser/ExecuteDeParserTest.java @@ -9,7 +9,7 @@ */ package net.sf.jsqlparser.util.deparser; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.mock; @@ -18,24 +18,24 @@ import org.junit.Before; import org.junit.Test; -import org.mockito.Mock; - import net.sf.jsqlparser.expression.Expression; -import net.sf.jsqlparser.expression.ExpressionVisitor; +import net.sf.jsqlparser.expression.JdbcParameter; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.statement.execute.Execute; +import net.sf.jsqlparser.statement.execute.Execute.EXEC_TYPE; public class ExecuteDeParserTest { - private ExecuteDeParser executeDeParser; - @Mock - private ExpressionVisitor expressionVisitor; + private ExecuteDeParser executeDeParser; + private ExpressionDeParser expressionVisitor; private StringBuilder buffer; @Before public void setUp() { buffer = new StringBuilder(); + expressionVisitor = new ExpressionDeParser(); + expressionVisitor.setBuffer(buffer); executeDeParser = new ExecuteDeParser(expressionVisitor, buffer); } @@ -43,38 +43,36 @@ public void setUp() { public void shouldDeParseExecute() { Execute execute = new Execute(); String name = "name"; - ExpressionList exprList = new ExpressionList(); - List expressions = new ArrayList(); - Expression expression1 = mock(Expression.class); - Expression expression2 = mock(Expression.class); - execute.setName(name); - execute.setExprList(exprList); - exprList.setExpressions(expressions); - expressions.add(expression1); - expressions.add(expression2); + List expressions = new ArrayList<>(); + expressions.add(new JdbcParameter()); + expressions.add(new JdbcParameter()); + + execute.withName(name) + .withExecType(EXEC_TYPE.EXECUTE).withParenthesis(true) + .withExprList(new ExpressionList().withExpressions(expressions)); executeDeParser.deParse(execute); String actual = buffer.toString(); - assertTrue(actual.matches("EXECUTE " + name + " .*?, .*")); + assertEquals("EXECUTE " + name + " (?, ?)", actual); } @Test public void shouldUseProvidedExpressionVisitorWhenDeParsingExecute() { Execute execute = new Execute(); String name = "name"; - ExpressionList exprList = new ExpressionList(); - List expressions = new ArrayList(); + Expression expression1 = mock(Expression.class); Expression expression2 = mock(Expression.class); - execute.setName(name); - execute.setExprList(exprList); - exprList.setExpressions(expressions); + List expressions = new ArrayList<>(); expressions.add(expression1); expressions.add(expression2); + ExpressionList exprList = new ExpressionList().addExpressions(expressions); + execute.withName(name).withExprList(exprList); + executeDeParser.deParse(execute); then(expression1).should().accept(expressionVisitor);