From 750a5ed1f5c690ebea34188a66e94177bfbb85c0 Mon Sep 17 00:00:00 2001 From: Andreas Reichel Date: Thu, 28 Dec 2023 20:41:56 +0700 Subject: [PATCH] style: fix all QA execptions --- README.md | 89 +- build.gradle | 148 +- config/pmd/ruleset.xml | 2 +- .../com/manticore/jsqlformatter/Comment.java | 2 +- .../manticore/jsqlformatter/CommentMap.java | 38 +- .../jsqlformatter/FragmentContentHandler.java | 20 +- .../jsqlformatter/JSQLFormatter.java | 1248 +++++++++-------- .../manticore/jsqlformatter/JavaTools.java | 72 +- .../com/manticore/jsqlformatter/RRTools.java | 16 +- .../jsqlformatter/ASTVisualizationTest.java | 1 - .../jsqlformatter/DebugStatementTest.java | 3 +- .../manticore/jsqlformatter/ParserTest.java | 2 +- .../jsqlformatter/StandardFileTest.java | 16 +- .../jsqlformatter/simple/SQLFileTest.sql | 1 + .../jsqlformatter/simple/SQLFileTest_1.sql | 368 ++++- .../jsqlformatter/standard/ExpressionTest.sql | 8 + .../standard/StandardCreateViewTest.sql | 2 +- .../{simple => wip}/EmptyStatementTest.sql | 0 .../{simple => wip}/Issue0003.sql | 0 19 files changed, 1308 insertions(+), 728 deletions(-) create mode 100644 src/test/resources/com/manticore/jsqlformatter/standard/ExpressionTest.sql rename src/test/resources/com/manticore/jsqlformatter/{simple => wip}/EmptyStatementTest.sql (100%) rename src/test/resources/com/manticore/jsqlformatter/{simple => wip}/Issue0003.sql (100%) diff --git a/README.md b/README.md index b7db749..ba2f363 100644 --- a/README.md +++ b/README.md @@ -14,53 +14,53 @@ Java SQL Formatter, Beautifier and Pretty Printer. Please visit our [Website](ht * Export to Java String, StringBuilder or MessageFormat, while handling parameters * Command Line Option (CLI) and SQL Inline Options - ```shell - java -jar JSQLFormatter.jar [-i ] [-o ] [-f | - --ansi | --html] [-t | -2 | -8] [--keywordSpelling ] - [--functionSpelling ] [--objectSpelling ] [--separation - ] [--squareBracketQuotation ] - - -i,--inputFile The input SQL file or folder. - -o,--outputFile The out SQL file for the formatted - statements. - -f,--outputFormat The output-format. - [PLAIN* ANSI HTML RTF] - --ansi Output ANSI annotated text. - --html Output HTML annotated text. - -t,--indent The indent width. - [2 4* 8] - -2 Indent with 2 characters. - -8 Indent with 8 characters. - --keywordSpelling Keyword spelling. - [UPPER*, LOWER, CAMEL, KEEP] - --functionSpelling Function name spelling. - [UPPER, LOWER, CAMEL*, KEEP] - --objectSpelling Object name spelling. - [UPPER, LOWER*, CAMEL, KEEP] - --separation Position of the field separator. - [BEFORE*, AFTER] - --squareBracketQuotation Position of the field separator. - [AUTO*, YES, NO] - ``` + ```shell + java -jar JSQLFormatter.jar [-i ] [-o ] [-f | + --ansi | --html] [-t | -2 | -8] [--keywordSpelling ] + [--functionSpelling ] [--objectSpelling ] [--separation + ] [--squareBracketQuotation ] + + -i,--inputFile The input SQL file or folder. + -o,--outputFile The out SQL file for the formatted + statements. + -f,--outputFormat The output-format. + [PLAIN* ANSI HTML RTF] + --ansi Output ANSI annotated text. + --html Output HTML annotated text. + -t,--indent The indent width. + [2 4* 8] + -2 Indent with 2 characters. + -8 Indent with 8 characters. + --keywordSpelling Keyword spelling. + [UPPER*, LOWER, CAMEL, KEEP] + --functionSpelling Function name spelling. + [UPPER, LOWER, CAMEL*, KEEP] + --objectSpelling Object name spelling. + [UPPER, LOWER*, CAMEL, KEEP] + --separation Position of the field separator. + [BEFORE*, AFTER] + --squareBracketQuotation Position of the field separator. + [AUTO*, YES, NO] + ``` * simple usage of the Java library - ```java - import com.manticore.jsqlformatter.JSqlFormatter; - ... - String formattedSql = JSqlFormatter.format("SELECT * FROM table1") - ``` + ```java + import com.manticore.jsqlformatter.JSqlFormatter; + ... + String formattedSql = JSqlFormatter.format("SELECT * FROM table1") + ``` - with Maven Artifact: + with Maven Artifact: - ```xml - - com.manticore-projects.jsqlformatter - jsqlformatter - 1.0.0 - - ``` + ```xml + + com.manticore-projects.jsqlformatter + jsqlformatter + 1.0.0 + + ``` ## Samples @@ -104,19 +104,18 @@ WHERE id_calendar = ? MERGE /*+ PARALLEL */ INTO test1 /*the target table*/ a USING all_objects /*the source table*/ ON ( /*joins in()!*/ a.object_id = b.object_id ) --- INSERT CLAUSE +-- INSERT CLAUSE WHEN /*comments between keywords!*/ NOT MATCHED THEN INSERT ( object_id /*ID Column*/ , status /*Status Column*/ ) VALUES ( b.object_id , b.status ) /* UPDATE CLAUSE -WITH A WHERE CONDITION */ +WITH A WHERE CONDITION */ WHEN MATCHED THEN /* Lets rock */ UPDATE SET a.status = '/*this is no comment!*/ and -- this ain''t either' WHERE b."--status" != 'VALID' ; ``` -[More Samples](http://manticore-projects.com/JSQLFormatter/samples.html) - +[More Samples](http://manticore-projects.com/JSQLFormatter/samples.html) diff --git a/build.gradle b/build.gradle index 4b52ca3..df4ffde 100644 --- a/build.gradle +++ b/build.gradle @@ -6,10 +6,12 @@ plugins { id 'maven-publish' id 'signing' - id "com.github.spotbugs" version "latest.release" - id "com.diffplug.spotless" version "latest.release" id 'pmd' id 'checkstyle' + id 'jacoco' + id 'com.github.kt3k.coveralls' version "latest.release" + id "com.github.spotbugs" version "latest.release" + id "com.diffplug.spotless" version "latest.release" // download the RR tools which have no Maven Repository id "de.undercouch.download" version "latest.release" @@ -42,7 +44,7 @@ configurations { } dependencies { - implementation 'com.github.jsqlparser:jsqlparser:4.8-SNAPSHOT' + implementation('com.github.jsqlparser:jsqlparser:+'){ changing = true } // Java Doc in XML Format xmlDoclet 'com.manticore-projects.tools:xml-doclet:+' @@ -182,12 +184,150 @@ license { ignoreFailures = true } +coveralls { + jacocoReportPath 'build/reports/jacoco/test/jacocoTestReport.xml' +} + +jacocoTestReport { + dependsOn test // tests are required to run before generating the report + reports { + xml.required = false + csv.required = false + html.outputLocation = layout.buildDirectory.dir('reports/jacoco') + } +} +jacocoTestCoverageVerification { + violationRules { + rule { + //element = 'CLASS' + limit { + //@todo: temporarily reduced it 80%, we need to bring that back to 84% accepting the Keywords PR + minimum = 0.80 + } + excludes = [ + 'net.sf.jsqlparser.util.validation.*', + 'net.sf.jsqlparser.**.*Adapter', + 'net.sf.jsqlparser.parser.JJTCCJSqlParserState', + 'net.sf.jsqlparser.parser.TokenMgrError', + 'net.sf.jsqlparser.parser.StreamProvider', + 'net.sf.jsqlparser.parser.CCJSqlParserTokenManager', + 'net.sf.jsqlparser.parser.ParseException', + 'net.sf.jsqlparser.parser.SimpleNode', + 'net.sf.jsqlparser.parser.SimpleCharStream', + 'net.sf.jsqlparser.parser.StringProvider', + ] + } + rule { + //element = 'CLASS' + limit { + counter = 'LINE' + value = 'MISSEDCOUNT' + + //@todo: temporarily increased to 7000, we need to bring that down to 5500 after accepting the Keywords PR + maximum = 7000 + } + excludes = [ + 'net.sf.jsqlparser.util.validation.*', + 'net.sf.jsqlparser.**.*Adapter', + 'net.sf.jsqlparser.parser.JJTCCJSqlParserState', + 'net.sf.jsqlparser.parser.TokenMgrError', + 'net.sf.jsqlparser.parser.StreamProvider', + 'net.sf.jsqlparser.parser.CCJSqlParserTokenManager', + 'net.sf.jsqlparser.parser.ParseException', + 'net.sf.jsqlparser.parser.SimpleNode', + 'net.sf.jsqlparser.parser.SimpleCharStream', + 'net.sf.jsqlparser.parser.StringProvider', + ] + } +// rule { +// element = 'CLASS' +// limit { +// counter = 'LINE' +// value = 'MISSEDRATIO' +// maximum = 0.3 +// } +// excludes = [ +// 'net.sf.jsqlparser.util.validation.*', +// 'net.sf.jsqlparser.**.*Adapter', +// 'net.sf.jsqlparser.parser.JJTCCJSqlParserState', +// 'net.sf.jsqlparser.parser.TokenMgrError', +// 'net.sf.jsqlparser.parser.StreamProvider', +// 'net.sf.jsqlparser.parser.CCJSqlParserTokenManager', +// 'net.sf.jsqlparser.parser.ParseException', +// 'net.sf.jsqlparser.parser.SimpleNode', +// 'net.sf.jsqlparser.parser.SimpleCharStream', +// 'net.sf.jsqlparser.parser.StringProvider', +// ] +// } + } +} + +spotbugsMain { + reports { + html { + enabled = true + destination = file("build/reports/spotbugs/main/spotbugs.html") + stylesheet = 'fancy-hist.xsl' + } + } +} + +spotbugs { + // fail only on P1 and without the net.sf.jsqlparser.parser.* + excludeFilter = file("config/spotbugs/spotBugsExcludeFilter.xml") + + // do not run over the test, although we should do that eventually + spotbugsTest.enabled = false +} + +pmd { + consoleOutput = true + sourceSets = [sourceSets.main] + + // clear the ruleset in order to use configured rules only + ruleSets = [] + + //rulesMinimumPriority = 1 + ruleSetFiles = files("config/pmd/ruleset.xml") + + pmdMain { + excludes = [ + "build/generated/*" + ] + } +} + +checkstyle { + sourceSets = [sourceSets.main, sourceSets.test] + configFile = rootProject.file('config/checkstyle/checkstyle.xml') +} + spotless { + // optional: limit format enforcement to just the files changed by this feature branch + ratchetFrom 'origin/master' + + format 'misc', { + // define the files to apply `misc` to + target '*.rst', '*.md', '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces(4) // or spaces. Takes an integer argument if you don't like 4 + endWithNewline() + } java { + indentWithSpaces(4) eclipse().configFile('config/formatter/eclipse-java-google-style.xml') } } +tasks.withType(Checkstyle).configureEach { + reports { + xml.required = false + html.required = true + } +} + publishing { publications { mavenJava(MavenPublication) { @@ -195,7 +335,7 @@ publishing { from(components.java) versionMapping { usage('java-api') { - fromResolutionOf('testFixturesRuntimeClasspath') + fromResolutionOf('runtimeClasspath') } usage('java-runtime') { fromResolutionResult() diff --git a/config/pmd/ruleset.xml b/config/pmd/ruleset.xml index c4826a9..322ceea 100644 --- a/config/pmd/ruleset.xml +++ b/config/pmd/ruleset.xml @@ -79,7 +79,7 @@ under the License. - + diff --git a/src/main/java/com/manticore/jsqlformatter/Comment.java b/src/main/java/com/manticore/jsqlformatter/Comment.java index 4bd313c..e9c2d1d 100644 --- a/src/main/java/com/manticore/jsqlformatter/Comment.java +++ b/src/main/java/com/manticore/jsqlformatter/Comment.java @@ -1,6 +1,6 @@ /** * Manticore Projects JSQLFormatter is a SQL Beautifying and Formatting Software. - * Copyright (C) 2022 Andreas Reichel + * Copyright (C) 2023 Andreas Reichel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published diff --git a/src/main/java/com/manticore/jsqlformatter/CommentMap.java b/src/main/java/com/manticore/jsqlformatter/CommentMap.java index f4011fe..bab0a57 100644 --- a/src/main/java/com/manticore/jsqlformatter/CommentMap.java +++ b/src/main/java/com/manticore/jsqlformatter/CommentMap.java @@ -1,6 +1,6 @@ /** * Manticore Projects JSQLFormatter is a SQL Beautifying and Formatting Software. - * Copyright (C) 2022 Andreas Reichel + * Copyright (C) 2023 Andreas Reichel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published @@ -64,22 +64,20 @@ private static StringBuilder appendComment(StringBuilder builder, OutputFormat f return builder; } + @SuppressWarnings({"PMD.CyclomaticComplexity"}) public CommentMap(String sqlStr) { Matcher matcher = COMMENT_PATTERN.matcher(sqlStr); - int i = 0; while (matcher.find()) { - i++; - String group = matcher.group(0); int start = matcher.start(0); int end = matcher.end(0); if (!STRING_PATTERN.matcher(group).matches()) { - if (OracleHint.isHintMatch(group)) + if (OracleHint.isHintMatch(group)) { LOGGER.log(Level.FINE, "Oracle hint {0}", group); - else { + } else { Comment comment = new Comment(start, group); - if (start == 0 || (sqlStr.charAt(start - 1) == '\n' && sqlStr.charAt(end - 1) == '\n')) { + if (start == 0 || sqlStr.charAt(start - 1) == '\n' && sqlStr.charAt(end - 1) == '\n') { comment.newLine = true; comment.extraNewLine = start > 1 && sqlStr.charAt(start - 2) == '\n'; } @@ -95,8 +93,9 @@ public CommentMap(String sqlStr) { for (Comment comment : values()) { while (absolutePosition < comment.absolutePosition) { char c = sqlStr.charAt(absolutePosition); - if (!Character.isWhitespace(c)) + if (!Character.isWhitespace(c)) { relativePosition++; + } absolutePosition++; } @@ -108,6 +107,7 @@ public CommentMap(String sqlStr) { } } + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength"}) public StringBuilder insertComments(StringBuilder sqlStrWithoutComments, OutputFormat outputFormat) { @@ -124,15 +124,16 @@ public StringBuilder insertComments(StringBuilder sqlStrWithoutComments, for (int position = 0; position < sqlStrWithoutComments.length(); position++) { String c = sqlStrWithoutComments.substring(position, position + 1); - if (ansiStarted < 0) + if (ansiStarted < 0) { while (next.relativePosition <= relativePosition) { if (next.extraNewLine) { builder.append("\n"); } else if (next.newLine && builder.length() > 1 && builder.charAt(builder.length() - 1) != '\n') { builder.append("\n"); - } else if (!c.matches("\\w")) + } else if (!c.matches("\\w")) { builder.append(" "); + } if (!next.newLine && next.text.startsWith("--")) { appendComment(builder, outputFormat, next.text.trim().replaceFirst("--\\s?", "/* "), @@ -148,23 +149,27 @@ public StringBuilder insertComments(StringBuilder sqlStrWithoutComments, break; } } + } if (wasLastComment) { String remaining = sqlStrWithoutComments.substring(position); if (next.newLine) { int nextBreak = remaining.indexOf('\n'); - if (nextBreak >= 0 && remaining.substring(0, nextBreak).trim().length() == 0) { + if (nextBreak >= 0 && remaining.substring(0, nextBreak).trim().isEmpty()) { builder.append(remaining.substring(nextBreak + 1)); - } else + } else { builder.append(remaining); - } else + } + } else { builder.append(remaining); + } break; } if (ansiStarted < 0 && position + 2 <= sqlStrWithoutComments.length() - && sqlStrWithoutComments.substring(position, position + 2).matches("\u001B\\[")) + && sqlStrWithoutComments.substring(position, position + 2).matches("\u001B\\[")) { ansiStarted = position; + } if (ansiStarted >= 0 && sqlStrWithoutComments.substring(ansiStarted, position + 1) .matches("\u001B\\[[;\\d]*[ -/]*[@-~]")) { @@ -176,8 +181,9 @@ public StringBuilder insertComments(StringBuilder sqlStrWithoutComments, if (lastBreak < 0 || builder.substring(lastBreak).trim().length() > 0) { builder.append(c); } - } else + } else { builder.append(c); + } if (ansiStarted < 0) { relativePosition = sqlStrWithoutComments.substring(0, position + 1) @@ -189,10 +195,8 @@ public StringBuilder insertComments(StringBuilder sqlStrWithoutComments, Matcher matcher = LINE_END_COMMENT_PATTERN.matcher(builder); ArrayList matches = new ArrayList<>(); - int i = 0; int maxPosition = 0; while (matcher.find()) { - i++; int start = matcher.start(0); int lastLineBreak = builder.lastIndexOf("\n", start); diff --git a/src/main/java/com/manticore/jsqlformatter/FragmentContentHandler.java b/src/main/java/com/manticore/jsqlformatter/FragmentContentHandler.java index c436bf4..1eede8b 100644 --- a/src/main/java/com/manticore/jsqlformatter/FragmentContentHandler.java +++ b/src/main/java/com/manticore/jsqlformatter/FragmentContentHandler.java @@ -1,3 +1,20 @@ +/** + * Manticore Projects JSQLFormatter is a SQL Beautifying and Formatting Software. + * Copyright (C) 2023 Andreas Reichel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ package com.manticore.jsqlformatter; import org.xml.sax.Attributes; @@ -48,9 +65,10 @@ public void startElement(String uri, String localName, String qName, Attributes int attsLength = atts.getLength(); builder.append(childXPath); for (int x = 0; x < attsLength; x++) { - if (!atts.getQName(x).equals("object") && !atts.getQName(x).equals("class")) + if (!atts.getQName(x).equals("object") && !atts.getQName(x).equals("class")) { builder.append("[@").append(atts.getQName(x)).append("='").append(atts.getValue(x)) .append("']"); + } } builder.append("\n"); diff --git a/src/main/java/com/manticore/jsqlformatter/JSQLFormatter.java b/src/main/java/com/manticore/jsqlformatter/JSQLFormatter.java index 78fb107..658631d 100644 --- a/src/main/java/com/manticore/jsqlformatter/JSQLFormatter.java +++ b/src/main/java/com/manticore/jsqlformatter/JSQLFormatter.java @@ -1,6 +1,6 @@ /** * Manticore Projects JSQLFormatter is a SQL Beautifying and Formatting Software. - * Copyright (C) 2022 Andreas Reichel + * Copyright (C) 2023 Andreas Reichel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published @@ -50,6 +50,7 @@ import net.sf.jsqlparser.expression.WhenClause; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.relational.Between; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExistsExpression; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; @@ -156,7 +157,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Enumeration; -import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.logging.Level; @@ -170,6 +170,7 @@ * @author Andreas Reichel * @version 0.1 */ +@SuppressWarnings({"PMD.CyclomaticComplexity"}) public class JSQLFormatter { public static final Pattern SQUARED_BRACKET_QUOTATION_PATTERN = Pattern.compile( @@ -305,8 +306,9 @@ static String toCamelCase(String s) { String[] nameParts = s.split("_"); int i = 0; for (String part : nameParts) { - if (i > 0) + if (i > 0) { camelCaseString.append("_"); + } camelCaseString.append(part.substring(0, 1).toUpperCase()) .append(part.substring(1).toLowerCase()); i++; @@ -337,10 +339,8 @@ private static StringBuilder appendKeyWord(StringBuilder builder, OutputFormat f builder.append(before).append(ANSI_FORMAT_KEYWORD.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("").append(s) + .append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -387,10 +387,9 @@ private static StringBuilder appendNormalizedLineBreak(StringBuilder builder) { return appendNormalizingTrailingWhiteSpace(builder, Ansi.RESET + ANSI_FORMAT_LINE_NUMBER.format("\n" + lineCountStr) + Ansi.RESET + fillerStr); case HTML: - return builder - .append("\n") - .append("").append(lineCountStr).append("") - .append(fillerStr); + return builder.append("\n") + .append("") + .append(lineCountStr).append("").append(fillerStr); default: return appendNormalizingTrailingWhiteSpace(builder, "\n" + lineCountStr + fillerStr); } @@ -399,10 +398,6 @@ private static StringBuilder appendNormalizedLineBreak(StringBuilder builder) { } } - private static StringBuilder appendNormalizedSpace(StringBuilder builder) { - return appendNormalizingTrailingWhiteSpace(builder, " "); - } - private static StringBuilder appendHint(StringBuilder builder, OutputFormat format, String hint, String before, String after) { @@ -426,10 +421,8 @@ private static StringBuilder appendHint(StringBuilder builder, OutputFormat form builder.append(before).append(ANSI_FORMAT_HINT.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("") + .append(s).append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -461,10 +454,8 @@ private static StringBuilder appendOperator(StringBuilder builder, OutputFormat builder.append(before).append(ANSI_FORMAT_OPERATOR.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("").append(s) + .append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -480,10 +471,8 @@ private static StringBuilder appendValue(StringBuilder builder, OutputFormat for builder.append(before).append(ANSI_FORMAT_PARAMETER.format(value)).append(after); break; case HTML: - builder - .append(before) - .append("").append(value).append("") - .append(after); + builder.append(before).append("") + .append(value).append("").append(after); break; default: builder.append(before).append(value).append(after); @@ -519,10 +508,8 @@ private static StringBuilder appendAlias(StringBuilder builder, OutputFormat for builder.append(before).append(ANSI_FORMAT_ALIAS.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("").append(s) + .append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -539,8 +526,9 @@ private static StringBuilder appendObjectName(StringBuilder builder, OutputForma int j = 0; String[] parts = objectName.contains(".") ? objectName.split("\\.") : new String[] {objectName}; for (String w : parts) { - if (j > 0) + if (j > 0) { nameBuilder.append("."); + } if (w.trim().startsWith("\"") || w.trim().startsWith("[")) { nameBuilder.append(w); } else { @@ -590,10 +578,8 @@ private static StringBuilder appendFunction(StringBuilder builder, OutputFormat builder.append(before).append(ANSI_FORMAT_FUNCTION.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("") + .append(s).append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -625,10 +611,8 @@ private static StringBuilder appendType(StringBuilder builder, OutputFormat form builder.append(before).append(ANSI_FORMAT_TYPE.format(s)).append(after); break; case HTML: - builder - .append(before) - .append("").append(s).append("") - .append(after); + builder.append(before).append("").append(s) + .append("").append(after); break; default: builder.append(before).append(s).append(after); @@ -649,20 +633,22 @@ private static int getSubIndent(StringBuilder builder, boolean moveToTab) { int subIndent = lastLineLength / indentWidth + (lastLineLength % indentWidth > 0 ? 1 : 0); - for (int i = lastLineLength; moveToTab && i < subIndent * indentWidth; i++) + for (int i = lastLineLength; moveToTab && i < subIndent * indentWidth; i++) { builder.append(" "); + } return subIndent; } + @SuppressWarnings({"PMD.CyclomaticComplexity"}) private static void appendDelete(StringBuilder builder, Delete delete, int indent) { List withItems = delete.getWithItemsList(); - if (withItems != null && withItems.size() > 0) { + if (withItems != null && !withItems.isEmpty()) { int i = 0; appendKeyWord(builder, outputFormat, "WITH", "", " "); for (WithItem withItem : withItems) { - appendWithItem(withItem, withItem.getAlias(), builder, indent, i, withItems.size()); + appendWithItem(withItem, builder, indent, i, withItems.size()); i++; } @@ -671,12 +657,13 @@ private static void appendDelete(StringBuilder builder, Delete delete, int inden appendKeyWord(builder, outputFormat, "DELETE", "", " "); OracleHint oracleHint = delete.getOracleHint(); - if (oracleHint != null) + if (oracleHint != null) { appendHint(builder, outputFormat, oracleHint.toString(), "", " "); + } List tables = delete.getTables(); - if (tables != null && tables.size() > 0) { + if (tables != null && !tables.isEmpty()) { int j = 0; for (Table table : tables) { switch (separation) { @@ -700,7 +687,7 @@ private static void appendDelete(StringBuilder builder, Delete delete, int inden Table table = delete.getTable(); Alias alias = table.getAlias(); - appendTable(table, alias, builder, indent, 0, 1); + appendTable(table, alias, builder); List joins = delete.getJoins(); appendJoins(joins, builder, indent); @@ -714,8 +701,9 @@ private static void appendDelete(StringBuilder builder, Delete delete, int inden Limit limit = delete.getLimit(); if (limit != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "LIMIT", "", ""); @@ -739,11 +727,10 @@ private static void appendDelete(StringBuilder builder, Delete delete, int inden public static File getAbsoluteFile(String filename) { String homePath = new File(System.getProperty("user.home")).toURI().getPath(); - filename = filename.replaceFirst("~", Matcher.quoteReplacement(homePath)); - filename = filename.replaceFirst("\\$\\{user.home}", Matcher.quoteReplacement(homePath)); - - File f = new File(filename); + String _filename = filename.replaceFirst("~", Matcher.quoteReplacement(homePath)) + .replaceFirst("\\$\\{user.home}", Matcher.quoteReplacement(homePath)); + File f = new File(_filename); if (!f.isAbsolute()) { Path basePath = Paths.get("").toAbsolutePath(); @@ -761,6 +748,7 @@ public static String getAbsoluteFileName(String filename) { /** * @param args The Command Line Parameters. */ + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength"}) public static void main(String[] args) throws Exception { Options options = new Options(); @@ -803,7 +791,7 @@ public static void main(String[] args) throws Exception { .hasArg().desc("Show Line Numbers.\n[YES, NO*]").build()); options.addOption(Option.builder(null).longOpt(FormattingOption.BACKSLASH_QUOTING.toString()) - .hasArg().desc("Allow Back Slash '\\' for escaping.\n[YES, NO*]").build()); + .hasArg().desc("Allow Back Slash '\\' for escaping.\n[YES, NO*]").build()); // create the parser CommandLineParser parser = new DefaultParser(); @@ -813,19 +801,23 @@ public static void main(String[] args) throws Exception { ArrayList formatterOptions = new ArrayList<>(); - if (line.hasOption("ansi")) + if (line.hasOption("ansi")) { FormattingOption.OUTPUT_FORMAT.addFormatterOption(OutputFormat.ANSI.toString(), formatterOptions); + } - if (line.hasOption("html")) + if (line.hasOption("html")) { FormattingOption.OUTPUT_FORMAT.addFormatterOption(OutputFormat.HTML.toString(), formatterOptions); + } - if (line.hasOption("2")) + if (line.hasOption("2")) { FormattingOption.INDENT_WIDTH.addFormatterOption("2", formatterOptions); + } - if (line.hasOption("8")) + if (line.hasOption("8")) { FormattingOption.INDENT_WIDTH.addFormatterOption("4", formatterOptions); + } FormattingOption.INDENT_WIDTH.addFormatterOption(line, formatterOptions); FormattingOption.KEYWORD_SPELLING.addFormatterOption(line, formatterOptions); @@ -836,7 +828,7 @@ public static void main(String[] args) throws Exception { FormattingOption.BACKSLASH_QUOTING.addFormatterOption(line, formatterOptions); FormattingOption.SHOW_LINE_NUMBERS.addFormatterOption(line, formatterOptions); - if (line.hasOption("help") || (line.getOptions().length == 0 && line.getArgs().length == 0)) { + if (line.hasOption("help") || line.getOptions().length == 0 && line.getArgs().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(null); @@ -852,9 +844,10 @@ public static void main(String[] args) throws Exception { if (line.hasOption("inputFile")) { inputFile = getAbsoluteFile(line.getOptionValue("inputFile")); - if (!inputFile.canRead()) + if (!inputFile.canRead()) { throw new Exception( "Can't read the specified INPUT-FILE " + inputFile.getCanonicalPath()); + } try (FileInputStream inputStream = new FileInputStream(inputFile)) { String sqlStr = IOUtils.toString(inputStream, Charset.defaultCharset()); @@ -867,9 +860,9 @@ public static void main(String[] args) throws Exception { } List argsList = line.getArgList(); - if (argsList.isEmpty() && !line.hasOption("input-file")) + if (argsList.isEmpty() && !line.hasOption("input-file")) { throw new Exception("No SQL statements provided for formatting."); - else + } else { for (String s : argsList) { try { System.out.println("\n-- FROM ARGUMENT LIST\n" @@ -878,6 +871,7 @@ public static void main(String[] args) throws Exception { LOGGER.log(Level.WARNING, "Failed to format statement\n" + s, ex); } } + } } catch (ParseException ex) { LOGGER.log(Level.FINE, "Parsing failed. Reason: " + ex.getMessage(), ex); @@ -912,12 +906,13 @@ public static CCharPointer format(IsolateThread thread, CCharPointer sql, CCharP System.out.println(ex.getMessage()); } - try (final CTypeConversion.CCharPointerHolder holder = CTypeConversion.toCString(sqlStr)) { + try (CTypeConversion.CCharPointerHolder holder = CTypeConversion.toCString(sqlStr)) { final CCharPointer result = holder.get(); return result; } } + @SuppressWarnings({"PMD.CyclomaticComplexity"}) public static ArrayList verify(String sqlStr, String... options) { ArrayList exceptions = new ArrayList<>(); @@ -927,7 +922,7 @@ public static ArrayList verify(String sqlStr, String... options) { Matcher m = SEMICOLON_PATTERN.matcher(sqlStr); ArrayList semicolons = new ArrayList<>(); - for (int i = 0; m.find(); i++) { + while (m.find()) { semicolons.add(m.start()); } @@ -956,8 +951,9 @@ public static ArrayList verify(String sqlStr, String... options) { pos = semicolonPos + 1; // we are at the end and find only remaining whitespace - if (statementSql.trim().length() == 0) + if (statementSql.trim().isEmpty()) { break; + } boolean useSquareBracketQuotation; switch (squaredBracketQuotation) { @@ -979,21 +975,21 @@ public static ArrayList verify(String sqlStr, String... options) { useSquareBracketQuotation); } try { - Statement statement = CCJSqlParserUtil.parse(statementSql, + CCJSqlParserUtil.parse(statementSql, parser -> parser.withSquareBracketQuotation(useSquareBracketQuotation)); } catch (Exception ex1) { exceptions.add(new Exception("Cannot parse the Statement:\n" + statementSql, ex1)); } - } else + } else { break; + } } return exceptions; } + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength"}) public static String format(String sqlStr, String... options) throws Exception { - ArrayList exceptions = new ArrayList<>(); - applyFormattingOptions(options); StringBuilder builder = new StringBuilder(); @@ -1001,12 +997,13 @@ public static String format(String sqlStr, String... options) throws Exception { int indent = 0; lineCount = 0; - //Pattern SEMICOLON_PATTERN = Pattern.compile("((?:(?:'[^']*+')|(?:\"[^\"]*+\")|(?:--.*)|(?:\\/\\*[^\\*\\/]*+\\*\\/)|[^;])*+);"); + // Pattern SEMICOLON_PATTERN = + // Pattern.compile("((?:(?:'[^']*+')|(?:\"[^\"]*+\")|(?:--.*)|(?:\\/\\*[^\\*\\/]*+\\*\\/)|[^;])*+);"); Pattern SEMICOLON_PATTERN = Pattern.compile(";|$|\\n\\n\\n"); Matcher m = SEMICOLON_PATTERN.matcher(sqlStr); ArrayList semicolons = new ArrayList<>(); - for (int i = 0; m.find(); i++) { + while (m.find()) { semicolons.add(m.start()); } @@ -1036,10 +1033,8 @@ public static String format(String sqlStr, String... options) throws Exception { // we are at the end and find only remaining whitespace // or comments - if (statementSql.trim().length() == 0 - || ( i==n-1 && statementSql.trim().startsWith("--") ) - || ( i==n-1 && statementSql.trim().startsWith("/*") ) - ) { + if (statementSql.trim().isEmpty() || i == n - 1 && statementSql.trim().startsWith("--") + || i == n - 1 && statementSql.trim().startsWith("/*")) { break; } @@ -1068,14 +1063,10 @@ public static String format(String sqlStr, String... options) throws Exception { boolean useBackSlashQuoting; if (Objects.requireNonNull(backSlashQuoting) == BackSlashQuoting.YES) { useBackSlashQuoting = true; - LOGGER.log(Level.FINE, "Back Slash Quoting set as {0}.", - true - ); + LOGGER.log(Level.FINE, "Back Slash Quoting set as {0}.", true); } else { useBackSlashQuoting = false; - LOGGER.log(Level.FINE, "Back Slash Quoting set as {0}.", - false - ); + LOGGER.log(Level.FINE, "Back Slash Quoting set as {0}.", false); } CommentMap commentMap = new CommentMap(statementSql); @@ -1090,8 +1081,9 @@ public static String format(String sqlStr, String... options) throws Exception { } try { - Statement statement = CCJSqlParserUtil.parse(statementSql, - parser -> parser.withSquareBracketQuotation(useSquareBracketQuotation).withBackslashEscapeCharacter(useBackSlashQuoting)); + Statement statement = CCJSqlParserUtil.parse(statementSql.replaceAll("\\n\\n+", "\n"), + parser -> parser.withSquareBracketQuotation(useSquareBracketQuotation) + .withBackslashEscapeCharacter(useBackSlashQuoting).withTimeOut(60000)); if (statement instanceof Select) { Select select = (Select) statement; @@ -1115,7 +1107,7 @@ public static String format(String sqlStr, String... options) throws Exception { } else if (statement instanceof Truncate) { Truncate truncate = (Truncate) statement; - appendTruncate(statementBuilder, truncate, indent); + appendTruncate(statementBuilder, truncate); } else if (statement instanceof CreateTable) { CreateTable createTable = (CreateTable) statement; @@ -1143,9 +1135,8 @@ public static String format(String sqlStr, String... options) throws Exception { } appendNormalizedLineBreak(statementBuilder).append(";\n"); - builder.append(commentMap.isEmpty() - ? statementBuilder - : commentMap.insertComments(statementBuilder, outputFormat)); + builder.append(commentMap.isEmpty() ? statementBuilder + : commentMap.insertComments(statementBuilder, outputFormat)); } catch (Exception ex1) { if (statementSql.trim().length() <= commentMap.getLength()) { @@ -1155,28 +1146,20 @@ public static String format(String sqlStr, String... options) throws Exception { LOGGER.log(Level.WARNING, "Failed for format statement between \n" + statementSql, ex1); - exceptions.add(new Exception( - "Failed for format statement between " + " and " + "\n" + statementSql)); builder.append("-- failed to format start\n").append(statementSql) .append("\n-- failed to format end\n").append("\n"); } } - } else + } else { break; + } } if (outputFormat == OutputFormat.HTML) { - builder = new StringBuilder() - .append("\n") - .append("\n") - .append("SQL Statement's Java Object Tree\n") - .append("\n") - .append("\n") - .append("
\n")
-                  .append(builder)
-                  .append("\n
\n") - .append("\n") - .append(""); + builder = new StringBuilder().append("\n").append("\n") + .append("SQL Statement's Java Object Tree\n").append("\n") + .append("\n").append("
\n")
+          .append(builder).append("\n
\n").append("\n").append(""); } return builder.toString().trim(); @@ -1207,141 +1190,6 @@ public static StringBuilder formatToJava(String sqlStr, int indent, String... op return builder; } - public static class JavaObjectNode implements TreeNode { - private final TreeNode parent; - public String fieldName; - public Object object; - private final ArrayList children = new ArrayList<>(); - - public JavaObjectNode(TreeNode parent, String fieldName, Object object) { - this.parent = parent; - this.fieldName = fieldName; - this.object = object; - addChildren(); - } - - private void addChildren() { - ArrayList fields = new ArrayList<>(FieldUtils.getAllFieldsList(object.getClass())); - - for (Field field : fields) - try { - // System.out.println(object.getClass().getName() + " : " + field); - Object child = FieldUtils.readField(field, this.object, true); - if (object instanceof net.sf.jsqlparser.schema.Column) { - // enforce Leaf - } else if (child.getClass().getName().startsWith("net.sf.jsqlparser") - && !child.getClass().getName().startsWith("net.sf.jsqlparser.parser") - && !child.getClass().isEnum()) { - JavaObjectNode childNode = new JavaObjectNode(this, field.getName(), child); - children.add(childNode); - } else if (child instanceof Collection) { - Collection collection = (Collection) child; - if (!collection.isEmpty() - && collection.toArray()[0].getClass().getName().startsWith("net.sf.jsqlparser")) { - for (Object element : collection) - if (element.getClass().getName().startsWith("net.sf.jsqlparser")) { - JavaObjectNode subChildNode = new JavaObjectNode(this, field.getName(), element); - this.children.add(subChildNode); - } - } - } - } catch (Exception ignore) { - - } - } - - @Override - public TreeNode getChildAt(int childIndex) { - return children.get(childIndex); - } - - @Override - public int getChildCount() { - return children.size(); - } - - @Override - public TreeNode getParent() { - return parent; - } - - @Override - public int getIndex(TreeNode node) { - return children.indexOf(node); - } - - @Override - public boolean getAllowsChildren() { - return true; - } - - @Override - public boolean isLeaf() { - return children.isEmpty(); - } - - @Override - public Enumeration children() { - return Collections.enumeration(children); - } - - - private String formatClassName(Object o) { - if (outputFormat.equals(OutputFormat.HTML)) { - return "" + object.getClass().getSimpleName() + ": " - + object + ""; - } else if (outputFormat.equals(OutputFormat.ANSI)) { - return ANSI_FORMAT_KEYWORD.format(object.getClass().getSimpleName()) + ": " - + ANSI_FORMAT_PARAMETER.format(object.toString()); - } else { - return object.getClass().getSimpleName() + ": " + object; - } - } - - private String formatFieldClassName(Object o) { - if (outputFormat.equals(OutputFormat.HTML)) { - return "" + fieldName + ": " - + o.getClass().getCanonicalName() + ""; - } else if (outputFormat.equals(OutputFormat.ANSI)) { - return ANSI_FORMAT_KEYWORD.format(fieldName) + ": " - + ANSI_FORMAT_PARAMETER.format(o.getClass().getCanonicalName().replace("net.sf.jsqlparser.", "")); - } else { - return fieldName + ": " + object.getClass().getCanonicalName().replace("net.sf.jsqlparser.", ""); - } - } - - private String formatCollection(Collection collection) { - if (outputFormat.equals(OutputFormat.HTML)) { - return "" + fieldName + " -> Collection<" - + collection.toArray()[0].getClass().getSimpleName() + ">"; - } else if (outputFormat.equals(OutputFormat.ANSI)) { - return ANSI_FORMAT_KEYWORD.format(fieldName) + " -> Collection<" - + ANSI_FORMAT_PARAMETER.format(collection.toArray()[0].getClass().getSimpleName()) - + ">"; - } else { - return object.getClass().getSimpleName() + ": " + object; - } - } - - @Override - public String toString() { - if (object instanceof net.sf.jsqlparser.schema.Column - || object instanceof net.sf.jsqlparser.schema.Table - || object instanceof net.sf.jsqlparser.schema.Database - || object instanceof net.sf.jsqlparser.schema.Sequence - || object instanceof net.sf.jsqlparser.schema.Server - || object instanceof net.sf.jsqlparser.schema.Synonym) { - return formatClassName(object); - } else if (object instanceof Collection) { - return formatCollection((Collection) object); - } else if (isLeaf()) { - return formatClassName(object); - } else { - return formatFieldClassName(object); - } - } - } - public static ArrayList getAstNodes(String sqlStr, String... options) throws Exception { ArrayList nodes = new ArrayList<>(); @@ -1364,7 +1212,6 @@ public static SimpleTreeNode translateNode(TreeNode node) { return simpleTreeNode; } - public static String encodeObject(Object object) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream); @@ -1377,7 +1224,6 @@ public static String encodeObject(Object object) throws IOException { } public static String formatToTree(String sqlStr, String... options) throws Exception { - TreeNode rootTreeNode = null; applyFormattingOptions(options); // The Java TreeNode Structure @@ -1473,9 +1319,10 @@ public static Collection extract(String sql, Class clazz, String xpath return objects; } + @SuppressWarnings({"PMD.CyclomaticComplexity"}) public static void applyFormattingOptions(String[] options) { // set the formatting options - if (options != null) + if (options != null) { for (String s : options) { String[] o = s.split("="); if (o.length == 2) { @@ -1559,17 +1406,18 @@ public static void applyFormattingOptions(String[] options) { LOGGER.log(Level.WARNING, "Invalid Formatting Option {0}", s); } } + } } private static void appendMerge(StringBuilder builder, Merge merge, int indent) { List withItems = merge.getWithItemsList(); - if (withItems != null && withItems.size() > 0) { + if (withItems != null && !withItems.isEmpty()) { int i = 0; appendKeyWord(builder, outputFormat, "WITH", "", " "); for (WithItem withItem : withItems) { - appendWithItem(withItem, withItem.getAlias(), builder, indent, i, withItems.size()); + appendWithItem(withItem, builder, indent, i, withItems.size()); i++; } @@ -1578,63 +1426,65 @@ private static void appendMerge(StringBuilder builder, Merge merge, int indent) appendKeyWord(builder, outputFormat, "MERGE", "", " "); OracleHint oracleHint = merge.getOracleHint(); - if (oracleHint != null) + if (oracleHint != null) { appendHint(builder, outputFormat, oracleHint.toString(), "", " "); + } appendKeyWord(builder, outputFormat, "INTO", "", " "); Table table = merge.getTable(); Alias alias = table.getAlias(); - appendTable(table, alias, builder, indent, 0, 1); + appendTable(table, alias, builder); appendNormalizedLineBreak(builder); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "USING", "", " "); int subIndent = getSubIndent(builder, false); FromItem fromItem = merge.getFromItem(); - appendFromItem(fromItem, builder, subIndent, 0, 1); + appendFromItem(fromItem, builder, indent, 0, 1); Expression onExpression = merge.getOnCondition(); if (onExpression != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent + 2; j++) + for (int j = 0; j < indent + 2; j++) { builder.append(indentString); - appendKeyWord(builder, outputFormat, "ON", "", " ( "); - - - - appendExpression(onExpression, null, builder, subIndent, 0, 1, false, BreakLine.AFTER_FIRST); + } + appendKeyWord(builder, outputFormat, "ON", "", " "); + appendExpression(onExpression, null, builder, indent, 0, 1, false, BreakLine.AS_NEEDED); - appendNormalizingTrailingWhiteSpace(builder, " )"); + appendNormalizingTrailingWhiteSpace(builder, " "); } MergeInsert insert = merge.getMergeInsert(); MergeUpdate update = merge.getMergeUpdate(); if (merge.isInsertFirst()) { appendMergeInsert(insert, builder, indent, 0); - appendMergeUpdate(update, builder, indent, 0); + appendMergeUpdate(update, builder, indent); } else { - appendMergeUpdate(update, builder, indent, 0); + appendMergeUpdate(update, builder, indent); appendMergeInsert(insert, builder, indent, 0); } appendOutputClaus(merge.getOutputClause(), builder, indent); } - private static void appendOutputClaus(OutputClause outputClause, StringBuilder builder, int indent) { - if (outputClause!=null) { + private static void appendOutputClaus(OutputClause outputClause, StringBuilder builder, + int indent) { + if (outputClause != null) { appendNormalizedLineBreak(builder); for (int j = 0; j < indent; j++) { builder.append(indentString); } appendKeyWord(builder, outputFormat, "OUTPUT", "", " "); - int i=0; - int subIndent = getSubIndent(builder, outputClause.getSelectItemList().size()>3); - appendSelectItemList(outputClause.getSelectItemList(), builder, subIndent, i, BreakLine.AS_NEEDED, indent); + int i = 0; + int subIndent = getSubIndent(builder, outputClause.getSelectItemList().size() > 3); + appendSelectItemList(outputClause.getSelectItemList(), builder, subIndent, i, + BreakLine.AS_NEEDED, indent); appendNormalizedLineBreak(builder); for (int j = 0; j < indent + 1; j++) { @@ -1642,44 +1492,46 @@ private static void appendOutputClaus(OutputClause outputClause, StringBuilder b } appendKeyWord(builder, outputFormat, "INTO", "", " "); - if (outputClause.getOutputTable()!=null) { + if (outputClause.getOutputTable() != null) { Table table = outputClause.getOutputTable(); - appendTable(table, table.getAlias(), builder, indent + 1, 0, 1); + appendTable(table, table.getAlias(), builder); - appendStringList( outputClause.getColumnList(), null, builder, indent + 1, true, BreakLine.AS_NEEDED); - } else if (outputClause.getTableVariable()!=null) { - appendObjectName(builder, outputFormat,outputClause.getTableVariable().toString(), " ", ""); + appendStringList(outputClause.getColumnList(), builder, indent + 1, true, + BreakLine.AS_NEEDED); + } else if (outputClause.getTableVariable() != null) { + appendObjectName(builder, outputFormat, outputClause.getTableVariable().toString(), " ", + ""); } } } - public static void appendMergeUpdate(MergeUpdate update, StringBuilder builder, int indent, - int i) { + public static void appendMergeUpdate(MergeUpdate update, StringBuilder builder, int indent) { if (update != null) { appendNormalizedLineBreak(builder); - i = 0; - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "WHEN", "", " "); appendKeyWord(builder, outputFormat, "MATCHED", "", " "); appendKeyWord(builder, outputFormat, "THEN", "", "\n"); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "UPDATE", "", " "); appendKeyWord(builder, outputFormat, "SET", "", " "); int subIndent = getSubIndent(builder, true); - List updateSets = update.getUpdateSets(); appendUpdateSets(builder, update.getUpdateSets(), subIndent); Expression whereCondition = update.getWhereCondition(); if (whereCondition != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "WHERE", "", " "); subIndent = getSubIndent(builder, true); @@ -1691,8 +1543,9 @@ public static void appendMergeUpdate(MergeUpdate update, StringBuilder builder, Expression deleteWhereCondition = update.getDeleteWhereCondition(); if (deleteWhereCondition != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "DELETE", "", " "); appendKeyWord(builder, outputFormat, "WHERE", "", " "); @@ -1704,56 +1557,62 @@ public static void appendMergeUpdate(MergeUpdate update, StringBuilder builder, } } + @SuppressWarnings({"PMD.CyclomaticComplexity"}) public static void appendMergeInsert(MergeInsert insert, StringBuilder builder, int indent, int i) { if (insert != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "WHEN", "", " "); appendKeyWord(builder, outputFormat, "NOT", "", " "); appendKeyWord(builder, outputFormat, "MATCHED", "", " "); appendKeyWord(builder, outputFormat, "THEN", "", "\n"); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "INSERT", "", " "); List columns = insert.getColumns(); List expressions = insert.getValues(); - if (columns != null && columns.size() > 0) { + int k = i; + if (columns != null && !columns.isEmpty()) { builder.append("( "); int subIndent = getSubIndent(builder, false); for (Column column : columns) { - appendExpression(column, null, builder, subIndent, i, columns.size(), true, + appendExpression(column, null, builder, subIndent, k++, columns.size(), true, BreakLine.AFTER_FIRST); - i++; } appendNormalizingTrailingWhiteSpace(builder, " )\n"); } - i = 0; - if (columns != null && columns.size() > 0) - for (int j = 0; j < indent + 1; j++) + if (columns != null && !columns.isEmpty()) { + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } + } appendKeyWord(builder, outputFormat, "VALUES", "", " ( "); int subIndent = getSubIndent(builder, false); - if (expressions != null) + if (expressions != null) { + int j = 0; for (Expression expression : expressions) { - appendExpression(expression, null, builder, subIndent, i, expressions.size(), true, + appendExpression(expression, null, builder, subIndent, j++, expressions.size(), true, BreakLine.AFTER_FIRST); - i++; } + } appendNormalizingTrailingWhiteSpace(builder, " )"); Expression whereCondition = insert.getWhereCondition(); if (whereCondition != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent + 1; j++) + for (int j = 0; j < indent + 1; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "WHERE", "", " "); subIndent = getSubIndent(builder, true); @@ -1766,12 +1625,12 @@ public static void appendMergeInsert(MergeInsert insert, StringBuilder builder, private static void appendInsert(StringBuilder builder, Insert insert, int indent) { List withItems = insert.getWithItemsList(); - if (withItems != null && withItems.size() > 0) { + if (withItems != null && !withItems.isEmpty()) { int i = 0; appendKeyWord(builder, outputFormat, "WITH", "", " "); for (WithItem withItem : withItems) { - appendWithItem(withItem, withItem.getAlias(), builder, indent, i, withItems.size()); + appendWithItem(withItem, builder, indent, i, withItems.size()); i++; } @@ -1780,14 +1639,15 @@ private static void appendInsert(StringBuilder builder, Insert insert, int inden appendKeyWord(builder, outputFormat, "INSERT", "", " "); OracleHint oracleHint = insert.getOracleHint(); - if (oracleHint != null) + if (oracleHint != null) { appendHint(builder, outputFormat, oracleHint.toString(), "", " "); + } appendKeyWord(builder, outputFormat, "INTO", "", " "); Table table = insert.getTable(); Alias alias = table.getAlias(); - appendTable(table, alias, builder, indent, 0, 1); + appendTable(table, alias, builder); List columns = insert.getColumns(); if (columns != null) { @@ -1807,12 +1667,12 @@ private static void appendInsert(StringBuilder builder, Insert insert, int inden private static void appendUpdate(StringBuilder builder, Update update, int indent) { List withItems = update.getWithItemsList(); - if (withItems != null && withItems.size() > 0) { + if (withItems != null && !withItems.isEmpty()) { int i = 0; appendKeyWord(builder, outputFormat, "WITH", "", " "); for (WithItem withItem : withItems) { - appendWithItem(withItem, withItem.getAlias(), builder, indent, i, withItems.size()); + appendWithItem(withItem, builder, indent, i, withItems.size()); i++; } @@ -1822,21 +1682,23 @@ private static void appendUpdate(StringBuilder builder, Update update, int inden appendKeyWord(builder, outputFormat, "UPDATE", "", " "); OracleHint oracleHint = update.getOracleHint(); - if (oracleHint != null) + if (oracleHint != null) { appendHint(builder, outputFormat, oracleHint.toString(), "", " "); + } Table table = update.getTable(); Alias alias = table.getAlias(); - appendTable(table, alias, builder, indent, 0, 1); + appendTable(table, alias, builder); if (update.getStartJoins() != null) { appendJoins(update.getStartJoins(), builder, indent); } appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "SET", "", " "); final int subIndent = getSubIndent(builder, true); @@ -1844,8 +1706,9 @@ private static void appendUpdate(StringBuilder builder, Update update, int inden if (update.getFromItem() != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "FROM", "", " "); appendFromItem(update.getFromItem(), builder, indent, 0, 1); } @@ -1860,14 +1723,16 @@ private static void appendUpdate(StringBuilder builder, Update update, int inden appendOrderByElements(orderByElements, builder, indent); } - private static void appendUpdateSets(StringBuilder builder, List updateSets, int subIndent) { + private static void appendUpdateSets(StringBuilder builder, List updateSets, + int subIndent) { int i = 0; int n = updateSets.size(); for (UpdateSet updateSet : updateSets) { if (i > 0) { appendNormalizedLineBreak(builder); - for (int j = 0; j < subIndent; j++) + for (int j = 0; j < subIndent; j++) { builder.append(indentString); + } } switch (separation) { @@ -1889,21 +1754,23 @@ private static void appendUpdateSets(StringBuilder builder, List upda } } + @SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength"}) private static void appendSelect(Select select, StringBuilder builder, int indent, boolean breakLineBefore, boolean indentFirstLine) { List withItems = select.getWithItemsList(); - if (withItems != null && withItems.size() > 0) { + if (withItems != null && !withItems.isEmpty()) { int i = 0; if (breakLineBefore) { appendNormalizedLineBreak(builder); - for (int j = 0; indentFirstLine && j < indent; j++) + for (int j = 0; indentFirstLine && j < indent; j++) { builder.append(indentString); + } } appendKeyWord(builder, outputFormat, "WITH", "", " "); for (WithItem withItem : withItems) { - appendWithItem(withItem, withItem.getAlias(), builder, indent, i, withItems.size()); + appendWithItem(withItem, builder, indent, i, withItems.size()); i++; } } @@ -1914,18 +1781,20 @@ private static void appendSelect(Select select, StringBuilder builder, int inden PlainSelect plainSelect = (PlainSelect) select; int i = 0; - if (breakLineBefore || (withItems != null && withItems.size() > 0)) { + if (breakLineBefore || withItems != null && !withItems.isEmpty()) { appendNormalizedLineBreak(builder); - for (int j = 0; indentFirstLine && j < indent; j++) + for (int j = 0; indentFirstLine && j < indent; j++) { builder.append(indentString); + } } appendKeyWord(builder, outputFormat, "SELECT", "", " "); OracleHint oracleHint = plainSelect.getOracleHint(); - if (oracleHint != null) + if (oracleHint != null) { appendHint(builder, outputFormat, oracleHint.toString(), "", " "); + } Distinct distinct = plainSelect.getDistinct(); if (distinct != null) { @@ -1934,19 +1803,18 @@ private static void appendSelect(Select select, StringBuilder builder, int inden throw new UnsupportedOperationException("Unique DISTINCT not supported yet."); } - if (distinct.getOnSelectItems() != null && distinct.getOnSelectItems().size() > 0) { + if (distinct.getOnSelectItems() != null && !distinct.getOnSelectItems().isEmpty()) { // @todo: implement Use Unique Distinct clause throw new UnsupportedOperationException( - "DISTINCT on select items are not supported yet."); + "DISTINCT on select items are not supported yet."); } appendKeyWord(builder, outputFormat, "DISTINCT", "", " "); } - int subIndent = (oracleHint != null || distinct != null) - ? indent + 1 - : getSubIndent(builder, plainSelect.getSelectItems().size() > 1); + int subIndent = oracleHint != null || distinct != null ? indent + 1 + : getSubIndent(builder, plainSelect.getSelectItems().size() > 1); BreakLine bl = - (oracleHint != null || distinct != null) ? BreakLine.ALWAYS : BreakLine.AFTER_FIRST; + oracleHint != null || distinct != null ? BreakLine.ALWAYS : BreakLine.AFTER_FIRST; List> selectItems = plainSelect.getSelectItems(); appendSelectItemList(selectItems, builder, subIndent, i, bl, indent); @@ -1954,8 +1822,9 @@ private static void appendSelect(Select select, StringBuilder builder, int inden FromItem fromItem = plainSelect.getFromItem(); if (fromItem != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "FROM", "", " "); appendFromItem(fromItem, builder, indent, i, 1); @@ -1978,8 +1847,9 @@ private static void appendSelect(Select select, StringBuilder builder, int inden Limit limit = plainSelect.getLimit(); if (limit != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "LIMIT", "", " "); Expression rowCount = limit.getRowCount(); @@ -1989,12 +1859,12 @@ private static void appendSelect(Select select, StringBuilder builder, int inden } else { if (null != limit.getOffset()) { appendExpression(limit.getOffset(), null, builder, indent, 0, 1, false, - BreakLine.NEVER); + BreakLine.NEVER); builder.append(", "); } if (null != limit.getRowCount()) { appendExpression(limit.getRowCount(), null, builder, indent, 0, 1, false, - BreakLine.NEVER); + BreakLine.NEVER); } } } @@ -2002,23 +1872,26 @@ private static void appendSelect(Select select, StringBuilder builder, int inden Offset offset = plainSelect.getOffset(); if (offset != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "OFFSET", "", " "); Expression offsetExpression = offset.getOffset(); appendExpression(offsetExpression, null, builder, indent, 0, 1, false, BreakLine.NEVER); String offsetParam = offset.getOffsetParam(); - if (offsetParam != null) - appendString(offsetParam, null, builder, indent, 0, 1, false, BreakLine.NEVER); + if (offsetParam != null) { + appendString(offsetParam, builder, indent, 0, 1, false, BreakLine.NEVER); + } } Fetch fetch = plainSelect.getFetch(); - if (fetch!=null) { + if (fetch != null) { appendNormalizedLineBreak(builder); - for (int j = 0; j < indent; j++) + for (int j = 0; j < indent; j++) { builder.append(indentString); + } appendKeyWord(builder, outputFormat, "FETCH", "", ""); if (fetch.isFetchParamFirst()) { @@ -2028,12 +1901,12 @@ private static void appendSelect(Select select, StringBuilder builder, int inden } Expression expression = fetch.getExpression(); - if (expression!=null) { + if (expression != null) { appendNormalizingTrailingWhiteSpace(builder, " "); appendExpression(expression, null, builder, indent, 0, 1, false, BreakLine.NEVER); } - for (String s: fetch.getFetchParameters()) { + for (String s : fetch.getFetchParameters()) { appendKeyWord(builder, outputFormat, s, " ", ""); } @@ -2047,7 +1920,7 @@ private static void appendSelect(Select select, StringBuilder builder, int inden int k = 0; List