diff --git a/src/main/java/org/schemaspy/Config.java b/src/main/java/org/schemaspy/Config.java index d5bf70c8c..e833accef 100644 --- a/src/main/java/org/schemaspy/Config.java +++ b/src/main/java/org/schemaspy/Config.java @@ -862,9 +862,7 @@ public Pattern getTableInclusions() { try { tableInclusions = Pattern.compile(strInclusions); } catch (PatternSyntaxException badPattern) { - throw new InvalidConfigurationException(badPattern) - .setParamName("-i") - .setParamValue(strInclusions); + throw new InvalidConfigurationException(badPattern, "-i", strInclusions); } } @@ -896,9 +894,7 @@ public Pattern getTableExclusions() { try { tableExclusions = Pattern.compile(strExclusions); } catch (PatternSyntaxException badPattern) { - throw new InvalidConfigurationException(badPattern) - .setParamName("-I") - .setParamValue(strExclusions); + throw new InvalidConfigurationException(badPattern, "-I", strExclusions); } } @@ -1383,7 +1379,7 @@ public static Set getBuiltInDatabaseTypes(String loadedFromJar) { try (JarInputStream jar = new JarInputStream(new FileInputStream(loadedFromJar))){ JarEntry entry; - while ((entry = jar.getNextJarEntry()) != null) { + while ((entry = jar.getNextJarEntry()) != null) { //NOSONAR Matcher dbTypeMatcher = DBTYPE_PATTERN.matcher(entry.getName()); if (dbTypeMatcher.find()) { databaseTypes.add(dbTypeMatcher.group(1)); diff --git a/src/main/java/org/schemaspy/cli/DegreeOfSeparationValidator.java b/src/main/java/org/schemaspy/cli/DegreeOfSeparationValidator.java index 9452fa1f4..44d44dfbb 100644 --- a/src/main/java/org/schemaspy/cli/DegreeOfSeparationValidator.java +++ b/src/main/java/org/schemaspy/cli/DegreeOfSeparationValidator.java @@ -23,7 +23,7 @@ public class DegreeOfSeparationValidator implements IValueValidator { @Override - public void validate(String name, Integer value) throws ParameterException { + public void validate(String name, Integer value) { if (value > 2 || value < 1 ) { throw new ParameterException("Illegal value for '"+name+"', allowed values are ['1','2']"); } diff --git a/src/main/java/org/schemaspy/cli/PropertyFileDefaultProvider.java b/src/main/java/org/schemaspy/cli/PropertyFileDefaultProvider.java index a3e9a9a69..fcadff5e8 100644 --- a/src/main/java/org/schemaspy/cli/PropertyFileDefaultProvider.java +++ b/src/main/java/org/schemaspy/cli/PropertyFileDefaultProvider.java @@ -23,10 +23,13 @@ import com.beust.jcommander.IDefaultProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.util.FileCopyUtils; -import java.io.*; +import java.io.IOException; +import java.io.StringReader; import java.lang.invoke.MethodHandles; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Objects; import java.util.Properties; @@ -52,15 +55,14 @@ public PropertyFileDefaultProvider(String propertiesFilename) { } private static Properties loadProperties(String path) { - try (Reader reader = new InputStreamReader(new FileInputStream(path), "UTF-8")){ + try { + String contents = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); Properties properties = new Properties(); - String contents = FileCopyUtils.copyToString(reader); // Replace backslashes with double backslashes to escape windows path separator. // Example input: schemaspy.o=C:\tools\schemaspy\output properties.load(new StringReader(contents.replace("\\", "\\\\"))); return properties; } catch (IOException e) { - LOGGER.error("File not found: {}", path, e); throw new IllegalArgumentException("Could not find or load properties file: " + path, e); } } diff --git a/src/main/java/org/schemaspy/input/dbms/config/PropertiesFinder.java b/src/main/java/org/schemaspy/input/dbms/config/PropertiesFinder.java index a839428ab..5f74948b7 100644 --- a/src/main/java/org/schemaspy/input/dbms/config/PropertiesFinder.java +++ b/src/main/java/org/schemaspy/input/dbms/config/PropertiesFinder.java @@ -68,7 +68,7 @@ private URL findFile(String file) { try { return path.toUri().toURL(); } catch (MalformedURLException e) { - LOGGER.debug("Couldn't convert existing file: {}", path.toString(), e); + LOGGER.debug("Couldn't convert existing file: {}", path, e); return null; } } @@ -93,7 +93,7 @@ private URL findClassPath(String resource) { LOGGER.debug("Couldn't convert url to uri to file: {}", url, e); return null; } catch (IOException e) { - LOGGER.error("Unable to create filesystem for url: {}", url.toString(), e); + LOGGER.error("Unable to create filesystem for url: {}", url, e); } } return null; diff --git a/src/main/java/org/schemaspy/input/dbms/config/PropertiesResolver.java b/src/main/java/org/schemaspy/input/dbms/config/PropertiesResolver.java index 73b347f27..21243012a 100644 --- a/src/main/java/org/schemaspy/input/dbms/config/PropertiesResolver.java +++ b/src/main/java/org/schemaspy/input/dbms/config/PropertiesResolver.java @@ -64,9 +64,7 @@ public Properties getDbProperties(String dbType) { LOGGER.debug(resolutionInfo.getTrace()); return props; } catch (ResourceNotFoundException rnfe) { - throw new InvalidConfigurationException("Unable to resolve databaseType: " + dbType, rnfe) - .setParamName("-t") - .setParamValue(dbType); + throw new InvalidConfigurationException("Unable to resolve databaseType: " + dbType, rnfe, "-t", dbType); } } diff --git a/src/main/java/org/schemaspy/input/dbms/service/ColumnService.java b/src/main/java/org/schemaspy/input/dbms/service/ColumnService.java index 48d0bb4dc..85443c45a 100644 --- a/src/main/java/org/schemaspy/input/dbms/service/ColumnService.java +++ b/src/main/java/org/schemaspy/input/dbms/service/ColumnService.java @@ -154,7 +154,7 @@ private void initColumnAutoUpdate(Table table, boolean forceQuotes) { if (forceQuotes) { if (!table.isLogical()) { // don't completely choke just because we couldn't do this.... - LOGGER.warn("Failed to determine auto increment status: {}", exc); + LOGGER.warn("Failed to determine auto increment status: {}", exc.getMessage(), exc); LOGGER.warn("SQL: {}", sql); } } else { diff --git a/src/main/java/org/schemaspy/input/dbms/service/IndexService.java b/src/main/java/org/schemaspy/input/dbms/service/IndexService.java index 91b002e65..c0611c694 100644 --- a/src/main/java/org/schemaspy/input/dbms/service/IndexService.java +++ b/src/main/java/org/schemaspy/input/dbms/service/IndexService.java @@ -79,7 +79,7 @@ private void initIndexes(Database db, Table table) throws SQLException { } } catch (SQLException exc) { if (!table.isLogical()) { - LOGGER.warn("Unable to extract index info for table '{}' in schema '{}': {}", table.getName(), table.getContainer(), exc); + LOGGER.warn("Unable to extract index info for table '{}' in schema '{}': {}", table.getName(), table.getContainer(), exc.getMessage(), exc); } } } @@ -171,12 +171,12 @@ private void processPrimaryKeyResultSet(final Table table, final ResultSet resul TableColumn tableColumn = table.getColumn(primaryKeyColumn.column); if (Objects.nonNull(tableColumn)) { table.setPrimaryColumn(tableColumn); - updateIndex(primaryKeyColumn.pk_name, table, tableColumn); + updateIndex(primaryKeyColumn.name, table, tableColumn); } else { LOGGER.error( "Found PrimaryKey index '{}' with column '{}.{}.{}.{}'" + ", but was unable to find column in table '{}'", - primaryKeyColumn.pk_name, + primaryKeyColumn.name, primaryKeyColumn.catalog, primaryKeyColumn.schema, primaryKeyColumn.table, @@ -216,15 +216,15 @@ private class PrimaryKeyColumn { public final String schema; public final String table; public final String column; - public final String pk_name; + public final String name; public final int seqno; public PrimaryKeyColumn(ResultSet resultSet) throws SQLException { this.catalog = resultSet.getString("TABLE_CAT"); this.schema = resultSet.getString("TABLE_SCHEM"); this.table = resultSet.getString("TABLE_NAME"); - this.column = resultSet.getString("COLUMN_NAME");; - this.pk_name = resultSet.getString("PK_NAME"); + this.column = resultSet.getString("COLUMN_NAME"); + this.name = resultSet.getString("PK_NAME"); this.seqno = resultSet.getShort("KEY_SEQ"); } } diff --git a/src/main/java/org/schemaspy/input/dbms/service/RoutineService.java b/src/main/java/org/schemaspy/input/dbms/service/RoutineService.java index 96bf2d302..4e3adf372 100644 --- a/src/main/java/org/schemaspy/input/dbms/service/RoutineService.java +++ b/src/main/java/org/schemaspy/input/dbms/service/RoutineService.java @@ -133,7 +133,7 @@ private static String getOptionalString(ResultSet rs, String columnName) { try { return rs.getString(columnName); } catch (SQLException sqlException) { - LOGGER.debug("Failed to get value for column '{}'", sqlException); + LOGGER.debug("Failed to get value for column '{}'", sqlException.getMessage(), sqlException); return null; } } diff --git a/src/main/java/org/schemaspy/input/dbms/service/SequenceService.java b/src/main/java/org/schemaspy/input/dbms/service/SequenceService.java index cbecea3a7..ba1c3c16e 100644 --- a/src/main/java/org/schemaspy/input/dbms/service/SequenceService.java +++ b/src/main/java/org/schemaspy/input/dbms/service/SequenceService.java @@ -20,8 +20,6 @@ import org.schemaspy.Config; import org.schemaspy.model.Database; -import org.schemaspy.model.Routine; -import org.schemaspy.model.RoutineParameter; import org.schemaspy.model.Sequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,7 +74,7 @@ private static int getOptionalInt(ResultSet rs, String columnName, int defaultIf try { return rs.getInt(columnName); } catch (SQLException sqlException) { - LOGGER.debug("Failed to get value for column '{}'", sqlException); + LOGGER.debug("Failed to get value for column '{}'", sqlException.getMessage(), sqlException); return defaultIfNotFound; } } diff --git a/src/main/java/org/schemaspy/input/dbms/xml/SchemaMeta.java b/src/main/java/org/schemaspy/input/dbms/xml/SchemaMeta.java index d9ea1a078..60cfa7263 100644 --- a/src/main/java/org/schemaspy/input/dbms/xml/SchemaMeta.java +++ b/src/main/java/org/schemaspy/input/dbms/xml/SchemaMeta.java @@ -170,7 +170,7 @@ private Document parse(File file) { try { validate(doc); } catch (SAXException | IOException exc) { - LOGGER.warn("Failed to validate {}: {}", file, exc); + LOGGER.warn("Failed to validate {}: {}", file, exc.getMessage(), exc); } return doc; diff --git a/src/main/java/org/schemaspy/model/ForeignKeyConstraint.java b/src/main/java/org/schemaspy/model/ForeignKeyConstraint.java index 360ab93e9..3f85558db 100644 --- a/src/main/java/org/schemaspy/model/ForeignKeyConstraint.java +++ b/src/main/java/org/schemaspy/model/ForeignKeyConstraint.java @@ -45,12 +45,12 @@ public class ForeignKeyConstraint implements Comparable { private final String name; private Table parentTable; - private final List parentColumns = new ArrayList(); + private final List parentColumns = new ArrayList<>(); private final Table childTable; - private final List childColumns = new ArrayList(); + private final List childColumns = new ArrayList<>(); private final int deleteRule; private final int updateRule; - private final static Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * Construct a foreign key for the specified child table. @@ -366,14 +366,11 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if (obj == null) { - return false; + if (obj instanceof ForeignKeyConstraint) { + ForeignKeyConstraint other = (ForeignKeyConstraint)obj; + return parentTable == other.parentTable && childTable == other.childTable; } - if (this.childTable != ((ForeignKeyConstraint)obj).childTable) { - return false; - } - - return this.parentTable == ((ForeignKeyConstraint) obj).parentTable; + return false; } @Override diff --git a/src/main/java/org/schemaspy/model/InvalidConfigurationException.java b/src/main/java/org/schemaspy/model/InvalidConfigurationException.java index f03e7ef56..48c6ae763 100644 --- a/src/main/java/org/schemaspy/model/InvalidConfigurationException.java +++ b/src/main/java/org/schemaspy/model/InvalidConfigurationException.java @@ -20,8 +20,6 @@ */ package org.schemaspy.model; -import java.util.Objects; - /** * Base class to indicate that there was problem with how SchemaSpy was configured / used. * @@ -30,8 +28,8 @@ */ public class InvalidConfigurationException extends RuntimeException { private static final long serialVersionUID = 1L; - private String paramName; - private String paramValue = ""; + private final String paramName; + private final String paramValue; /** * When a message is sufficient @@ -40,6 +38,8 @@ public class InvalidConfigurationException extends RuntimeException { */ public InvalidConfigurationException(String msg) { super(msg); + paramName = null; + paramValue = null; } /** @@ -51,6 +51,14 @@ public InvalidConfigurationException(String msg) { */ public InvalidConfigurationException(String msg, Throwable cause) { super(msg, cause); + paramName = null; + paramValue = null; + } + + public InvalidConfigurationException(String msg, Throwable cause, String paramName, String paramValue) { + super(msg, cause); + this.paramName = paramName; + this.paramValue = paramValue; } /** @@ -60,22 +68,20 @@ public InvalidConfigurationException(String msg, Throwable cause) { */ public InvalidConfigurationException(Throwable cause) { super(cause); + paramName = null; + paramValue = null; } - public InvalidConfigurationException setParamName(String paramName) { + public InvalidConfigurationException(Throwable cause, String paramName, String paramValue) { + super(cause); this.paramName = paramName; - return this; + this.paramValue = paramValue; } public String getParamName() { return paramName; } - public InvalidConfigurationException setParamValue(String paramValue) { - if (Objects.nonNull(paramValue)) - this.paramValue = paramValue; - return this; - } public String getParamValue() { return paramValue; diff --git a/src/main/java/org/schemaspy/model/Table.java b/src/main/java/org/schemaspy/model/Table.java index aa250c23b..ddebfbb43 100644 --- a/src/main/java/org/schemaspy/model/Table.java +++ b/src/main/java/org/schemaspy/model/Table.java @@ -60,7 +60,7 @@ public class Table implements Comparable { private int maxChildren; private int maxParents; - private final static Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * Construct a table that knows everything about the database table's metadata @@ -75,7 +75,7 @@ public Table(Database db, String catalog, String schema, String name, String com this.db = db; this.catalog = catalog; this.schema = schema; - this.container = schema != null ? schema : catalog != null ? catalog : db.getName(); + this.container = Optional.ofNullable(schema).orElse(Optional.ofNullable(catalog).orElse(db.getName())); this.name = name; this.fullName = getFullName(db.getName(), catalog, schema, name); LOGGER.debug("Creating {} {}", getClass().getSimpleName(), fullName); @@ -547,18 +547,18 @@ public int getNumNonImpliedParents() { * @return */ public ForeignKeyConstraint removeAForeignKeyConstraint() { - final List columns = getColumns(); + final List sortedColumns = getColumns(); int numParents = 0; int numChildren = 0; // remove either a child or parent, choosing which based on which has the // least number of foreign key associations (when either gets to zero then // the table can be pruned) - for (TableColumn column : columns) { + for (TableColumn column : sortedColumns) { numParents += column.getParents().size(); numChildren += column.getChildren().size(); } - for (TableColumn column : columns) { + for (TableColumn column : sortedColumns) { ForeignKeyConstraint constraint; if (numParents <= numChildren) constraint = column.removeAParentFKConstraint(); diff --git a/src/main/java/org/schemaspy/model/TableColumn.java b/src/main/java/org/schemaspy/model/TableColumn.java index f623ca03a..058685ea1 100644 --- a/src/main/java/org/schemaspy/model/TableColumn.java +++ b/src/main/java/org/schemaspy/model/TableColumn.java @@ -413,13 +413,11 @@ public ForeignKeyConstraint getParentConstraint(TableColumn parent) { * @return the removed {@link ForeignKeyConstraint} */ public ForeignKeyConstraint removeAParentFKConstraint() { - for (TableColumn relatedColumn : parents.keySet()) { - ForeignKeyConstraint constraint = parents.remove(relatedColumn); - relatedColumn.removeChild(this); - return constraint; - } - - return null; + return parents.entrySet().stream().findFirst().map(entry -> { + parents.remove(entry.getKey()); + entry.getKey().removeChild(this); + return entry.getValue(); + }).orElse(null); } /** @@ -428,13 +426,11 @@ public ForeignKeyConstraint removeAParentFKConstraint() { * @return the removed constraint, or null if none were available to be removed */ public ForeignKeyConstraint removeAChildFKConstraint() { - for (TableColumn relatedColumn : children.keySet()) { - ForeignKeyConstraint constraint = children.remove(relatedColumn); - relatedColumn.removeParent(this); - return constraint; - } - - return null; + return children.entrySet().stream().findFirst().map(entry -> { + children.remove(entry.getKey()); + entry.getKey().removeParent(this); + return entry.getValue(); + }).orElse(null); } /** diff --git a/src/main/java/org/schemaspy/output/diagram/vizjs/VizJSDot.java b/src/main/java/org/schemaspy/output/diagram/vizjs/VizJSDot.java index 6e40ff994..8fe0aa3ed 100644 --- a/src/main/java/org/schemaspy/output/diagram/vizjs/VizJSDot.java +++ b/src/main/java/org/schemaspy/output/diagram/vizjs/VizJSDot.java @@ -29,6 +29,7 @@ import java.io.File; import java.io.FileWriter; import java.io.InputStream; +import java.nio.charset.StandardCharsets; public class VizJSDot implements DiagramProducer { @@ -44,7 +45,7 @@ public VizJSDot() { } ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); - scriptEngine.eval(IOUtils.toString(vizJs,"UTF-8")); + scriptEngine.eval(IOUtils.toString(vizJs, StandardCharsets.UTF_8)); } catch (Exception e) { throw new IllegalArgumentException("viz.js", e); } @@ -62,7 +63,7 @@ public String getDiagramFormat() { public String generateDiagram(File dotFile, File diagramFile) { try { - String dotSource = IOUtils.toString(dotFile.toURI().toURL(), "UTF-8"); + String dotSource = IOUtils.toString(dotFile.toURI().toURL(), StandardCharsets.UTF_8); String svg = toSvg(dotSource, MB_64); try (FileWriter diagramWriter = new FileWriter(diagramFile)){ IOUtils.write(svg, diagramWriter); diff --git a/src/main/java/org/schemaspy/output/dot/schemaspy/DotNode.java b/src/main/java/org/schemaspy/output/dot/schemaspy/DotNode.java index a1021a35d..6ecdbd8b8 100644 --- a/src/main/java/org/schemaspy/output/dot/schemaspy/DotNode.java +++ b/src/main/java/org/schemaspy/output/dot/schemaspy/DotNode.java @@ -60,6 +60,7 @@ public class DotNode { private static final StyleSheet CSS = StyleSheet.getInstance(); private static final String INDENT_6 = " "; + private static final String TABLES_PATH = "/tables/"; //NOSONAR private final Table table; private final String path; @@ -81,12 +82,12 @@ public DotNode(Table table, boolean fromRoot, DotNodeConfig config, DotConfig do private String createPath(boolean fromRoot) { if (dotConfig.useRelativeLinks()) { - return (table.isRemote() ? "../../../" + table.getContainer() : "../..") + "/tables/"; + return (table.isRemote() ? "../../../" + table.getContainer() : "../..") + TABLES_PATH; } if (fromRoot) { - return (table.isRemote() ? ("../" + table.getContainer() + "/tables/") : "tables/"); + return (table.isRemote() ? ("../" + table.getContainer() + TABLES_PATH) : "tables/"); } - return (table.isRemote() ? ("../../" + table.getContainer() + "/tables/") : ""); + return (table.isRemote() ? ("../../" + table.getContainer() + TABLES_PATH) : ""); } @@ -174,8 +175,7 @@ private Set getIndexColumns() { } private int getTitleMaxWidth(String titleTable) { - int maxTitleWidth = getTextWidth(titleTable); - return maxTitleWidth; + return getTextWidth(titleTable); } private int getColumnMaxWidth() { diff --git a/src/main/java/org/schemaspy/util/ResourceWriter.java b/src/main/java/org/schemaspy/util/ResourceWriter.java index fea7f304b..767bad6ae 100644 --- a/src/main/java/org/schemaspy/util/ResourceWriter.java +++ b/src/main/java/org/schemaspy/util/ResourceWriter.java @@ -92,7 +92,7 @@ private static void copyJarResourceToPath(JarURLConnection jarConnection, File d * Iterate all entries in the jar file. */ for (Enumeration e = jarFile.entries(); e.hasMoreElements();) { - JarEntry jarEntry = e.nextElement(); + JarEntry jarEntry = e.nextElement(); //NOSONAR String jarEntryName = jarEntry.getName(); /** diff --git a/src/main/java/org/schemaspy/view/HtmlColumnsPage.java b/src/main/java/org/schemaspy/view/HtmlColumnsPage.java index 9f0f7eaf0..402175216 100644 --- a/src/main/java/org/schemaspy/view/HtmlColumnsPage.java +++ b/src/main/java/org/schemaspy/view/HtmlColumnsPage.java @@ -109,7 +109,7 @@ private static JSONObject switchToLinkedHashMap(JSONObject jsonObject) { map.set(jsonObject, new LinkedHashMap<>()); map.setAccessible(false); } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); + LOGGER.debug("Failed to replace hashmap with linkedhashmap in JSONObject", e); } return jsonObject; } diff --git a/src/main/java/org/schemaspy/view/MustacheCompiler.java b/src/main/java/org/schemaspy/view/MustacheCompiler.java index 07c3c86f7..5f58b6670 100644 --- a/src/main/java/org/schemaspy/view/MustacheCompiler.java +++ b/src/main/java/org/schemaspy/view/MustacheCompiler.java @@ -59,7 +59,7 @@ public void write(PageData pageData, Writer writer) throws IOException { StringWriter result = new StringWriter(); HashMap pageScope = new HashMap<>(); - pageScope.put("toFileName", (Function) name -> FileNameGenerator.generate(name)); + pageScope.put("toFileName", (Function) FileNameGenerator::generate); pageScope.put("databaseName", databaseName); pageScope.put("paginationEnabled", htmlConfig.isPaginationEnabled()); pageScope.put("displayNumRows", htmlConfig.isNumRowsEnabled()); diff --git a/src/main/java/org/schemaspy/view/SqlAnalyzer.java b/src/main/java/org/schemaspy/view/SqlAnalyzer.java index 6d29f3e65..b113246e7 100644 --- a/src/main/java/org/schemaspy/view/SqlAnalyzer.java +++ b/src/main/java/org/schemaspy/view/SqlAnalyzer.java @@ -39,7 +39,7 @@ public class SqlAnalyzer { private Map tablesByPossibleNames; private static final String TOKENS = " \t\n\r\f()<>|,"; - { + static { quoters.add(s -> "'" + s + "'"); quoters.add(s -> "`" + s + "`"); quoters.add(s -> "\"" + s +"\""); diff --git a/src/main/resources/org/schemaspy/types/mssql17.properties b/src/main/resources/org/schemaspy/types/mssql17.properties index af586c6ed..de4ca4ef5 100644 --- a/src/main/resources/org/schemaspy/types/mssql17.properties +++ b/src/main/resources/org/schemaspy/types/mssql17.properties @@ -28,4 +28,4 @@ selectColumnCommentsSql=select x.table_name, x.column_name, x.comments from ( se selectViewCommentsSql=SELECT objname as view_name, cast(value as nvarchar(max)) as comments FROM fn_listextendedproperty(N'MS_Description', N'schema', :schema, 'view', null, default, default) selectViewColumnCommentsSql=select x.view_name, x.column_name, x.comments from ( select v.name as view_name, c.name as column_name, cast((SELECT value from fn_listextendedproperty(N'MS_Description', N'schema', SCHEMA_NAME(v.schema_id), 'view', v.name, 'column', c.name)) as NVARCHAR(MAX)) as comments from sys.views v left join sys.columns c on (v.object_id = c.object_id) where SCHEMA_NAME(v.schema_id) = :schema ) x where not x.comments is null -selectRoutinesSql=SELECT i_s.routine_name, i_s.routine_type, i_s.data_type AS dtd_identifier, i_s.routine_body, i_s.routine_definition, i_s.is_deterministic, i_s.sql_data_access, NULL AS security_type, NULL AS sql_mode, (select cast(value as nvarchar(max)) from fn_listextendedproperty(N'MS_Description', N'schema', i_s.routine_schema, 'procedure', i_s.ROUTINE_NAME, default, default)) AS routine_comment FROM information_schema.routines i_s WHERE routine_schema = :schema \ No newline at end of file +selectRoutinesSql=SELECT i_s.routine_name, i_s.routine_type, i_s.data_type AS dtd_identifier, i_s.routine_body, i_s.routine_definition, i_s.is_deterministic, i_s.sql_data_access, NULL AS security_type, NULL AS sql_mode, (select cast(value as nvarchar(max)) from fn_listextendedproperty(N'MS_Description', N'schema', i_s.routine_schema, 'procedure', i_s.ROUTINE_NAME, default, default)) AS routine_comment FROM INFORMATION_SCHEMA.ROUTINES i_s WHERE routine_schema = :schema \ No newline at end of file diff --git a/src/test/java/org/schemaspy/model/InvalidConfigurationExceptionTest.java b/src/test/java/org/schemaspy/model/InvalidConfigurationExceptionTest.java deleted file mode 100644 index 89ee2ff3a..000000000 --- a/src/test/java/org/schemaspy/model/InvalidConfigurationExceptionTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2017 Rafal Kasa - * - * This file is part of SchemaSpy. - * - * SchemaSpy is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * SchemaSpy 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with SchemaSpy. If not, see . - */ -package org.schemaspy.model; - -import org.junit.Test; -import org.testcontainers.shaded.io.netty.util.internal.StringUtil; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Rafal Kasa - */ -public class InvalidConfigurationExceptionTest { - - @Test - public void shouldSetParamName() { - try { - throw new InvalidConfigurationException("Unable to resolve databaseType: ").setParamName("-t"); - } catch (InvalidConfigurationException exception) { - assertThat(exception.getParamName()).isEqualTo("-t"); - } - } - - - @Test(expected = InvalidConfigurationException.class) - public void shouldThrowInvalidConfigurationExceptionWithMessage() { - SimpleClass simpleClass = new SimpleClass(); - simpleClass.getParam(); - } - - @Test(expected = InvalidConfigurationException.class) - public void shouldThrowInvalidConfigurationException() { - invokeGetParam(); - } - - public void invokeGetParam() { - try { - SimpleClass simpleClass = new SimpleClass(); - simpleClass.getInstance().setParam(StringUtil.EMPTY_STRING); - } catch (IllegalArgumentException exc) { - throw new InvalidConfigurationException(exc); - } catch (Exception exc) { - if (exc.getCause() instanceof InvalidConfigurationException) - throw (InvalidConfigurationException) exc.getCause(); - throw new InvalidConfigurationException(exc.getCause()); - } - } - - class SimpleClass { - private SimpleClass instance; - private String param; - - public void createInstance() { - instance = new SimpleClass(); - } - - public SimpleClass getInstance() throws InvalidConfigurationException { - return this.instance; - } - - public String getParam() throws InvalidConfigurationException { - try { - return this.instance.param; - } catch (Exception exc) { - throw new InvalidConfigurationException("Failed to initialize instance of SimpleClass: ", exc); - } - } - - public void setParam(String param) { - this.param = param; - } - } -} \ No newline at end of file diff --git a/src/test/java/org/schemaspy/model/TableTest.java b/src/test/java/org/schemaspy/model/TableTest.java new file mode 100644 index 000000000..11732cca7 --- /dev/null +++ b/src/test/java/org/schemaspy/model/TableTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2020 Nils Petzaell + * + * This file is part of SchemaSpy. + * + * SchemaSpy is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * SchemaSpy 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with SchemaSpy. If not, see . + */ +package org.schemaspy.model; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class TableTest { + + private static final Database database = mock(Database.class); + + static { + when(database.getName()).thenReturn("DBNAME"); + } + + @Test + public void containerIsSchema() { + Table table = new Table(database, "CATNAME", "SNAME", "table", null); + assertThat(table.getContainer()).isEqualToIgnoringCase("SNAME"); + } + + @Test + public void containerIsCatalog() { + Table table = new Table(database, "CATNAME", null, "table", null); + assertThat(table.getContainer()).isEqualToIgnoringCase("CATNAME"); + } + + @Test + public void containerIsDatabaseName() { + Table table = new Table(database, null, null, "table", null); + assertThat(table.getContainer()).isEqualToIgnoringCase("DBNAME"); + } + +} \ No newline at end of file