diff --git a/.editorconfig b/.editorconfig index b636bea8..7e731d3d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,7 +6,7 @@ indent_style = space insert_final_newline = true max_line_length = 199 tab_width = 4 -ij_continuation_indent_size = 8 +ij_continuation_indent_size = 4 [*.java] ij_java_imports_layout = *,|,java.**,javax.**,|,$* diff --git a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/AbstractDbMigrationGenerator.java b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/AbstractDbMigrationGenerator.java index a7674b50..66c97ffd 100644 --- a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/AbstractDbMigrationGenerator.java +++ b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/AbstractDbMigrationGenerator.java @@ -21,7 +21,6 @@ * Base class for all migration generators. * * @param represents an object in a database associated with a table - * * @author Ivan Vahrushev * @since 0.6.2 */ diff --git a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGenerator.java b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGenerator.java index fac0cf40..0de7f413 100644 --- a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGenerator.java +++ b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGenerator.java @@ -34,7 +34,7 @@ public ColumnWithSerialTypeMigrationGenerator(@Nonnull final GeneratingOptions o @Nonnull protected String generate(@Nonnull final ColumnWithSerialType column) { return dropDefaultValueGenerator.generate(column) + - System.lineSeparator() + - dropSequenceGenerator.generate(column); + System.lineSeparator() + + dropSequenceGenerator.generate(column); } } diff --git a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DbMigrationGenerator.java b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DbMigrationGenerator.java index 6a9900ce..67c9f1d3 100644 --- a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DbMigrationGenerator.java +++ b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DbMigrationGenerator.java @@ -19,7 +19,6 @@ * Database migrations generator. * * @param represents an object in a database associated with a table - * * @author Ivan Vahrushev * @since 0.5.0 */ diff --git a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DropDefaultValueGenerator.java b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DropDefaultValueGenerator.java index 20b705e9..1d835728 100644 --- a/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DropDefaultValueGenerator.java +++ b/pg-index-health-generator/src/main/java/io/github/mfvanek/pg/generator/DropDefaultValueGenerator.java @@ -32,13 +32,13 @@ final class DropDefaultValueGenerator extends AbstractOptionsAwareSqlGenerator n + keyword(" is not null")) - .collect(Collectors.joining(" and ")); + .filter(Column::isNullable) + .map(Column::getColumnName) + .map(n -> n + keyword(" is not null")) + .collect(Collectors.joining(" and ")); queryBuilder.append(columnsList); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGeneratorTest.java index d7b5fe9f..e9e699bb 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ColumnWithSerialTypeMigrationGeneratorTest.java @@ -26,8 +26,8 @@ class ColumnWithSerialTypeMigrationGeneratorTest { @Test void shouldHandleInvalidArguments() { assertThatThrownBy(() -> new ColumnWithSerialTypeMigrationGenerator(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("options cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("options cannot be null"); } @Test @@ -35,10 +35,10 @@ void forSingleColumn() { final ColumnWithSerialTypeMigrationGenerator generator = new ColumnWithSerialTypeMigrationGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(List.of(column()))) - .hasSize(1) - .containsExactly("alter table if exists s1.t1" + System.lineSeparator() + - " alter column col1 drop default;" + System.lineSeparator() + - "drop sequence if exists s1.seq1;"); + .hasSize(1) + .containsExactly("alter table if exists s1.t1" + System.lineSeparator() + + " alter column col1 drop default;" + System.lineSeparator() + + "drop sequence if exists s1.seq1;"); } @Test @@ -47,13 +47,13 @@ void forSeveralColumns() { final ColumnWithSerialTypeMigrationGenerator generator = new ColumnWithSerialTypeMigrationGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(List.of(column(), secondColumn))) - .hasSize(2) - .containsExactly("alter table if exists s1.t1" + System.lineSeparator() + - " alter column col1 drop default;" + System.lineSeparator() + - "drop sequence if exists s1.seq1;", - "alter table if exists s2.t2" + System.lineSeparator() + - " alter column col2 drop default;" + System.lineSeparator() + - "drop sequence if exists s2.seq2;"); + .hasSize(2) + .containsExactly("alter table if exists s1.t1" + System.lineSeparator() + + " alter column col1 drop default;" + System.lineSeparator() + + "drop sequence if exists s1.seq1;", + "alter table if exists s2.t2" + System.lineSeparator() + + " alter column col2 drop default;" + System.lineSeparator() + + "drop sequence if exists s2.seq2;"); } @Nonnull diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropDefaultValueGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropDefaultValueGeneratorTest.java index de833c0c..47f45073 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropDefaultValueGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropDefaultValueGeneratorTest.java @@ -25,42 +25,42 @@ class DropDefaultValueGeneratorTest { @Test void shouldHandleInvalidArguments() { assertThatThrownBy(() -> new DropDefaultValueGenerator(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("options cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("options cannot be null"); final DropDefaultValueGenerator generator = new DropDefaultValueGenerator(GeneratingOptions.builder().build()); assertThatThrownBy(() -> generator.generate(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("column cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("column cannot be null"); } @Test void generateForColumnLowerCase() { final DropDefaultValueGenerator generator = new DropDefaultValueGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(column())) - .isEqualTo("alter table if exists s1.t1" + System.lineSeparator() + - " alter column col1 drop default;"); + .isEqualTo("alter table if exists s1.t1" + System.lineSeparator() + + " alter column col1 drop default;"); } @Test void generateWithoutBreakingLines() { final DropDefaultValueGenerator generator = new DropDefaultValueGenerator( - GeneratingOptions.builder() - .doNotBreakLines() - .build()); + GeneratingOptions.builder() + .doNotBreakLines() + .build()); assertThat(generator.generate(column())) - .isEqualTo("alter table if exists s1.t1 alter column col1 drop default;"); + .isEqualTo("alter table if exists s1.t1 alter column col1 drop default;"); } @Test void generateForColumnUpperCase() { final DropDefaultValueGenerator generator = new DropDefaultValueGenerator( - GeneratingOptions.builder() - .uppercaseForKeywords() - .doNotBreakLines() - .build()); + GeneratingOptions.builder() + .uppercaseForKeywords() + .doNotBreakLines() + .build()); assertThat(generator.generate(column())) - .isEqualTo("ALTER TABLE IF EXISTS s1.t1 ALTER COLUMN col1 DROP DEFAULT;"); + .isEqualTo("ALTER TABLE IF EXISTS s1.t1 ALTER COLUMN col1 DROP DEFAULT;"); } @Nonnull diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropSequenceGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropSequenceGeneratorTest.java index d19061a0..34e5c2df 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropSequenceGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/DropSequenceGeneratorTest.java @@ -25,30 +25,30 @@ class DropSequenceGeneratorTest { @Test void shouldHandleInvalidArguments() { assertThatThrownBy(() -> new DropSequenceGenerator(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("options cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("options cannot be null"); final DropSequenceGenerator generator = new DropSequenceGenerator(GeneratingOptions.builder().build()); assertThatThrownBy(() -> generator.generate(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("column cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("column cannot be null"); } @Test void generateForColumnLowerCase() { final DropSequenceGenerator generator = new DropSequenceGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(column())) - .isEqualTo("drop sequence if exists s1.seq1;"); + .isEqualTo("drop sequence if exists s1.seq1;"); } @Test void generateForColumnUpperCase() { final DropSequenceGenerator generator = new DropSequenceGenerator( - GeneratingOptions.builder() - .uppercaseForKeywords() - .build()); + GeneratingOptions.builder() + .uppercaseForKeywords() + .build()); assertThat(generator.generate(column())) - .isEqualTo("DROP SEQUENCE IF EXISTS s1.seq1;"); + .isEqualTo("DROP SEQUENCE IF EXISTS s1.seq1;"); } @Nonnull diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ForeignKeyMigrationGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ForeignKeyMigrationGeneratorTest.java index ad0f4f1e..0f674ec5 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ForeignKeyMigrationGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/ForeignKeyMigrationGeneratorTest.java @@ -26,11 +26,11 @@ void generateForSingleForeignKey() { final DbMigrationGenerator generator = new ForeignKeyMigrationGenerator(GeneratingOptions.builder().build()); final List result = generator.generate(List.of(nullableColumnWithSchema())); assertThat(result) - .hasSize(1) - .containsExactly("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + - "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + - " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + - "where column_with_very_very_very_long_name is not null;"); + .hasSize(1) + .containsExactly("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + + "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + + " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + + "where column_with_very_very_very_long_name is not null;"); } @Test @@ -38,15 +38,15 @@ void generateForSeveralForeignKeys() { final DbMigrationGenerator generator = new ForeignKeyMigrationGenerator(GeneratingOptions.builder().build()); final List result = generator.generate(List.of(severalColumnsWithNulls(), severalColumnsWithNulls(), nullableColumnWithSchema())); assertThat(result) - .hasSize(3) - .containsExactly( - "create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + - " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;", - "create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + - " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;", - "/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + - "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + - " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + - "where column_with_very_very_very_long_name is not null;"); + .hasSize(3) + .containsExactly( + "create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + + " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;", + "create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + + " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;", + "/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + + "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + + " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + + "where column_with_very_very_very_long_name is not null;"); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/GeneratingOptionsTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/GeneratingOptionsTest.java index 4f1aebae..92be170b 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/GeneratingOptionsTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/GeneratingOptionsTest.java @@ -22,27 +22,27 @@ void testToString() { final GeneratingOptions.Builder builder = GeneratingOptions.builder(); final GeneratingOptions options = builder.build(); assertThat(options) - .hasToString("GeneratingOptions{concurrently=true, excludeNulls=true, breakLines=true, indentation=4, uppercaseForKeywords=false, nameWithoutNulls=true, idxPosition=SUFFIX}"); + .hasToString("GeneratingOptions{concurrently=true, excludeNulls=true, breakLines=true, indentation=4, uppercaseForKeywords=false, nameWithoutNulls=true, idxPosition=SUFFIX}"); builder.normally() - .includeNulls() - .doNotBreakLines() - .withIndentation(2) - .uppercaseForKeywords() - .doNotNameWithoutNulls() - .withIdxPosition(IdxPosition.PREFIX); + .includeNulls() + .doNotBreakLines() + .withIndentation(2) + .uppercaseForKeywords() + .doNotNameWithoutNulls() + .withIdxPosition(IdxPosition.PREFIX); assertThat(builder) - .hasToString("Builder{concurrently=false, excludeNulls=false, breakLines=false, indentation=2, uppercaseForKeywords=true, nameWithoutNulls=false, idxPosition=PREFIX}"); + .hasToString("Builder{concurrently=false, excludeNulls=false, breakLines=false, indentation=2, uppercaseForKeywords=true, nameWithoutNulls=false, idxPosition=PREFIX}"); builder.concurrently() - .excludeNulls() - .breakLines() - .withIndentation(4) - .lowercaseForKeywords() - .nameWithoutNulls() - .withIdxPosition(IdxPosition.SUFFIX); + .excludeNulls() + .breakLines() + .withIndentation(4) + .lowercaseForKeywords() + .nameWithoutNulls() + .withIdxPosition(IdxPosition.SUFFIX); assertThat(builder) - .hasToString("Builder{concurrently=true, excludeNulls=true, breakLines=true, indentation=4, uppercaseForKeywords=false, nameWithoutNulls=true, idxPosition=SUFFIX}"); + .hasToString("Builder{concurrently=true, excludeNulls=true, breakLines=true, indentation=4, uppercaseForKeywords=false, nameWithoutNulls=true, idxPosition=SUFFIX}"); } @SuppressWarnings("checkstyle:ExecutableStatementCount") @@ -96,16 +96,16 @@ void withInvalidArguments() { final GeneratingOptions.Builder builder = GeneratingOptions.builder(); assertThatThrownBy(() -> builder.withIndentation(-1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indentation should be in the range [0, 8]"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indentation should be in the range [0, 8]"); assertThatThrownBy(() -> builder.withIndentation(9)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indentation should be in the range [0, 8]"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indentation should be in the range [0, 8]"); //noinspection ConstantConditions assertThatThrownBy(() -> builder.withIdxPosition(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("idxPosition cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("idxPosition cannot be null"); } @Test @@ -113,11 +113,11 @@ void withValidIndentation() { final GeneratingOptions.Builder builder = GeneratingOptions.builder(); assertThat(builder.withIndentation(0).build()) - .isNotNull() - .satisfies(b -> assertThat(b.getIndentation()).isZero()); + .isNotNull() + .satisfies(b -> assertThat(b.getIndentation()).isZero()); assertThat(builder.withIndentation(8).build()) - .isNotNull() - .satisfies(b -> assertThat(b.getIndentation()).isEqualTo(8)); + .isNotNull() + .satisfies(b -> assertThat(b.getIndentation()).isEqualTo(8)); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIdentifierNameGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIdentifierNameGeneratorTest.java index 7a24b676..037839fe 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIdentifierNameGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIdentifierNameGeneratorTest.java @@ -27,175 +27,175 @@ class PgIdentifierNameGeneratorTest { @Test void shouldThrowExceptionOnInvalidArguments() { assertThatThrownBy(() -> PgIdentifierNameGenerator.of(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("foreignKey cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("foreignKey cannot be null"); final ForeignKey foreignKey = ForeignKey.ofNullableColumn("t", "cn", "c"); assertThatThrownBy(() -> PgIdentifierNameGenerator.of(foreignKey, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("options cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("options cannot be null"); } @Test void shouldGenerateFullIndexName() { final ForeignKey withoutNulls = notNullColumnWithSchema(); assertThat(PgIdentifierNameGenerator.of(withoutNulls, GeneratingOptions.builder().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(withoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_column_with_very_very_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_column_with_very_very_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); final ForeignKey withNulls = nullableColumnWithSchema(); assertThat(PgIdentifierNameGenerator.of(withNulls, GeneratingOptions.builder().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(withNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithoutNulls = severalColumnsWithoutNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, GeneratingOptions.builder().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_idx") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_idx") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithNulls = severalColumnsWithNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, GeneratingOptions.builder().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls_idx") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls_idx") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateFullIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, GeneratingOptions.builder().doNotNameWithoutNulls().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_idx") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_idx") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).doNotNameWithoutNulls().build()).generateFullIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).doNotNameWithoutNulls().build()).generateFullIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); } @Test void shouldGenerateFullNameWithoutIdx() { final ForeignKey severalColumnsWithoutNulls = severalColumnsWithoutNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateFullIndexName()) + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateFullIndexName()) + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithNulls = severalColumnsWithNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateFullIndexName()) + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name_without_nulls") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateFullIndexName()) - .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") - .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateFullIndexName()) + .isEqualTo("table_with_very_very_very_long_name_column_1_with_very_long_name_column_2_with_very_long_name") + .hasSizeGreaterThan(MAX_IDENTIFIER_LENGTH); } @Test void shouldGenerateTruncatedIndexName() { final ForeignKey withoutNulls = notNullColumnWithSchema(); assertThat(PgIdentifierNameGenerator.of(withoutNulls, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_3202677_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_3202677_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(withoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_3202677") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_3202677") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithoutNulls = severalColumnsWithoutNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithNulls = severalColumnsWithNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, GeneratingOptions.builder().doNotNameWithoutNulls().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_n1959284032_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).doNotNameWithoutNulls().build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).doNotNameWithoutNulls().build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); } @Test void shouldGenerateTruncatedIndexNameWithoutNulls() { final ForeignKey first = nullableColumnWithSchema(); assertThat(PgIdentifierNameGenerator.of(first, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_3202677_without_nulls_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_3202677_without_nulls_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(first, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_3202677_without_nulls") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_3202677_without_nulls") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); final ForeignKey second = ForeignKey.ofNullableColumn("table_with_very_very_very_long_name_1", "cn", "column1"); assertThat(PgIdentifierNameGenerator.of(second, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_1_column1_without_nulls_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_1_column1_without_nulls_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); final ForeignKey third = ForeignKey.ofNullableColumn("table_with_very_very_very_long_name_12", "cn", "column1"); assertThat(PgIdentifierNameGenerator.of(third, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_12_column1_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_12_column1_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); } @Test void shouldGenerateTruncatedIndexNameForColumnWithZeroHash() { final ForeignKey columnWithZeroHash = notNullColumnWithZeroHash(); assertThat(PgIdentifierNameGenerator.of(columnWithZeroHash, GeneratingOptions.builder().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_that_is_even_longer_0_idx") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + .isEqualTo("table_with_very_very_very_long_name_that_is_even_longer_0_idx") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(columnWithZeroHash, - GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) - .isEqualTo("idx_table_with_very_very_very_long_name_that_is_even_longer_0") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.PREFIX).build()).generateTruncatedIndexName()) + .isEqualTo("idx_table_with_very_very_very_long_name_that_is_even_longer_0") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); } @Test void shouldGenerateTruncatedNameWithoutIdx() { final ForeignKey severalColumnsWithoutNulls = severalColumnsWithoutNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateTruncatedIndexName()) + .isEqualTo("table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithoutNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateTruncatedIndexName()) + .isEqualTo("table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); final ForeignKey severalColumnsWithNulls = severalColumnsWithNulls(); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032_without_nulls") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).build()).generateTruncatedIndexName()) + .isEqualTo("table_with_very_very_very_long_name_n1959284032_without_nulls") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); assertThat(PgIdentifierNameGenerator.of(severalColumnsWithNulls, - GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateTruncatedIndexName()) - .isEqualTo("table_with_very_very_very_long_name_n1959284032") - .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); + GeneratingOptions.builder().withIdxPosition(IdxPosition.NONE).includeNulls().build()).generateTruncatedIndexName()) + .isEqualTo("table_with_very_very_very_long_name_n1959284032") + .hasSizeLessThanOrEqualTo(MAX_IDENTIFIER_LENGTH); } @Test @@ -203,61 +203,61 @@ void fullAndTruncatedNamesShouldBeTheSameForShortCases() { final ForeignKey first = ForeignKey.ofNotNullColumn("t", "cn", "col"); PgIdentifierNameGenerator generator = PgIdentifierNameGenerator.of(first, GeneratingOptions.builder().build()); assertThat(generator.generateFullIndexName()) - .isEqualTo("t_col_idx") - .isEqualTo(generator.generateTruncatedIndexName()); + .isEqualTo("t_col_idx") + .isEqualTo(generator.generateTruncatedIndexName()); final ForeignKey second = ForeignKey.ofNotNullColumn("t_1234567890_1234567890_1234567890_1234567890", "cn", "col_123456789"); generator = PgIdentifierNameGenerator.of(second, GeneratingOptions.builder().build()); assertThat(generator.generateFullIndexName()) - .isEqualTo("t_1234567890_1234567890_1234567890_1234567890_col_123456789_idx") - .isEqualTo(generator.generateTruncatedIndexName()); + .isEqualTo("t_1234567890_1234567890_1234567890_1234567890_col_123456789_idx") + .isEqualTo(generator.generateTruncatedIndexName()); final ForeignKey third = ForeignKey.ofNotNullColumn("t_1234567890_1234567890_1234567890_1234567890", "cn", "col_12345678"); generator = PgIdentifierNameGenerator.of(third, GeneratingOptions.builder().build()); assertThat(generator.generateFullIndexName()) - .isEqualTo("t_1234567890_1234567890_1234567890_1234567890_col_12345678_idx") - .isEqualTo(generator.generateTruncatedIndexName()); + .isEqualTo("t_1234567890_1234567890_1234567890_1234567890_col_12345678_idx") + .isEqualTo(generator.generateTruncatedIndexName()); final ForeignKey nullableColumn = ForeignKey.ofNullableColumn("t2", "cn2", "col2"); generator = PgIdentifierNameGenerator.of(nullableColumn, GeneratingOptions.builder().build()); assertThat(generator.generateFullIndexName()) - .isEqualTo("t2_col2_without_nulls_idx") - .isEqualTo(generator.generateTruncatedIndexName()); + .isEqualTo("t2_col2_without_nulls_idx") + .isEqualTo(generator.generateTruncatedIndexName()); } @Nonnull static ForeignKey notNullColumnWithSchema() { return ForeignKey.ofNotNullColumn("schema_name_that_should_be_omitted.table_with_very_very_very_long_name", - "cn", "column_with_very_very_very_long_name"); + "cn", "column_with_very_very_very_long_name"); } @Nonnull static ForeignKey nullableColumnWithSchema() { return ForeignKey.ofNullableColumn("schema_name_that_should_be_omitted.table_with_very_very_very_long_name", - "cn", "column_with_very_very_very_long_name"); + "cn", "column_with_very_very_very_long_name"); } @Nonnull static ForeignKey notNullColumnWithZeroHash() { return ForeignKey.ofNotNullColumn("table_with_very_very_very_long_name_that_is_even_longer", - "cn", "corrugatestendentiousness"); + "cn", "corrugatestendentiousness"); } @Nonnull static ForeignKey severalColumnsWithoutNulls() { return ForeignKey.of("table_with_very_very_very_long_name", "cn", - List.of( - Column.ofNotNull("table_with_very_very_very_long_name", "column_1_with_very_long_name"), - Column.ofNotNull("table_with_very_very_very_long_name", "column_2_with_very_long_name") - )); + List.of( + Column.ofNotNull("table_with_very_very_very_long_name", "column_1_with_very_long_name"), + Column.ofNotNull("table_with_very_very_very_long_name", "column_2_with_very_long_name") + )); } @Nonnull static ForeignKey severalColumnsWithNulls() { return ForeignKey.of("table_with_very_very_very_long_name", "cn", - List.of( - Column.ofNotNull("table_with_very_very_very_long_name", "column_1_with_very_long_name"), - Column.ofNullable("table_with_very_very_very_long_name", "column_2_with_very_long_name") - )); + List.of( + Column.ofNotNull("table_with_very_very_very_long_name", "column_1_with_very_long_name"), + Column.ofNullable("table_with_very_very_very_long_name", "column_2_with_very_long_name") + )); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIndexOnForeignKeyGeneratorTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIndexOnForeignKeyGeneratorTest.java index 09216ee9..73b6d14e 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIndexOnForeignKeyGeneratorTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/PgIndexOnForeignKeyGeneratorTest.java @@ -27,72 +27,72 @@ class PgIndexOnForeignKeyGeneratorTest { void generateForSingleNotNullColumn() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(notNullColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + - "create index concurrently if not exists table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + - " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + + "create index concurrently if not exists table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + + " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); } @Test void generateForSingleNotNullColumnNormallyAndInSingleLine() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().normally().doNotBreakLines().build()); assertThat(generator.generate(notNullColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */ " + - "create index if not exists table_with_very_very_very_long_name_3202677_idx " + - "on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */ " + + "create index if not exists table_with_very_very_very_long_name_3202677_idx " + + "on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); } @Test void generateForSingleNotNullColumnWithUppercase() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().uppercaseForKeywords().build()); assertThat(generator.generate(notNullColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + - "CREATE INDEX CONCURRENTLY IF NOT EXISTS table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + - " ON schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + + "CREATE INDEX CONCURRENTLY IF NOT EXISTS table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + + " ON schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); } @Test void generateForSingleNullableColumn() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(nullableColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + - "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + - " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + - "where column_with_very_very_very_long_name is not null;"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + + "create index concurrently if not exists table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + + " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + + "where column_with_very_very_very_long_name is not null;"); } @Test void generateForSingleNullableColumnWithUppercase() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().uppercaseForKeywords().build()); assertThat(generator.generate(nullableColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + - "CREATE INDEX CONCURRENTLY IF NOT EXISTS table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + - " ON schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + - "WHERE column_with_very_very_very_long_name IS NOT NULL;"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_without_nulls_idx */" + System.lineSeparator() + + "CREATE INDEX CONCURRENTLY IF NOT EXISTS table_with_very_very_very_long_name_3202677_without_nulls_idx" + System.lineSeparator() + + " ON schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name) " + + "WHERE column_with_very_very_very_long_name IS NOT NULL;"); } @Test void generateForSingleNullableColumnWithNulls() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().includeNulls().build()); assertThat(generator.generate(nullableColumnWithSchema())) - .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + - "create index concurrently if not exists table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + - " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); + .isEqualTo("/* table_with_very_very_very_long_name_column_with_very_very_very_long_name_idx */" + System.lineSeparator() + + "create index concurrently if not exists table_with_very_very_very_long_name_3202677_idx" + System.lineSeparator() + + " on schema_name_that_should_be_omitted.table_with_very_very_very_long_name (column_with_very_very_very_long_name);"); } @Test void generateWithoutTruncation() { final PgIndexOnForeignKeyGenerator generator = new PgIndexOnForeignKeyGenerator(GeneratingOptions.builder().build()); assertThat(generator.generate(severalColumnsWithNulls())) - .isEqualTo("create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + - " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;"); + .isEqualTo("create index concurrently if not exists custom_table_custom_column_1_custom_column_22_without_nulls_idx" + System.lineSeparator() + + " on custom_table (custom_column_1, custom_column_22) where custom_column_22 is not null;"); } @Nonnull static ForeignKey severalColumnsWithNulls() { return ForeignKey.of("custom_table", "cn", - List.of( - Column.ofNotNull("custom_table", "custom_column_1"), - Column.ofNullable("custom_table", "custom_column_22") - )); + List.of( + Column.ofNotNull("custom_table", "custom_column_1"), + Column.ofNullable("custom_table", "custom_column_22") + )); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/NameUtilsTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/NameUtilsTest.java index 7df2594b..6ab8b536 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/NameUtilsTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/NameUtilsTest.java @@ -22,21 +22,21 @@ class NameUtilsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(NameUtils.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void getTableNameWithoutSchemaShouldWork() { final Table first = Table.of("t1", 1L); assertThat(NameUtils.getTableNameWithoutSchema(first)) - .isEqualTo("t1"); + .isEqualTo("t1"); final Table second = Table.of("public.t2", 1L); assertThat(NameUtils.getTableNameWithoutSchema(second)) - .isEqualTo("t2"); + .isEqualTo("t2"); final Table third = Table.of(".t3", 1L); assertThat(NameUtils.getTableNameWithoutSchema(third)) - .isEqualTo("t3"); + .isEqualTo("t3"); } } diff --git a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/StringUtilsTest.java b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/StringUtilsTest.java index c1807a14..b0aaf10c 100644 --- a/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/StringUtilsTest.java +++ b/pg-index-health-generator/src/test/java/io/github/mfvanek/pg/generator/utils/StringUtilsTest.java @@ -25,35 +25,35 @@ class StringUtilsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(StringUtils.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @SuppressWarnings("ConstantConditions") @Test void truncateShouldThrowExceptionOnInvalidArguments() { assertThatThrownBy(() -> StringUtils.truncate(null, 1)) - .isInstanceOf(NullPointerException.class) - .hasMessage("str cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("str cannot be null"); assertThatThrownBy(() -> StringUtils.truncate("", -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("maxWith cannot be negative"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxWith cannot be negative"); } @Test void truncationShouldBePerformed() { try (LogsCaptor logsCaptor = new LogsCaptor(StringUtils.class, Level.TRACE)) { assertThat(StringUtils.truncate(TARGET, 0)) - .isEmpty(); + .isEmpty(); assertThat(StringUtils.truncate(TARGET, 1)) - .isEqualTo("a"); + .isEqualTo("a"); assertThat(StringUtils.truncate(TARGET, 2)) - .isEqualTo("ab"); + .isEqualTo("ab"); assertThat(StringUtils.truncate(TARGET, 5)) - .isEqualTo("abcqw"); + .isEqualTo("abcqw"); assertThat(logsCaptor.getLogs()) - .hasSize(4); + .hasSize(4); } } @@ -61,14 +61,14 @@ void truncationShouldBePerformed() { void truncationShouldNotBePerformed() { try (LogsCaptor logsCaptor = new LogsCaptor(StringUtils.class, Level.TRACE)) { assertThat(StringUtils.truncate(TARGET, 6)) - .isEqualTo("abcqwe") - .isSameAs(TARGET); + .isEqualTo("abcqwe") + .isSameAs(TARGET); assertThat(StringUtils.truncate(TARGET, 7)) - .isEqualTo("abcqwe") - .isSameAs(TARGET); + .isEqualTo("abcqwe") + .isSameAs(TARGET); assertThat(logsCaptor.getLogs()) - .isEmpty(); + .isEmpty(); } } } diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/ConnectionCredentials.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/ConnectionCredentials.java index a059b7ca..ea9986d9 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/ConnectionCredentials.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/ConnectionCredentials.java @@ -88,8 +88,8 @@ public final boolean equals(final Object other) { final ConnectionCredentials that = (ConnectionCredentials) other; return Objects.equals(connectionUrls, that.connectionUrls) && - Objects.equals(userName, that.userName) && - Objects.equals(password, that.password); + Objects.equals(userName, that.userName) && + Objects.equals(password, that.password); } /** @@ -107,10 +107,10 @@ public final int hashCode() { @Override public String toString() { return ConnectionCredentials.class.getSimpleName() + '{' + - "connectionUrls=" + connectionUrls + - ", userName='" + userName + '\'' + - ", password='" + password + '\'' + - '}'; + "connectionUrls=" + connectionUrls + + ", userName='" + userName + '\'' + + ", password='" + password + '\'' + + '}'; } @Nonnull diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImpl.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImpl.java index 10b83748..cde62a1e 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImpl.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImpl.java @@ -37,7 +37,7 @@ public HighAvailabilityPgConnection of(@Nonnull final ConnectionCredentials cred Objects.requireNonNull(credentials, "credentials cannot be null"); final Map connectionsToAllHostsInCluster = new LinkedHashMap<>(); credentials.getConnectionUrls().forEach( - url -> addDataSourcesForAllHostsFromUrl(connectionsToAllHostsInCluster, url, credentials)); + url -> addDataSourcesForAllHostsFromUrl(connectionsToAllHostsInCluster, url, credentials)); final PgConnection connectionToPrimary = findConnectionToPrimary(connectionsToAllHostsInCluster); return HighAvailabilityPgConnectionImpl.of(connectionToPrimary, connectionsToAllHostsInCluster.values()); } @@ -48,7 +48,7 @@ private void addDataSourcesForAllHostsFromUrl(@Nonnull final Map> allHosts = PgUrlParser.extractNameWithPortAndUrlForEachHost(anyUrl); for (final Map.Entry host : allHosts) { connectionsToAllHostsInCluster.computeIfAbsent(host.getKey(), - h -> pgConnectionFactory.forUrl(host.getValue(), credentials.getUserName(), credentials.getPassword())); + h -> pgConnectionFactory.forUrl(host.getValue(), credentials.getUserName(), credentials.getPassword())); } } diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImpl.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImpl.java index f50f7b45..98d5f2f1 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImpl.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImpl.java @@ -26,7 +26,7 @@ public PgConnection forUrl(@Nonnull final String pgUrl, @Nonnull final String userName, @Nonnull final String password) { LOGGER.debug("Creating {} with pgUrl = {}, userName = {}, password = {}", - PgConnection.class.getSimpleName(), pgUrl, userName, "*****"); + PgConnection.class.getSimpleName(), pgUrl, userName, "*****"); final DataSource dataSource = dataSourceFor(pgUrl, userName, password); return PgConnectionImpl.of(dataSource, PgHostImpl.ofUrl(pgUrl)); } diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionImpl.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionImpl.java index 3b55cb24..07705bcd 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionImpl.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgConnectionImpl.java @@ -52,9 +52,8 @@ public PgHost getHost() { * Constructs a {@code PgConnection} object with given dataSource and host. * * @param dataSource a factory for connections to the physical database - * @param host information about database host + * @param host information about database host * @return {@code PgConnection} - * * @see DataSource * @see PgHost */ @@ -95,7 +94,7 @@ public final int hashCode() { @Override public String toString() { return PgConnectionImpl.class.getSimpleName() + '{' + - "host=" + host + - '}'; + "host=" + host + + '}'; } } diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgHostImpl.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgHostImpl.java index d1e9f3b2..e4fd2397 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgHostImpl.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgHostImpl.java @@ -124,10 +124,10 @@ public final int hashCode() { @Override public String toString() { return PgHostImpl.class.getSimpleName() + '{' + - "pgUrl='" + pgUrl + '\'' + - ", hostName=" + hostName + - ", port=" + port + - ", maybePrimary=" + maybePrimary + - '}'; + "pgUrl='" + pgUrl + '\'' + + ", hostName=" + hostName + + ", port=" + port + + ", maybePrimary=" + maybePrimary + + '}'; } } diff --git a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgUrlParser.java b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgUrlParser.java index acde9e95..a76b1456 100644 --- a/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgUrlParser.java +++ b/pg-index-health-jdbc-connection/src/main/java/io/github/mfvanek/pg/connection/PgUrlParser.java @@ -24,10 +24,10 @@ public final class PgUrlParser { public static final String URL_HEADER = "jdbc:postgresql://"; private static final String PG_URL = "pgUrl"; private static final Map DEFAULT_URL_PARAMETERS = Map.ofEntries( - Map.entry("targetServerType", "primary"), - Map.entry("hostRecheckSeconds", "2"), - Map.entry("connectTimeout", "1"), - Map.entry("socketTimeout", "600") + Map.entry("targetServerType", "primary"), + Map.entry("hostRecheckSeconds", "2"), + Map.entry("connectTimeout", "1"), + Map.entry("socketTimeout", "600") ); private PgUrlParser() { @@ -37,7 +37,7 @@ private PgUrlParser() { static boolean isReplicaUrl(@Nonnull final String pgUrl) { PgConnectionValidators.pgUrlNotBlankAndValid(pgUrl, PG_URL); return pgUrl.contains("targetServerType=slave") || - pgUrl.contains("targetServerType=secondary"); + pgUrl.contains("targetServerType=secondary"); } // For example, jdbc:postgresql://host-1:6432/db_name?param=value @@ -49,10 +49,10 @@ static List> extractNameWithPortAndUrlForEachHost(@Non final String dbNameWithParamsForReplica = convertToReplicaConnectionString(dbNameWithParams); final String allHostsWithPort = extractAllHostsWithPort(pgUrl); return Arrays.stream(allHostsWithPort.split(",")) - .distinct() - .sorted() - .map(h -> Map.entry(h, URL_HEADER + h + dbNameWithParamsForReplica)) - .collect(Collectors.toUnmodifiableList()); + .distinct() + .sorted() + .map(h -> Map.entry(h, URL_HEADER + h + dbNameWithParamsForReplica)) + .collect(Collectors.toUnmodifiableList()); } @Nonnull @@ -71,14 +71,14 @@ static List> extractHostNames(@Nonnull final String p PgConnectionValidators.pgUrlNotBlankAndValid(pgUrl, PG_URL); final String allHostsWithPort = extractAllHostsWithPort(pgUrl); return Arrays.stream(allHostsWithPort.split(",")) - .filter(Predicate.not(String::isBlank)) - .map(h -> { - final String[] hostToPort = h.split(":"); - return Map.entry(hostToPort[0], Integer.valueOf(hostToPort[1])); - }) - .distinct() - .sorted(Map.Entry.comparingByKey()) - .collect(Collectors.toUnmodifiableList()); + .filter(Predicate.not(String::isBlank)) + .map(h -> { + final String[] hostToPort = h.split(":"); + return Map.entry(hostToPort[0], Integer.valueOf(hostToPort[1])); + }) + .distinct() + .sorted(Map.Entry.comparingByKey()) + .collect(Collectors.toUnmodifiableList()); } @Nonnull @@ -127,10 +127,10 @@ public static String buildCommonUrlToPrimary(@Nonnull final Set pgUrls, @Nonnull final Map urlParameters) { final String additionalUrlParams = constructUrlParameters(urlParameters); return URL_HEADER + pgUrls.stream() - .map(PgUrlParser::extractAllHostsWithPort) - .sorted() - .collect(Collectors.joining(",")) + - extractDatabaseName(pgUrls) + additionalUrlParams; + .map(PgUrlParser::extractAllHostsWithPort) + .sorted() + .collect(Collectors.joining(",")) + + extractDatabaseName(pgUrls) + additionalUrlParams; } @Nonnull @@ -139,8 +139,8 @@ static String constructUrlParameters(@Nonnull final Map urlParam DEFAULT_URL_PARAMETERS.forEach(jointUrlParameters::putIfAbsent); final String additionalParameters = jointUrlParameters.entrySet().stream() - .map(e -> e.getKey() + "=" + e.getValue()) - .collect(Collectors.joining("&")); + .map(e -> e.getKey() + "=" + e.getValue()) + .collect(Collectors.joining("&")); return "?" + additionalParameters; } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/ConnectionCredentialsTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/ConnectionCredentialsTest.java index 072efab4..4b3b9038 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/ConnectionCredentialsTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/ConnectionCredentialsTest.java @@ -32,34 +32,34 @@ void getters() { assertThat(credentials.getUserName()).isEqualTo("user"); assertThat(credentials.getPassword()).isEqualTo("pswrd"); assertThat(credentials.getConnectionUrls()) - .hasSize(1) - .contains(DEFAULT_URL) - .isUnmodifiable(); + .hasSize(1) + .contains(DEFAULT_URL) + .isUnmodifiable(); } @Test void shouldDeduplicateUrls() { final ConnectionCredentials credentials = ConnectionCredentials.of(List.of(DEFAULT_URL, DEFAULT_URL, DEFAULT_URL), "user", "pswrd"); assertThat(credentials.getConnectionUrls()) - .hasSize(1) - .contains(DEFAULT_URL) - .isUnmodifiable(); + .hasSize(1) + .contains(DEFAULT_URL) + .isUnmodifiable(); } @Test void shouldCreateDefensiveCopyOfUrlsList() { final List urls = new ArrayList<>(List.of( - "jdbc:postgresql://localhost/first", - "jdbc:postgresql://localhost/second", - "jdbc:postgresql://localhost/third")); + "jdbc:postgresql://localhost/first", + "jdbc:postgresql://localhost/second", + "jdbc:postgresql://localhost/third")); final ConnectionCredentials credentials = ConnectionCredentials.of(urls, "user", "password"); urls.add("jdbc:postgresql://localhost/fourth"); assertThat(credentials.getConnectionUrls()) - .hasSize(3) - .doesNotContain("jdbc:postgresql://localhost/fourth") - .isUnmodifiable(); + .hasSize(3) + .doesNotContain("jdbc:postgresql://localhost/fourth") + .isUnmodifiable(); } @SuppressWarnings("ConstantConditions") @@ -76,94 +76,94 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(ConnectionCredentials.ofUrl(DEFAULT_URL, "u", "p")) - .isEqualTo(first); + .isEqualTo(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); assertThat(fourth) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(ConnectionCredentials.class) - .verify(); + .verify(); } @Test void testToString() { ConnectionCredentials credentials = ConnectionCredentials.ofUrl(DEFAULT_URL, "user", "pswrd"); assertThat(credentials) - .hasToString("ConnectionCredentials{connectionUrls=[jdbc:postgresql://localhost/postgres], userName='user', password='pswrd'}"); + .hasToString("ConnectionCredentials{connectionUrls=[jdbc:postgresql://localhost/postgres], userName='user', password='pswrd'}"); credentials = ConnectionCredentials.of(List.of(DEFAULT_URL, "jdbc:postgresql://host1:5432/postgres"), "user", "pswrd"); assertThat(credentials) - .hasToString("ConnectionCredentials{connectionUrls=[jdbc:postgresql://host1:5432/postgres, jdbc:postgresql://localhost/postgres], userName='user', password='pswrd'}"); + .hasToString("ConnectionCredentials{connectionUrls=[jdbc:postgresql://host1:5432/postgres, jdbc:postgresql://localhost/postgres], userName='user', password='pswrd'}"); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> ConnectionCredentials.ofUrl(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("writeUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("writeUrl cannot be null"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("userName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("userName cannot be null"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, "u", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("password cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("password cannot be null"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl("", "u", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("writeUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("writeUrl cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(" ", "u", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("writeUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("writeUrl cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl("url", "u", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("writeUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("writeUrl has invalid format"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, "", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("userName cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("userName cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, " ", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("userName cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("userName cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, "u", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("password cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("password cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.ofUrl(DEFAULT_URL, "u", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("password cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("password cannot be blank or empty"); assertThatThrownBy(() -> ConnectionCredentials.of(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("connectionUrls cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("connectionUrls cannot be null"); final Set defaultUrls = Set.of(DEFAULT_URL); assertThatThrownBy(() -> ConnectionCredentials.of(defaultUrls, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("userName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("userName cannot be null"); assertThatThrownBy(() -> ConnectionCredentials.of(defaultUrls, "u", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("password cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("password cannot be null"); final List emptyList = List.of(); assertThatThrownBy(() -> ConnectionCredentials.of(emptyList, "u", "p")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("connectionUrls have to contain at least one url"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("connectionUrls have to contain at least one url"); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImplTest.java index bc75d991..dfddd6d0 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionFactoryImplTest.java @@ -29,7 +29,7 @@ class HighAvailabilityPgConnectionFactoryImplTest { private final PrimaryHostDeterminer primaryHostDeterminer = Mockito.mock(PrimaryHostDeterminer.class); private final HighAvailabilityPgConnectionFactory connectionFactory = - new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), primaryHostDeterminer); + new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), primaryHostDeterminer); @Test void onlyWriteUrl() { @@ -38,12 +38,12 @@ void onlyWriteUrl() { return "host-1".equals(connection.getHost().getName()); }).when(primaryHostDeterminer).isPrimary(any(PgConnection.class)); final HighAvailabilityPgConnection haPgConnection = connectionFactory.ofUrl( - "jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", "postgres", "postgres"); + "jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", "postgres", "postgres"); assertThat(haPgConnection) - .isNotNull() - .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) - .hasSize(2) - .isUnmodifiable()); + .isNotNull() + .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) + .hasSize(2) + .isUnmodifiable()); checkPrimary(haPgConnection); } @@ -54,14 +54,14 @@ void writeAndReadUrl() { return "host-2".equals(connection.getHost().getName()); }).when(primaryHostDeterminer).isPrimary(any(PgConnection.class)); final HighAvailabilityPgConnection haPgConnection = connectionFactory.ofUrls( - List.of("jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", - "jdbc:postgresql://host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require"), - "postgres", "postgres"); + List.of("jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", + "jdbc:postgresql://host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require"), + "postgres", "postgres"); assertThat(haPgConnection) - .isNotNull() - .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) - .hasSize(4) - .isUnmodifiable()); + .isNotNull() + .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) + .hasSize(4) + .isUnmodifiable()); checkPrimary(haPgConnection); } @@ -72,15 +72,15 @@ void asyncReplica() { return "host-2".equals(connection.getHost().getName()); }).when(primaryHostDeterminer).isPrimary(any(PgConnection.class)); final ConnectionCredentials credentials = ConnectionCredentials.of(List.of( - "jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", - "jdbc:postgresql://host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require", - "jdbc:postgresql://host-5:6432/db_name?ssl=true&sslmode=require"), "postgres", "postgres"); + "jdbc:postgresql://host-1:6432,host-2:6432/db_name?ssl=true&sslmode=require", + "jdbc:postgresql://host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require", + "jdbc:postgresql://host-5:6432/db_name?ssl=true&sslmode=require"), "postgres", "postgres"); final HighAvailabilityPgConnection haPgConnection = connectionFactory.of(credentials); assertThat(haPgConnection) - .isNotNull() - .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) - .hasSize(5) - .isUnmodifiable()); + .isNotNull() + .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) + .hasSize(5) + .isUnmodifiable()); checkPrimary(haPgConnection); } @@ -88,59 +88,59 @@ void asyncReplica() { @Test void withInvalidArguments() { assertThatThrownBy(() -> connectionFactory.of(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("credentials cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("credentials cannot be null"); assertThatThrownBy(() -> connectionFactory.ofUrl(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("writeUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("writeUrl cannot be null"); assertThatThrownBy(() -> connectionFactory.ofUrl("jdbc:postgresql://host-1:6432/db_name", null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("userName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("userName cannot be null"); assertThatThrownBy(() -> connectionFactory.ofUrl("jdbc:postgresql://host-1:6432/db_name", "u", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("password cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("password cannot be null"); assertThatThrownBy(() -> connectionFactory.ofUrls(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("connectionUrls cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("connectionUrls cannot be null"); final Set urls = Set.of("jdbc:postgresql://host-1:6432/db_name"); assertThatThrownBy(() -> connectionFactory.ofUrls(urls, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("userName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("userName cannot be null"); assertThatThrownBy(() -> connectionFactory.ofUrls(urls, "u", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("password cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("password cannot be null"); } @Test void shouldFailWhenPrimaryHosNotFound() { Mockito.when(primaryHostDeterminer.isPrimary(any(PgConnection.class))).thenReturn(Boolean.FALSE); assertThatThrownBy(() -> connectionFactory.ofUrl("jdbc:postgresql://host-1:6432,host-2:6432/db_name", "postgres", "postgres")) - .isInstanceOf(NoSuchElementException.class) - .hasMessageStartingWith("Connection to primary host not found in "); + .isInstanceOf(NoSuchElementException.class) + .hasMessageStartingWith("Connection to primary host not found in "); } @Test void shouldNotFailWhenSplitBrainOrMultyMasterConfiguration() { Mockito.when(primaryHostDeterminer.isPrimary(any(PgConnection.class))).thenReturn(Boolean.TRUE); final HighAvailabilityPgConnection haPgConnection = connectionFactory.ofUrl( - "jdbc:postgresql://host-D:6432,host-A:6432/db_name", "postgres", "postgres"); + "jdbc:postgresql://host-D:6432,host-A:6432/db_name", "postgres", "postgres"); assertThat(haPgConnection) - .isNotNull() - .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) - .hasSize(2) - .isUnmodifiable()); + .isNotNull() + .satisfies(c -> assertThat(c.getConnectionsToAllHostsInCluster()) + .hasSize(2) + .isUnmodifiable()); assertThat(haPgConnection.getConnectionToPrimary()) - .isNotNull() - .satisfies(c -> assertThat(c.getHost().getName()).isEqualTo("host-A")); + .isNotNull() + .satisfies(c -> assertThat(c.getHost().getName()).isEqualTo("host-A")); } @SuppressWarnings("DirectInvocationOnMock") private void checkPrimary(@Nonnull final HighAvailabilityPgConnection haPgConnection) { assertThat(haPgConnection.getConnectionToPrimary()) - .isNotNull() - .satisfies(c -> verify(primaryHostDeterminer).isPrimary(c)); + .isNotNull() + .satisfies(c -> verify(primaryHostDeterminer).isPrimary(c)); for (final PgConnection connection : haPgConnection.getConnectionsToAllHostsInCluster()) { if (primaryHostDeterminer.isPrimary(connection)) { assertThat(connection).isSameAs(haPgConnection.getConnectionToPrimary()); diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionImplTest.java index 2cd0cec0..c3208ed8 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionImplTest.java @@ -26,10 +26,10 @@ void ofPrimary() { final HighAvailabilityPgConnection haPgConnection = HighAvailabilityPgConnectionImpl.of(getPgConnection()); assertThat(haPgConnection).isNotNull(); assertThat(haPgConnection.getConnectionsToAllHostsInCluster()) - .isNotNull() - .hasSize(1) - .containsExactly(getPgConnection()) - .isUnmodifiable(); + .isNotNull() + .hasSize(1) + .containsExactly(getPgConnection()) + .isUnmodifiable(); assertThat(haPgConnection.getConnectionsToAllHostsInCluster().iterator().next()).isEqualTo(haPgConnection.getConnectionToPrimary()); } @@ -38,10 +38,10 @@ void shouldBeUnmodifiable() { final HighAvailabilityPgConnection haPgConnection = HighAvailabilityPgConnectionImpl.of(getPgConnection()); assertThat(haPgConnection).isNotNull(); assertThat(haPgConnection.getConnectionsToAllHostsInCluster()) - .isNotNull() - .hasSize(1) - .containsExactly(getPgConnection()) - .isUnmodifiable(); + .isNotNull() + .hasSize(1) + .containsExactly(getPgConnection()) + .isUnmodifiable(); } @Test @@ -51,10 +51,10 @@ void withReplicas() { final HighAvailabilityPgConnection haPgConnection = HighAvailabilityPgConnectionImpl.of(primary, List.of(primary, replica)); assertThat(haPgConnection).isNotNull(); assertThat(haPgConnection.getConnectionsToAllHostsInCluster()) - .isNotNull() - .hasSize(2) - .containsExactlyInAnyOrder(primary, replica) - .isUnmodifiable(); + .isNotNull() + .hasSize(2) + .containsExactlyInAnyOrder(primary, replica) + .isUnmodifiable(); } @Test @@ -63,8 +63,8 @@ void shouldContainsConnectionToPrimary() { final PgConnection replica = getConnectionToReplica(); final List connectionsOnlyToReplicas = List.of(replica); assertThatThrownBy(() -> HighAvailabilityPgConnectionImpl.of(primary, connectionsOnlyToReplicas)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("connectionsToAllHostsInCluster have to contain a connection to the primary"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("connectionsToAllHostsInCluster have to contain a connection to the primary"); } @Nonnull diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionUnitTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionUnitTest.java index c11b03c9..516d4215 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionUnitTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/HighAvailabilityPgConnectionUnitTest.java @@ -44,35 +44,35 @@ void cachedPrimaryWillBeReturnedIfThereIsNoPrimaryUpdate() throws SQLException { final HighAvailabilityPgConnection haPgConnection = HighAvailabilityPgConnectionImpl.of(pgConnections.get(0), pgConnections, 400L); assertThat(haPgConnection.getConnectionToPrimary()) - .as("First connection is primary") - .isEqualTo(pgConnections.get(0)) - .as("Second connection is not primary") - .isNotEqualTo(pgConnections.get(1)); + .as("First connection is primary") + .isEqualTo(pgConnections.get(0)) + .as("Second connection is not primary") + .isNotEqualTo(pgConnections.get(1)); Awaitility - .await() - .atMost(Duration.ofMillis(1000L)) - .pollDelay(Duration.ofMillis(500L)) - .until(() -> Boolean.TRUE); + .await() + .atMost(Duration.ofMillis(1000L)) + .pollDelay(Duration.ofMillis(500L)) + .until(() -> Boolean.TRUE); Mockito.when(firstConnectionMocks.resultSet.getBoolean(1)).thenReturn(Boolean.FALSE); Awaitility - .await() - .atMost(Duration.ofMillis(1000L)) - .pollDelay(Duration.ofMillis(500L)) - .until(() -> Boolean.TRUE); + .await() + .atMost(Duration.ofMillis(1000L)) + .pollDelay(Duration.ofMillis(500L)) + .until(() -> Boolean.TRUE); assertThat(haPgConnection.getConnectionToPrimary()) - .as("Without new primary first connection considered as primary") - .isEqualTo(pgConnections.get(0)); + .as("Without new primary first connection considered as primary") + .isEqualTo(pgConnections.get(0)); Mockito.when(secondConnectionMocks.resultSet.getBoolean(1)).thenReturn(Boolean.TRUE); Awaitility - .await() - .atMost(Duration.ofMillis(1000L)) - .pollDelay(Duration.ofMillis(500L)) - .until(() -> Boolean.TRUE); + .await() + .atMost(Duration.ofMillis(1000L)) + .pollDelay(Duration.ofMillis(500L)) + .until(() -> Boolean.TRUE); assertThat(haPgConnection.getConnectionToPrimary()) - .as("Second connection become new primary") - .isEqualTo(pgConnections.get(1)); + .as("Second connection become new primary") + .isEqualTo(pgConnections.get(1)); } @Test @@ -84,9 +84,9 @@ void primaryUpdaterExpectedToExecuteTenTimes() throws SQLException { HighAvailabilityPgConnectionImpl.of(pgConnections.get(0), pgConnections, 50L); Awaitility - .await() - .pollDelay(Duration.ofMillis(650)) // start delay compensation + OS dependent behavior - .until(() -> Boolean.TRUE); + .await() + .pollDelay(Duration.ofMillis(650)) // start delay compensation + OS dependent behavior + .until(() -> Boolean.TRUE); // Due to interleaving method may be called more than 10 times but not less than 10 Mockito.verify(firstConnectionMocks.dataSource, Mockito.atLeast(10)).getConnection(); @@ -104,13 +104,13 @@ void updateConnectionToPrimaryShouldCatchAndLogExceptions() throws SQLException HighAvailabilityPgConnectionImpl.of(pgConnections.get(0), pgConnections, 10L); Awaitility - .await() - .pollDelay(Duration.ofMillis(120)) // start delay compensation + OS dependent behavior - .until(() -> Boolean.TRUE); + .await() + .pollDelay(Duration.ofMillis(120)) // start delay compensation + OS dependent behavior + .until(() -> Boolean.TRUE); assertThat(logsCaptor.getLogs()) - .hasSizeGreaterThanOrEqualTo(10) - .allMatch(l -> l.getMessage().contains("Exception during primary detection for host")); + .hasSizeGreaterThanOrEqualTo(10) + .allMatch(l -> l.getMessage().contains("Exception during primary detection for host")); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImplTest.java index ab4dfbb3..6aa761f1 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionFactoryImplTest.java @@ -23,10 +23,10 @@ class PgConnectionFactoryImplTest { @Test void forUrlTest() { final PgConnection pgConnection = pgConnectionFactory.forUrl( - "jdbc:postgresql://localhost:5432/postgres?prepareThreshold=0&preparedStatementCacheQueries=0", "postgres", "postgres"); + "jdbc:postgresql://localhost:5432/postgres?prepareThreshold=0&preparedStatementCacheQueries=0", "postgres", "postgres"); assertThat(pgConnection) - .isNotNull() - .extracting(c -> c.getHost().getPgUrl()) - .isEqualTo("jdbc:postgresql://localhost:5432/postgres?prepareThreshold=0&preparedStatementCacheQueries=0"); + .isNotNull() + .extracting(c -> c.getHost().getPgUrl()) + .isEqualTo("jdbc:postgresql://localhost:5432/postgres?prepareThreshold=0&preparedStatementCacheQueries=0"); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionHelperTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionHelperTest.java index cca0e160..6a67c79a 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionHelperTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionHelperTest.java @@ -27,26 +27,26 @@ class PgConnectionHelperTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(PgConnectionHelper.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void createDataSource() { final DataSource dataSource = PgConnectionHelper.createDataSource(getWriteUrl(), "postgres_user", "postgres_pwd"); assertThat(dataSource) - .isNotNull() - .isInstanceOfSatisfying(BasicDataSource.class, ds -> { - assertThat(ds.getDriverClassName()).isEqualTo("org.postgresql.Driver"); - assertThat(ds.getUsername()).isEqualTo("postgres_user"); - assertThat(ds.getPassword()).isEqualTo("postgres_pwd"); - assertThat(ds.getValidationQuery()).isEqualTo("select 1"); - assertThat(ds.getMaxTotal()).isEqualTo(1); - assertThat(ds.getMaxIdle()).isEqualTo(1); - assertThat(ds.getMaxOpenPreparedStatements()).isEqualTo(1); - assertThat(ds.getUrl()) - .isNotBlank() - .startsWith("jdbc:postgresql://localhost"); - }); + .isNotNull() + .isInstanceOfSatisfying(BasicDataSource.class, ds -> { + assertThat(ds.getDriverClassName()).isEqualTo("org.postgresql.Driver"); + assertThat(ds.getUsername()).isEqualTo("postgres_user"); + assertThat(ds.getPassword()).isEqualTo("postgres_pwd"); + assertThat(ds.getValidationQuery()).isEqualTo("select 1"); + assertThat(ds.getMaxTotal()).isEqualTo(1); + assertThat(ds.getMaxIdle()).isEqualTo(1); + assertThat(ds.getMaxOpenPreparedStatements()).isEqualTo(1); + assertThat(ds.getUrl()) + .isNotBlank() + .startsWith("jdbc:postgresql://localhost"); + }); } @Nonnull diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionImplTest.java index e83eeadf..2f4b410a 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionImplTest.java @@ -26,16 +26,16 @@ class PgConnectionImplTest extends DatabaseAwareTestBase { void getPrimaryDataSource() { final PgConnection connection = getPgConnection(); assertThat(connection.getDataSource()) - .isNotNull(); + .isNotNull(); assertThat(connection.getHost()) - .isEqualTo(getHost()); + .isEqualTo(getHost()); } @Test void isPrimaryForAnyHost() { final int port = getPort(); final String readUrl = String.format("jdbc:postgresql://localhost:%d/postgres?" + - "prepareThreshold=0&preparedStatementCacheQueries=0&targetServerType=preferSecondary", port); + "prepareThreshold=0&preparedStatementCacheQueries=0&targetServerType=preferSecondary", port); final PgConnection any = PgConnectionImpl.of(getDataSource(), PgHostImpl.ofUrl(readUrl)); assertThat(any).isNotNull(); } @@ -45,8 +45,8 @@ void isPrimaryForAnyHost() { void withInvalidArguments() { final DataSource dataSource = getDataSource(); assertThatThrownBy(() -> PgConnectionImpl.of(dataSource, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("host cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("host cannot be null"); } @SuppressWarnings("ConstantConditions") @@ -63,18 +63,18 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); // another implementation of PgConnection final PgConnection connectionMock = Mockito.mock(PgConnection.class); @@ -86,15 +86,15 @@ void equalsAndHashCode() { @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(PgConnectionImpl.class) - .withIgnoredFields("dataSource") - .verify(); + .withIgnoredFields("dataSource") + .verify(); } @Test void toStringTest() { final PgConnection connection = PgConnectionImpl.of(getDataSource(), PgHostImpl.ofUrl("jdbc:postgresql://primary:5432")); assertThat(connection) - .hasToString("PgConnectionImpl{host=PgHostImpl{pgUrl='jdbc:postgresql://primary:5432', hostName=primary, port=5432, maybePrimary=true}}"); + .hasToString("PgConnectionImpl{host=PgHostImpl{pgUrl='jdbc:postgresql://primary:5432', hostName=primary, port=5432, maybePrimary=true}}"); } @Test diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionValidatorsTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionValidatorsTest.java index 24180180..c52a89f7 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionValidatorsTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgConnectionValidatorsTest.java @@ -25,44 +25,44 @@ class PgConnectionValidatorsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(PgConnectionValidators.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void connectionUrlsNotEmptyAndValid() { final List urls = List.of("jdbc:postgresql:/", "jdb:postgresl://"); assertThatThrownBy(() -> PgConnectionValidators.connectionUrlsNotEmptyAndValid(urls)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("connectionUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("connectionUrl has invalid format"); } @Test void portInAcceptableRange() { assertThatThrownBy(() -> PgConnectionValidators.portInAcceptableRange(1023)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("the port number must be in the range from 1024 to 65535"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("the port number must be in the range from 1024 to 65535"); assertThatThrownBy(() -> PgConnectionValidators.portInAcceptableRange(65_536)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("the port number must be in the range from 1024 to 65535"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("the port number must be in the range from 1024 to 65535"); assertThat(PgConnectionValidators.portInAcceptableRange(1024)) - .isEqualTo(1024); + .isEqualTo(1024); assertThat(PgConnectionValidators.portInAcceptableRange(65_535)) - .isEqualTo(65_535); + .isEqualTo(65_535); } @SuppressWarnings("DataFlowIssue") @Test void hostNameNotBlank() { assertThatThrownBy(() -> PgConnectionValidators.hostNameNotBlank(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("hostName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("hostName cannot be null"); assertThatThrownBy(() -> PgConnectionValidators.hostNameNotBlank("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("hostName cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("hostName cannot be blank or empty"); assertThatThrownBy(() -> PgConnectionValidators.hostNameNotBlank(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("hostName cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("hostName cannot be blank or empty"); assertThat(PgConnectionValidators.hostNameNotBlank("localhost")) - .isEqualTo("localhost"); + .isEqualTo("localhost"); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgHostImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgHostImplTest.java index ce69b2d9..5edbaec1 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgHostImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgHostImplTest.java @@ -24,15 +24,15 @@ class PgHostImplTest { @Test void ofUrl() { assertThatThrownBy(() -> PgHostImpl.ofUrl("jdbc:postgresql://host-4:6432,host-2:6432,host-3:6432,host-1:6432/db_name?ssl=true&sslmode=require")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl couldn't contain multiple hosts"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl couldn't contain multiple hosts"); } @Test void ofUrlWithMultipleHosts() { assertThatThrownBy(() -> PgHostImpl.ofUrl("jdbc:postgresql://host-4:6432,host-2:6432,host-3:6432,host-1:6432/db_name?ssl=true&sslmode=require")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl couldn't contain multiple hosts"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl couldn't contain multiple hosts"); } @Test @@ -50,23 +50,23 @@ void ofSecondaryUrl() { @Test void withInvalidValues() { assertThatThrownBy(() -> PgHostImpl.ofUrl(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgUrl cannot be null"); assertThatThrownBy(() -> PgHostImpl.ofUrl("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl cannot be blank or empty"); assertThatThrownBy(() -> PgHostImpl.ofUrl("host")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl has invalid format"); assertThatThrownBy(() -> PgHostImpl.ofUrl("jdbc:postgresql://:6432")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("hostName cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("hostName cannot be blank or empty"); assertThatThrownBy(() -> PgHostImpl.ofUrl("jdbc:postgresql://localhost:1023")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("the port number must be in the range from 1024 to 65535"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("the port number must be in the range from 1024 to 65535"); assertThatThrownBy(() -> PgHostImpl.ofUrl("jdbc:postgresql://localhost:65536")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("the port number must be in the range from 1024 to 65535"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("the port number must be in the range from 1024 to 65535"); } @Test @@ -81,7 +81,7 @@ void ofUncompletedUrl() { @Test void toStringTest() { assertThat(PgHostImpl.ofUrl("jdbc:postgresql://primary:5432")) - .hasToString("PgHostImpl{pgUrl='jdbc:postgresql://primary:5432', hostName=primary, port=5432, maybePrimary=true}"); + .hasToString("PgHostImpl{pgUrl='jdbc:postgresql://primary:5432', hostName=primary, port=5432, maybePrimary=true}"); } @SuppressWarnings("ConstantConditions") @@ -97,18 +97,18 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); // another implementation of PgHost final PgHost pgHostMock = Mockito.mock(PgHost.class); @@ -116,19 +116,19 @@ void equalsAndHashCode() { Mockito.when(pgHostMock.getName()).thenReturn("primary"); Mockito.when(pgHostMock.getPgUrl()).thenReturn("jdbc:postgresql://primary:5432"); assertThat(pgHostMock) - .isNotEqualTo(second) - .satisfies(h -> { - assertThat(h.canBePrimary()).isEqualTo(second.canBePrimary()); - assertThat(h.getName()).isEqualTo(second.getName()); - assertThat(h.getPgUrl()).isEqualTo(second.getPgUrl()); - }); + .isNotEqualTo(second) + .satisfies(h -> { + assertThat(h.canBePrimary()).isEqualTo(second.canBePrimary()); + assertThat(h.getName()).isEqualTo(second.getName()); + assertThat(h.getPgUrl()).isEqualTo(second.getPgUrl()); + }); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(PgHostImpl.class) - .withIgnoredFields("pgUrl", "maybePrimary") - .verify(); + .withIgnoredFields("pgUrl", "maybePrimary") + .verify(); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgUrlParserTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgUrlParserTest.java index 84389a6d..3e5e2e20 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgUrlParserTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PgUrlParserTest.java @@ -26,115 +26,115 @@ class PgUrlParserTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(PgUrlParser.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void extractNamesAndUrlsForEachHost() { assertThat(PgUrlParser.extractNameWithPortAndUrlForEachHost( - "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require")) - .hasSize(4) - .containsExactlyInAnyOrder( - Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?ssl=true&sslmode=require"), - Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?ssl=true&sslmode=require"), - Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?ssl=true&sslmode=require"), - Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?ssl=true&sslmode=require")) - .isUnmodifiable(); + "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require")) + .hasSize(4) + .containsExactlyInAnyOrder( + Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?ssl=true&sslmode=require"), + Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?ssl=true&sslmode=require"), + Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?ssl=true&sslmode=require"), + Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?ssl=true&sslmode=require")) + .isUnmodifiable(); } @SuppressWarnings("ConstantConditions") @Test void extractNamesAndUrlsForEachHostWithInvalidUrl() { assertThatThrownBy(() -> PgUrlParser.extractNameWithPortAndUrlForEachHost(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgUrl cannot be null"); assertThatThrownBy(() -> PgUrlParser.extractNameWithPortAndUrlForEachHost("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl cannot be blank or empty"); assertThatThrownBy(() -> PgUrlParser.extractNameWithPortAndUrlForEachHost("host-name:5432")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl has invalid format"); } @Test void extractNamesAndUrlsForDeprecatedMaster() { assertThat(PgUrlParser.extractNameWithPortAndUrlForEachHost( - "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?targetServerType=master&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) - .hasSize(4) - .containsExactlyInAnyOrder( - Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) - .isUnmodifiable(); + "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?targetServerType=master&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) + .hasSize(4) + .containsExactlyInAnyOrder( + Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) + .isUnmodifiable(); } @Test void extractNamesAndUrlsForPrimary() { assertThat(PgUrlParser.extractNameWithPortAndUrlForEachHost( - "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?targetServerType=primary&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) - .hasSize(4) - .containsExactlyInAnyOrder( - Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), - Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) - .isUnmodifiable(); + "jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?targetServerType=primary&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) + .hasSize(4) + .containsExactlyInAnyOrder( + Map.entry("host-1:6432", "jdbc:postgresql://host-1:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-2:6432", "jdbc:postgresql://host-2:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-3:6432", "jdbc:postgresql://host-3:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require"), + Map.entry("host-4:6432", "jdbc:postgresql://host-4:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")) + .isUnmodifiable(); } @Test void extractHostNames() { assertThat(PgUrlParser.extractHostNames("jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432/db_name?ssl=true&sslmode=require")) - .hasSize(4) - .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432), Map.entry("host-3", 6432), Map.entry("host-4", 6432)) - .isUnmodifiable(); + .hasSize(4) + .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432), Map.entry("host-3", 6432), Map.entry("host-4", 6432)) + .isUnmodifiable(); } @Test void extractHostNamesWithIncompleteUrl() { assertThat(PgUrlParser.extractHostNames("jdbc:postgresql://host-1:6432,host-2:6432,host-3:6432,host-4:6432")) - .hasSize(4) - .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432), Map.entry("host-3", 6432), Map.entry("host-4", 6432)) - .isUnmodifiable(); + .hasSize(4) + .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432), Map.entry("host-3", 6432), Map.entry("host-4", 6432)) + .isUnmodifiable(); } @Test void extractHostNamesWithDuplicatesInUrl() { assertThat(PgUrlParser.extractHostNames("jdbc:postgresql://host-1:6432,host-1:6432,host-1:6432,host-2:6432")) - .hasSize(2) - .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432)) - .isUnmodifiable(); + .hasSize(2) + .containsExactly(Map.entry("host-1", 6432), Map.entry("host-2", 6432)) + .isUnmodifiable(); } @Test void extractHostNamesWithEmptyUrl() { assertThat(PgUrlParser.extractHostNames("jdbc:postgresql://")) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); } @Test void extractHostNamesWithBadUrl() { assertThat(PgUrlParser.extractHostNames("jdbc:postgresql:///")) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); } @SuppressWarnings("ConstantConditions") @Test void extractHostNamesWithInvalidUrl() { assertThatThrownBy(() -> PgUrlParser.extractHostNames(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgUrl cannot be null"); assertThatThrownBy(() -> PgUrlParser.extractHostNames("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl cannot be blank or empty"); assertThatThrownBy(() -> PgUrlParser.extractHostNames("host-name:5432")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl has invalid format"); assertThatThrownBy(() -> PgUrlParser.extractHostNames("jdbc:postgresql:/")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl has invalid format"); } @Test @@ -143,9 +143,9 @@ void isReplicaUrl() { assertThat(PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=master&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); assertThat(PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=any&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); assertThat( - PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=preferSlave&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); + PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=preferSlave&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); assertThat(PgUrlParser.isReplicaUrl( - "jdbc:postgresql://host-1:6432/db_name?targetServerType=preferSecondary&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); + "jdbc:postgresql://host-1:6432/db_name?targetServerType=preferSecondary&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isFalse(); assertThat(PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=slave&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isTrue(); assertThat(PgUrlParser.isReplicaUrl("jdbc:postgresql://host-1:6432/db_name?targetServerType=secondary&ssl=true&prepareThreshold=0&preparedStatementCacheQueries=0&sslmode=require")).isTrue(); } @@ -154,71 +154,71 @@ void isReplicaUrl() { @Test void isReplicaUrlWithInvalidUrl() { assertThatThrownBy(() -> PgUrlParser.isReplicaUrl(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgUrl cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgUrl cannot be null"); assertThatThrownBy(() -> PgUrlParser.isReplicaUrl("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl cannot be blank or empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl cannot be blank or empty"); assertThatThrownBy(() -> PgUrlParser.isReplicaUrl("host-name:5432")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrl has invalid format"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrl has invalid format"); } @Test void extractDatabaseNameShouldWork() { assertThat(PgUrlParser.extractDatabaseName(Set.of("jdbc:postgresql://host:5432/db1?param=1"))) - .isEqualTo("/db1"); + .isEqualTo("/db1"); assertThat(PgUrlParser.extractDatabaseName(Set.of("jdbc:postgresql://host:5432/db2?"))) - .isEqualTo("/db2"); + .isEqualTo("/db2"); assertThat(PgUrlParser.extractDatabaseName(Set.of("jdbc:postgresql://host:5432/db3"))) - .isEqualTo("/db3"); + .isEqualTo("/db3"); final Set pgUrls = Set.of("jdbc:postgresql://host:5432/?"); assertThatThrownBy(() -> PgUrlParser.extractDatabaseName(pgUrls)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgUrls contains invalid connection string jdbc:postgresql://host:5432/?"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgUrls contains invalid connection string jdbc:postgresql://host:5432/?"); } @Test void constructUrlParametersShouldAddDefaultValues() { assertThat(PgUrlParser.constructUrlParameters(Map.of())) - .isEqualTo("?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); + .isEqualTo("?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); assertThat(PgUrlParser.constructUrlParameters( - Map.ofEntries( - Map.entry("connectTimeout", "10")))) - .isEqualTo("?connectTimeout=10&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); + Map.ofEntries( + Map.entry("connectTimeout", "10")))) + .isEqualTo("?connectTimeout=10&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); assertThat(PgUrlParser.constructUrlParameters( - Map.ofEntries( - Map.entry("targetServerType", "any"), - Map.entry("readOnly", "true")))) - .isEqualTo("?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=any"); + Map.ofEntries( + Map.entry("targetServerType", "any"), + Map.entry("readOnly", "true")))) + .isEqualTo("?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=any"); } @Test void buildCommonUrlToPrimaryWithTwoUrls() { assertThat(PgUrlParser.buildCommonUrlToPrimary("jdbc:postgresql://host:5432/db1", "jdbc:postgresql://host:6432/db1")) - .isEqualTo("jdbc:postgresql://host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); + .isEqualTo("jdbc:postgresql://host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); assertThat(PgUrlParser.buildCommonUrlToPrimary("jdbc:postgresql://host:5432/db1", "jdbc:postgresql://host:6432/db1", - Map.ofEntries( - Map.entry("targetServerType", "secondary"), - Map.entry("readOnly", "true")))) - .isEqualTo("jdbc:postgresql://host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=secondary"); + Map.ofEntries( + Map.entry("targetServerType", "secondary"), + Map.entry("readOnly", "true")))) + .isEqualTo("jdbc:postgresql://host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=secondary"); } @Test void buildCommonUrlToPrimaryWithSeveralUrls() { assertThat(PgUrlParser.buildCommonUrlToPrimary(Set.of("jdbc:postgresql://host2:5432/db1", "jdbc:postgresql://host:5432/db1", "jdbc:postgresql://host:6432/db1"))) - .isEqualTo("jdbc:postgresql://host2:5432,host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); + .isEqualTo("jdbc:postgresql://host2:5432,host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); assertThat(PgUrlParser.buildCommonUrlToPrimary(Set.of("jdbc:postgresql://host2:5432/db1", "jdbc:postgresql://host:5432/db1", "jdbc:postgresql://host:6432/db1"), - Map.ofEntries( - Map.entry("targetServerType", "secondary"), - Map.entry("readOnly", "true")))) - .isEqualTo("jdbc:postgresql://host2:5432,host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=secondary"); + Map.ofEntries( + Map.entry("targetServerType", "secondary"), + Map.entry("readOnly", "true")))) + .isEqualTo("jdbc:postgresql://host2:5432,host:5432,host:6432/db1?connectTimeout=1&hostRecheckSeconds=2&readOnly=true&socketTimeout=600&targetServerType=secondary"); } } diff --git a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PrimaryHostDeterminerImplTest.java b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PrimaryHostDeterminerImplTest.java index 663ae3b4..1edc4246 100644 --- a/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PrimaryHostDeterminerImplTest.java +++ b/pg-index-health-jdbc-connection/src/test/java/io/github/mfvanek/pg/connection/PrimaryHostDeterminerImplTest.java @@ -44,10 +44,10 @@ void isPrimaryWithExecutionError() throws SQLException { Mockito.when(statement.executeQuery(anyString())).thenThrow(new SQLException("bad query")); final PgConnection pgConnection = PgConnectionImpl.of(dataSource, localhost); assertThatThrownBy(() -> primaryHostDeterminer.isPrimary(pgConnection)) - .isInstanceOf(PgSqlException.class) - .hasMessage("bad query") - .hasCauseInstanceOf(SQLException.class) - .hasRootCauseMessage("bad query"); + .isInstanceOf(PgSqlException.class) + .hasMessage("bad query") + .hasCauseInstanceOf(SQLException.class) + .hasRootCauseMessage("bad query"); } } @@ -55,14 +55,14 @@ void isPrimaryWithExecutionError() throws SQLException { @Test void withInvalidArgument() { assertThatThrownBy(() -> primaryHostDeterminer.isPrimary(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgConnection cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgConnection cannot be null"); } @Test void isPrimaryForSecondaryHost() { final String readUrl = String.format("jdbc:postgresql://localhost:%d/postgres?" + - "prepareThreshold=0&preparedStatementCacheQueries=0&targetServerType=secondary", getPort()); + "prepareThreshold=0&preparedStatementCacheQueries=0&targetServerType=secondary", getPort()); final PgConnection secondary = PgConnectionImpl.of(getDataSource(), PgHostImpl.ofUrl(readUrl)); assertThat(secondary).isNotNull(); assertThat(primaryHostDeterminer.isPrimary(secondary)).isFalse(); diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/MemoryUnit.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/MemoryUnit.java index c16a8b2e..665548d1 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/MemoryUnit.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/MemoryUnit.java @@ -49,8 +49,8 @@ public long convertToBytes(final int unitsCount) { @Override public String toString() { return MemoryUnit.class.getSimpleName() + '{' + - "dimension=" + dimension + - ", description='" + description + '\'' + - '}'; + "dimension=" + dimension + + ", description='" + description + '\'' + + '}'; } } diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/PgContext.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/PgContext.java index 9c83fff7..9df3f144 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/PgContext.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/PgContext.java @@ -34,7 +34,7 @@ public class PgContext { private PgContext(@Nonnull final String schemaName, final int bloatPercentageThreshold) { this.schemaName = Validators.notBlank(schemaName, "schemaName").toLowerCase(Locale.ROOT); this.bloatPercentageThreshold = Validators.argumentNotNegative( - bloatPercentageThreshold, "bloatPercentageThreshold"); + bloatPercentageThreshold, "bloatPercentageThreshold"); } /** @@ -72,9 +72,9 @@ public int getBloatPercentageThreshold() { @Override public String toString() { return PgContext.class.getSimpleName() + '{' + - "schemaName='" + schemaName + '\'' + - ", bloatPercentageThreshold=" + bloatPercentageThreshold + - '}'; + "schemaName='" + schemaName + '\'' + + ", bloatPercentageThreshold=" + bloatPercentageThreshold + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/Column.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/Column.java index 83724481..d5a50ed0 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/Column.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/Column.java @@ -87,8 +87,8 @@ public boolean isNotNull() { @Override public String toString() { return Column.class.getSimpleName() + "{tableName='" + tableName + '\'' + - ", columnName='" + columnName + '\'' + - ", notNull=" + notNull + '}'; + ", columnName='" + columnName + '\'' + + ", notNull=" + notNull + '}'; } /** @@ -106,8 +106,8 @@ public final boolean equals(final Object other) { final Column that = (Column) other; return notNull == that.notNull && - Objects.equals(tableName, that.tableName) && - Objects.equals(columnName, that.columnName); + Objects.equals(tableName, that.tableName) && + Objects.equals(columnName, that.columnName); } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnNameAware.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnNameAware.java index 9990901c..f4320ba5 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnNameAware.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnNameAware.java @@ -18,8 +18,8 @@ * Allows getting column name. * * @author Ivan Vakhrushev - * @since 0.6.2 * @see io.github.mfvanek.pg.model.table.TableNameAware + * @since 0.6.2 */ public interface ColumnNameAware extends TableNameAware { diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnWithSerialType.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnWithSerialType.java index 9ab589ec..78b3cf2d 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnWithSerialType.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/ColumnWithSerialType.java @@ -102,9 +102,9 @@ public String getSequenceName() { @Override public String toString() { return ColumnWithSerialType.class.getSimpleName() + "{column=" + column + - ", serialType=" + serialType + - ", sequenceName='" + sequenceName + '\'' + - '}'; + ", serialType=" + serialType + + ", sequenceName='" + sequenceName + '\'' + + '}'; } /** @@ -122,8 +122,8 @@ public boolean equals(final Object other) { final ColumnWithSerialType that = (ColumnWithSerialType) other; return Objects.equals(column, that.column) && - Objects.equals(serialType, that.serialType) && - Objects.equals(sequenceName, that.sequenceName); + Objects.equals(serialType, that.serialType) && + Objects.equals(sequenceName, that.sequenceName); } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/SerialType.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/SerialType.java index 6a63c77a..56bc06fa 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/SerialType.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/column/SerialType.java @@ -18,9 +18,8 @@ /** * A mapping to PostgreSQL serial types. * - * @see Serial types - * * @author Ivan Vakhrushev + * @see Serial types * @since 0.6.2 */ public enum SerialType { @@ -64,8 +63,8 @@ public String getColumnType() { @Override public String toString() { return SerialType.class.getSimpleName() + '{' + - "columnType='" + columnType + '\'' + - '}'; + "columnType='" + columnType + '\'' + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/Constraint.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/Constraint.java index 8999998f..765f0a25 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/Constraint.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/Constraint.java @@ -40,9 +40,9 @@ public class Constraint implements DbObject, TableNameAware { * @param constraintType constraint type; should be non-null. */ protected Constraint( - @Nonnull final String tableName, - @Nonnull final String constraintName, - @Nonnull final ConstraintType constraintType) { + @Nonnull final String tableName, + @Nonnull final String constraintName, + @Nonnull final ConstraintType constraintType) { this.tableName = Validators.tableNameNotBlank(tableName); this.constraintName = Validators.notBlank(constraintName, "constraintName"); this.constraintType = Objects.requireNonNull(constraintType, "constraintType cannot be null"); @@ -102,7 +102,7 @@ public final boolean equals(final Object other) { final Constraint that = (Constraint) other; return Objects.equals(tableName, that.tableName) && - Objects.equals(constraintName, that.constraintName); + Objects.equals(constraintName, that.constraintName); } /** @@ -121,7 +121,7 @@ public final int hashCode() { @Nonnull final String innerToString() { return "tableName='" + tableName + '\'' + - ", constraintName='" + constraintName + '\''; + ", constraintName='" + constraintName + '\''; } /** @@ -130,9 +130,9 @@ final String innerToString() { @Override public String toString() { return Constraint.class.getSimpleName() + '{' + - innerToString() + - ", constraintType=" + constraintType + - '}'; + innerToString() + + ", constraintType=" + constraintType + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ConstraintType.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ConstraintType.java index b4e7d039..a6b0091a 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ConstraintType.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ConstraintType.java @@ -17,8 +17,8 @@ * A mapping to PostgreSQL constraint types. * * @author Blohny - * @since 0.11.0 * @see pg_constraint + * @since 0.11.0 */ public enum ConstraintType { diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ForeignKey.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ForeignKey.java index 6291f033..417e5213 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ForeignKey.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/constraint/ForeignKey.java @@ -59,9 +59,9 @@ public List getColumnsInConstraint() { @Override public String toString() { return ForeignKey.class.getSimpleName() + '{' + - innerToString() + - ", columnsInConstraint=" + columnsInConstraint + - '}'; + innerToString() + + ", columnsInConstraint=" + columnsInConstraint + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/function/StoredFunction.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/function/StoredFunction.java index cadf368b..1b77acce 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/function/StoredFunction.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/function/StoredFunction.java @@ -32,7 +32,7 @@ public class StoredFunction implements DbObject, Comparable { private StoredFunction(@Nonnull final String functionName, @Nonnull final String functionSignature) { this.functionName = Validators.notBlank(functionName, "functionName"); this.functionSignature = Objects.requireNonNull(functionSignature, "functionSignature cannot be null") - .trim(); // can be empty + .trim(); // can be empty } /** @@ -71,7 +71,7 @@ public String getFunctionSignature() { @Override public String toString() { return StoredFunction.class.getSimpleName() + "{functionName='" + functionName + '\'' + - ", functionSignature='" + functionSignature + "'}"; + ", functionSignature='" + functionSignature + "'}"; } /** @@ -89,7 +89,7 @@ public final boolean equals(final Object other) { final StoredFunction that = (StoredFunction) other; return Objects.equals(functionName, that.functionName) && - Objects.equals(functionSignature, that.functionSignature); + Objects.equals(functionSignature, that.functionSignature); } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/DuplicatedIndexes.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/DuplicatedIndexes.java index 7ddc8d3f..270dabd5 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/DuplicatedIndexes.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/DuplicatedIndexes.java @@ -34,9 +34,9 @@ public class DuplicatedIndexes implements DbObject, TableNameAware { private static final Comparator INDEX_WITH_SIZE_COMPARATOR = - Comparator.comparing(IndexWithSize::getTableName) - .thenComparing(IndexWithSize::getIndexName) - .thenComparing(IndexWithSize::getIndexSizeInBytes); + Comparator.comparing(IndexWithSize::getTableName) + .thenComparing(IndexWithSize::getIndexName) + .thenComparing(IndexWithSize::getIndexSizeInBytes); private final List indexes; private final long totalSize; @@ -46,14 +46,14 @@ private DuplicatedIndexes(@Nonnull final List duplicatedIndexes) final List defensiveCopy = List.copyOf(Objects.requireNonNull(duplicatedIndexes, "duplicatedIndexes cannot be null")); validateThatTableIsTheSame(defensiveCopy); this.indexes = defensiveCopy.stream() - .sorted(INDEX_WITH_SIZE_COMPARATOR) - .collect(Collectors.toUnmodifiableList()); + .sorted(INDEX_WITH_SIZE_COMPARATOR) + .collect(Collectors.toUnmodifiableList()); this.totalSize = this.indexes.stream() - .mapToLong(IndexWithSize::getIndexSizeInBytes) - .sum(); + .mapToLong(IndexWithSize::getIndexSizeInBytes) + .sum(); this.indexesNames = this.indexes.stream() - .map(Index::getIndexName) - .collect(Collectors.toUnmodifiableList()); + .map(Index::getIndexName) + .collect(Collectors.toUnmodifiableList()); } /** @@ -134,10 +134,10 @@ public final int hashCode() { @Override public String toString() { return DuplicatedIndexes.class.getSimpleName() + '{' + - "tableName='" + getTableName() + '\'' + - ", totalSize=" + totalSize + - ", indexes=" + indexes + - '}'; + "tableName='" + getTableName() + '\'' + + ", totalSize=" + totalSize + + ", indexes=" + indexes + + '}'; } @Nonnull @@ -149,10 +149,10 @@ public static DuplicatedIndexes of(@Nonnull final List duplicated public static DuplicatedIndexes of(@Nonnull final String tableName, @Nonnull final String duplicatedAsString) { Validators.tableNameNotBlank(tableName); final List> indexesWithNameAndSize = DuplicatedIndexesParser.parseAsIndexNameAndSize( - Validators.notBlank(duplicatedAsString, "duplicatedAsString")); + Validators.notBlank(duplicatedAsString, "duplicatedAsString")); final List duplicatedIndexes = indexesWithNameAndSize.stream() - .map(e -> IndexWithSize.of(tableName, e.getKey(), e.getValue())) - .collect(Collectors.toUnmodifiableList()); + .map(e -> IndexWithSize.of(tableName, e.getKey(), e.getValue())) + .collect(Collectors.toUnmodifiableList()); return new DuplicatedIndexes(duplicatedIndexes); } @@ -167,7 +167,7 @@ public static DuplicatedIndexes of(@Nonnull final IndexWithSize firstIndex, } final Stream basePart = Stream.of(firstIndex, secondIndex); return new DuplicatedIndexes(Stream.concat(basePart, Stream.of(otherIndexes)) - .collect(Collectors.toUnmodifiableList())); + .collect(Collectors.toUnmodifiableList())); } private static void validateThatTableIsTheSame(@Nonnull final List duplicatedIndexes) { diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/Index.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/Index.java index 97210e78..0bc37479 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/Index.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/Index.java @@ -82,7 +82,7 @@ public String toString() { @Nonnull protected String innerToString() { return "tableName='" + tableName + '\'' + - ", indexName='" + indexName + '\''; + ", indexName='" + indexName + '\''; } /** @@ -100,7 +100,7 @@ public final boolean equals(final Object other) { final Index that = (Index) other; return Objects.equals(tableName, that.tableName) && - Objects.equals(indexName, that.indexName); + Objects.equals(indexName, that.indexName); } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexBloatAware.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexBloatAware.java index 8d04b409..3cb61c24 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexBloatAware.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexBloatAware.java @@ -16,8 +16,9 @@ * Allows getting information about index bloat. * * @author Ivan Vakhrushev - * @since 0.6.0 * @see BloatAware + * @since 0.6.0 */ public interface IndexBloatAware extends BloatAware, IndexSizeAware { + } diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexWithBloat.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexWithBloat.java index 0e7235a6..5b20d186 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexWithBloat.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/IndexWithBloat.java @@ -59,7 +59,7 @@ public int getBloatPercentage() { @Override protected String innerToString() { return super.innerToString() + ", bloatSizeInBytes=" + bloatSizeInBytes + - ", bloatPercentage=" + bloatPercentage; + ", bloatPercentage=" + bloatPercentage; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/UnusedIndex.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/UnusedIndex.java index 2e4f336b..d0a1a91a 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/UnusedIndex.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/UnusedIndex.java @@ -39,9 +39,9 @@ public long getIndexScans() { @Override public String toString() { return UnusedIndex.class.getSimpleName() + '{' + - innerToString() + - ", indexScans=" + indexScans + - '}'; + innerToString() + + ", indexScans=" + indexScans + + '}'; } public static UnusedIndex of(@Nonnull final String tableName, diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParser.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParser.java index af92a6bf..b50dacb0 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParser.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParser.java @@ -28,13 +28,13 @@ public static List> parseAsIndexNameAndSize(@Nonnull fin Validators.notBlank(duplicatedAsString, "duplicatedAsString"); final String[] indexes = duplicatedAsString.split("; "); return Arrays.stream(indexes) - .map(s -> s.split(",")) - .filter(a -> a[0].trim().startsWith("idx=") && a[1].trim().startsWith("size=")) - .map(a -> { - final String indexName = a[0].trim().substring("idx=".length()); - final String sizeAsString = a[1].trim().substring("size=".length()); - return Map.entry(indexName, Long.valueOf(sizeAsString)); - }) - .collect(Collectors.toUnmodifiableList()); + .map(s -> s.split(",")) + .filter(a -> a[0].trim().startsWith("idx=") && a[1].trim().startsWith("size=")) + .map(a -> { + final String indexName = a[0].trim().substring("idx=".length()); + final String sizeAsString = a[1].trim().substring("size=".length()); + return Map.entry(indexName, Long.valueOf(sizeAsString)); + }) + .collect(Collectors.toUnmodifiableList()); } } diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/Table.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/Table.java index 1c3edf77..750e69f8 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/Table.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/Table.java @@ -67,7 +67,7 @@ public long getTableSizeInBytes() { @Nonnull final String innerToString() { return "tableName='" + tableName + '\'' + - ", tableSizeInBytes=" + tableSizeInBytes; + ", tableSizeInBytes=" + tableSizeInBytes; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableBloatAware.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableBloatAware.java index d3d24c60..45daddef 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableBloatAware.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableBloatAware.java @@ -16,8 +16,9 @@ * Allows getting information about table bloat. * * @author Ivan Vakhrushev - * @since 0.6.0 * @see BloatAware + * @since 0.6.0 */ public interface TableBloatAware extends BloatAware, TableSizeAware { + } diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithBloat.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithBloat.java index 75a1b55c..8293fa74 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithBloat.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithBloat.java @@ -58,9 +58,9 @@ public int getBloatPercentage() { @Override public String toString() { return TableWithBloat.class.getSimpleName() + '{' + - table.innerToString() + - ", bloatSizeInBytes=" + bloatSizeInBytes + - ", bloatPercentage=" + bloatPercentage + '}'; + table.innerToString() + + ", bloatSizeInBytes=" + bloatSizeInBytes + + ", bloatPercentage=" + bloatPercentage + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithMissingIndex.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithMissingIndex.java index 44bc5772..3a554fc2 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithMissingIndex.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/model/table/TableWithMissingIndex.java @@ -52,10 +52,10 @@ public long getIndexScans() { @Override public String toString() { return TableWithMissingIndex.class.getSimpleName() + '{' + - table.innerToString() + - ", seqScans=" + seqScans + - ", indexScans=" + indexScans + - '}'; + table.innerToString() + + ", seqScans=" + seqScans + + ", indexScans=" + indexScans + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ImportantParam.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ImportantParam.java index 04469932..819bd66e 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ImportantParam.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ImportantParam.java @@ -34,7 +34,7 @@ public enum ImportantParam implements ParamNameAware { ImportantParam(@Nonnull final String name, @Nonnull final String defaultValue) { this.name = Validators.notBlank(name, "name"); this.defaultValue = ParamValidators.paramValueNotNull( - defaultValue, "defaultValue for '" + name + "' cannot be null"); + defaultValue, "defaultValue for '" + name + "' cannot be null"); } @Nonnull @@ -55,8 +55,8 @@ public String getName() { @Override public String toString() { return ImportantParam.class.getSimpleName() + '{' + - "name='" + name + '\'' + - ", defaultValue='" + defaultValue + '\'' + - '}'; + "name='" + name + '\'' + + ", defaultValue='" + defaultValue + '\'' + + '}'; } } diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/PgParamImpl.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/PgParamImpl.java index f1f89dee..10c66ce9 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/PgParamImpl.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/PgParamImpl.java @@ -45,9 +45,9 @@ public String getValue() { @Override public String toString() { return PgParamImpl.class.getSimpleName() + '{' + - "name='" + name + '\'' + - ", value='" + value + '\'' + - '}'; + "name='" + name + '\'' + + ", value='" + value + '\'' + + '}'; } /** diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecification.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecification.java index 3e75b569..935a2aa0 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecification.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecification.java @@ -48,10 +48,10 @@ public boolean hasSSD() { @Override public String toString() { return ServerSpecification.class.getSimpleName() + '{' + - "cpuCoresAmount=" + cpuCoresAmount + - ", memoryAmountInBytes=" + memoryAmountInBytes + - ", hasSSD=" + hasSSD + - '}'; + "cpuCoresAmount=" + cpuCoresAmount + + ", memoryAmountInBytes=" + memoryAmountInBytes + + ", hasSSD=" + hasSSD + + '}'; } @Nonnull diff --git a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilder.java b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilder.java index f1f1b047..293f9090 100644 --- a/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilder.java +++ b/pg-index-health-model/src/main/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilder.java @@ -59,9 +59,9 @@ public ServerSpecification build() { @Override public String toString() { return ServerSpecificationBuilder.class.getSimpleName() + '{' + - "cpuCoresAmount=" + cpuCoresAmount + - ", memoryAmountInBytes=" + memoryAmountInBytes + - ", hasSSD=" + hasSSD + - '}'; + "cpuCoresAmount=" + cpuCoresAmount + + ", memoryAmountInBytes=" + memoryAmountInBytes + + ", hasSSD=" + hasSSD + + '}'; } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/MemoryUnitTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/MemoryUnitTest.java index 01f606a5..bde8dd50 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/MemoryUnitTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/MemoryUnitTest.java @@ -26,6 +26,6 @@ void convertToBytes() { @Test void toStringTest() { assertThat(MemoryUnit.MB) - .hasToString("MemoryUnit{dimension=1048576, description='megabyte'}"); + .hasToString("MemoryUnit{dimension=1048576, description='megabyte'}"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/PgContextTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/PgContextTest.java index a265e6b1..62bf75ad 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/PgContextTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/PgContextTest.java @@ -49,27 +49,27 @@ void getBloatPercentageThreshold() { @Test void withInvalidArguments() { assertThatThrownBy(() -> PgContext.of(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("schemaName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("schemaName cannot be null"); assertThatThrownBy(() -> PgContext.of("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("schemaName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("schemaName cannot be blank"); assertThatThrownBy(() -> PgContext.of(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("schemaName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("schemaName cannot be blank"); assertThatThrownBy(() -> PgContext.of("s", -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("bloatPercentageThreshold cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("bloatPercentageThreshold cannot be less than zero"); } @Test void testToString() { assertThat(PgContext.of("s")) - .hasToString("PgContext{schemaName='s', bloatPercentageThreshold=10}"); + .hasToString("PgContext{schemaName='s', bloatPercentageThreshold=10}"); assertThat(PgContext.of("s", 11)) - .hasToString("PgContext{schemaName='s', bloatPercentageThreshold=11}"); + .hasToString("PgContext{schemaName='s', bloatPercentageThreshold=11}"); assertThat(PgContext.ofPublic()) - .hasToString("PgContext{schemaName='public', bloatPercentageThreshold=10}"); + .hasToString("PgContext{schemaName='public', bloatPercentageThreshold=10}"); } @Test @@ -95,13 +95,13 @@ void complementWithPublicSchema() { void complementWithSchemaWithInvalidArguments() { final PgContext pgContext = PgContext.ofPublic(); assertThatThrownBy(() -> pgContext.enrichWithSchema(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("objectName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("objectName cannot be null"); assertThatThrownBy(() -> pgContext.enrichWithSchema("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("objectName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("objectName cannot be blank"); assertThatThrownBy(() -> pgContext.enrichWithSchema(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("objectName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("objectName cannot be blank"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnTest.java index 15822d42..15c403b0 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnTest.java @@ -22,23 +22,23 @@ class ColumnTest { void gettersShouldWork() { final Column column = Column.ofNotNull("t1", "c1"); assertThat(column.getTableName()) - .isNotBlank() - .isEqualTo("t1"); + .isNotBlank() + .isEqualTo("t1"); assertThat(column.getColumnName()) - .isNotBlank() - .isEqualTo("c1") - .isEqualTo(column.getName()); + .isNotBlank() + .isEqualTo("c1") + .isEqualTo(column.getName()); assertThat(column.isNotNull()).isTrue(); assertThat(column.isNullable()).isFalse(); final Column nullableColumn = Column.ofNullable("t2", "c2"); assertThat(nullableColumn.getTableName()) - .isNotBlank() - .isEqualTo("t2"); + .isNotBlank() + .isEqualTo("t2"); assertThat(nullableColumn.getColumnName()) - .isNotBlank() - .isEqualTo("c2") - .isEqualTo(nullableColumn.getName()); + .isNotBlank() + .isEqualTo("c2") + .isEqualTo(nullableColumn.getName()); assertThat(nullableColumn.isNotNull()).isFalse(); assertThat(nullableColumn.isNullable()).isTrue(); } @@ -47,33 +47,33 @@ void gettersShouldWork() { @Test void withInvalidValuesShouldThrowException() { assertThatThrownBy(() -> Column.ofNotNull(null, "c1")) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> Column.ofNotNull("", "c1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Column.ofNotNull(" ", "c1")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Column.ofNotNull("t1", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columnName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columnName cannot be null"); assertThatThrownBy(() -> Column.ofNotNull("t1", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); assertThatThrownBy(() -> Column.ofNotNull("t1", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); } @Test void testToString() { assertThat(Column.ofNotNull("t1", "c1")) - .hasToString("Column{tableName='t1', columnName='c1', notNull=true}"); + .hasToString("Column{tableName='t1', columnName='c1', notNull=true}"); assertThat(Column.ofNullable("t2", "c2")) - .hasToString("Column{tableName='t2', columnName='c2', notNull=false}"); + .hasToString("Column{tableName='t2', columnName='c2', notNull=false}"); } @SuppressWarnings("ConstantConditions") @@ -90,30 +90,30 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // do not ignore nullability of column assertThat(theSameButNullable) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(Column.class) - .verify(); + .verify(); } @Test @@ -126,24 +126,24 @@ void compareToTest() { //noinspection ResultOfMethodCallIgnored,ConstantConditions assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isGreaterThan(theSameButNullable) // do not ignore nullability of column - .isLessThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isGreaterThan(theSameButNullable) // do not ignore nullability of column + .isLessThan(second) + .isLessThan(third); assertThat(theSameButNullable).isLessThan(first); assertThat(second) - .isGreaterThan(first) - .isLessThan(third); + .isGreaterThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnWithSerialTypeTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnWithSerialTypeTest.java index 227acb76..6bf522ec 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnWithSerialTypeTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/ColumnWithSerialTypeTest.java @@ -24,72 +24,72 @@ class ColumnWithSerialTypeTest { void gettersShouldWork() { final ColumnWithSerialType column = prepare(); assertThat(column) - .isNotNull() - .satisfies(c -> { - assertThat(c.getTableName()) - .isEqualTo("t1"); - assertThat(c.getColumnName()) - .isEqualTo("c1") - .isEqualTo(c.getName()); - assertThat(c.isNullable()) - .isFalse(); - assertThat(c.isNotNull()) - .isTrue(); - assertThat(c.getSerialType()) - .isEqualTo(SerialType.SERIAL); - assertThat(c.getSequenceName()) - .isEqualTo("s1"); - }); + .isNotNull() + .satisfies(c -> { + assertThat(c.getTableName()) + .isEqualTo("t1"); + assertThat(c.getColumnName()) + .isEqualTo("c1") + .isEqualTo(c.getName()); + assertThat(c.isNullable()) + .isFalse(); + assertThat(c.isNotNull()) + .isTrue(); + assertThat(c.getSerialType()) + .isEqualTo(SerialType.SERIAL); + assertThat(c.getSequenceName()) + .isEqualTo("s1"); + }); final ColumnWithSerialType theSameButNullable = prepareNullable(); assertThat(theSameButNullable) - .isNotNull() - .satisfies(c -> { - assertThat(c.getTableName()) - .isEqualTo("t1"); - assertThat(c.getColumnName()) - .isEqualTo("c1") - .isEqualTo(c.getName()); - assertThat(c.isNullable()) - .isTrue(); - assertThat(c.isNotNull()) - .isFalse(); - assertThat(c.getSerialType()) - .isEqualTo(SerialType.SERIAL); - assertThat(c.getSequenceName()) - .isEqualTo("s1"); - }); + .isNotNull() + .satisfies(c -> { + assertThat(c.getTableName()) + .isEqualTo("t1"); + assertThat(c.getColumnName()) + .isEqualTo("c1") + .isEqualTo(c.getName()); + assertThat(c.isNullable()) + .isTrue(); + assertThat(c.isNotNull()) + .isFalse(); + assertThat(c.getSerialType()) + .isEqualTo(SerialType.SERIAL); + assertThat(c.getSequenceName()) + .isEqualTo("s1"); + }); } @SuppressWarnings("ConstantConditions") @Test void withInvalidValuesShouldThrowException() { assertThatThrownBy(() -> ColumnWithSerialType.of(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("column cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("column cannot be null"); final Column column = Column.ofNullable("t1", "c1"); assertThatThrownBy(() -> ColumnWithSerialType.of(column, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("serialType cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("serialType cannot be null"); assertThatThrownBy(() -> ColumnWithSerialType.of(column, SerialType.BIG_SERIAL, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("sequenceName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("sequenceName cannot be null"); assertThatThrownBy(() -> ColumnWithSerialType.of(column, SerialType.SMALL_SERIAL, "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("sequenceName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sequenceName cannot be blank"); assertThatThrownBy(() -> ColumnWithSerialType.of(column, SerialType.SMALL_SERIAL, " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("sequenceName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sequenceName cannot be blank"); } @Test void toStringTest() { assertThat(prepare()) - .hasToString("ColumnWithSerialType{column=Column{tableName='t1', columnName='c1', notNull=true}, serialType=SerialType{columnType='serial'}, sequenceName='s1'}"); + .hasToString("ColumnWithSerialType{column=Column{tableName='t1', columnName='c1', notNull=true}, serialType=SerialType{columnType='serial'}, sequenceName='s1'}"); } @SuppressWarnings("ConstantConditions") @@ -108,38 +108,38 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // do not ignore nullability of column assertThat(theSameButNullable) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(forth) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(ColumnWithSerialType.class) - .verify(); + .verify(); } @Test @@ -154,32 +154,32 @@ void compareToTest() { //noinspection ResultOfMethodCallIgnored,ConstantConditions assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isGreaterThan(theSameButNullable) // do not ignore nullability of column - .isGreaterThan(second) - .isLessThan(third) - .isLessThan(forth) - .isLessThan(fifth); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isGreaterThan(theSameButNullable) // do not ignore nullability of column + .isGreaterThan(second) + .isLessThan(third) + .isLessThan(forth) + .isLessThan(fifth); assertThat(theSameButNullable) - .isLessThan(first); + .isLessThan(first); assertThat(second) - .isLessThan(first) - .isLessThan(third) - .isLessThan(forth) - .isLessThan(fifth); + .isLessThan(first) + .isLessThan(third) + .isLessThan(forth) + .isLessThan(fifth); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second) - .isLessThan(forth) - .isGreaterThan(fifth); + .isGreaterThan(first) + .isGreaterThan(second) + .isLessThan(forth) + .isGreaterThan(fifth); } @Nonnull diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/SerialTypeTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/SerialTypeTest.java index 51223407..cc75864f 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/SerialTypeTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/column/SerialTypeTest.java @@ -25,46 +25,46 @@ void allPgTypeNamesShouldBeUnique() { final Set types = new HashSet<>(); for (final SerialType serialType : SerialType.values()) { assertThat(serialType.getColumnType()) - .isNotBlank(); + .isNotBlank(); types.add(serialType.getColumnType()); } assertThat(types) - .hasSameSizeAs(SerialType.values()); + .hasSameSizeAs(SerialType.values()); } @Test void toStringTest() { assertThat(SerialType.SMALL_SERIAL) - .hasToString("SerialType{columnType='smallserial'}"); + .hasToString("SerialType{columnType='smallserial'}"); assertThat(SerialType.SERIAL) - .hasToString("SerialType{columnType='serial'}"); + .hasToString("SerialType{columnType='serial'}"); assertThat(SerialType.BIG_SERIAL) - .hasToString("SerialType{columnType='bigserial'}"); + .hasToString("SerialType{columnType='bigserial'}"); } @Test void creationFromStringShouldWork() { assertThat(SerialType.valueFrom("smallserial")) - .isEqualTo(SerialType.SMALL_SERIAL); + .isEqualTo(SerialType.SMALL_SERIAL); assertThat(SerialType.valueOf("SMALL_SERIAL")) - .isEqualTo(SerialType.SMALL_SERIAL); + .isEqualTo(SerialType.SMALL_SERIAL); } @SuppressWarnings("ConstantConditions") @Test void creationFromStringShouldThrowExceptionWhenNotFound() { assertThatThrownBy(() -> SerialType.valueFrom(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgColumnType cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgColumnType cannot be null"); assertThatThrownBy(() -> SerialType.valueFrom("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("pgColumnType = ''"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pgColumnType = ''"); assertThatThrownBy(() -> SerialType.valueOf(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Name is null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("Name is null"); assertThatThrownBy(() -> SerialType.valueOf("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("No enum constant io.github.mfvanek.pg.model.column.SerialType."); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("No enum constant io.github.mfvanek.pg.model.column.SerialType."); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTest.java index 1a90fdfd..d980ba49 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTest.java @@ -22,52 +22,52 @@ class ConstraintTest { void testToString() { final Constraint constraintWithCheck = Constraint.ofType("t", "not_valid_id", ConstraintType.CHECK); assertThat(constraintWithCheck) - .hasToString("Constraint{tableName='t', constraintName='not_valid_id', constraintType=CHECK}"); + .hasToString("Constraint{tableName='t', constraintName='not_valid_id', constraintType=CHECK}"); final Constraint constraintWithForeignKey = Constraint.ofType("t", "not_valid_id", ConstraintType.FOREIGN_KEY); assertThat(constraintWithForeignKey) - .hasToString("Constraint{tableName='t', constraintName='not_valid_id', constraintType=FOREIGN_KEY}"); + .hasToString("Constraint{tableName='t', constraintName='not_valid_id', constraintType=FOREIGN_KEY}"); } @Test void constraint() { final Constraint constraintWithCheck = Constraint.ofType("t", "not_valid_id", ConstraintType.CHECK); assertThat(constraintWithCheck.getTableName()) - .isNotBlank() - .isEqualTo("t"); + .isNotBlank() + .isEqualTo("t"); assertThat(constraintWithCheck.getConstraintName()) - .isNotBlank() - .isEqualTo("not_valid_id") - .isEqualTo(constraintWithCheck.getName()); + .isNotBlank() + .isEqualTo("not_valid_id") + .isEqualTo(constraintWithCheck.getName()); assertThat(constraintWithCheck.getConstraintType()) - .isNotNull() - .isEqualTo(ConstraintType.CHECK); + .isNotNull() + .isEqualTo(ConstraintType.CHECK); final Constraint constraintWithForeignKey = Constraint.ofType("t", "not_valid_id", ConstraintType.FOREIGN_KEY); assertThat(constraintWithForeignKey.getTableName()) - .isNotBlank() - .isEqualTo("t"); + .isNotBlank() + .isEqualTo("t"); assertThat(constraintWithForeignKey.getConstraintName()) - .isNotBlank() - .isEqualTo("not_valid_id") - .isEqualTo(constraintWithForeignKey.getName()); + .isNotBlank() + .isEqualTo("not_valid_id") + .isEqualTo(constraintWithForeignKey.getName()); assertThat(constraintWithForeignKey.getConstraintType()) - .isNotNull() - .isEqualTo(ConstraintType.FOREIGN_KEY); + .isNotNull() + .isEqualTo(ConstraintType.FOREIGN_KEY); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> Constraint.ofType(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> Constraint.ofType("t", null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("constraintName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("constraintName cannot be null"); assertThatThrownBy(() -> Constraint.ofType("t", "c_t_order_id", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("constraintType cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("constraintType cannot be null"); } @SuppressWarnings("ConstantConditions") @@ -84,33 +84,33 @@ void equalsAndHashCode() { assertThat(first.equals(Integer.MAX_VALUE)).isFalse(); assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); assertThat(different) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(constraintTypeDoesntMatter) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(constraintTypeDoesntMatter) - .doesNotHaveSameHashCodeAs(constraintTypeDoesntMatter); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(constraintTypeDoesntMatter) + .doesNotHaveSameHashCodeAs(constraintTypeDoesntMatter); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(Constraint.class) - .withIgnoredFields("constraintType") - .verify(); + .withIgnoredFields("constraintType") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTypeTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTypeTest.java index 01dc2293..25d1df7d 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTypeTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ConstraintTypeTest.java @@ -20,19 +20,19 @@ class ConstraintTypeTest { @Test void valueFrom() { assertThat(ConstraintType.valueFrom("c")) - .isEqualTo(ConstraintType.CHECK); + .isEqualTo(ConstraintType.CHECK); assertThat(ConstraintType.valueFrom("f")) - .isEqualTo(ConstraintType.FOREIGN_KEY); + .isEqualTo(ConstraintType.FOREIGN_KEY); } @SuppressWarnings("ConstantConditions") @Test void creationFromStringShouldThrowExceptionWhenNotFound() { assertThatThrownBy(() -> ConstraintType.valueFrom(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgConType cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgConType cannot be null"); assertThatThrownBy(() -> ConstraintType.valueFrom("hi")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Unknown pgConType: hi"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown pgConType: hi"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ForeignKeyTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ForeignKeyTest.java index a69311bf..ea085618 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ForeignKeyTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/constraint/ForeignKeyTest.java @@ -26,113 +26,113 @@ class ForeignKeyTest { void testToString() { final ForeignKey foreignKey = ForeignKey.ofNotNullColumn("t", "c_t_order_id", "order_id"); assertThat(foreignKey) - .hasToString("ForeignKey{tableName='t', constraintName='c_t_order_id', columnsInConstraint=[Column{tableName='t', columnName='order_id', notNull=true}]}"); + .hasToString("ForeignKey{tableName='t', constraintName='c_t_order_id', columnsInConstraint=[Column{tableName='t', columnName='order_id', notNull=true}]}"); final ForeignKey foreignKeyWithNullableColumn = ForeignKey.ofNullableColumn("t", "c_t_order_id", "order_id"); assertThat(foreignKeyWithNullableColumn) - .hasToString("ForeignKey{tableName='t', constraintName='c_t_order_id', columnsInConstraint=[Column{tableName='t', columnName='order_id', notNull=false}]}"); + .hasToString("ForeignKey{tableName='t', constraintName='c_t_order_id', columnsInConstraint=[Column{tableName='t', columnName='order_id', notNull=false}]}"); } @Test void foreignKey() { final ForeignKey foreignKey = ForeignKey.ofNotNullColumn("t", "c_t_order_id", "order_id"); assertThat(foreignKey.getTableName()) - .isNotBlank() - .isEqualTo("t"); + .isNotBlank() + .isEqualTo("t"); assertThat(foreignKey.getConstraintName()) - .isNotBlank() - .isEqualTo("c_t_order_id") - .isEqualTo(foreignKey.getName()); + .isNotBlank() + .isEqualTo("c_t_order_id") + .isEqualTo(foreignKey.getName()); assertThat(foreignKey.getColumnsInConstraint()) - .hasSize(1) - .containsExactly(Column.ofNotNull("t", "order_id")) - .isUnmodifiable(); + .hasSize(1) + .containsExactly(Column.ofNotNull("t", "order_id")) + .isUnmodifiable(); } @Test void getColumnsInConstraint() { final ForeignKey key = ForeignKey.of("t", "c_t_order_id", - List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "item_id"))); + List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "item_id"))); assertThat(key.getColumnsInConstraint()) - .hasSize(2) - .containsExactly(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "item_id")) - .isUnmodifiable(); + .hasSize(2) + .containsExactly(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "item_id")) + .isUnmodifiable(); } @Test void shouldCreateDefensiveCopyOfColumnsList() { final List columns = new ArrayList<>(List.of( - Column.ofNotNull("t", "first"), - Column.ofNotNull("t", "second"), - Column.ofNotNull("t", "third"))); + Column.ofNotNull("t", "first"), + Column.ofNotNull("t", "second"), + Column.ofNotNull("t", "third"))); final ForeignKey key = ForeignKey.of("t", "c_t_fk", columns); columns.add(Column.ofNotNull("t", "fourth")); assertThat(key.getColumnsInConstraint()) - .hasSize(3) - .doesNotContain(Column.ofNotNull("t", "fourth")) - .isUnmodifiable(); + .hasSize(3) + .doesNotContain(Column.ofNotNull("t", "fourth")) + .isUnmodifiable(); } @Test void allColumnMustBelongToTheSameTable() { final List columns = List.of( - Column.ofNotNull("t", "first"), - Column.ofNotNull("t1", "second")); + Column.ofNotNull("t", "first"), + Column.ofNotNull("t1", "second")); assertThatThrownBy(() -> ForeignKey.of("t", "c_t_fk", columns)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Table name is not the same within given rows"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name is not the same within given rows"); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> ForeignKey.of(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> ForeignKey.of("t", null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("constraintName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("constraintName cannot be null"); assertThatThrownBy(() -> ForeignKey.of("t", "c_t_order_id", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columnsInConstraint cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columnsInConstraint cannot be null"); final List columns = List.of(); assertThatThrownBy(() -> ForeignKey.of("t", "c_t_order_id", columns)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnsInConstraint cannot be empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnsInConstraint cannot be empty"); assertThatThrownBy(() -> ForeignKey.ofColumn("t", "fk", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("column cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("column cannot be null"); assertThatThrownBy(() -> ForeignKey.ofNotNullColumn("t", "fk", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columnName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columnName cannot be null"); assertThatThrownBy(() -> ForeignKey.ofNotNullColumn("t", "fk", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); assertThatThrownBy(() -> ForeignKey.ofNotNullColumn("t", "fk", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); assertThatThrownBy(() -> ForeignKey.ofNullableColumn("t", "fk", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columnName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columnName cannot be null"); assertThatThrownBy(() -> ForeignKey.ofNullableColumn("t", "fk", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); assertThatThrownBy(() -> ForeignKey.ofNullableColumn("t", "fk", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); } @SuppressWarnings("ConstantConditions") @Test void equalsAndHashCode() { final ForeignKey first = ForeignKey.of("t", "c_t_order_id", - List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); + List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); final ForeignKey theSame = ForeignKey.of("t", "c_t_order_id", - List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); + List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); final ForeignKey withDifferentOrderOfColumns = ForeignKey.of("t", "c_t_order_id", - List.of(Column.ofNotNull("t", "limit"), Column.ofNotNull("t", "order_id"))); + List.of(Column.ofNotNull("t", "limit"), Column.ofNotNull("t", "order_id"))); final ForeignKey withDifferentColumnName = ForeignKey.ofNullableColumn("t", "c_t_order_id", "no_matter_what"); assertThat(first.equals(null)).isFalse(); @@ -141,42 +141,42 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // column order doesn't matter assertThat(withDifferentOrderOfColumns) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // column name doesn't matter assertThat(withDifferentColumnName) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); final ForeignKey third = ForeignKey.of("table", "c_t_order_id", - List.of(Column.ofNotNull("table", "order_id"), Column.ofNotNull("table", "limit"))); + List.of(Column.ofNotNull("table", "order_id"), Column.ofNotNull("table", "limit"))); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); final ForeignKey fourth = ForeignKey.of("t", "other_id", - List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); + List.of(Column.ofNotNull("t", "order_id"), Column.ofNotNull("t", "limit"))); assertThat(fourth) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(ForeignKey.class) - .withIgnoredFields("constraintType", "columnsInConstraint") - .verify(); + .withIgnoredFields("constraintType", "columnsInConstraint") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/function/StoredFunctionTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/function/StoredFunctionTest.java index 0d912da1..f59cab50 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/function/StoredFunctionTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/function/StoredFunctionTest.java @@ -22,66 +22,66 @@ class StoredFunctionTest { void gettersShouldWork() { final StoredFunction noArgsFunction = StoredFunction.ofNoArgs("f1"); assertThat(noArgsFunction) - .isNotNull(); + .isNotNull(); assertThat(noArgsFunction.getFunctionName()) - .isEqualTo("f1") - .isEqualTo(noArgsFunction.getName()); + .isEqualTo("f1") + .isEqualTo(noArgsFunction.getName()); assertThat(noArgsFunction.getFunctionSignature()) - .isEmpty(); + .isEmpty(); final StoredFunction function = StoredFunction.of("f2", "IN a integer, IN b integer, IN c integer"); assertThat(function) - .isNotNull(); + .isNotNull(); assertThat(function.getFunctionName()) - .isEqualTo("f2") - .isEqualTo(function.getName()); + .isEqualTo("f2") + .isEqualTo(function.getName()); assertThat(function.getFunctionSignature()) - .isEqualTo("IN a integer, IN b integer, IN c integer"); + .isEqualTo("IN a integer, IN b integer, IN c integer"); } @Test void trimShouldBeApplied() { final StoredFunction function = StoredFunction.of("f1", " "); assertThat(function) - .isNotNull(); + .isNotNull(); assertThat(function.getFunctionSignature()) - .isEmpty(); + .isEmpty(); } @SuppressWarnings("ConstantConditions") @Test void withInvalidValuesShouldThrowException() { assertThatThrownBy(() -> StoredFunction.ofNoArgs(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("functionName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("functionName cannot be null"); assertThatThrownBy(() -> StoredFunction.ofNoArgs("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("functionName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("functionName cannot be blank"); assertThatThrownBy(() -> StoredFunction.ofNoArgs(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("functionName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("functionName cannot be blank"); assertThatThrownBy(() -> StoredFunction.of(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("functionName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("functionName cannot be null"); assertThatThrownBy(() -> StoredFunction.of("", null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("functionName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("functionName cannot be blank"); assertThatThrownBy(() -> StoredFunction.of(" ", null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("functionName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("functionName cannot be blank"); assertThatThrownBy(() -> StoredFunction.of("f1", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("functionSignature cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("functionSignature cannot be null"); } @Test void testToString() { assertThat(StoredFunction.ofNoArgs("f1")) - .hasToString("StoredFunction{functionName='f1', functionSignature=''}"); + .hasToString("StoredFunction{functionName='f1', functionSignature=''}"); assertThat(StoredFunction.of("f2", "IN a integer, IN b integer, IN c integer")) - .hasToString("StoredFunction{functionName='f2', functionSignature='IN a integer, IN b integer, IN c integer'}"); + .hasToString("StoredFunction{functionName='f2', functionSignature='IN a integer, IN b integer, IN c integer'}"); } @SuppressWarnings("ConstantConditions") @@ -98,27 +98,27 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(third) - .doesNotHaveSameHashCodeAs(third); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(third) + .doesNotHaveSameHashCodeAs(third); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(StoredFunction.class) - .verify(); + .verify(); } @Test @@ -130,21 +130,21 @@ void compareToTest() { //noinspection ResultOfMethodCallIgnored,ConstantConditions assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isGreaterThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isGreaterThan(second) + .isLessThan(third); assertThat(second) - .isLessThan(first) - .isLessThan(third); + .isLessThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/DuplicatedIndexesTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/DuplicatedIndexesTest.java index d28689cb..418e4686 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/DuplicatedIndexesTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/DuplicatedIndexesTest.java @@ -24,100 +24,100 @@ class DuplicatedIndexesTest { @Test void withTheSameTable() { final DuplicatedIndexes index = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t", "i1", 101L), - IndexWithSize.of("t", "i2", 202L))); + IndexWithSize.of("t", "i1", 101L), + IndexWithSize.of("t", "i2", 202L))); assertThat(index).isNotNull(); assertThat(index.getTableName()).isEqualTo("t"); assertThat(index.getTotalSize()).isEqualTo(303L); assertThat(index.getIndexNames()) - .hasSize(2) - .containsExactly("i1", "i2") - .isUnmodifiable(); + .hasSize(2) + .containsExactly("i1", "i2") + .isUnmodifiable(); assertThat(index.getName()) - .isEqualTo("i1,i2"); + .isEqualTo("i1,i2"); } @Test void ordering() { final DuplicatedIndexes indexes = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t1", "i3", 303L), - IndexWithSize.of("t1", "i1", 101L), - IndexWithSize.of("t1", "i2", 202L))); + IndexWithSize.of("t1", "i3", 303L), + IndexWithSize.of("t1", "i1", 101L), + IndexWithSize.of("t1", "i2", 202L))); assertThat(indexes).isNotNull(); assertThat(indexes.getTotalSize()).isEqualTo(606L); assertThat(indexes.getDuplicatedIndexes()) - .hasSize(3) - .containsExactly( - IndexWithSize.of("t1", "i1", 101L), - IndexWithSize.of("t1", "i2", 202L), - IndexWithSize.of("t1", "i3", 303L)) - .isUnmodifiable(); + .hasSize(3) + .containsExactly( + IndexWithSize.of("t1", "i1", 101L), + IndexWithSize.of("t1", "i2", 202L), + IndexWithSize.of("t1", "i3", 303L)) + .isUnmodifiable(); assertThat(indexes.getIndexNames()) - .hasSize(3) - .containsExactly("i1", "i2", "i3") - .isUnmodifiable(); + .hasSize(3) + .containsExactly("i1", "i2", "i3") + .isUnmodifiable(); } @Test void shouldCreateDefensiveCopyOfIndexesList() { final List sourceIndexes = new ArrayList<>(List.of( - IndexWithSize.of("t1", "i3", 303L), - IndexWithSize.of("t1", "i1", 101L), - IndexWithSize.of("t1", "i2", 202L))); + IndexWithSize.of("t1", "i3", 303L), + IndexWithSize.of("t1", "i1", 101L), + IndexWithSize.of("t1", "i2", 202L))); final DuplicatedIndexes indexes = DuplicatedIndexes.of(sourceIndexes); final IndexWithSize fourth = IndexWithSize.of("t1", "i4", 404L); sourceIndexes.add(fourth); assertThat(indexes.getDuplicatedIndexes()) - .hasSize(3) - .doesNotContain(fourth) - .isUnmodifiable(); + .hasSize(3) + .doesNotContain(fourth) + .isUnmodifiable(); assertThat(indexes.getIndexNames()) - .hasSize(3) - .doesNotContain("i4") - .isUnmodifiable(); + .hasSize(3) + .doesNotContain("i4") + .isUnmodifiable(); } @Test void testToString() { final DuplicatedIndexes indexes = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t", "i3", 303L), - IndexWithSize.of("t", "i1", 101L), - IndexWithSize.of("t", "i2", 202L))); + IndexWithSize.of("t", "i3", 303L), + IndexWithSize.of("t", "i1", 101L), + IndexWithSize.of("t", "i2", 202L))); assertThat(indexes) - .hasToString("DuplicatedIndexes{tableName='t', totalSize=606, indexes=[" + "IndexWithSize{tableName='t', indexName='i1', indexSizeInBytes=101}, " + - "IndexWithSize{tableName='t', indexName='i2', indexSizeInBytes=202}, " + "IndexWithSize{tableName='t', indexName='i3', indexSizeInBytes=303}]}"); + .hasToString("DuplicatedIndexes{tableName='t', totalSize=606, indexes=[" + "IndexWithSize{tableName='t', indexName='i1', indexSizeInBytes=101}, " + + "IndexWithSize{tableName='t', indexName='i2', indexSizeInBytes=202}, " + "IndexWithSize{tableName='t', indexName='i3', indexSizeInBytes=303}]}"); } @SuppressWarnings("ConstantConditions") @Test void withoutIndexes() { assertThatThrownBy(() -> DuplicatedIndexes.of(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("duplicatedIndexes cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("duplicatedIndexes cannot be null"); final List firstIndexes = List.of(); assertThatThrownBy(() -> DuplicatedIndexes.of(firstIndexes)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("duplicatedIndexes cannot be empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duplicatedIndexes cannot be empty"); final List secondIndexes = List.of(IndexWithSize.of("t", "i", 1L)); assertThatThrownBy(() -> DuplicatedIndexes.of(secondIndexes)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("duplicatedIndexes should contains at least two rows"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duplicatedIndexes should contains at least two rows"); } @Test void withDifferentTables() { final List indexWithSizeList = List.of( - IndexWithSize.of("t1", "i1", 1L), - IndexWithSize.of("t2", "i2", 2L)); + IndexWithSize.of("t1", "i1", 1L), + IndexWithSize.of("t2", "i2", 2L)); assertThatThrownBy(() -> DuplicatedIndexes.of(indexWithSizeList)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Table name is not the same within given rows"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name is not the same within given rows"); } @Test @@ -127,9 +127,9 @@ void fromValidString() { assertThat(index.getTableName()).isEqualTo("t"); assertThat(index.getTotalSize()).isEqualTo(178L); assertThat(index.getIndexNames()) - .hasSize(2) - .containsExactly("i3", "i4") - .isUnmodifiable(); + .hasSize(2) + .containsExactly("i3", "i4") + .isUnmodifiable(); } @SuppressWarnings("ConstantConditions") @@ -147,14 +147,14 @@ void fromInvalidString() { @Test void testEqualsAndHashCode() { final DuplicatedIndexes first = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t1", "i1", 101L), - IndexWithSize.of("t1", "i2", 202L))); + IndexWithSize.of("t1", "i1", 101L), + IndexWithSize.of("t1", "i2", 202L))); final DuplicatedIndexes second = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t1", "i3", 301L), - IndexWithSize.of("t1", "i4", 402L))); + IndexWithSize.of("t1", "i3", 301L), + IndexWithSize.of("t1", "i4", 402L))); final DuplicatedIndexes third = DuplicatedIndexes.of(List.of( - IndexWithSize.of("t2", "i5", 101L), - IndexWithSize.of("t2", "i6", 202L))); + IndexWithSize.of("t2", "i5", 101L), + IndexWithSize.of("t2", "i6", 202L))); assertThat(first.equals(null)).isFalse(); //noinspection EqualsBetweenInconvertibleTypes @@ -162,69 +162,69 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same final DuplicatedIndexes theSame = DuplicatedIndexes.of( - IndexWithSize.of("t1", "i2", 505L), // different order - IndexWithSize.of("t1", "i1", 606L) // different size + IndexWithSize.of("t1", "i2", 505L), // different order + IndexWithSize.of("t1", "i1", 606L) // different size ); assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(DuplicatedIndexes.class) - .withIgnoredFields("totalSize", "indexesNames") - .verify(); + .withIgnoredFields("totalSize", "indexesNames") + .verify(); } @SuppressWarnings("ConstantConditions") @Test void newFactoryConstructor() { assertThatThrownBy(() -> DuplicatedIndexes.of(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); final IndexWithSize indexWithSize = IndexWithSize.of("t", "i1", 1L); assertThatThrownBy(() -> DuplicatedIndexes.of(indexWithSize, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("secondIndex cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("secondIndex cannot be null"); final IndexWithSize firstIndex = IndexWithSize.of("t", "i1", 1L); final IndexWithSize secondIndex = IndexWithSize.of("t", "i2", 2L); final IndexWithSize fourthIndex = IndexWithSize.of("t", "i4", 4L); assertThatThrownBy(() -> DuplicatedIndexes.of(firstIndex, secondIndex, null, fourthIndex)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("otherIndexes cannot contain nulls"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("otherIndexes cannot contain nulls"); final DuplicatedIndexes indexes = DuplicatedIndexes.of( - IndexWithSize.of("t", "i3", 3L), - IndexWithSize.of("t", "i1", 1L), - IndexWithSize.of("t", "i2", 2L), - IndexWithSize.of("t", "i4", 4L)); + IndexWithSize.of("t", "i3", 3L), + IndexWithSize.of("t", "i1", 1L), + IndexWithSize.of("t", "i2", 2L), + IndexWithSize.of("t", "i4", 4L)); assertThat(indexes).isNotNull(); assertThat(indexes.getDuplicatedIndexes()) - .hasSize(4) - .containsExactly( - IndexWithSize.of("t", "i1", 1L), - IndexWithSize.of("t", "i2", 2L), - IndexWithSize.of("t", "i3", 3L), - IndexWithSize.of("t", "i4", 4L)) - .isUnmodifiable(); + .hasSize(4) + .containsExactly( + IndexWithSize.of("t", "i1", 1L), + IndexWithSize.of("t", "i2", 2L), + IndexWithSize.of("t", "i3", 3L), + IndexWithSize.of("t", "i4", 4L)) + .isUnmodifiable(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexTest.java index 13070fab..2f531603 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexTest.java @@ -22,41 +22,41 @@ class IndexTest { @Test void validation() { assertThatThrownBy(() -> Index.of(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> Index.of("t", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("indexName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("indexName cannot be null"); assertThatThrownBy(() -> Index.of("", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Index.of(" ", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Index.of("t", "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexName cannot be blank"); assertThatThrownBy(() -> Index.of("t", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexName cannot be blank"); } @Test void getTableAndIndexName() { final Index index = Index.of("t", "i"); assertThat(index) - .isNotNull(); + .isNotNull(); assertThat(index.getTableName()) - .isEqualTo("t"); + .isEqualTo("t"); assertThat(index.getIndexName()) - .isEqualTo("i") - .isEqualTo(index.getName()); + .isEqualTo("i") + .isEqualTo(index.getName()); } @Test void testToString() { assertThat(Index.of("t", "i")) - .hasToString("Index{tableName='t', indexName='i'}"); + .hasToString("Index{tableName='t', indexName='i'}"); } @SuppressWarnings("ConstantConditions") @@ -72,31 +72,31 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(Index.of("t1", "i1")) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(Index.class) - .verify(); + .verify(); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @@ -107,21 +107,21 @@ void compareToTest() { final Index third = Index.of("t2", "i2"); assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(Index.of("t1", "i1")) // the same - .isLessThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(Index.of("t1", "i1")) // the same + .isLessThan(second) + .isLessThan(third); assertThat(second) - .isGreaterThan(first) - .isLessThan(third); + .isGreaterThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithBloatTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithBloatTest.java index f655a569..bc1b1923 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithBloatTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithBloatTest.java @@ -22,10 +22,10 @@ class IndexWithBloatTest { void getBloatSizeInBytes() { final IndexWithBloat bloat = IndexWithBloat.of("t", "i", 10L, 2L, 20); assertThat(bloat.getIndexName()) - .isEqualTo("i") - .isEqualTo(bloat.getName()); + .isEqualTo("i") + .isEqualTo(bloat.getName()); assertThat(bloat.getBloatSizeInBytes()) - .isEqualTo(2L); + .isEqualTo(2L); } @Test @@ -37,20 +37,20 @@ void getBloatPercentage() { @Test void testToString() { assertThat(IndexWithBloat.of("t", "i", 2L, 1L, 50)) - .hasToString("IndexWithBloat{tableName='t', indexName='i', indexSizeInBytes=2, bloatSizeInBytes=1, bloatPercentage=50}"); + .hasToString("IndexWithBloat{tableName='t', indexName='i', indexSizeInBytes=2, bloatSizeInBytes=1, bloatPercentage=50}"); } @Test void withInvalidArguments() { assertThatThrownBy(() -> IndexWithBloat.of("t", "i", 0L, -1L, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("bloatSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("bloatSizeInBytes cannot be less than zero"); assertThatThrownBy(() -> IndexWithBloat.of("t", "i", 0L, 0L, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("bloatPercentage cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("bloatPercentage cannot be less than zero"); assertThatThrownBy(() -> IndexWithBloat.of("t", "i", -1L, 0L, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexSizeInBytes cannot be less than zero"); final IndexWithBloat bloat = IndexWithBloat.of("t", "i", 0L, 0L, 0); assertThat(bloat).isNotNull(); } @@ -69,37 +69,37 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another final Index anotherType = Index.of("t1", "i1"); assertThat(anotherType) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(IndexWithBloat.class) - .withIgnoredFields("indexSizeInBytes", "bloatSizeInBytes", "bloatPercentage") - .verify(); + .withIgnoredFields("indexSizeInBytes", "bloatSizeInBytes", "bloatPercentage") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithColumnsTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithColumnsTest.java index 55aaca23..61c661a8 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithColumnsTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithColumnsTest.java @@ -27,54 +27,54 @@ void gettersShouldWork() { final IndexWithColumns index = IndexWithColumns.ofSingle("t", "i", 11L, column); assertThat(index.getTableName()).isEqualTo("t"); assertThat(index.getIndexName()) - .isEqualTo("i") - .isEqualTo(index.getName()); + .isEqualTo("i") + .isEqualTo(index.getName()); assertThat(index.getIndexSizeInBytes()).isEqualTo(11L); assertThat(index.getColumns()) - .hasSize(1) - .isUnmodifiable() - .containsExactly(Column.ofNullable("t", "f")); + .hasSize(1) + .isUnmodifiable() + .containsExactly(Column.ofNullable("t", "f")); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> IndexWithColumns.ofColumns(null, null, 0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> IndexWithColumns.ofColumns("", null, 0, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> IndexWithColumns.ofColumns(" ", null, 0, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> IndexWithColumns.ofColumns("t", null, 0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("indexName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("indexName cannot be null"); assertThatThrownBy(() -> IndexWithColumns.ofColumns("t", "", 0, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexName cannot be blank"); assertThatThrownBy(() -> IndexWithColumns.ofSingle("t", "i", 0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("column cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("column cannot be null"); assertThatThrownBy(() -> IndexWithColumns.ofColumns("t", "i", 0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columns cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columns cannot be null"); } @Test void tableShouldBeTheSame() { final Column column = Column.ofNullable("t2", "f"); assertThatThrownBy(() -> IndexWithColumns.ofSingle("t", "i", 1L, column)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Table name is not the same within given rows"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name is not the same within given rows"); } @Test void testToString() { final Column column = Column.ofNullable("t", "f"); assertThat(IndexWithColumns.ofSingle("t", "i", 22L, column)) - .hasToString("IndexWithColumns{tableName='t', indexName='i', " + "indexSizeInBytes=22, columns=[Column{tableName='t', columnName='f', notNull=false}]}"); + .hasToString("IndexWithColumns{tableName='t', indexName='i', " + "indexSizeInBytes=22, columns=[Column{tableName='t', columnName='f', notNull=false}]}"); } @SuppressWarnings("ConstantConditions") @@ -85,8 +85,8 @@ void testEqualsAndHashCode() { final IndexWithColumns theSame = IndexWithColumns.ofSingle("t1", "i1", 3, column); // different size! final IndexWithColumns second = IndexWithColumns.ofSingle("t2", "i2", 2, Column.ofNotNull("t2", "f2")); final List columns = List.of( - Column.ofNullable("t3", "t"), - Column.ofNullable("t3", "f")); + Column.ofNullable("t3", "t"), + Column.ofNullable("t3", "f")); final IndexWithColumns third = IndexWithColumns.ofColumns("t3", "i3", 2, columns); assertThat(first.equals(null)).isFalse(); @@ -95,37 +95,37 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another final Index anotherType = Index.of("t1", "i1"); assertThat(anotherType) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(IndexWithColumns.class) - .withIgnoredFields("indexSizeInBytes", "columns") - .verify(); + .withIgnoredFields("indexSizeInBytes", "columns") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithNullsTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithNullsTest.java index 602f1d26..97dd45b2 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithNullsTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithNullsTest.java @@ -24,8 +24,8 @@ void gettersShouldWork() { final IndexWithNulls index = IndexWithNulls.of("t", "i", 11L, "f"); assertThat(index.getTableName()).isEqualTo("t"); assertThat(index.getIndexName()) - .isEqualTo("i") - .isEqualTo(index.getName()); + .isEqualTo("i") + .isEqualTo(index.getName()); assertThat(index.getIndexSizeInBytes()).isEqualTo(11L); assertThat(index.getNullableColumn()).isEqualTo(Column.ofNullable("t", "f")); } @@ -34,35 +34,35 @@ void gettersShouldWork() { @Test void withInvalidArguments() { assertThatThrownBy(() -> IndexWithNulls.of(null, null, 0, "f")) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> IndexWithNulls.of("", null, 0, "f")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> IndexWithNulls.of(" ", null, 0, "f")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> IndexWithNulls.of("t", null, 0, "f")) - .isInstanceOf(NullPointerException.class) - .hasMessage("indexName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("indexName cannot be null"); assertThatThrownBy(() -> IndexWithNulls.of("t", "", 0, "f")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexName cannot be blank"); assertThatThrownBy(() -> IndexWithNulls.of("t", "i", 0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("columnName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("columnName cannot be null"); assertThatThrownBy(() -> IndexWithNulls.of("t", "i", 0, "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); assertThatThrownBy(() -> IndexWithNulls.of("t", "i", 0, " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("columnName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("columnName cannot be blank"); } @Test void testToString() { assertThat(IndexWithNulls.of("t", "i", 22L, "f")) - .hasToString("IndexWithNulls{tableName='t', indexName='i', " + "indexSizeInBytes=22, columns=[Column{tableName='t', columnName='f', notNull=false}]}"); + .hasToString("IndexWithNulls{tableName='t', indexName='i', " + "indexSizeInBytes=22, columns=[Column{tableName='t', columnName='f', notNull=false}]}"); } @SuppressWarnings("ConstantConditions") @@ -79,37 +79,37 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another final Index anotherType = Index.of("t1", "i1"); assertThat(anotherType) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(IndexWithNulls.class) - .withIgnoredFields("indexSizeInBytes", "columns") - .verify(); + .withIgnoredFields("indexSizeInBytes", "columns") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithSizeTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithSizeTest.java index df6f1d1b..4f129988 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithSizeTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/IndexWithSizeTest.java @@ -22,8 +22,8 @@ class IndexWithSizeTest { void indexWithZeroSize() { final IndexWithSize index = IndexWithSize.of("t", "i", 0L); assertThat(index.getIndexName()) - .isEqualTo("i") - .isEqualTo(index.getName()); + .isEqualTo("i") + .isEqualTo(index.getName()); assertThat(index.getIndexSizeInBytes()).isZero(); } @@ -36,14 +36,14 @@ void indexWithPositiveSize() { @Test void indexWithNegativeSize() { assertThatThrownBy(() -> IndexWithSize.of("t", "i", -1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexSizeInBytes cannot be less than zero"); } @Test void testToString() { assertThat(IndexWithSize.of("t", "i", 33L)) - .hasToString("IndexWithSize{tableName='t', indexName='i', indexSizeInBytes=33}"); + .hasToString("IndexWithSize{tableName='t', indexName='i', indexSizeInBytes=33}"); } @SuppressWarnings("ConstantConditions") @@ -60,38 +60,38 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another final Index another = Index.of("t1", "i1"); assertThat(another) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(IndexWithSize.class) - .withIgnoredFields("indexSizeInBytes") - .verify(); + .withIgnoredFields("indexSizeInBytes") + .verify(); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @@ -103,21 +103,21 @@ void compareToTest() { final IndexWithSize third = IndexWithSize.of("t3", "i3", 22L); assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isLessThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isLessThan(second) + .isLessThan(third); assertThat(second) - .isGreaterThan(first) - .isLessThan(third); + .isGreaterThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/UnusedIndexTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/UnusedIndexTest.java index e4db4065..d135e3b5 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/UnusedIndexTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/UnusedIndexTest.java @@ -23,8 +23,8 @@ void getIndexScans() { final UnusedIndex index = UnusedIndex.of("t", "i", 1L, 2L); assertThat(index.getTableName()).isEqualTo("t"); assertThat(index.getIndexName()) - .isEqualTo("i") - .isEqualTo(index.getName()); + .isEqualTo("i") + .isEqualTo(index.getName()); assertThat(index.getIndexSizeInBytes()).isEqualTo(1L); assertThat(index.getIndexScans()).isEqualTo(2L); } @@ -32,17 +32,17 @@ void getIndexScans() { @Test void testToString() { assertThat(UnusedIndex.of("t", "i", 1L, 2L)) - .hasToString("UnusedIndex{tableName='t', indexName='i', " + "indexSizeInBytes=1, indexScans=2}"); + .hasToString("UnusedIndex{tableName='t', indexName='i', " + "indexSizeInBytes=1, indexScans=2}"); } @Test void indexWithNegativeScans() { assertThatThrownBy(() -> UnusedIndex.of("t", "i", -1L, 0L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexSizeInBytes cannot be less than zero"); assertThatThrownBy(() -> UnusedIndex.of("t", "i", 1L, -1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexScans cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexScans cannot be less than zero"); } @SuppressWarnings("ConstantConditions") @@ -59,37 +59,37 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another final Index anotherType = Index.of("t1", "i1"); assertThat(anotherType) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(UnusedIndex.class) - .withIgnoredFields("indexSizeInBytes", "indexScans") - .verify(); + .withIgnoredFields("indexSizeInBytes", "indexScans") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParserTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParserTest.java index ef827ffd..5bb8d7ae 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParserTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/index/utils/DuplicatedIndexesParserTest.java @@ -23,65 +23,65 @@ class DuplicatedIndexesParserTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(DuplicatedIndexesParser.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> DuplicatedIndexesParser.parseAsIndexNameAndSize(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("duplicatedAsString cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("duplicatedAsString cannot be null"); assertThatThrownBy(() -> DuplicatedIndexesParser.parseAsIndexNameAndSize("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("duplicatedAsString cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duplicatedAsString cannot be blank"); assertThatThrownBy(() -> DuplicatedIndexesParser.parseAsIndexNameAndSize(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("duplicatedAsString cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duplicatedAsString cannot be blank"); } @Test void withIncompleteString() { assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize("i")) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize("idx=i1, size=1")) - .isUnmodifiable() - .hasSize(1) - .contains(Map.entry("i1", 1L)); + .isUnmodifiable() + .hasSize(1) + .contains(Map.entry("i1", 1L)); assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize("idx=i2,size=3")) - .isUnmodifiable() - .hasSize(1) - .contains(Map.entry("i2", 3L)); + .isUnmodifiable() + .hasSize(1) + .contains(Map.entry("i2", 3L)); } @Test void withSpaces() { assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize(" idx=i2, size=3 ; idx=i3 , size=5 ")) - .isUnmodifiable() - .hasSize(2) - .containsExactly( - Map.entry("i2", 3L), - Map.entry("i3", 5L)); + .isUnmodifiable() + .hasSize(2) + .containsExactly( + Map.entry("i2", 3L), + Map.entry("i3", 5L)); } @Test void withWrongDataFormat() { assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize("idx=i2, input=3")) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); assertThat(DuplicatedIndexesParser.parseAsIndexNameAndSize("indx=i2, size=3")) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); } @Test void withWrongNumberFormat() { assertThatThrownBy(() -> DuplicatedIndexesParser.parseAsIndexNameAndSize("idx=i2, size=AB3")) - .isInstanceOf(NumberFormatException.class) - .hasMessage("For input string: \"AB3\""); + .isInstanceOf(NumberFormatException.class) + .hasMessage("For input string: \"AB3\""); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableTest.java index 7e588eae..c4eb0a7e 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableTest.java @@ -22,33 +22,33 @@ class TableTest { void getTableName() { final Table table = Table.of("t", 1L); assertThat(table.getTableName()) - .isEqualTo("t") - .isEqualTo(table.getName()); + .isEqualTo("t") + .isEqualTo(table.getName()); assertThat(table.getTableSizeInBytes()) - .isEqualTo(1L); + .isEqualTo(1L); } @SuppressWarnings("ConstantConditions") @Test void withInvalidValues() { assertThatThrownBy(() -> Table.of(null, 1L)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> Table.of("", 1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Table.of(" ", 1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> Table.of("t", -1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableSizeInBytes cannot be less than zero"); } @Test void testToString() { assertThat(Table.of("t", 2L)) - .hasToString("Table{tableName='t', tableSizeInBytes=2}"); + .hasToString("Table{tableName='t', tableSizeInBytes=2}"); } @SuppressWarnings("ConstantConditions") @@ -65,39 +65,39 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another implementation of Table final TableWithBloat another = TableWithBloat.of("t1", 23L, 11L, 50); //noinspection AssertBetweenInconvertibleTypes assertThat(another) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(Table.class) - .withIgnoredFields("tableSizeInBytes") - .verify(); + .withIgnoredFields("tableSizeInBytes") + .verify(); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @@ -109,21 +109,21 @@ void compareToTest() { final Table third = Table.of("t3", 22L); assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isLessThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isLessThan(second) + .isLessThan(third); assertThat(second) - .isGreaterThan(first) - .isLessThan(third); + .isGreaterThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithBloatTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithBloatTest.java index f36a28f2..59afbc34 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithBloatTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithBloatTest.java @@ -22,43 +22,43 @@ class TableWithBloatTest { void gettersShouldWork() { final TableWithBloat bloat = TableWithBloat.of("t1", 10L, 2L, 25); assertThat(bloat.getTableName()) - .isEqualTo("t1") - .isEqualTo(bloat.getName()); + .isEqualTo("t1") + .isEqualTo(bloat.getName()); assertThat(bloat.getTableSizeInBytes()) - .isEqualTo(10L); + .isEqualTo(10L); assertThat(bloat.getBloatSizeInBytes()) - .isEqualTo(2L); + .isEqualTo(2L); assertThat(bloat.getBloatPercentage()) - .isEqualTo(25); + .isEqualTo(25); } @Test void testToString() { assertThat(TableWithBloat.of("t", 2L, 1L, 50)) - .hasToString("TableWithBloat{tableName='t', tableSizeInBytes=2, bloatSizeInBytes=1, bloatPercentage=50}"); + .hasToString("TableWithBloat{tableName='t', tableSizeInBytes=2, bloatSizeInBytes=1, bloatPercentage=50}"); } @SuppressWarnings("ConstantConditions") @Test void withInvalidArguments() { assertThatThrownBy(() -> TableWithBloat.of(null, 0L, 0L, 0)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> TableWithBloat.of(null, 0L, 0)) - .isInstanceOf(NullPointerException.class) - .hasMessage("table cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("table cannot be null"); assertThatThrownBy(() -> TableWithBloat.of("t", 0L, -1L, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("bloatSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("bloatSizeInBytes cannot be less than zero"); assertThatThrownBy(() -> TableWithBloat.of("t", 0L, 0L, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("bloatPercentage cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("bloatPercentage cannot be less than zero"); assertThatThrownBy(() -> TableWithBloat.of("t", -1L, 0L, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableSizeInBytes cannot be less than zero"); assertThat(TableWithBloat.of("t", 0L, 0L, 0)) - .isNotNull(); + .isNotNull(); } @SuppressWarnings("ConstantConditions") @@ -76,39 +76,39 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); // another Table final Table anotherType = Table.of("t1", tableSize); //noinspection AssertBetweenInconvertibleTypes assertThat(anotherType) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(TableWithBloat.class) - .withIgnoredFields("bloatSizeInBytes", "bloatPercentage") - .verify(); + .withIgnoredFields("bloatSizeInBytes", "bloatPercentage") + .verify(); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @@ -121,21 +121,21 @@ void compareToTest() { final TableWithBloat third = TableWithBloat.of("t3", tableSize, 11L, 50); assertThatThrownBy(() -> first.compareTo(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("other cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("other cannot be null"); assertThat(first) - .isEqualByComparingTo(first) // self - .isEqualByComparingTo(theSame) // the same - .isLessThan(second) - .isLessThan(third); + .isEqualByComparingTo(first) // self + .isEqualByComparingTo(theSame) // the same + .isLessThan(second) + .isLessThan(third); assertThat(second) - .isGreaterThan(first) - .isLessThan(third); + .isGreaterThan(first) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(second); + .isGreaterThan(first) + .isGreaterThan(second); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithMissingIndexTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithMissingIndexTest.java index b9ec150c..d0734123 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithMissingIndexTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/table/TableWithMissingIndexTest.java @@ -22,46 +22,46 @@ class TableWithMissingIndexTest { void gettersShouldWork() { final TableWithMissingIndex table = TableWithMissingIndex.of("t", 1L, 2L, 3L); assertThat(table.getTableName()) - .isEqualTo("t") - .isEqualTo(table.getName()); + .isEqualTo("t") + .isEqualTo(table.getName()); assertThat(table.getTableSizeInBytes()) - .isEqualTo(1L); + .isEqualTo(1L); assertThat(table.getSeqScans()) - .isEqualTo(2L); + .isEqualTo(2L); assertThat(table.getIndexScans()) - .isEqualTo(3L); + .isEqualTo(3L); } @SuppressWarnings("ConstantConditions") @Test void invalidArguments() { assertThatThrownBy(() -> TableWithMissingIndex.of(null, 0, 0, 0)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> TableWithMissingIndex.of("", 0, 0, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> TableWithMissingIndex.of(" ", 0, 0, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableName cannot be blank"); assertThatThrownBy(() -> TableWithMissingIndex.of("t", -1, 0, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableSizeInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableSizeInBytes cannot be less than zero"); assertThatThrownBy(() -> TableWithMissingIndex.of("t", 0, -1, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("seqScans cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("seqScans cannot be less than zero"); assertThatThrownBy(() -> TableWithMissingIndex.of("t", 0, 0, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexScans cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexScans cannot be less than zero"); assertThatThrownBy(() -> TableWithMissingIndex.of(null, 0L, 0L)) - .isInstanceOf(NullPointerException.class) - .hasMessage("table cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("table cannot be null"); } @Test void testToString() { assertThat(TableWithMissingIndex.of("t", 11L, 33L, 22L)) - .hasToString("TableWithMissingIndex{tableName='t', tableSizeInBytes=11, seqScans=33, indexScans=22}"); + .hasToString("TableWithMissingIndex{tableName='t', tableSizeInBytes=11, seqScans=33, indexScans=22}"); } @SuppressWarnings("ConstantConditions") @@ -77,35 +77,35 @@ void testEqualsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(third) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first) - .isNotEqualTo(theSame) - .doesNotHaveSameHashCodeAs(theSame); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first) + .isNotEqualTo(theSame) + .doesNotHaveSameHashCodeAs(theSame); // another Table final TableWithBloat anotherType = TableWithBloat.of("t1", 4L, 11L, 50); //noinspection AssertBetweenInconvertibleTypes assertThat(anotherType) - .isNotEqualTo(first) - .hasSameHashCodeAs(first); + .isNotEqualTo(first) + .hasSameHashCodeAs(first); } @Test @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(TableWithMissingIndex.class) - .withIgnoredFields("seqScans", "indexScans") - .verify(); + .withIgnoredFields("seqScans", "indexScans") + .verify(); } @Test @@ -114,12 +114,12 @@ void compareToTest() { final TableWithMissingIndex theSame = TableWithMissingIndex.of("t1", 2L, 2, 3); final TableWithMissingIndex third = TableWithMissingIndex.of("t2", 3L, 4, 5); assertThat(first) - .isEqualByComparingTo(first) - .isEqualByComparingTo(theSame) - .isLessThan(third); + .isEqualByComparingTo(first) + .isEqualByComparingTo(theSame) + .isLessThan(third); assertThat(third) - .isGreaterThan(first) - .isGreaterThan(theSame); + .isGreaterThan(first) + .isGreaterThan(theSame); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/validation/ValidatorsTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/validation/ValidatorsTest.java index 411402ec..39ec2aa0 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/validation/ValidatorsTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/model/validation/ValidatorsTest.java @@ -21,28 +21,28 @@ class ValidatorsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(Validators.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void valueIsPositive() { assertThat(Validators.valueIsPositive(1L, "arg")) - .isEqualTo(1L); + .isEqualTo(1L); assertThatThrownBy(() -> Validators.valueIsPositive(0, "arg")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("arg should be greater than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("arg should be greater than zero"); } @SuppressWarnings("ConstantConditions") @Test void indexNameNotBlank() { assertThat(Validators.indexNameNotBlank("idx")) - .isEqualTo("idx"); + .isEqualTo("idx"); assertThatThrownBy(() -> Validators.indexNameNotBlank(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("indexName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("indexName cannot be null"); assertThatThrownBy(() -> Validators.indexNameNotBlank("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexName cannot be blank"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ImportantParamTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ImportantParamTest.java index aaa97ce1..dae7d0ac 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ImportantParamTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ImportantParamTest.java @@ -39,6 +39,6 @@ void uniquenessTest() { @Test void testToString() { assertThat(ImportantParam.MAINTENANCE_WORK_MEM) - .hasToString("ImportantParam{name='maintenance_work_mem', defaultValue='64MB'}"); + .hasToString("ImportantParam{name='maintenance_work_mem', defaultValue='64MB'}"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/PgParamImplTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/PgParamImplTest.java index d1d50abb..31ac7b4d 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/PgParamImplTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/PgParamImplTest.java @@ -31,17 +31,17 @@ void getNameAndValue() { @Test void withInvalidArguments() { assertThatThrownBy(() -> PgParamImpl.of(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("name cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("name cannot be null"); assertThatThrownBy(() -> PgParamImpl.of("", null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("name cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("name cannot be blank"); assertThatThrownBy(() -> PgParamImpl.of(" ", null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("name cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("name cannot be blank"); assertThatThrownBy(() -> PgParamImpl.of("param_name", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("value for 'param_name' cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("value for 'param_name' cannot be null"); } @Test @@ -58,7 +58,7 @@ void withEmptyValue() { @Test void testToString() { assertThat(PgParamImpl.of("statement_timeout", "2s")) - .hasToString("PgParamImpl{name='statement_timeout', value='2s'}"); + .hasToString("PgParamImpl{name='statement_timeout', value='2s'}"); } @SuppressWarnings("ConstantConditions") @@ -74,18 +74,18 @@ void equalsAndHashCode() { // self assertThat(first) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // the same assertThat(theSame) - .isEqualTo(first) - .hasSameHashCodeAs(first); + .isEqualTo(first) + .hasSameHashCodeAs(first); // others assertThat(second) - .isNotEqualTo(first) - .doesNotHaveSameHashCodeAs(first); + .isNotEqualTo(first) + .doesNotHaveSameHashCodeAs(first); // another implementation of PgParam final PgParam pgParamMock = Mockito.mock(PgParam.class); @@ -97,7 +97,7 @@ void equalsAndHashCode() { @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") void equalsHashCodeShouldAdhereContracts() { EqualsVerifier.forClass(PgParamImpl.class) - .withIgnoredFields("value") - .verify(); + .withIgnoredFields("value") + .verify(); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilderTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilderTest.java index 741240a0..1a91d850 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilderTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationBuilderTest.java @@ -21,11 +21,11 @@ class ServerSpecificationBuilderTest { void toStringTest() { final ServerSpecificationBuilder builder = ServerSpecification.builder(); assertThat(builder) - .hasToString("ServerSpecificationBuilder{cpuCoresAmount=1, memoryAmountInBytes=1073741824, hasSSD=false}"); + .hasToString("ServerSpecificationBuilder{cpuCoresAmount=1, memoryAmountInBytes=1073741824, hasSSD=false}"); builder.withCpuCores(2) - .withMemoryAmount(512, MemoryUnit.MB) - .withSSD(); + .withMemoryAmount(512, MemoryUnit.MB) + .withSSD(); assertThat(builder) - .hasToString("ServerSpecificationBuilder{cpuCoresAmount=2, memoryAmountInBytes=536870912, hasSSD=true}"); + .hasToString("ServerSpecificationBuilder{cpuCoresAmount=2, memoryAmountInBytes=536870912, hasSSD=true}"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationTest.java index e9e83a2b..f0ca5874 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/ServerSpecificationTest.java @@ -21,8 +21,8 @@ class ServerSpecificationTest { @Test void getCpuCoresAmount() { final ServerSpecification specification = ServerSpecification.builder() - .withCpuCores(2) - .build(); + .withCpuCores(2) + .build(); assertThat(specification).isNotNull(); assertThat(specification.getCpuCoresAmount()).isEqualTo(2); assertThat(specification.getMemoryAmountInBytes()).isEqualTo(1024L * 1024L * 1024L); @@ -30,18 +30,18 @@ void getCpuCoresAmount() { final ServerSpecificationBuilder serverSpecificationBuilder = ServerSpecification.builder(); assertThatThrownBy(() -> serverSpecificationBuilder.withCpuCores(0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("cpuCoresAmount should be greater than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("cpuCoresAmount should be greater than zero"); assertThatThrownBy(() -> serverSpecificationBuilder.withCpuCores(-1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("cpuCoresAmount should be greater than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("cpuCoresAmount should be greater than zero"); } @Test void getMemoryAmountInBytes() { final ServerSpecification specification = ServerSpecification.builder() - .withMemoryAmount(160, MemoryUnit.GB) - .build(); + .withMemoryAmount(160, MemoryUnit.GB) + .build(); assertThat(specification).isNotNull(); assertThat(specification.getCpuCoresAmount()).isEqualTo(1); assertThat(specification.getMemoryAmountInBytes()).isEqualTo(160L * 1024L * 1024L * 1024L); @@ -49,18 +49,18 @@ void getMemoryAmountInBytes() { final ServerSpecificationBuilder serverSpecificationBuilder = ServerSpecification.builder(); assertThatThrownBy(() -> serverSpecificationBuilder.withMemoryAmount(0, MemoryUnit.GB)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("unitsCount should be greater than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unitsCount should be greater than zero"); assertThatThrownBy(() -> serverSpecificationBuilder.withMemoryAmount(-1, MemoryUnit.GB)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("unitsCount should be greater than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("unitsCount should be greater than zero"); } @Test void hasSSD() { final ServerSpecification specification = ServerSpecification.builder() - .withSSD() - .build(); + .withSSD() + .build(); assertThat(specification).isNotNull(); assertThat(specification.getCpuCoresAmount()).isEqualTo(1); assertThat(specification.getMemoryAmountInBytes()).isEqualTo(1024L * 1024L * 1024L); @@ -70,6 +70,6 @@ void hasSSD() { @Test void toStringTest() { assertThat(ServerSpecification.builder().build()) - .hasToString("ServerSpecification{cpuCoresAmount=1, memoryAmountInBytes=1073741824, hasSSD=false}"); + .hasToString("ServerSpecification{cpuCoresAmount=1, memoryAmountInBytes=1073741824, hasSSD=false}"); } } diff --git a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/validation/ParamValidatorsTest.java b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/validation/ParamValidatorsTest.java index b5b92e6a..1cab6d23 100644 --- a/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/validation/ParamValidatorsTest.java +++ b/pg-index-health-model/src/test/java/io/github/mfvanek/pg/settings/validation/ParamValidatorsTest.java @@ -20,6 +20,6 @@ class ParamValidatorsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(ParamValidators.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } } diff --git a/pg-index-health-model/src/testFixtures/java/io/github/mfvanek/pg/support/TestUtils.java b/pg-index-health-model/src/testFixtures/java/io/github/mfvanek/pg/support/TestUtils.java index fec3b60e..60a5a43d 100644 --- a/pg-index-health-model/src/testFixtures/java/io/github/mfvanek/pg/support/TestUtils.java +++ b/pg-index-health-model/src/testFixtures/java/io/github/mfvanek/pg/support/TestUtils.java @@ -22,7 +22,7 @@ private TestUtils() { @SuppressWarnings("checkstyle:IllegalThrows") public static void invokePrivateConstructor(@Nonnull final Class type) - throws Throwable { + throws Throwable { final Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); diff --git a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolder.java b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolder.java index d04ef010..7b3db932 100644 --- a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolder.java +++ b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolder.java @@ -48,7 +48,7 @@ String getStandbyAlias() { @Nonnull Map createPrimaryEnvVarsMap( - @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder + @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder ) { final Map envVarsMap = createCommonEnvVarsMap(builder); envVarsMap.put("REPMGR_NODE_NAME", primaryAlias); @@ -58,7 +58,7 @@ Map createPrimaryEnvVarsMap( @Nonnull Map createStandbyEnvVarsMap( - @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder + @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder ) { final Map envVarsMap = createCommonEnvVarsMap(builder); envVarsMap.put("REPMGR_NODE_NAME", standbyAlias); @@ -69,20 +69,20 @@ Map createStandbyEnvVarsMap( @Nonnull WaitStrategy getWaitStrategyForPrimary() { return new LogMessageWaitStrategy() - .withRegEx(".*Starting repmgrd.*\\s") - .withStartupTimeout(STARTUP_TIMEOUT); + .withRegEx(".*Starting repmgrd.*\\s") + .withStartupTimeout(STARTUP_TIMEOUT); } @Nonnull WaitStrategy getWaitStrategyForStandBy() { return new LogMessageWaitStrategy() - .withRegEx(".*starting monitoring of node.*\\s") - .withStartupTimeout(STARTUP_TIMEOUT); + .withRegEx(".*starting monitoring of node.*\\s") + .withStartupTimeout(STARTUP_TIMEOUT); } @Nonnull private Map createCommonEnvVarsMap( - @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder + @Nonnull final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder ) { final Map envVarsMap = new HashMap<>(); envVarsMap.put("POSTGRESQL_POSTGRES_PASSWORD", "adminpassword"); diff --git a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapper.java b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapper.java index 1c2ecece..1133495b 100644 --- a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapper.java +++ b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapper.java @@ -53,33 +53,33 @@ public final class PostgreSqlClusterWrapper implements AutoCloseable { private PostgreSqlClusterWrapper(@Nonnull final PostgreSqlClusterBuilder builder) { this.pgVersion = builder.getPostgresVersion() != null ? - PostgresVersionHolder.forCluster(builder.getPostgresVersion()) : - PostgresVersionHolder.forCluster(); + PostgresVersionHolder.forCluster(builder.getPostgresVersion()) : + PostgresVersionHolder.forCluster(); this.network = Network.newNetwork(); final PostgreSqlClusterAliasHolder aliases = new PostgreSqlClusterAliasHolder(); // Primary node this.containerForPrimary = createContainerAndInitWith( - aliases.createPrimaryEnvVarsMap(builder), - aliases.getPrimaryAlias(), - aliases.getWaitStrategyForPrimary()); + aliases.createPrimaryEnvVarsMap(builder), + aliases.getPrimaryAlias(), + aliases.getWaitStrategyForPrimary()); // Standby node this.containerForStandBy = createContainerAndInitWith( - aliases.createStandbyEnvVarsMap(builder), - aliases.getStandbyAlias(), - aliases.getWaitStrategyForStandBy() + aliases.createStandbyEnvVarsMap(builder), + aliases.getStandbyAlias(), + aliases.getWaitStrategyForStandBy() ); this.containerForPrimary.start(); Awaitility.await("Ensure primary is ready") - .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) - .pollInterval(Duration.ofSeconds(1L)) - .until(() -> containerForPrimary.getLogs().contains("database system is ready to accept connections")); + .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) + .pollInterval(Duration.ofSeconds(1L)) + .until(() -> containerForPrimary.getLogs().contains("database system is ready to accept connections")); this.containerForStandBy.start(); Awaitility.await("Ensure cluster is ready") - .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) - .pollInterval(Duration.ofSeconds(1L)) - .until(() -> containerForStandBy.getLogs().contains("started streaming WAL from primary")); + .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) + .pollInterval(Duration.ofSeconds(1L)) + .until(() -> containerForStandBy.getLogs().contains("started streaming WAL from primary")); this.dataSourceForPrimary = PostgreSqlDataSourceHelper.buildDataSource(containerForPrimary); this.dataSourceForStandBy = PostgreSqlDataSourceHelper.buildDataSource(containerForStandBy); @@ -154,33 +154,33 @@ public boolean stopFirstContainer() { containerForPrimary.stop(); LOGGER.info("Waiting for standby will be promoted to primary"); Awaitility.await("Promoting standby to primary") - .atMost(WAIT_INTERVAL_SECONDS) - .pollInterval(Duration.ofSeconds(1L)) - .until(() -> containerForStandBy.getLogs().contains("promoting standby to primary")); + .atMost(WAIT_INTERVAL_SECONDS) + .pollInterval(Duration.ofSeconds(1L)) + .until(() -> containerForStandBy.getLogs().contains("promoting standby to primary")); Awaitility.await("Standby promoted to primary") - .atMost(WAIT_INTERVAL_SECONDS) - .pollInterval(Duration.ofSeconds(1L)) - .until(() -> containerForStandBy.getLogs().contains("standby promoted to primary after")); + .atMost(WAIT_INTERVAL_SECONDS) + .pollInterval(Duration.ofSeconds(1L)) + .until(() -> containerForStandBy.getLogs().contains("standby promoted to primary after")); return true; } @Nonnull private PostgresBitnamiRepmgrContainer createContainerAndInitWith( - final Map envVars, - final String alias, - final WaitStrategy waitStrategy + final Map envVars, + final String alias, + final WaitStrategy waitStrategy ) { final DockerImageName dockerImageName = DockerImageName.parse(IMAGE_NAME) - .withTag(pgVersion.getVersion()); + .withTag(pgVersion.getVersion()); //noinspection resource return new PostgresBitnamiRepmgrContainer(dockerImageName, envVars) //NOSONAR - .withCreateContainerCmdModifier(cmd -> cmd.withName(alias)) - .withSharedMemorySize(MemoryUnit.MB.convertToBytes(768)) - .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) - .withNetwork(network) - .withNetworkAliases(alias) - .withExposedPorts(5432) - .waitingFor(waitStrategy); + .withCreateContainerCmdModifier(cmd -> cmd.withName(alias)) + .withSharedMemorySize(MemoryUnit.MB.convertToBytes(768)) + .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) + .withNetwork(network) + .withNetworkAliases(alias) + .withExposedPorts(5432) + .waitingFor(waitStrategy); } @ExcludeFromJacocoGeneratedReport diff --git a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapper.java b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapper.java index e9860714..aec5c3ce 100644 --- a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapper.java +++ b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapper.java @@ -37,22 +37,22 @@ public final class PostgreSqlContainerWrapper implements AutoCloseable, Postgres this.pgVersion = Objects.requireNonNull(pgVersion, "pgVersion cannot be null"); //noinspection resource this.container = new PostgreSQLContainer<>(DockerImageName.parse("postgres") //NOSONAR - .withTag(pgVersion.getVersion())) - .withSharedMemorySize(MemoryUnit.MB.convertToBytes(512)) - .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) - .withCommand(prepareCommandParts(additionalParameters)) - .waitingFor(Wait.defaultWaitStrategy()); + .withTag(pgVersion.getVersion())) + .withSharedMemorySize(MemoryUnit.MB.convertToBytes(512)) + .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) + .withCommand(prepareCommandParts(additionalParameters)) + .waitingFor(Wait.defaultWaitStrategy()); this.container.start(); this.dataSource = PostgreSqlDataSourceHelper.buildDataSource(container); } PostgreSqlContainerWrapper(@Nonnull final PostgresVersionHolder pgVersion) { this(pgVersion, List.of( - Map.entry(ImportantParam.LOCK_TIMEOUT.getName(), "1000"), - Map.entry(ImportantParam.SHARED_BUFFERS.getName(), "256MB"), - Map.entry(ImportantParam.MAINTENANCE_WORK_MEM.getName(), "128MB"), - Map.entry(ImportantParam.WORK_MEM.getName(), "16MB"), - Map.entry(ImportantParam.RANDOM_PAGE_COST.getName(), "1") + Map.entry(ImportantParam.LOCK_TIMEOUT.getName(), "1000"), + Map.entry(ImportantParam.SHARED_BUFFERS.getName(), "256MB"), + Map.entry(ImportantParam.MAINTENANCE_WORK_MEM.getName(), "128MB"), + Map.entry(ImportantParam.WORK_MEM.getName(), "16MB"), + Map.entry(ImportantParam.RANDOM_PAGE_COST.getName(), "1") )); } @@ -73,8 +73,8 @@ public void close() { @Nonnull private static String[] prepareCommandParts(@Nonnull final List> additionalParameters) { return additionalParameters.stream() - .flatMap(kv -> Stream.of("-c", kv.getKey() + "=" + kv.getValue())) - .toArray(String[]::new); + .flatMap(kv -> Stream.of("-c", kv.getKey() + "=" + kv.getValue())) + .toArray(String[]::new); } @Nonnull diff --git a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainer.java b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainer.java index f7af1b94..c5755eee 100644 --- a/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainer.java +++ b/pg-index-health-testing/src/main/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainer.java @@ -44,12 +44,12 @@ public String getDriverClassName() { public String getJdbcUrl() { final String additionalUrlParams = constructUrlParameters("?", "&"); return PgUrlParser.URL_HEADER + - getHost() + - ":" + - getMappedPort(POSTGRESQL_PORT) + - "/" + - envVars.get("POSTGRESQL_DATABASE") + - additionalUrlParams; + getHost() + + ":" + + getMappedPort(POSTGRESQL_PORT) + + "/" + + envVars.get("POSTGRESQL_DATABASE") + + additionalUrlParams; } @Override diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolderTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolderTest.java index cac99c57..e76af1bc 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolderTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterAliasHolderTest.java @@ -22,28 +22,28 @@ class PostgreSqlClusterAliasHolderTest { void primaryAndStandbyNamesShouldDiffer() { final PostgreSqlClusterAliasHolder aliases = new PostgreSqlClusterAliasHolder(); assertThat(aliases) - .isNotNull() - .satisfies(a -> { - assertThat(a.getPrimaryAlias()) - .startsWith("pg-") - .endsWith("-0"); - assertThat(a.getStandbyAlias()) - .endsWith("-1") - .startsWith(a.getPrimaryAlias().substring(0, a.getPrimaryAlias().length() - 1)); - }); + .isNotNull() + .satisfies(a -> { + assertThat(a.getPrimaryAlias()) + .startsWith("pg-") + .endsWith("-0"); + assertThat(a.getStandbyAlias()) + .endsWith("-1") + .startsWith(a.getPrimaryAlias().substring(0, a.getPrimaryAlias().length() - 1)); + }); } @Test void shouldCreateEnvMaps() { final PostgreSqlClusterAliasHolder aliases = new PostgreSqlClusterAliasHolder(); final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder = PostgreSqlClusterWrapper.builder() - .withUsername("username") - .withPassword("any#pwd") - .withDatabaseName("test_db"); + .withUsername("username") + .withPassword("any#pwd") + .withDatabaseName("test_db"); assertThat(aliases) - .isNotNull() - .satisfies(a -> assertThat(a.createPrimaryEnvVarsMap(builder)) - .hasSize(14) - .hasSameSizeAs(a.createStandbyEnvVarsMap(builder))); + .isNotNull() + .satisfies(a -> assertThat(a.createPrimaryEnvVarsMap(builder)) + .hasSize(14) + .hasSameSizeAs(a.createStandbyEnvVarsMap(builder))); } } diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapperTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapperTest.java index 338a01a4..aaead5e9 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapperTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlClusterWrapperTest.java @@ -24,35 +24,35 @@ class PostgreSqlClusterWrapperTest { void shouldWork() { try (PostgreSqlClusterWrapper cluster = PostgreSqlClusterWrapper.builder().build()) { assertThat(cluster) - .isNotNull(); + .isNotNull(); assertThat(cluster.getDataSourceForPrimary()) - .isNotNull() - .isInstanceOf(BasicDataSource.class); + .isNotNull() + .isInstanceOf(BasicDataSource.class); assertThat(cluster.getDataSourceForStandBy()) - .isNotNull() - .isInstanceOf(BasicDataSource.class) - .isNotEqualTo(cluster.getDataSourceForPrimary()); + .isNotNull() + .isInstanceOf(BasicDataSource.class) + .isNotEqualTo(cluster.getDataSourceForPrimary()); assertThat(cluster.getFirstContainerJdbcUrl()) - .startsWith("jdbc:postgresql://"); + .startsWith("jdbc:postgresql://"); assertThat(cluster.getSecondContainerJdbcUrl()) - .startsWith("jdbc:postgresql://") - .isNotEqualTo(cluster.getFirstContainerJdbcUrl()); + .startsWith("jdbc:postgresql://") + .isNotEqualTo(cluster.getFirstContainerJdbcUrl()); assertThat(cluster.getCommonUrlToPrimary()) - .startsWith("jdbc:postgresql://") - .containsPattern("^.+/localhost:[0-9]{4,6},localhost:[0-9]{4,6}/.+$") - .endsWith("/customdatabase?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); + .startsWith("jdbc:postgresql://") + .containsPattern("^.+/localhost:[0-9]{4,6},localhost:[0-9]{4,6}/.+$") + .endsWith("/customdatabase?connectTimeout=1&hostRecheckSeconds=2&socketTimeout=600&targetServerType=primary"); } } @Test void stopFirstContainerShouldWork() { try (PostgreSqlClusterWrapper cluster = PostgreSqlClusterWrapper.builder().build(); - LogsCaptor logsCaptor = new LogsCaptor(PostgreSqlClusterWrapper.class)) { + LogsCaptor logsCaptor = new LogsCaptor(PostgreSqlClusterWrapper.class)) { assertThat(cluster.stopFirstContainer()) - .isTrue(); + .isTrue(); assertThat(logsCaptor.getLogs()) - .hasSizeGreaterThanOrEqualTo(1) - .anyMatch(l -> l.getMessage().contains("Waiting for standby will be promoted to primary")); + .hasSizeGreaterThanOrEqualTo(1) + .anyMatch(l -> l.getMessage().contains("Waiting for standby will be promoted to primary")); } } @@ -60,49 +60,49 @@ void stopFirstContainerShouldWork() { void builderWithDefaultFields() { try (PostgreSqlClusterWrapper cluster = PostgreSqlClusterWrapper.builder().build()) { assertThat(cluster) - .satisfies(it -> { - assertThat(it.getUsername()).isEqualTo("customuser"); - assertThat(it.getPassword()).isEqualTo("custompassword"); - assertThat(it.getFirstContainerJdbcUrl()).contains("/customdatabase"); - assertThat(it.getSecondContainerJdbcUrl()).contains("/customdatabase"); - }); + .satisfies(it -> { + assertThat(it.getUsername()).isEqualTo("customuser"); + assertThat(it.getPassword()).isEqualTo("custompassword"); + assertThat(it.getFirstContainerJdbcUrl()).contains("/customdatabase"); + assertThat(it.getSecondContainerJdbcUrl()).contains("/customdatabase"); + }); } } @Test void builderWithCustomFields() { try (PostgreSqlClusterWrapper cluster = PostgreSqlClusterWrapper.builder() - .withUsername("user") - .withPassword("password") - .withDatabaseName("test_db_with_repmgr") - .build()) { + .withUsername("user") + .withPassword("password") + .withDatabaseName("test_db_with_repmgr") + .build()) { assertThat(cluster) - .satisfies(it -> { - assertThat(it.getUsername()).isEqualTo("user"); - assertThat(it.getPassword()).isEqualTo("password"); - assertThat(it.getFirstContainerJdbcUrl()).contains("/test_db_with_repmgr"); - assertThat(it.getSecondContainerJdbcUrl()).contains("/test_db_with_repmgr"); - }); + .satisfies(it -> { + assertThat(it.getUsername()).isEqualTo("user"); + assertThat(it.getPassword()).isEqualTo("password"); + assertThat(it.getFirstContainerJdbcUrl()).contains("/test_db_with_repmgr"); + assertThat(it.getSecondContainerJdbcUrl()).contains("/test_db_with_repmgr"); + }); } } @Test void builderWithForcedVersion() { final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder = PostgreSqlClusterWrapper.builder() - .withUsername("user") - .withPassword("password") - .withDatabaseName("test_db_with_repmgr") - .withPostgresVersion("14.7"); + .withUsername("user") + .withPassword("password") + .withDatabaseName("test_db_with_repmgr") + .withPostgresVersion("14.7"); assertThat(builder.getPostgresVersion()) - .isEqualTo("14.7"); + .isEqualTo("14.7"); try (PostgreSqlClusterWrapper cluster = builder.build()) { assertThat(cluster) - .satisfies(it -> { - assertThat(it.getUsername()).isEqualTo("user"); - assertThat(it.getPassword()).isEqualTo("password"); - assertThat(it.getFirstContainerJdbcUrl()).contains("/test_db_with_repmgr"); - assertThat(it.getSecondContainerJdbcUrl()).contains("/test_db_with_repmgr"); - }); + .satisfies(it -> { + assertThat(it.getUsername()).isEqualTo("user"); + assertThat(it.getPassword()).isEqualTo("password"); + assertThat(it.getFirstContainerJdbcUrl()).contains("/test_db_with_repmgr"); + assertThat(it.getSecondContainerJdbcUrl()).contains("/test_db_with_repmgr"); + }); final String actualPgVersionString = PostgresVersionReader.readVersion(cluster.getDataSourceForPrimary()); assertThat(actualPgVersionString).startsWith("14.7"); } @@ -113,16 +113,16 @@ void builderWithForcedVersion() { void builderWithInvalidArgs() { final PostgreSqlClusterWrapper.PostgreSqlClusterBuilder builder = PostgreSqlClusterWrapper.builder(); assertThatThrownBy(() -> builder.withUsername(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("username cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("username cannot be null"); assertThatThrownBy(() -> builder.withPassword(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("password cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("password cannot be null"); assertThatThrownBy(() -> builder.withDatabaseName(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("databaseName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("databaseName cannot be null"); assertThatThrownBy(() -> builder.withPostgresVersion(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("postgresVersion cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("postgresVersion cannot be null"); } } diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapperTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapperTest.java index acf1fb5f..bfb70c75 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapperTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlContainerWrapperTest.java @@ -22,20 +22,20 @@ class PostgreSqlContainerWrapperTest { void withDefaultVersionShouldWork() { try (PostgreSqlContainerWrapper container = PostgreSqlContainerWrapper.withDefaultVersion()) { assertThat(container) - .isNotNull() - .satisfies(c -> { - assertThat(c.getDataSource()) - .isNotNull() - .isInstanceOf(BasicDataSource.class); - assertThat(c.getPort()) - .isPositive(); - assertThat(c.getUrl()) - .startsWith("jdbc:postgresql://"); - assertThat(c.getUsername()) - .isNotBlank(); - assertThat(c.getPassword()) - .isNotBlank(); - }); + .isNotNull() + .satisfies(c -> { + assertThat(c.getDataSource()) + .isNotNull() + .isInstanceOf(BasicDataSource.class); + assertThat(c.getPort()) + .isPositive(); + assertThat(c.getUrl()) + .startsWith("jdbc:postgresql://"); + assertThat(c.getUsername()) + .isNotBlank(); + assertThat(c.getPassword()) + .isNotBlank(); + }); } } @@ -43,26 +43,26 @@ void withDefaultVersionShouldWork() { void withVersionShouldWork() { try (PostgreSqlContainerWrapper container = PostgreSqlContainerWrapper.withVersion("16.2")) { assertThat(container) - .isNotNull() - .satisfies(c -> { - assertThat(c.getDataSource()) - .isNotNull() - .isInstanceOf(BasicDataSource.class); - assertThat(c.getPort()) - .isPositive(); - assertThat(c.getUrl()) - .startsWith("jdbc:postgresql://"); - assertThat(c.getUsername()) - .isNotBlank(); - assertThat(c.getPassword()) - .isNotBlank(); - assertThat(c.isProceduresSupported()) - .isTrue(); - assertThat(c.isOutParametersInProcedureSupported()) - .isTrue(); - assertThat(c.isCumulativeStatisticsSystemSupported()) - .isTrue(); - }); + .isNotNull() + .satisfies(c -> { + assertThat(c.getDataSource()) + .isNotNull() + .isInstanceOf(BasicDataSource.class); + assertThat(c.getPort()) + .isPositive(); + assertThat(c.getUrl()) + .startsWith("jdbc:postgresql://"); + assertThat(c.getUsername()) + .isNotBlank(); + assertThat(c.getPassword()) + .isNotBlank(); + assertThat(c.isProceduresSupported()) + .isTrue(); + assertThat(c.isOutParametersInProcedureSupported()) + .isTrue(); + assertThat(c.isCumulativeStatisticsSystemSupported()) + .isTrue(); + }); } } @@ -70,7 +70,7 @@ void withVersionShouldWork() { @Test void shouldThrowExceptionWhenVersionIsNull() { assertThatThrownBy(() -> PostgreSqlContainerWrapper.withVersion(null)) //NOSONAR - .isInstanceOf(NullPointerException.class) - .hasMessage("pgVersion cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgVersion cannot be null"); } } diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlDataSourceHelperTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlDataSourceHelperTest.java index 831559a7..2361a023 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlDataSourceHelperTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgreSqlDataSourceHelperTest.java @@ -26,7 +26,7 @@ class PostgreSqlDataSourceHelperTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(PostgreSqlDataSourceHelper.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test @@ -38,13 +38,13 @@ void buildDataSourceShouldUseFieldsFromTestcontainer() { when(container.getDriverClassName()).thenReturn("some postgresql driver"); assertThat(PostgreSqlDataSourceHelper.buildDataSource(container)) - .isNotNull() - .satisfies(ds -> { - assertThat(ds.getUrl()).isEqualTo("test url"); - assertThat(ds.getUsername()).isEqualTo("some user name"); - assertThat(ds.getPassword()).isEqualTo("test password"); - assertThat(ds.getDriverClassName()).isEqualTo("some postgresql driver"); - }); + .isNotNull() + .satisfies(ds -> { + assertThat(ds.getUrl()).isEqualTo("test url"); + assertThat(ds.getUsername()).isEqualTo("some user name"); + assertThat(ds.getPassword()).isEqualTo("test password"); + assertThat(ds.getDriverClassName()).isEqualTo("some postgresql driver"); + }); } } } diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainerTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainerTest.java index 0f2cd296..0bf7a892 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainerTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresBitnamiRepmgrContainerTest.java @@ -29,27 +29,27 @@ class PostgresBitnamiRepmgrContainerTest { void containerShouldWork() { final PostgreSqlClusterAliasHolder aliasHolder = new PostgreSqlClusterAliasHolder(); try (PostgresBitnamiRepmgrContainer container = new PostgresBitnamiRepmgrContainer( - prepareDockerImageName(), aliasHolder.createPrimaryEnvVarsMap(PostgreSqlClusterWrapper.builder())) - .withCreateContainerCmdModifier(cmd -> cmd.withName(aliasHolder.getPrimaryAlias())) - .withSharedMemorySize(MemoryUnit.MB.convertToBytes(768)) - .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) - .withNetwork(Network.newNetwork()) - .withNetworkAliases(aliasHolder.getPrimaryAlias()) - .withExposedPorts(5432) - .waitingFor(aliasHolder.getWaitStrategyForPrimary())) { + prepareDockerImageName(), aliasHolder.createPrimaryEnvVarsMap(PostgreSqlClusterWrapper.builder())) + .withCreateContainerCmdModifier(cmd -> cmd.withName(aliasHolder.getPrimaryAlias())) + .withSharedMemorySize(MemoryUnit.MB.convertToBytes(768)) + .withTmpFs(Map.of("/var/lib/postgresql/data", "rw")) + .withNetwork(Network.newNetwork()) + .withNetworkAliases(aliasHolder.getPrimaryAlias()) + .withExposedPorts(5432) + .waitingFor(aliasHolder.getWaitStrategyForPrimary())) { container.start(); Awaitility.await("Ensure container is ready") - .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) - .pollInterval(Duration.ofSeconds(1L)) - .until(() -> container.getLogs().contains("database system is ready to accept connections")); + .atMost(PostgreSqlClusterAliasHolder.STARTUP_TIMEOUT) + .pollInterval(Duration.ofSeconds(1L)) + .until(() -> container.getLogs().contains("database system is ready to accept connections")); assertThat(container) - .isNotNull() - .satisfies(c -> { - assertThat(c.getTestQueryString()).isEqualTo("SELECT 1"); - assertThat(c.getDriverClassName()).isEqualTo("org.postgresql.Driver"); - assertThat(c.getJdbcUrl()).startsWith("jdbc:postgresql://"); - }); + .isNotNull() + .satisfies(c -> { + assertThat(c.getTestQueryString()).isEqualTo("SELECT 1"); + assertThat(c.getDriverClassName()).isEqualTo("org.postgresql.Driver"); + assertThat(c.getJdbcUrl()).startsWith("jdbc:postgresql://"); + }); } } @@ -60,13 +60,13 @@ void testEqualsAndHashCode() { try (PostgresBitnamiRepmgrContainer first = new PostgresBitnamiRepmgrContainer(prepareDockerImageName(), aliasHolder.createPrimaryEnvVarsMap(builder)); PostgresBitnamiRepmgrContainer second = new PostgresBitnamiRepmgrContainer(prepareDockerImageName(), aliasHolder.createStandbyEnvVarsMap(builder))) { assertThat(first) - .isNotNull() - .isNotEqualTo(null) - .isEqualTo(first) - .isNotEqualTo(BigDecimal.ONE) - .doesNotHaveSameHashCodeAs(aliasHolder.createPrimaryEnvVarsMap(builder)) - .isNotEqualTo(second) - .doesNotHaveSameHashCodeAs(second); + .isNotNull() + .isNotEqualTo(null) + .isEqualTo(first) + .isNotEqualTo(BigDecimal.ONE) + .doesNotHaveSameHashCodeAs(aliasHolder.createPrimaryEnvVarsMap(builder)) + .isNotEqualTo(second) + .doesNotHaveSameHashCodeAs(second); } } @@ -74,6 +74,6 @@ void testEqualsAndHashCode() { private DockerImageName prepareDockerImageName() { final PostgresVersionHolder versionHolder = PostgresVersionHolder.forCluster(); return DockerImageName.parse("docker.io/bitnami/postgresql-repmgr") - .withTag(versionHolder.getVersion()); + .withTag(versionHolder.getVersion()); } } diff --git a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresVersionHolderTest.java b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresVersionHolderTest.java index 88791e28..67a9efa9 100644 --- a/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresVersionHolderTest.java +++ b/pg-index-health-testing/src/test/java/io/github/mfvanek/pg/testing/PostgresVersionHolderTest.java @@ -23,64 +23,64 @@ class PostgresVersionHolderTest { @Test void shouldThrowExceptionForInvalidVersion() { assertThatThrownBy(() -> new PostgresVersionHolder(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgVersion cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgVersion cannot be null"); } @Test void oldPostgresVersionsSupportNothing() { assertThat(new PostgresVersionHolder("9.6.24")) - .isNotNull() - .satisfies(v -> { - assertThat(v.getVersion()).isEqualTo("9.6.24"); - assertThat(v.isOutParametersInProcedureSupported()).isFalse(); - assertThat(v.isProceduresSupported()).isFalse(); - assertThat(v.isCumulativeStatisticsSystemSupported()).isFalse(); - }); + .isNotNull() + .satisfies(v -> { + assertThat(v.getVersion()).isEqualTo("9.6.24"); + assertThat(v.isOutParametersInProcedureSupported()).isFalse(); + assertThat(v.isProceduresSupported()).isFalse(); + assertThat(v.isCumulativeStatisticsSystemSupported()).isFalse(); + }); } @Test void newPostgresVersionsSupportEverything() { assertThat(new PostgresVersionHolder("15.1")) - .isNotNull() - .satisfies(v -> { - assertThat(v.getVersion()).isEqualTo("15.1"); - assertThat(v.isOutParametersInProcedureSupported()).isTrue(); - assertThat(v.isProceduresSupported()).isTrue(); - assertThat(v.isCumulativeStatisticsSystemSupported()).isTrue(); - }); + .isNotNull() + .satisfies(v -> { + assertThat(v.getVersion()).isEqualTo("15.1"); + assertThat(v.isOutParametersInProcedureSupported()).isTrue(); + assertThat(v.isProceduresSupported()).isTrue(); + assertThat(v.isCumulativeStatisticsSystemSupported()).isTrue(); + }); } @Test void outParametersNotSupported() { assertThat(new PostgresVersionHolder("13.4.1")) - .isNotNull() - .satisfies(v -> { - assertThat(v.getVersion()).isEqualTo("13.4.1"); - assertThat(v.isOutParametersInProcedureSupported()).isFalse(); - assertThat(v.isProceduresSupported()).isTrue(); - assertThat(v.isCumulativeStatisticsSystemSupported()).isFalse(); - }); + .isNotNull() + .satisfies(v -> { + assertThat(v.getVersion()).isEqualTo("13.4.1"); + assertThat(v.isOutParametersInProcedureSupported()).isFalse(); + assertThat(v.isProceduresSupported()).isTrue(); + assertThat(v.isCumulativeStatisticsSystemSupported()).isFalse(); + }); } @Test void forClusterShouldBeBitnamiAware() { final PostgresVersionHolder versionHolder = PostgresVersionHolder.forCluster(); assertThat(versionHolder) - .isNotNull() - .satisfies(v -> { - assertThat(v.getVersion()).endsWith(".0"); - assertThat(v.getVersion().chars() - .mapToObj(c -> (char) c) - .filter(c -> c == '.')) - .hasSize(2); - }); + .isNotNull() + .satisfies(v -> { + assertThat(v.getVersion()).endsWith(".0"); + assertThat(v.getVersion().chars() + .mapToObj(c -> (char) c) + .filter(c -> c == '.')) + .hasSize(2); + }); if (System.getenv("TEST_PG_VERSION") != null) { assertThat(versionHolder.getVersion()) - .isEqualTo(System.getenv("TEST_PG_VERSION").split("-")[0] + ".0"); + .isEqualTo(System.getenv("TEST_PG_VERSION").split("-")[0] + ".0"); } else { assertThat(versionHolder.getVersion()) - .isEqualTo("16.2.0"); + .isEqualTo("16.2.0"); } } @@ -88,29 +88,29 @@ void forClusterShouldBeBitnamiAware() { void forClusterShouldUseForcedVersionWhenSet() { final PostgresVersionHolder versionHolder = PostgresVersionHolder.forCluster("14.3"); assertThat(versionHolder) - .isNotNull() - .satisfies(v -> { - assertThat(v.getVersion()).endsWith(".0"); - assertThat(v.getVersion().chars() - .mapToObj(c -> (char) c) - .filter(c -> c == '.')) - .hasSize(2); - }); + .isNotNull() + .satisfies(v -> { + assertThat(v.getVersion()).endsWith(".0"); + assertThat(v.getVersion().chars() + .mapToObj(c -> (char) c) + .filter(c -> c == '.')) + .hasSize(2); + }); assertThat(versionHolder.getVersion()) - .isEqualTo("14.3.0"); + .isEqualTo("14.3.0"); } @Test void forSingleNodeShouldBeEnvAware() { final PostgresVersionHolder versionHolder = PostgresVersionHolder.forSingleNode(); assertThat(versionHolder) - .isNotNull(); + .isNotNull(); if (System.getenv("TEST_PG_VERSION") != null) { assertThat(versionHolder.getVersion()) - .isEqualTo(System.getenv("TEST_PG_VERSION")); + .isEqualTo(System.getenv("TEST_PG_VERSION")); } else { assertThat(versionHolder.getVersion()) - .isEqualTo("16.2"); + .isEqualTo("16.2"); } } @@ -118,16 +118,16 @@ void forSingleNodeShouldBeEnvAware() { void forSingleNodeShouldBeAbleToForceVersion() { final PostgresVersionHolder versionHolder = PostgresVersionHolder.forSingleNode("345.678"); assertThat(versionHolder) - .isNotNull(); + .isNotNull(); assertThat(versionHolder.getVersion()) - .isEqualTo("345.678"); + .isEqualTo("345.678"); } @Test void toBitnamiVersionShouldSkipSuffix() { assertThat(PostgresVersionHolder.toBitnamiVersion("15.4")) - .isEqualTo("15.4.0"); + .isEqualTo("15.4.0"); assertThat(PostgresVersionHolder.toBitnamiVersion("14.5-alpine3.17")) - .isEqualTo("14.5.0"); + .isEqualTo("14.5.0"); } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnCluster.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnCluster.java index b057f164..28d38760 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnCluster.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnCluster.java @@ -36,7 +36,6 @@ * An abstract class for all database checks performed on entire cluster. * * @param represents an object in a database associated with a table - * * @author Ivan Vakhrushev * @since 0.6.0 */ @@ -116,8 +115,8 @@ private List executeOnPrimary(@Nonnull final PgContext pgContext, @Nonnull fi final DatabaseCheckOnHost checkOnPrimary = computeCheckForPrimaryIfNeed(); LOGGER.debug("Going to execute on primary host {}", checkOnPrimary.getHost().getName()); return checkOnPrimary.check(pgContext).stream() - .filter(exclusionsFilter) - .collect(Collectors.toList()); + .filter(exclusionsFilter) + .collect(Collectors.toList()); } @Nonnull @@ -129,9 +128,9 @@ private List executeOnCluster(@Nonnull final PgContext pgContext, @Nonnull fi acrossClusterResults.add(resultsFromHost); } return acrossClusterResultsMapper.apply(acrossClusterResults) - .stream() - .filter(exclusionsFilter) - .collect(Collectors.toList()); + .stream() + .filter(exclusionsFilter) + .collect(Collectors.toList()); } @Nonnull diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnCluster.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnCluster.java index 53a3abcd..dd4a1333 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnCluster.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnCluster.java @@ -39,10 +39,10 @@ public TablesWithMissingIndexesCheckOnCluster(@Nonnull final HighAvailabilityPgC static List getResultAsUnion(@Nonnull final List> tablesWithMissingIndexesFromAllHosts) { LOGGER.debug("tablesWithMissingIndexesFromAllHosts = {}", tablesWithMissingIndexesFromAllHosts); final List result = tablesWithMissingIndexesFromAllHosts.stream() - .flatMap(Collection::stream) - .distinct() - .sorted() - .collect(Collectors.toList()); + .flatMap(Collection::stream) + .distinct() + .sorted() + .collect(Collectors.toList()); LOGGER.debug("Union result {}", result); return result; } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnCluster.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnCluster.java index 909b6150..143290ff 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnCluster.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnCluster.java @@ -65,7 +65,7 @@ private void logLastStatsResetDate(@Nonnull final PgConnection connectionToHost) @Nonnull static List getResultAsIntersection( - @Nonnull final List> potentiallyUnusedIndexesFromAllHosts) { + @Nonnull final List> potentiallyUnusedIndexesFromAllHosts) { LOGGER.debug("potentiallyUnusedIndexesFromAllHosts = {}", potentiallyUnusedIndexesFromAllHosts); Collection unusedIndexes = null; for (final List unusedIndexesFromHost : potentiallyUnusedIndexesFromAllHosts) { @@ -87,7 +87,7 @@ static String getLastStatsResetDateLogMessage(@Nonnull final StatisticsMaintenan if (statsResetTimestamp.isPresent()) { final long daysBetween = ChronoUnit.DAYS.between(statsResetTimestamp.get(), OffsetDateTime.now(ClockHolder.clock())); return String.format("Last statistics reset on this host was %d days ago (%s)", - daysBetween, statsResetTimestamp.get()); + daysBetween, statsResetTimestamp.get()); } return "Statistics have never been reset on this host"; } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHost.java index bb07eefe..7c0b2bc4 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHost.java @@ -29,7 +29,6 @@ * An abstract class for all database checks performed on a specific host. * * @param represents an object in a database associated with a table - * * @author Ivan Vahrushev * @since 0.6.0 */ diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHost.java index 583758c2..3bc2185d 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHost.java @@ -35,10 +35,9 @@ public ColumnsWithJsonTypeCheckOnHost(@Nonnull final PgConnection pgConnection) * Returns columns with json type in the specified schema. * These are candidates for conversion to the {@code jsonb} type. * - * @see JSON Types - * * @param pgContext check's context with the specified schema * @return list of columns with json type + * @see JSON Types */ @Nonnull @Override diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHost.java index 35e88ad6..7c29d6a7 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHost.java @@ -34,10 +34,9 @@ public ColumnsWithoutDescriptionCheckOnHost(@Nonnull final PgConnection pgConnec /** * Returns columns without description (comment) in the specified schema. * - * @see SQL Commands - COMMENT - * * @param pgContext check's context with the specified schema * @return list of columns without description + * @see SQL Commands - COMMENT */ @Nonnull @Override diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHost.java index b88ae0f8..f3042749 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHost.java @@ -34,10 +34,9 @@ public TablesWithoutDescriptionCheckOnHost(@Nonnull final PgConnection pgConnect /** * Returns tables without description (comment) in the specified schema. * - * @see SQL Commands - COMMENT - * * @param pgContext check's context with the specified schema * @return list of tables without description + * @see SQL Commands - COMMENT */ @Nonnull @Override diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByBloat.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByBloat.java index 415157bf..d10dd1da 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByBloat.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByBloat.java @@ -34,6 +34,6 @@ protected AbstractFilterByBloat(final long sizeThresholdInBytes, final int perce protected boolean isOk(@Nonnull final BloatAware bloatAware) { return bloatAware.getBloatSizeInBytes() >= sizeThresholdInBytes && - bloatAware.getBloatPercentage() >= percentageThreshold; + bloatAware.getBloatPercentage() >= percentageThreshold; } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByName.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByName.java index 518af36c..69a4bd43 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByName.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/AbstractFilterByName.java @@ -31,9 +31,9 @@ abstract class AbstractFilterByName { protected AbstractFilterByName(@Nonnull final Collection exclusions) { this.exclusions = Objects.requireNonNull(exclusions, "exclusions cannot be null") - .stream() - .map(s -> s.toLowerCase(Locale.ROOT)) - .collect(Collectors.toUnmodifiableSet()); + .stream() + .map(s -> s.toLowerCase(Locale.ROOT)) + .collect(Collectors.toUnmodifiableSet()); } protected AbstractFilterByName(@Nonnull final String objectName) { diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicate.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicate.java index f1f80536..3c6d9121 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicate.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicate.java @@ -39,8 +39,8 @@ public boolean test(@Nonnull final DuplicatedIndexes duplicatedIndexes) { return true; } return duplicatedIndexes.getIndexNames().stream() - .map(n -> n.toLowerCase(Locale.ROOT)) - .noneMatch(exclusions::contains); + .map(n -> n.toLowerCase(Locale.ROOT)) + .noneMatch(exclusions::contains); } @Nonnull diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicate.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicate.java index 294b5585..ade7e4d0 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicate.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicate.java @@ -19,8 +19,8 @@ * Allows filter tables by their size. * * @author Ivan Vakhrushev - * @since 0.6.0 * @see TableSizeAware + * @since 0.6.0 */ public class FilterTablesBySizePredicate extends AbstractFilterBySize implements Predicate { diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/AbstractHealthLogger.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/AbstractHealthLogger.java index 467b2fe7..6ba15b6c 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/AbstractHealthLogger.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/AbstractHealthLogger.java @@ -113,7 +113,7 @@ private String writeZeroToLog(@Nonnull final LoggingKey key) { private String logInvalidIndexes(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.INVALID_INDEXES, Index.class), - c -> true, pgContext, SimpleLoggingKey.INVALID_INDEXES); + c -> true, pgContext, SimpleLoggingKey.INVALID_INDEXES); } @Nonnull @@ -121,7 +121,7 @@ private String logDuplicatedIndexes(@Nonnull final DatabaseChecks databaseChecks @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.DUPLICATED_INDEXES, DuplicatedIndexes.class), - FilterDuplicatedIndexesByNamePredicate.of(exclusions.getDuplicatedIndexesExclusions()), pgContext, SimpleLoggingKey.DUPLICATED_INDEXES); + FilterDuplicatedIndexesByNamePredicate.of(exclusions.getDuplicatedIndexesExclusions()), pgContext, SimpleLoggingKey.DUPLICATED_INDEXES); } @Nonnull @@ -129,7 +129,7 @@ private String logIntersectedIndexes(@Nonnull final DatabaseChecks databaseCheck @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.INTERSECTED_INDEXES, DuplicatedIndexes.class), - FilterDuplicatedIndexesByNamePredicate.of(exclusions.getIntersectedIndexesExclusions()), pgContext, SimpleLoggingKey.INTERSECTED_INDEXES); + FilterDuplicatedIndexesByNamePredicate.of(exclusions.getIntersectedIndexesExclusions()), pgContext, SimpleLoggingKey.INTERSECTED_INDEXES); } @Nonnull @@ -137,15 +137,15 @@ private String logUnusedIndexes(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.UNUSED_INDEXES, UnusedIndex.class), - FilterIndexesBySizePredicate.of(exclusions.getIndexSizeThresholdInBytes()) - .and(FilterIndexesByNamePredicate.of(exclusions.getUnusedIndexesExclusions())), pgContext, SimpleLoggingKey.UNUSED_INDEXES); + FilterIndexesBySizePredicate.of(exclusions.getIndexSizeThresholdInBytes()) + .and(FilterIndexesByNamePredicate.of(exclusions.getUnusedIndexesExclusions())), pgContext, SimpleLoggingKey.UNUSED_INDEXES); } @Nonnull private String logForeignKeysNotCoveredWithIndex(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.FOREIGN_KEYS_WITHOUT_INDEX, ForeignKey.class), - c -> true, pgContext, SimpleLoggingKey.FOREIGN_KEYS_WITHOUT_INDEX); + c -> true, pgContext, SimpleLoggingKey.FOREIGN_KEYS_WITHOUT_INDEX); } @Nonnull @@ -153,8 +153,8 @@ private String logTablesWithMissingIndexes(@Nonnull final DatabaseChecks databas @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.TABLES_WITH_MISSING_INDEXES, TableWithMissingIndex.class), - FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes()) - .and(FilterTablesByNamePredicate.of(exclusions.getTablesWithMissingIndexesExclusions())), pgContext, SimpleLoggingKey.TABLES_WITH_MISSING_INDEXES); + FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes()) + .and(FilterTablesByNamePredicate.of(exclusions.getTablesWithMissingIndexesExclusions())), pgContext, SimpleLoggingKey.TABLES_WITH_MISSING_INDEXES); } @Nonnull @@ -162,8 +162,8 @@ private String logTablesWithoutPrimaryKey(@Nonnull final DatabaseChecks database @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.TABLES_WITHOUT_PRIMARY_KEY, Table.class), - FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes()) - .and(FilterTablesByNamePredicate.of(exclusions.getTablesWithoutPrimaryKeyExclusions())), pgContext, SimpleLoggingKey.TABLES_WITHOUT_PRIMARY_KEY); + FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes()) + .and(FilterTablesByNamePredicate.of(exclusions.getTablesWithoutPrimaryKeyExclusions())), pgContext, SimpleLoggingKey.TABLES_WITHOUT_PRIMARY_KEY); } @Nonnull @@ -171,7 +171,7 @@ private String logIndexesWithNullValues(@Nonnull final DatabaseChecks databaseCh @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.INDEXES_WITH_NULL_VALUES, IndexWithNulls.class), - FilterIndexesByNamePredicate.of(exclusions.getIndexesWithNullValuesExclusions()), pgContext, SimpleLoggingKey.INDEXES_WITH_NULL_VALUES); + FilterIndexesByNamePredicate.of(exclusions.getIndexesWithNullValuesExclusions()), pgContext, SimpleLoggingKey.INDEXES_WITH_NULL_VALUES); } @Nonnull @@ -179,8 +179,8 @@ private String logIndexesBloat(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.BLOATED_INDEXES, IndexWithBloat.class), - FilterIndexesByBloatPredicate.of(exclusions.getIndexBloatSizeThresholdInBytes(), exclusions.getIndexBloatPercentageThreshold()) - .and(FilterIndexesBySizePredicate.of(exclusions.getIndexSizeThresholdInBytes())), pgContext, SimpleLoggingKey.BLOATED_INDEXES); + FilterIndexesByBloatPredicate.of(exclusions.getIndexBloatSizeThresholdInBytes(), exclusions.getIndexBloatPercentageThreshold()) + .and(FilterIndexesBySizePredicate.of(exclusions.getIndexSizeThresholdInBytes())), pgContext, SimpleLoggingKey.BLOATED_INDEXES); } @Nonnull @@ -188,64 +188,64 @@ private String logTablesBloat(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.BLOATED_TABLES, TableWithBloat.class), - FilterTablesByBloatPredicate.of(exclusions.getTableBloatSizeThresholdInBytes(), exclusions.getTableBloatPercentageThreshold()) - .and(FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes())), pgContext, SimpleLoggingKey.BLOATED_TABLES); + FilterTablesByBloatPredicate.of(exclusions.getTableBloatSizeThresholdInBytes(), exclusions.getTableBloatPercentageThreshold()) + .and(FilterTablesBySizePredicate.of(exclusions.getTableSizeThresholdInBytes())), pgContext, SimpleLoggingKey.BLOATED_TABLES); } @Nonnull private String logTablesWithoutDescription(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.TABLES_WITHOUT_DESCRIPTION, Table.class), - c -> true, pgContext, SimpleLoggingKey.TABLES_WITHOUT_DESCRIPTION); + c -> true, pgContext, SimpleLoggingKey.TABLES_WITHOUT_DESCRIPTION); } @Nonnull private String logColumnsWithoutDescription(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.COLUMNS_WITHOUT_DESCRIPTION, Column.class), - c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITHOUT_DESCRIPTION); + c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITHOUT_DESCRIPTION); } @Nonnull private String logColumnsWithJsonType(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.COLUMNS_WITH_JSON_TYPE, Column.class), - c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITH_JSON_TYPE); + c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITH_JSON_TYPE); } @Nonnull private String logColumnsWithSerialTypes(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.COLUMNS_WITH_SERIAL_TYPES, ColumnWithSerialType.class), - c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITH_SERIAL_TYPES); + c -> true, pgContext, SimpleLoggingKey.COLUMNS_WITH_SERIAL_TYPES); } @Nonnull private String logFunctionsWithoutDescription(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.FUNCTIONS_WITHOUT_DESCRIPTION, StoredFunction.class), - c -> true, pgContext, SimpleLoggingKey.FUNCTIONS_WITHOUT_DESCRIPTION); + c -> true, pgContext, SimpleLoggingKey.FUNCTIONS_WITHOUT_DESCRIPTION); } @Nonnull private String logIndexesWithBoolean(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.INDEXES_WITH_BOOLEAN, IndexWithColumns.class), - c -> true, pgContext, SimpleLoggingKey.INDEXES_WITH_BOOLEAN); + c -> true, pgContext, SimpleLoggingKey.INDEXES_WITH_BOOLEAN); } private String logBtreeIndexesOnArrayColumns(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final Exclusions exclusions, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.BTREE_INDEXES_ON_ARRAY_COLUMNS, Index.class), - FilterIndexesByNamePredicate.of(exclusions.getBtreeIndexesOnArrayColumnsExclusions()), pgContext, SimpleLoggingKey.BTREE_INDEXES_ON_ARRAY_COLUMNS); + FilterIndexesByNamePredicate.of(exclusions.getBtreeIndexesOnArrayColumnsExclusions()), pgContext, SimpleLoggingKey.BTREE_INDEXES_ON_ARRAY_COLUMNS); } @Nonnull private String logNotValidConstraints(@Nonnull final DatabaseChecks databaseChecks, @Nonnull final PgContext pgContext) { return logCheckResult(databaseChecks.getCheck(Diagnostic.NOT_VALID_CONSTRAINTS, Constraint.class), - c -> true, pgContext, SimpleLoggingKey.NOT_VALID_CONSTRAINTS); + c -> true, pgContext, SimpleLoggingKey.NOT_VALID_CONSTRAINTS); } @Nonnull diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/Exclusions.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/Exclusions.java index 0448db9d..2da889f0 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/Exclusions.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/Exclusions.java @@ -64,17 +64,17 @@ public class Exclusions { this.indexesWithNullValuesExclusions = prepareExclusions(indexesWithNullValuesExclusions); this.btreeIndexesOnArrayColumnsExclusions = prepareExclusions(btreeIndexesOnArrayColumnsExclusions); this.indexSizeThresholdInBytes = Validators.sizeNotNegative( - indexSizeThresholdInBytes, "indexSizeThresholdInBytes"); + indexSizeThresholdInBytes, "indexSizeThresholdInBytes"); this.tableSizeThresholdInBytes = Validators.sizeNotNegative( - tableSizeThresholdInBytes, "tableSizeThresholdInBytes"); + tableSizeThresholdInBytes, "tableSizeThresholdInBytes"); this.indexBloatSizeThresholdInBytes = Validators.sizeNotNegative( - indexBloatSizeThresholdInBytes, "indexBloatSizeThresholdInBytes"); + indexBloatSizeThresholdInBytes, "indexBloatSizeThresholdInBytes"); this.indexBloatPercentageThreshold = AdditionalValidators.validPercent( - indexBloatPercentageThreshold, "indexBloatPercentageThreshold"); + indexBloatPercentageThreshold, "indexBloatPercentageThreshold"); this.tableBloatSizeThresholdInBytes = Validators.sizeNotNegative( - tableBloatSizeThresholdInBytes, "tableBloatSizeThresholdInBytes"); + tableBloatSizeThresholdInBytes, "tableBloatSizeThresholdInBytes"); this.tableBloatPercentageThreshold = AdditionalValidators.validPercent( - tableBloatPercentageThreshold, "tableBloatPercentageThreshold"); + tableBloatPercentageThreshold, "tableBloatPercentageThreshold"); } private static Set prepareExclusions(@Nonnull final String rawExclusions) { @@ -157,20 +157,20 @@ public int getTableBloatPercentageThreshold() { @Override public String toString() { return Exclusions.class.getSimpleName() + '{' + - "duplicatedIndexesExclusions=" + duplicatedIndexesExclusions + - ", intersectedIndexesExclusions=" + intersectedIndexesExclusions + - ", unusedIndexesExclusions=" + unusedIndexesExclusions + - ", tablesWithMissingIndexesExclusions=" + tablesWithMissingIndexesExclusions + - ", tablesWithoutPrimaryKeyExclusions=" + tablesWithoutPrimaryKeyExclusions + - ", indexesWithNullValuesExclusions=" + indexesWithNullValuesExclusions + - ", btreeIndexesOnArrayColumnsExclusions=" + btreeIndexesOnArrayColumnsExclusions + - ", indexSizeThresholdInBytes=" + indexSizeThresholdInBytes + - ", tableSizeThresholdInBytes=" + tableSizeThresholdInBytes + - ", indexBloatSizeThresholdInBytes=" + indexBloatSizeThresholdInBytes + - ", indexBloatPercentageThreshold=" + indexBloatPercentageThreshold + - ", tableBloatSizeThresholdInBytes=" + tableBloatSizeThresholdInBytes + - ", tableBloatPercentageThreshold=" + tableBloatPercentageThreshold + - '}'; + "duplicatedIndexesExclusions=" + duplicatedIndexesExclusions + + ", intersectedIndexesExclusions=" + intersectedIndexesExclusions + + ", unusedIndexesExclusions=" + unusedIndexesExclusions + + ", tablesWithMissingIndexesExclusions=" + tablesWithMissingIndexesExclusions + + ", tablesWithoutPrimaryKeyExclusions=" + tablesWithoutPrimaryKeyExclusions + + ", indexesWithNullValuesExclusions=" + indexesWithNullValuesExclusions + + ", btreeIndexesOnArrayColumnsExclusions=" + btreeIndexesOnArrayColumnsExclusions + + ", indexSizeThresholdInBytes=" + indexSizeThresholdInBytes + + ", tableSizeThresholdInBytes=" + tableSizeThresholdInBytes + + ", indexBloatSizeThresholdInBytes=" + indexBloatSizeThresholdInBytes + + ", indexBloatPercentageThreshold=" + indexBloatPercentageThreshold + + ", tableBloatSizeThresholdInBytes=" + tableBloatSizeThresholdInBytes + + ", tableBloatPercentageThreshold=" + tableBloatPercentageThreshold + + '}'; } /** diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilder.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilder.java index 568331b5..9f45b78a 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilder.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilder.java @@ -82,7 +82,7 @@ public ExclusionsBuilder withUnusedIndexesExclusions(@Nonnull final String unuse } public ExclusionsBuilder withTablesWithMissingIndexesExclusions( - @Nonnull final String tablesWithMissingIndexesExclusions) { + @Nonnull final String tablesWithMissingIndexesExclusions) { this.tablesWithMissingIndexesExclusions = Objects.requireNonNull(tablesWithMissingIndexesExclusions); return this; } @@ -104,79 +104,79 @@ public ExclusionsBuilder withBtreeIndexesOnArrayColumnsExclusions(@Nonnull final public ExclusionsBuilder withIndexSizeThreshold(final long indexSizeThresholdInBytes) { this.indexSizeThresholdInBytes = Validators.sizeNotNegative( - indexSizeThresholdInBytes, "indexSizeThresholdInBytes"); + indexSizeThresholdInBytes, "indexSizeThresholdInBytes"); return this; } public ExclusionsBuilder withIndexSizeThreshold(final int thresholdUnitsCount, final MemoryUnit unit) { final long indexSizeInBytes = unit.convertToBytes( - Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); + Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); return withIndexSizeThreshold(indexSizeInBytes); } public ExclusionsBuilder withTableSizeThreshold(final long tableSizeThresholdInBytes) { this.tableSizeThresholdInBytes = Validators.sizeNotNegative( - tableSizeThresholdInBytes, "tableSizeThresholdInBytes"); + tableSizeThresholdInBytes, "tableSizeThresholdInBytes"); return this; } public ExclusionsBuilder withTableSizeThreshold(final int thresholdUnitsCount, final MemoryUnit unit) { final long tableSizeInBytes = unit.convertToBytes( - Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); + Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); return withTableSizeThreshold(tableSizeInBytes); } public ExclusionsBuilder withIndexBloatSizeThreshold(final long indexBloatSizeThresholdInBytes) { this.indexBloatSizeThresholdInBytes = Validators.sizeNotNegative(indexBloatSizeThresholdInBytes, - "indexBloatSizeThresholdInBytes"); + "indexBloatSizeThresholdInBytes"); return this; } public ExclusionsBuilder withIndexBloatSizeThreshold(final int thresholdUnitsCount, final MemoryUnit unit) { final long indexBloatSizeInBytes = unit.convertToBytes( - Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); + Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); return withIndexBloatSizeThreshold(indexBloatSizeInBytes); } public ExclusionsBuilder withIndexBloatPercentageThreshold(final int indexBloatPercentageThreshold) { this.indexBloatPercentageThreshold = AdditionalValidators.validPercent( - indexBloatPercentageThreshold, "indexBloatPercentageThreshold"); + indexBloatPercentageThreshold, "indexBloatPercentageThreshold"); return this; } public ExclusionsBuilder withTableBloatSizeThreshold(final long tableBloatSizeThresholdInBytes) { this.tableBloatSizeThresholdInBytes = Validators.sizeNotNegative( - tableBloatSizeThresholdInBytes, "tableBloatSizeThresholdInBytes"); + tableBloatSizeThresholdInBytes, "tableBloatSizeThresholdInBytes"); return this; } public ExclusionsBuilder withTableBloatSizeThreshold(final int thresholdUnitsCount, final MemoryUnit unit) { final long tableBloatSizeInBytes = unit.convertToBytes( - Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); + Validators.argumentNotNegative(thresholdUnitsCount, THRESHOLD_UNITS_COUNT)); return withTableBloatSizeThreshold(tableBloatSizeInBytes); } public ExclusionsBuilder withTableBloatPercentageThreshold(final int tableBloatPercentageThreshold) { this.tableBloatPercentageThreshold = AdditionalValidators.validPercent( - tableBloatPercentageThreshold, "tableBloatPercentageThreshold"); + tableBloatPercentageThreshold, "tableBloatPercentageThreshold"); return this; } public Exclusions build() { return new Exclusions( - duplicatedIndexesExclusions, - intersectedIndexesExclusions, - unusedIndexesExclusions, - tablesWithMissingIndexesExclusions, - tablesWithoutPrimaryKeyExclusions, - indexesWithNullValuesExclusions, - btreeIndexesOnArrayColumnsExclusions, - indexSizeThresholdInBytes, - tableSizeThresholdInBytes, - indexBloatSizeThresholdInBytes, - indexBloatPercentageThreshold, - tableBloatSizeThresholdInBytes, - tableBloatPercentageThreshold); + duplicatedIndexesExclusions, + intersectedIndexesExclusions, + unusedIndexesExclusions, + tablesWithMissingIndexesExclusions, + tablesWithoutPrimaryKeyExclusions, + indexesWithNullValuesExclusions, + btreeIndexesOnArrayColumnsExclusions, + indexSizeThresholdInBytes, + tableSizeThresholdInBytes, + indexBloatSizeThresholdInBytes, + indexBloatPercentageThreshold, + tableBloatSizeThresholdInBytes, + tableBloatPercentageThreshold); } /** @@ -186,19 +186,19 @@ public Exclusions build() { @Override public String toString() { return ExclusionsBuilder.class.getSimpleName() + '{' + - "duplicatedIndexesExclusions='" + duplicatedIndexesExclusions + '\'' + - ", intersectedIndexesExclusions='" + intersectedIndexesExclusions + '\'' + - ", unusedIndexesExclusions='" + unusedIndexesExclusions + '\'' + - ", tablesWithMissingIndexesExclusions='" + tablesWithMissingIndexesExclusions + '\'' + - ", tablesWithoutPrimaryKeyExclusions='" + tablesWithoutPrimaryKeyExclusions + '\'' + - ", indexesWithNullValuesExclusions='" + indexesWithNullValuesExclusions + '\'' + - ", btreeIndexesOnArrayColumnsExclusions='" + btreeIndexesOnArrayColumnsExclusions + '\'' + - ", indexSizeThresholdInBytes=" + indexSizeThresholdInBytes + - ", tableSizeThresholdInBytes=" + tableSizeThresholdInBytes + - ", indexBloatSizeThresholdInBytes=" + indexBloatSizeThresholdInBytes + - ", indexBloatPercentageThreshold=" + indexBloatPercentageThreshold + - ", tableBloatSizeThresholdInBytes=" + tableBloatSizeThresholdInBytes + - ", tableBloatPercentageThreshold=" + tableBloatPercentageThreshold + - '}'; + "duplicatedIndexesExclusions='" + duplicatedIndexesExclusions + '\'' + + ", intersectedIndexesExclusions='" + intersectedIndexesExclusions + '\'' + + ", unusedIndexesExclusions='" + unusedIndexesExclusions + '\'' + + ", tablesWithMissingIndexesExclusions='" + tablesWithMissingIndexesExclusions + '\'' + + ", tablesWithoutPrimaryKeyExclusions='" + tablesWithoutPrimaryKeyExclusions + '\'' + + ", indexesWithNullValuesExclusions='" + indexesWithNullValuesExclusions + '\'' + + ", btreeIndexesOnArrayColumnsExclusions='" + btreeIndexesOnArrayColumnsExclusions + '\'' + + ", indexSizeThresholdInBytes=" + indexSizeThresholdInBytes + + ", tableSizeThresholdInBytes=" + tableSizeThresholdInBytes + + ", indexBloatSizeThresholdInBytes=" + indexBloatSizeThresholdInBytes + + ", indexBloatPercentageThreshold=" + indexBloatPercentageThreshold + + ", tableBloatSizeThresholdInBytes=" + tableBloatSizeThresholdInBytes + + ", tableBloatPercentageThreshold=" + tableBloatPercentageThreshold + + '}'; } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/KeyValueFileHealthLogger.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/KeyValueFileHealthLogger.java index d72d3a30..7b2b3ee4 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/KeyValueFileHealthLogger.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/health/logger/KeyValueFileHealthLogger.java @@ -62,6 +62,6 @@ protected String writeToLog(@Nonnull final LoggingKey key, final int value) { @Nonnull private String format(@Nonnull final String keyName, @Nonnull final String subKeyName, final int value) { return DateTimeFormatter.ISO_INSTANT.format( - ZonedDateTime.now(ClockHolder.clock())) + "\t" + keyName + "\t" + subKeyName + "\t" + value; + ZonedDateTime.now(ClockHolder.clock())) + "\t" + keyName + "\t" + subKeyName + "\t" + value; } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnCluster.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnCluster.java index 7a8e3d72..65d652cd 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnCluster.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnCluster.java @@ -24,15 +24,15 @@ * * @param any database object associated with a table (table itself, index, column, constraint) * @author Ivan Vahrushev - * @since 0.6.0 * @see DbObject + * @since 0.6.0 */ public interface DatabaseCheckOnCluster extends DiagnosticAware, RawTypeAware { /** * Executes the check in the specified schema. * - * @param pgContext check's context with the specified schema + * @param pgContext check's context with the specified schema * @param exclusionsFilter predicate to filter out unnecessary results * @return list of deviations from the specified rule * @see PgContext @@ -66,15 +66,15 @@ default List check() { /** * Executes the check in the specified schemas. * - * @param pgContexts a set of contexts specifying schemas + * @param pgContexts a set of contexts specifying schemas * @param exclusionsFilter predicate to filter out unnecessary results * @return list of deviations from the specified rule */ @Nonnull default List check(@Nonnull final Collection pgContexts, @Nonnull final Predicate exclusionsFilter) { return pgContexts.stream() - .map(ctx -> check(ctx, exclusionsFilter)) - .flatMap(List::stream) - .collect(Collectors.toList()); + .map(ctx -> check(ctx, exclusionsFilter)) + .flatMap(List::stream) + .collect(Collectors.toList()); } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnHost.java index 03467a9d..fb49b01d 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnHost.java @@ -21,10 +21,9 @@ * A check on database structure on a specific host. * * @param represents an object in a database associated with a table - * * @author Ivan Vahrushev - * @since 0.6.0 * @see DbObject + * @since 0.6.0 */ public interface DatabaseCheckOnHost extends DiagnosticAware, RawTypeAware, HostAware { diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecks.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecks.java index ed828261..24caa03b 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecks.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecks.java @@ -45,24 +45,24 @@ public class DatabaseChecks { public DatabaseChecks(@Nonnull final HighAvailabilityPgConnection haPgConnection) { final Stream> allChecks = Stream.of( - new TablesWithBloatCheckOnCluster(haPgConnection), - new TablesWithMissingIndexesCheckOnCluster(haPgConnection), - new TablesWithoutPrimaryKeyCheckOnCluster(haPgConnection), - new DuplicatedIndexesCheckOnCluster(haPgConnection), - new ForeignKeysNotCoveredWithIndexCheckOnCluster(haPgConnection), - new IndexesWithBloatCheckOnCluster(haPgConnection), - new IndexesWithNullValuesCheckOnCluster(haPgConnection), - new IntersectedIndexesCheckOnCluster(haPgConnection), - new InvalidIndexesCheckOnCluster(haPgConnection), - new UnusedIndexesCheckOnCluster(haPgConnection), - new TablesWithoutDescriptionCheckOnCluster(haPgConnection), - new ColumnsWithoutDescriptionCheckOnCluster(haPgConnection), - new ColumnsWithJsonTypeCheckOnCluster(haPgConnection), - new ColumnsWithSerialTypesCheckOnCluster(haPgConnection), - new FunctionsWithoutDescriptionCheckOnCluster(haPgConnection), - new IndexesWithBooleanCheckOnCluster(haPgConnection), - new NotValidConstraintsCheckOnCluster(haPgConnection), - new BtreeIndexesOnArrayColumnsCheckOnCluster(haPgConnection) + new TablesWithBloatCheckOnCluster(haPgConnection), + new TablesWithMissingIndexesCheckOnCluster(haPgConnection), + new TablesWithoutPrimaryKeyCheckOnCluster(haPgConnection), + new DuplicatedIndexesCheckOnCluster(haPgConnection), + new ForeignKeysNotCoveredWithIndexCheckOnCluster(haPgConnection), + new IndexesWithBloatCheckOnCluster(haPgConnection), + new IndexesWithNullValuesCheckOnCluster(haPgConnection), + new IntersectedIndexesCheckOnCluster(haPgConnection), + new InvalidIndexesCheckOnCluster(haPgConnection), + new UnusedIndexesCheckOnCluster(haPgConnection), + new TablesWithoutDescriptionCheckOnCluster(haPgConnection), + new ColumnsWithoutDescriptionCheckOnCluster(haPgConnection), + new ColumnsWithJsonTypeCheckOnCluster(haPgConnection), + new ColumnsWithSerialTypesCheckOnCluster(haPgConnection), + new FunctionsWithoutDescriptionCheckOnCluster(haPgConnection), + new IndexesWithBooleanCheckOnCluster(haPgConnection), + new NotValidConstraintsCheckOnCluster(haPgConnection), + new BtreeIndexesOnArrayColumnsCheckOnCluster(haPgConnection) ); allChecks.forEach(check -> this.checks.putIfAbsent(check.getDiagnostic(), check)); } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/Diagnostic.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/Diagnostic.java index bfdef3f1..65de7284 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/Diagnostic.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/Diagnostic.java @@ -51,8 +51,8 @@ public enum Diagnostic { * Creates a {@code Diagnostic} instance. * * @param executionTopology the place where the diagnostic should be executed - * @param sqlQueryFileName the associated sql query file name - * @param queryExecutor the lambda which executes the associated sql query + * @param sqlQueryFileName the associated sql query file name + * @param queryExecutor the lambda which executes the associated sql query */ Diagnostic(@Nonnull final ExecutionTopology executionTopology, @Nonnull final String sqlQueryFileName, diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/QueryExecutor.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/QueryExecutor.java index 59abe634..16fc886f 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/QueryExecutor.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/QueryExecutor.java @@ -21,8 +21,8 @@ * An abstraction of sql query executor. * * @author Ivan Vahrushev - * @since 0.6.0 * @see DbObject + * @since 0.6.0 */ @FunctionalInterface public interface QueryExecutor { diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/RawTypeAware.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/RawTypeAware.java index d19c0ef4..cdd728e9 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/RawTypeAware.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/RawTypeAware.java @@ -18,7 +18,6 @@ * Allows getting information about original generic type. * * @param represents an object in a database associated with a table - * * @author Ivan Vakhrushev * @since 0.6.0 */ diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/ResultSetExtractor.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/ResultSetExtractor.java index 08af0426..88f9eeb0 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/ResultSetExtractor.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/maintenance/ResultSetExtractor.java @@ -18,7 +18,6 @@ * A mapper from raw data to domain model. * * @param any type represents an object in a database - * * @author Ivan Vahrushev */ @FunctionalInterface diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagement.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagement.java index 267f77a1..a86e3bed 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagement.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagement.java @@ -26,8 +26,8 @@ public interface DatabaseManagement extends StatisticsAware, ConfigurationAware * It is safe running this method on your database. * It just reset counters without any impact on performance. * - * @see StatisticsMaintenanceOnHost * @return true if the operation is successful + * @see StatisticsMaintenanceOnHost */ @Override boolean resetStatistics(); diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagementImpl.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagementImpl.java index e0facce5..4ddf0177 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagementImpl.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/common/management/DatabaseManagementImpl.java @@ -77,21 +77,21 @@ public boolean resetStatistics() { @Nonnull public Optional getLastStatsResetTimestamp() { return computeStatisticsForHostIfNeed(getPrimaryAngLog()) - .getLastStatsResetTimestamp(); + .getLastStatsResetTimestamp(); } @Override @Nonnull public Set getParamsWithDefaultValues(@Nonnull final ServerSpecification specification) { return computeConfigurationForHostIfNeed(getPrimaryAngLog()) - .getParamsWithDefaultValues(specification); + .getParamsWithDefaultValues(specification); } @Override @Nonnull public Set getParamsCurrentValues() { return computeConfigurationForHostIfNeed(getPrimaryAngLog()) - .getParamsCurrentValues(); + .getParamsCurrentValues(); } @Nonnull diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImpl.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImpl.java index 89a0df96..b45b05ac 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImpl.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImpl.java @@ -69,7 +69,7 @@ public Set getParamsCurrentValues() { return PgParamImpl.of(paramName, currentValue); }); return params.stream() - .collect(Collectors.toUnmodifiableSet()); + .collect(Collectors.toUnmodifiableSet()); } @Override diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/StatisticsAware.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/StatisticsAware.java index 6ced62d2..3b159060 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/StatisticsAware.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/StatisticsAware.java @@ -26,8 +26,8 @@ public interface StatisticsAware { *

* Note: superuser privileges are required. * - * @see Monitoring Database Activity * @return true if the operation is successful + * @see Monitoring Database Activity */ boolean resetStatistics(); diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHost.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHost.java index 5faa81f3..36d7d4cd 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHost.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHost.java @@ -30,8 +30,8 @@ public interface StatisticsMaintenanceOnHost extends StatisticsAware, HostAware *

* Note: superuser privileges are required. * - * @see Monitoring Database Activity * @return true if the operation is successful + * @see Monitoring Database Activity */ @Override boolean resetStatistics(); diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImpl.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImpl.java index 36d82e37..05442dc2 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImpl.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImpl.java @@ -64,7 +64,7 @@ public boolean resetStatistics() { public Optional getLastStatsResetTimestamp() { final String query = "select stats_reset from pg_stat_database where datname = current_database()"; final List statsResetTimes = queryExecutor.executeQuery(pgConnection, query, - rs -> rs.getObject(1, OffsetDateTime.class)); + rs -> rs.getObject(1, OffsetDateTime.class)); return Optional.ofNullable(statsResetTimes.get(0)); } } diff --git a/pg-index-health/src/main/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParser.java b/pg-index-health/src/main/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParser.java index 583522ed..28cd6a08 100644 --- a/pg-index-health/src/main/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParser.java +++ b/pg-index-health/src/main/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParser.java @@ -33,8 +33,8 @@ public static List parseRawColumnData(@Nonnull final String tableName, @ throw new IllegalArgumentException("Columns array cannot be empty"); } return Arrays.stream(rawColumns) - .map(c -> toColumn(tableName, c)) - .collect(Collectors.toUnmodifiableList()); + .map(c -> toColumn(tableName, c)) + .collect(Collectors.toUnmodifiableList()); } @Nonnull diff --git a/pg-index-health/src/main/resources b/pg-index-health/src/main/resources index 0292369a..62f46cda 160000 --- a/pg-index-health/src/main/resources +++ b/pg-index-health/src/main/resources @@ -1 +1 @@ -Subproject commit 0292369abe0174c23c35cf43147c2809e1dc5f19 +Subproject commit 62f46cdacbd21188e4847f68869f4ea0c2845ee7 diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnClusterTest.java index d534a54d..9a3553a4 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/AbstractCheckOnClusterTest.java @@ -34,18 +34,18 @@ class AbstractCheckOnClusterTest extends DatabaseAwareTestBase { void shouldThrowExceptionIfMapperNotPassedForCrossClusterCheck() { final HighAvailabilityPgConnection haPgConnection = getHaPgConnection(); assertThatThrownBy(() -> new WrongCheck(haPgConnection)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("acrossClusterResultsMapper cannot be null for diagnostic UNUSED_INDEXES"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("acrossClusterResultsMapper cannot be null for diagnostic UNUSED_INDEXES"); } @ParameterizedTest @ValueSource(strings = PgContext.DEFAULT_SCHEMA_NAME) void forPublicSchema(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withNullValuesInIndex(), ctx -> - assertThat(check.check()) // executing on public schema by default - .hasSize(1) - .containsExactly( - IndexWithNulls.of("clients", "i_clients_middle_name", 0L, "middle_name")) + assertThat(check.check()) // executing on public schema by default + .hasSize(1) + .containsExactly( + IndexWithNulls.of("clients", "i_clients_middle_name", 0L, "middle_name")) ); } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/BtreeIndexesOnArrayColumnsCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/BtreeIndexesOnArrayColumnsCheckOnClusterTest.java index 9d626a0d..f6f4647c 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/BtreeIndexesOnArrayColumnsCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/BtreeIndexesOnArrayColumnsCheckOnClusterTest.java @@ -36,22 +36,22 @@ void shouldSatisfyContract() { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithoutThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withBtreeIndexesOnArrayColumn(), ctx -> - assertThat(check.check(ctx)) - .hasSize(2) - .containsExactlyInAnyOrder( - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_roles_btree_idx"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")), - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_roles_btree_idx"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")) - ) + assertThat(check.check(ctx)) + .hasSize(2) + .containsExactlyInAnyOrder( + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_roles_btree_idx"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")), + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_roles_btree_idx"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")) + ) ); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithJsonTypeCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithJsonTypeCheckOnClusterTest.java index d52f775a..b5c68616 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithJsonTypeCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithJsonTypeCheckOnClusterTest.java @@ -37,12 +37,12 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withJsonType(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "info")); + .hasSize(1) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "info")); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("clients")))) - .isEmpty(); + .isEmpty(); }); } @@ -51,7 +51,7 @@ void onDatabaseWithThem(final String schemaName) { void shouldIgnoreDroppedColumns(final String schemaName) { // withData - skipped here below executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withJsonType().withDroppedInfoColumn(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithSerialTypesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithSerialTypesCheckOnClusterTest.java index 0d2a69fa..655ee553 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithSerialTypesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithSerialTypesCheckOnClusterTest.java @@ -39,15 +39,15 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withSerialType, ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_account_id"), String.format("%s.bad_accounts_real_account_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName))); + .hasSize(2) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_account_id"), String.format("%s.bad_accounts_real_account_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName))); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_accounts")))) - .isEmpty(); + .isEmpty(); }); } @@ -55,47 +55,47 @@ void onDatabaseWithThem(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreDroppedColumns(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withSerialType().withDroppedSerialColumn(), ctx -> - assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) - )); + assertThat(check.check(ctx)) + .hasSize(1) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreCheckConstraintsOnSerialPrimaryKey(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withCheckConstraintOnSerialPrimaryKey, ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldDetectSerialColumnsWithUniqueConstraints(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withUniqueConstraintOnSerialColumn, ctx -> - assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)) - )); + assertThat(check.check(ctx)) + .hasSize(1) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)) + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldDetectPrimaryKeysThatAreForeignKeysAsWell(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withSerialPrimaryKeyReferencesToAnotherTable, ctx -> - assertThat(check.check(ctx)) - .hasSize(3) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("test_table"), "id"), String.format("%s.test_table_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("test_table"), "num"), String.format("%s.test_table_num_seq", schemaName)) - )); + assertThat(check.check(ctx)) + .hasSize(3) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("test_table"), "id"), String.format("%s.test_table_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("test_table"), "num"), String.format("%s.test_table_num_seq", schemaName)) + )); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithoutDescriptionCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithoutDescriptionCheckOnClusterTest.java index 1d4dbfa9..a414607c 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithoutDescriptionCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ColumnsWithoutDescriptionCheckOnClusterTest.java @@ -38,27 +38,27 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withReferences, ctx -> { assertThat(check.check(ctx)) - .hasSize(10) - .containsExactly( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_balance"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_number"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "first_name"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "last_name"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")) - .filteredOn(Column::isNullable) - .hasSize(2) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")); + .hasSize(10) + .containsExactly( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_balance"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_number"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "first_name"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "last_name"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")) + .filteredOn(Column::isNullable) + .hasSize(2) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")))) - .hasSize(5) - .allMatch(c -> c.getTableName().equals(ctx.enrichWithSchema("clients"))); + .hasSize(5) + .allMatch(c -> c.getTableName().equals(ctx.enrichWithSchema("clients"))); }); } @@ -66,24 +66,24 @@ void onDatabaseWithThem(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBlankCommentOnColumns(), ctx -> - assertThat(check.check(ctx)) - .hasSize(10) - .filteredOn(c -> "id".equalsIgnoreCase(c.getColumnName())) - .hasSize(2) - .containsExactly( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"))); + assertThat(check.check(ctx)) + .hasSize(10) + .filteredOn(c -> "id".equalsIgnoreCase(c.getColumnName())) + .hasSize(2) + .containsExactly( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreDroppedColumns(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDroppedInfoColumn(), ctx -> - assertThat(check.check(ctx)) - .hasSize(9) - .filteredOn(Column::isNullable) - .hasSize(1) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); + assertThat(check.check(ctx)) + .hasSize(9) + .filteredOn(Column::isNullable) + .hasSize(1) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/DuplicatedIndexesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/DuplicatedIndexesCheckOnClusterTest.java index c1729392..29ae49ea 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/DuplicatedIndexesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/DuplicatedIndexesCheckOnClusterTest.java @@ -38,18 +38,18 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDuplicatedIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L))) - .allMatch(d -> d.getTotalSize() >= 16_384L); + .hasSize(1) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L))) + .allMatch(d -> d.getTotalSize() >= 16_384L); assertThat(check.check(ctx, FilterDuplicatedIndexesByNamePredicate.of(ctx.enrichWithSchema("accounts_account_number_key")))) - .isEmpty(); + .isEmpty(); assertThat(check.check(ctx, FilterDuplicatedIndexesByNamePredicate.of(ctx.enrichWithSchema("i_accounts_account_number")))) - .isEmpty(); + .isEmpty(); }); } @@ -57,23 +57,23 @@ void onDatabaseWithThem(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withHashIndexShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDuplicatedHashIndex(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentOpclassShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDifferentOpclassIndexes(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentCollationShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withCustomCollation().withDuplicatedCustomCollationIndex(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ForeignKeysNotCoveredWithIndexCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ForeignKeysNotCoveredWithIndexCheckOnClusterTest.java index 5a95bb52..c76da79a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ForeignKeysNotCoveredWithIndexCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/ForeignKeysNotCoveredWithIndexCheckOnClusterTest.java @@ -40,8 +40,8 @@ void shouldSatisfyContract() { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithoutThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp, ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @@ -49,22 +49,22 @@ void onDatabaseWithoutThem(final String schemaName) { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withForeignKeyOnNullableColumn(), ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactlyInAnyOrder( - ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), - ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) - .flatExtracting(ForeignKey::getColumnsInConstraint) - .hasSize(2) - .containsExactlyInAnyOrder( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id")); + .hasSize(2) + .containsExactlyInAnyOrder( + ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), + ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) + .flatExtracting(ForeignKey::getColumnsInConstraint) + .hasSize(2) + .containsExactlyInAnyOrder( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id")); final Predicate predicate = FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")) - .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_clients"))); + .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_clients"))); assertThat(check.check(ctx, predicate)) - .isEmpty(); + .isEmpty(); }); } @@ -73,22 +73,22 @@ void onDatabaseWithThem(final String schemaName) { void onDatabaseWithNotSuitableIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withForeignKeyOnNullableColumn().withNonSuitableIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactlyInAnyOrder( - ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), - ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) - .flatExtracting(ForeignKey::getColumnsInConstraint) - .hasSize(2) - .containsExactlyInAnyOrder( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id")); + .hasSize(2) + .containsExactlyInAnyOrder( + ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), + ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) + .flatExtracting(ForeignKey::getColumnsInConstraint) + .hasSize(2) + .containsExactlyInAnyOrder( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id")); final Predicate predicate = FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")) - .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_clients"))); + .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_clients"))); assertThat(check.check(ctx, predicate)) - .isEmpty(); + .isEmpty(); }); } @@ -96,7 +96,7 @@ void onDatabaseWithNotSuitableIndex(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithSuitableIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withSuitableIndex(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/FunctionsWithoutDescriptionCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/FunctionsWithoutDescriptionCheckOnClusterTest.java index 55c14b5e..75974168 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/FunctionsWithoutDescriptionCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/FunctionsWithoutDescriptionCheckOnClusterTest.java @@ -38,13 +38,13 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withFunctions, ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer")); + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer")); assertThat(check.check(ctx, f -> !f.getFunctionName().contains("add"))) - .isEmpty(); + .isEmpty(); }); } @@ -54,18 +54,18 @@ void onDatabaseWithThem(final String schemaName) { void onDatabaseWithThemForProcedures(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withProcedures, ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("insert_data"), - isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("insert_data"), - isOutParametersInProcedureSupported() ? "IN a integer, IN b integer, IN c integer" : "a integer, b integer, c integer")); + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("insert_data"), + isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("insert_data"), + isOutParametersInProcedureSupported() ? "IN a integer, IN b integer, IN c integer" : "a integer, b integer, c integer")); assertThat(check.check(ctx, f -> !f.getFunctionSignature().contains("c integer"))) - .hasSize(1) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("insert_data"), - isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer")); + .hasSize(1) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("insert_data"), + isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer")); }); } @@ -73,20 +73,20 @@ void onDatabaseWithThemForProcedures(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withFunctions().withBlankCommentOnFunctions(), ctx -> - assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") - )); + assertThat(check.check(ctx)) + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldTakingIntoAccountNonBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withFunctions().withCommentOnFunctions(), ctx -> - assertThat(check.check(ctx)) - .isEmpty() + assertThat(check.check(ctx)) + .isEmpty() ); } @@ -95,8 +95,8 @@ void shouldTakingIntoAccountNonBlankComments(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldTakingIntoAccountNonBlankCommentsForProcedures(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withProcedures().withCommentOnProcedures(), ctx -> - assertThat(check.check(ctx)) - .isEmpty() + assertThat(check.check(ctx)) + .isEmpty() ); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBloatCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBloatCheckOnClusterTest.java index 1eae33f1..9ce9336d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBloatCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBloatCheckOnClusterTest.java @@ -44,7 +44,7 @@ void onDatabaseWithoutThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withReferences, ctx -> { collectStatistics(schemaName); assertThat(check.check(ctx)) - .isEmpty(); + .isEmpty(); }); } @@ -54,29 +54,29 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> { collectStatistics(schemaName); assertThat(existsStatisticsForTable(schemaName, "accounts")) - .isTrue(); + .isTrue(); assertThat(check.check(ctx)) - .hasSize(3) - .containsExactlyInAnyOrder( - IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L, 0L, 0), - IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_pkey"), 0L, 0L, 0), - IndexWithBloat.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("clients_pkey"), 0L, 0L, 0)) - .allMatch(i -> i.getIndexSizeInBytes() > 1L) - .allMatch(i -> i.getBloatSizeInBytes() > 1L && i.getBloatPercentage() >= 14); + .hasSize(3) + .containsExactlyInAnyOrder( + IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L, 0L, 0), + IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_pkey"), 0L, 0L, 0), + IndexWithBloat.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("clients_pkey"), 0L, 0L, 0)) + .allMatch(i -> i.getIndexSizeInBytes() > 1L) + .allMatch(i -> i.getBloatSizeInBytes() > 1L && i.getBloatPercentage() >= 14); final Predicate predicate = FilterIndexesBySizePredicate.of(1L) - .and(FilterIndexesByNamePredicate.of(ctx.enrichWithSchema("accounts_pkey"))); + .and(FilterIndexesByNamePredicate.of(ctx.enrichWithSchema("accounts_pkey"))); assertThat(check.check(ctx, predicate)) - .hasSize(2) - .containsExactlyInAnyOrder( - IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L, 0L, 0), - IndexWithBloat.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("clients_pkey"), 0L, 0L, 0)) - .allMatch(i -> i.getIndexSizeInBytes() > 1L) - .allMatch(i -> i.getBloatSizeInBytes() > 1L && i.getBloatPercentage() >= 14); + .hasSize(2) + .containsExactlyInAnyOrder( + IndexWithBloat.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L, 0L, 0), + IndexWithBloat.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("clients_pkey"), 0L, 0L, 0)) + .allMatch(i -> i.getIndexSizeInBytes() > 1L) + .allMatch(i -> i.getBloatSizeInBytes() > 1L && i.getBloatPercentage() >= 14); assertThat(check.check(ctx, FilterIndexesByBloatPredicate.of(1_000_000L, 50))) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBooleanCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBooleanCheckOnClusterTest.java index 86e6d550..ef93024b 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBooleanCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithBooleanCheckOnClusterTest.java @@ -38,13 +38,13 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBooleanValuesInIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_deleted"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"))); + .hasSize(1) + .containsExactly( + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_deleted"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"))); assertThat(check.check(ctx, FilterIndexesByNamePredicate.of(ctx.enrichWithSchema("i_accounts_deleted")))) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithNullValuesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithNullValuesCheckOnClusterTest.java index b5ba828b..df2ac189 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithNullValuesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IndexesWithNullValuesCheckOnClusterTest.java @@ -36,8 +36,8 @@ void shouldSatisfyContract() { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithoutThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } @ParameterizedTest @@ -45,13 +45,13 @@ void onDatabaseWithoutThem(final String schemaName) { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withNullValuesInIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - IndexWithNulls.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_middle_name"), 0L, "middle_name")) - .allMatch(i -> i.getNullableColumn().isNullable()); + .hasSize(1) + .containsExactly( + IndexWithNulls.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_middle_name"), 0L, "middle_name")) + .allMatch(i -> i.getNullableColumn().isNullable()); assertThat(check.check(ctx, FilterIndexesByNamePredicate.of(ctx.enrichWithSchema("i_clients_middle_name")))) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IntersectedIndexesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IntersectedIndexesCheckOnClusterTest.java index 42b61750..2cd2580b 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IntersectedIndexesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/IntersectedIndexesCheckOnClusterTest.java @@ -41,21 +41,21 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L) - ), - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) - .allMatch(d -> d.getTotalSize() >= 106_496L); + .hasSize(2) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L) + ), + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) + .allMatch(d -> d.getTotalSize() >= 106_496L); final Predicate predicate = FilterDuplicatedIndexesByNamePredicate.of( - List.of(ctx.enrichWithSchema("i_clients_last_first"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"))); + List.of(ctx.enrichWithSchema("i_clients_last_first"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"))); assertThat(check.check(ctx, predicate)) - .isEmpty(); + .isEmpty(); }); } @@ -64,18 +64,18 @@ void onDatabaseWithThem(final String schemaName) { void shouldFindHashIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedHashIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) - .allMatch(d -> d.getTotalSize() >= 106_496L); + .hasSize(1) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) + .allMatch(d -> d.getTotalSize() >= 106_496L); assertThat(check.check(ctx, FilterDuplicatedIndexesByNamePredicate.of(ctx.enrichWithSchema("i_clients_last_first")))) - .isEmpty(); + .isEmpty(); assertThat(check.check(ctx, FilterDuplicatedIndexesByNamePredicate.of(ctx.enrichWithSchema("i_clients_last_name")))) - .isEmpty(); + .isEmpty(); }); } @@ -83,7 +83,7 @@ void shouldFindHashIndex(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentOpclassShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDifferentOpclassIndexes(), ctx -> - assertThat(check.check(ctx)) - .isEmpty()); + assertThat(check.check(ctx)) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/InvalidIndexesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/InvalidIndexesCheckOnClusterTest.java index 4a9f8994..e3dfd66e 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/InvalidIndexesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/InvalidIndexesCheckOnClusterTest.java @@ -37,12 +37,12 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withInvalidIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - Index.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name_first_name"))); + .hasSize(1) + .containsExactly( + Index.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name_first_name"))); assertThat(check.check(ctx, FilterIndexesByNamePredicate.of(ctx.enrichWithSchema("i_clients_last_name_first_name")))) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/NotValidConstraintsCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/NotValidConstraintsCheckOnClusterTest.java index 3bb04102..5e79ef28 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/NotValidConstraintsCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/NotValidConstraintsCheckOnClusterTest.java @@ -42,23 +42,23 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withNotValidConstraints().withUniqueConstraintOnSerialColumn(), ctx -> { final List notValidConstraints = check.check(ctx); assertThat(notValidConstraints) - .hasSize(2) - .containsExactly( - Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_chk_client_id_not_validated_yet", ConstraintType.CHECK), - Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id_not_validated_yet", ConstraintType.FOREIGN_KEY)); + .hasSize(2) + .containsExactly( + Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_chk_client_id_not_validated_yet", ConstraintType.CHECK), + Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id_not_validated_yet", ConstraintType.FOREIGN_KEY)); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")))) - .isEmpty(); + .isEmpty(); ExecuteUtils.executeOnDatabase(getDataSource(), statement -> { for (final Constraint constraint : notValidConstraints) { statement.execute(String.format("alter table %s validate constraint %s;", - constraint.getTableName(), constraint.getConstraintName())); + constraint.getTableName(), constraint.getConstraintName())); } }); assertThat(check.check(ctx)) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithBloatCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithBloatCheckOnClusterTest.java index 43d4584e..cd755d73 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithBloatCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithBloatCheckOnClusterTest.java @@ -42,27 +42,27 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> { collectStatistics(schemaName); assertThat(existsStatisticsForTable(schemaName, "accounts")) - .isTrue(); + .isTrue(); assertThat(check.check(ctx)) - .hasSize(2) - .containsExactlyInAnyOrder( - TableWithBloat.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0), - TableWithBloat.of(ctx.enrichWithSchema("clients"), 0L, 0L, 0)) - .allMatch(t -> t.getTableSizeInBytes() > 0L) // real size doesn't matter - .allMatch(t -> t.getBloatPercentage() == 0 && t.getBloatSizeInBytes() == 0L); + .hasSize(2) + .containsExactlyInAnyOrder( + TableWithBloat.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0), + TableWithBloat.of(ctx.enrichWithSchema("clients"), 0L, 0L, 0)) + .allMatch(t -> t.getTableSizeInBytes() > 0L) // real size doesn't matter + .allMatch(t -> t.getBloatPercentage() == 0 && t.getBloatSizeInBytes() == 0L); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("clients")))) - .hasSize(1) - .containsExactly( - TableWithBloat.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0)) - .allMatch(t -> t.getTableSizeInBytes() > 0L) // real size doesn't matter - .allMatch(t -> t.getBloatPercentage() == 0 && t.getBloatSizeInBytes() == 0L); + .hasSize(1) + .containsExactly( + TableWithBloat.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0)) + .allMatch(t -> t.getTableSizeInBytes() > 0L) // real size doesn't matter + .allMatch(t -> t.getBloatPercentage() == 0 && t.getBloatSizeInBytes() == 0L); final Predicate predicate = FilterTablesByBloatPredicate.of(0L, 10) - .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("clients"))); + .and(FilterTablesByNamePredicate.of(ctx.enrichWithSchema("clients"))); assertThat(check.check(ctx, predicate)) - .isEmpty(); + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnClusterTest.java index c27f0949..b872e589 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithMissingIndexesCheckOnClusterTest.java @@ -41,26 +41,26 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> { tryToFindAccountByClientId(schemaName); assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly( - TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) - .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) - .allMatch(t -> t.getIndexScans() == 0) - .allMatch(t -> t.getTableSizeInBytes() > 1L); + .hasSize(1) + .containsExactly( + TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) + .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) + .allMatch(t -> t.getIndexScans() == 0) + .allMatch(t -> t.getTableSizeInBytes() > 1L); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")))) - .isEmpty(); + .isEmpty(); assertThat(check.check(ctx, FilterTablesBySizePredicate.of(1L))) - .hasSize(1) - .containsExactly( - TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) - .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) - .allMatch(t -> t.getIndexScans() == 0) - .allMatch(t -> t.getTableSizeInBytes() > 1L); + .hasSize(1) + .containsExactly( + TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) + .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) + .allMatch(t -> t.getIndexScans() == 0) + .allMatch(t -> t.getTableSizeInBytes() > 1L); assertThat(check.check(ctx, FilterTablesBySizePredicate.of(1_000_000L))) - .isEmpty(); + .isEmpty(); }); } @@ -70,15 +70,15 @@ void getResultAsUnion() { final TableWithMissingIndex t2 = TableWithMissingIndex.of("t2", 2L, 30L, 3L); final TableWithMissingIndex t3 = TableWithMissingIndex.of("t3", 3L, 40L, 4L); final List> tablesWithMissingIndexesFromAllHosts = List.of( - List.of(), - List.of(t1, t3), - List.of(t2), - List.of(t2, t3) + List.of(), + List.of(t1, t3), + List.of(t2), + List.of(t2, t3) ); final List tablesWithMissingIndexes = TablesWithMissingIndexesCheckOnCluster.getResultAsUnion( - tablesWithMissingIndexesFromAllHosts); + tablesWithMissingIndexesFromAllHosts); assertThat(tablesWithMissingIndexes) - .hasSize(3) - .containsExactlyInAnyOrder(t1, t2, t3); + .hasSize(3) + .containsExactlyInAnyOrder(t1, t2, t3); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutDescriptionCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutDescriptionCheckOnClusterTest.java index 53a191c1..f1cc7c93 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutDescriptionCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutDescriptionCheckOnClusterTest.java @@ -39,16 +39,16 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withReferences, ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - Table.of(ctx.enrichWithSchema("accounts"), 0L), - Table.of(ctx.enrichWithSchema("clients"), 0L)); + .hasSize(2) + .containsExactly( + Table.of(ctx.enrichWithSchema("accounts"), 0L), + Table.of(ctx.enrichWithSchema("clients"), 0L)); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("accounts")))) - .hasSize(1) - .containsExactly( - Table.of(ctx.enrichWithSchema("clients"), 0L)) - .allMatch(t -> t.getTableSizeInBytes() > 0L); + .hasSize(1) + .containsExactly( + Table.of(ctx.enrichWithSchema("clients"), 0L)) + .allMatch(t -> t.getTableSizeInBytes() > 0L); }); } @@ -57,16 +57,16 @@ void onDatabaseWithThem(final String schemaName) { void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBlankCommentOnTables(), ctx -> { assertThat(check.check(ctx)) - .hasSize(2) - .containsExactly( - Table.of(ctx.enrichWithSchema("accounts"), 0L), - Table.of(ctx.enrichWithSchema("clients"), 0L)); + .hasSize(2) + .containsExactly( + Table.of(ctx.enrichWithSchema("accounts"), 0L), + Table.of(ctx.enrichWithSchema("clients"), 0L)); assertThat(check.check(ctx, FilterTablesBySizePredicate.of(1_234L))) - .hasSize(1) - .containsExactly( - Table.of(ctx.enrichWithSchema("clients"), 0L)) - .allMatch(t -> t.getTableSizeInBytes() > 1_234L); + .hasSize(1) + .containsExactly( + Table.of(ctx.enrichWithSchema("clients"), 0L)) + .allMatch(t -> t.getTableSizeInBytes() > 1_234L); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutPrimaryKeyCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutPrimaryKeyCheckOnClusterTest.java index 05f9e206..e301c164 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutPrimaryKeyCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/TablesWithoutPrimaryKeyCheckOnClusterTest.java @@ -37,12 +37,12 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withTableWithoutPrimaryKey(), ctx -> { assertThat(check.check(ctx)) - .hasSize(1) - .containsExactly(Table.of(ctx.enrichWithSchema("bad_clients"), 0L)) - .allMatch(t -> t.getTableSizeInBytes() == 0L); + .hasSize(1) + .containsExactly(Table.of(ctx.enrichWithSchema("bad_clients"), 0L)) + .allMatch(t -> t.getTableSizeInBytes() == 0L); assertThat(check.check(ctx, FilterTablesByNamePredicate.of(ctx.enrichWithSchema("bad_clients")))) - .isEmpty(); + .isEmpty(); }); } @@ -50,7 +50,7 @@ void onDatabaseWithThem(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldReturnNothingForMaterializedViews(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withMaterializedView(), ctx -> - assertThat(check.check()) - .isEmpty()); + assertThat(check.check()) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnClusterTest.java index 9bb31460..dfb58de2 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/cluster/UnusedIndexesCheckOnClusterTest.java @@ -49,11 +49,11 @@ void shouldSatisfyContract() { void checkOnClusterShouldLogResetStatisticsData() { try (LogsCaptor logsCaptor = new LogsCaptor(UnusedIndexesCheckOnCluster.class)) { assertThat(check.check()) - .isEmpty(); + .isEmpty(); assertThat(logsCaptor.getLogs()) - .hasSize(1) - .allMatch(l -> l.getFormattedMessage().contains("reset")); + .hasSize(1) + .allMatch(l -> l.getFormattedMessage().contains("reset")); } } @@ -62,28 +62,28 @@ void checkOnClusterShouldLogResetStatisticsData() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedIndex(), ctx -> { assertThat(check.check(ctx)) - .hasSize(6) - .containsExactlyInAnyOrder( - UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) - .allMatch(i -> i.getIndexSizeInBytes() > 0L) - .allMatch(i -> i.getIndexScans() == 0); + .hasSize(6) + .containsExactlyInAnyOrder( + UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) + .allMatch(i -> i.getIndexSizeInBytes() > 0L) + .allMatch(i -> i.getIndexScans() == 0); final Predicate predicate = FilterIndexesByNamePredicate.of( - List.of(ctx.enrichWithSchema("i_clients_last_first"), ctx.enrichWithSchema("i_accounts_account_number"))); + List.of(ctx.enrichWithSchema("i_clients_last_first"), ctx.enrichWithSchema("i_accounts_account_number"))); assertThat(check.check(ctx, predicate)) - .hasSize(4) - .containsExactlyInAnyOrder( - UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) - .allMatch(i -> i.getIndexSizeInBytes() > 0L) - .allMatch(i -> i.getIndexScans() == 0); + .hasSize(4) + .containsExactlyInAnyOrder( + UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) + .allMatch(i -> i.getIndexSizeInBytes() > 0L) + .allMatch(i -> i.getIndexScans() == 0); }); } @@ -95,28 +95,28 @@ void getResultAsIntersectionShouldWork() { final UnusedIndex i4 = UnusedIndex.of("t3", "i4", 4L, 4L); final UnusedIndex i5 = UnusedIndex.of("t3", "i5", 5L, 5L); final List> potentiallyUnusedIndexesFromAllHosts = List.of( - List.of(i5, i4, i1, i3), - List.of(i2, i1, i5), - List.of(i2, i5, i1, i4)); + List.of(i5, i4, i1, i3), + List.of(i2, i1, i5), + List.of(i2, i5, i1, i4)); assertThat(getResultAsIntersection(potentiallyUnusedIndexesFromAllHosts)) - .hasSize(2) - .containsExactlyInAnyOrder(i1, i5) - .isUnmodifiable(); + .hasSize(2) + .containsExactlyInAnyOrder(i1, i5) + .isUnmodifiable(); } @Test void getResultAsIntersectionWithEmptyInput() { assertThat(getResultAsIntersection(List.of())) - .isUnmodifiable() - .isEmpty(); + .isUnmodifiable() + .isEmpty(); } @SuppressWarnings("ConstantConditions") @Test void getLastStatsResetDateLogMessageWithWrongArguments() { assertThatThrownBy(() -> getLastStatsResetDateLogMessage(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("statisticsMaintenance cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("statisticsMaintenance cannot be null"); } @Test @@ -125,7 +125,7 @@ void getLastStatsResetDateLogMessageWithoutResetTimestamp() { Mockito.when(statisticsMaintenance.getLastStatsResetTimestamp()).thenReturn(Optional.empty()); final String logMessage = getLastStatsResetDateLogMessage(statisticsMaintenance); assertThat(logMessage) - .isEqualTo("Statistics have never been reset on this host"); + .isEqualTo("Statistics have never been reset on this host"); } @Test @@ -135,6 +135,6 @@ void getLastStatsResetDateLogMessageWithResetTimestamp() { Mockito.when(statisticsMaintenance.getLastStatsResetTimestamp()).thenReturn(Optional.of(resetDate.minusDays(123L))); final String logMessage = getLastStatsResetDateLogMessage(statisticsMaintenance); assertThat(logMessage) - .startsWith("Last statistics reset on this host was 123 days ago ("); + .startsWith("Last statistics reset on this host was 123 days ago ("); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnExtractorTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnExtractorTest.java index a62993b6..48e67766 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnExtractorTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnExtractorTest.java @@ -21,7 +21,7 @@ class ColumnExtractorTest { @Test void shouldCreateInstance() { assertThat(ColumnExtractor.of()) - .isNotNull() - .isInstanceOf(ColumnExtractor.class); + .isNotNull() + .isInstanceOf(ColumnExtractor.class); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnWithSerialTypeExtractorTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnWithSerialTypeExtractorTest.java index 17ad49aa..f16eeb42 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnWithSerialTypeExtractorTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/ColumnWithSerialTypeExtractorTest.java @@ -21,7 +21,7 @@ class ColumnWithSerialTypeExtractorTest { @Test void shouldCreateInstance() { assertThat(ColumnWithSerialTypeExtractor.of()) - .isNotNull() - .isInstanceOf(ColumnWithSerialTypeExtractor.class); + .isNotNull() + .isInstanceOf(ColumnWithSerialTypeExtractor.class); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/TableExtractorTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/TableExtractorTest.java index 74e6cbcb..d1c23bce 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/TableExtractorTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/extractors/TableExtractorTest.java @@ -21,7 +21,7 @@ class TableExtractorTest { @Test void shouldCreateInstance() { assertThat(TableExtractor.of()) - .isNotNull() - .isInstanceOf(TableExtractor.class); + .isNotNull() + .isInstanceOf(TableExtractor.class); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHostTest.java index de9a2d2e..d997041a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/AbstractCheckOnHostTest.java @@ -37,16 +37,16 @@ void securityTest(final String schemaName) { final long before = getRowsCount(ctx.getSchemaName(), "clients"); assertThat(before).isEqualTo(1001L); assertThat(check.check(PgContext.of("; truncate table clients;"))) - .isEmpty(); + .isEmpty(); assertThat(getRowsCount(ctx.getSchemaName(), "clients")).isEqualTo(before); assertThat(check.check(PgContext.of("; select pg_sleep(100000000);"))) - .isEmpty(); + .isEmpty(); assertThat(check.check()) // executing on public schema by default - .hasSize(1) - .containsExactly( - IndexWithNulls.of("clients", "i_clients_middle_name", 0L, "middle_name")); + .hasSize(1) + .containsExactly( + IndexWithNulls.of("clients", "i_clients_middle_name", 0L, "middle_name")); }); } @@ -55,7 +55,7 @@ private long getRowsCount(@Nonnull final String schemaName, try (Connection connection = getDataSource().getConnection(); Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery( - "select count(*) from " + schemaName + '.' + tableName)) { + "select count(*) from " + schemaName + '.' + tableName)) { resultSet.next(); return resultSet.getLong(1); } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/BtreeIndexesOnArrayColumnsCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/BtreeIndexesOnArrayColumnsCheckOnHostTest.java index ac7852a9..5590b427 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/BtreeIndexesOnArrayColumnsCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/BtreeIndexesOnArrayColumnsCheckOnHostTest.java @@ -29,9 +29,9 @@ class BtreeIndexesOnArrayColumnsCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(IndexWithColumns.class) - .hasDiagnostic(Diagnostic.BTREE_INDEXES_ON_ARRAY_COLUMNS) - .hasHost(getHost()); + .hasType(IndexWithColumns.class) + .hasDiagnostic(Diagnostic.BTREE_INDEXES_ON_ARRAY_COLUMNS) + .hasHost(getHost()); } @ParameterizedTest @@ -39,14 +39,14 @@ void shouldSatisfyContract() { void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withBtreeIndexesOnArrayColumn(), ctx -> assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactlyInAnyOrder( - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_roles_btree_idx"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")), - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_roles_btree_idx"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")) - ) + .executing(ctx) + .hasSize(2) + .containsExactlyInAnyOrder( + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_roles_btree_idx"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")), + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_roles_btree_idx"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "roles")) + ) ); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHostTest.java index 079683d9..652346b7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithJsonTypeCheckOnHostTest.java @@ -28,20 +28,20 @@ class ColumnsWithJsonTypeCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Column.class) - .hasDiagnostic(Diagnostic.COLUMNS_WITH_JSON_TYPE) - .hasHost(getHost()); + .hasType(Column.class) + .hasDiagnostic(Diagnostic.COLUMNS_WITH_JSON_TYPE) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withJsonType(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "info"))); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "info"))); } @ParameterizedTest @@ -49,8 +49,8 @@ void onDatabaseWithThem(final String schemaName) { void shouldIgnoreDroppedColumns(final String schemaName) { // withData - skipped here below executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withJsonType().withDroppedInfoColumn(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithSerialTypesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithSerialTypesCheckOnHostTest.java index 0ad8719a..26bcdb1d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithSerialTypesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithSerialTypesCheckOnHostTest.java @@ -30,75 +30,75 @@ class ColumnsWithSerialTypesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(ColumnWithSerialType.class) - .hasDiagnostic(Diagnostic.COLUMNS_WITH_SERIAL_TYPES) - .hasHost(getHost()); + .hasType(ColumnWithSerialType.class) + .hasDiagnostic(Diagnostic.COLUMNS_WITH_SERIAL_TYPES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withSerialType, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_account_id"), String.format("%s.bad_accounts_real_account_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) - )); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_account_id"), String.format("%s.bad_accounts_real_account_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreDroppedColumns(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withSerialType().withDroppedSerialColumn(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) - )); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("bad_accounts"), "real_client_id"), String.format("%s.bad_accounts_real_client_id_seq", schemaName)) + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreCheckConstraintsOnSerialPrimaryKey(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withCheckConstraintOnSerialPrimaryKey, ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldDetectSerialColumnsWithUniqueConstraints(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withUniqueConstraintOnSerialColumn, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)) - )); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)) + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldDetectPrimaryKeysThatAreForeignKeysAsWell(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withSerialPrimaryKeyReferencesToAnotherTable, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(3) - .containsExactly( - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("test_table"), "id"), String.format("%s.test_table_id_seq", schemaName)), - ColumnWithSerialType.ofBigSerial( - Column.ofNotNull(ctx.enrichWithSchema("test_table"), "num"), String.format("%s.test_table_num_seq", schemaName)) - )); + assertThat(check) + .executing(ctx) + .hasSize(3) + .containsExactly( + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("one_more_table"), "id"), String.format("%s.one_more_table_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("test_table"), "id"), String.format("%s.test_table_id_seq", schemaName)), + ColumnWithSerialType.ofBigSerial( + Column.ofNotNull(ctx.enrichWithSchema("test_table"), "num"), String.format("%s.test_table_num_seq", schemaName)) + )); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHostTest.java index 33f89334..fca2a9af 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ColumnsWithoutDescriptionCheckOnHostTest.java @@ -29,60 +29,60 @@ class ColumnsWithoutDescriptionCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Column.class) - .hasDiagnostic(Diagnostic.COLUMNS_WITHOUT_DESCRIPTION) - .hasHost(getHost()); + .hasType(Column.class) + .hasDiagnostic(Diagnostic.COLUMNS_WITHOUT_DESCRIPTION) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withReferences, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(10) - .containsExactly( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_balance"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_number"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"), - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "first_name"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "last_name"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")) - .filteredOn(Column::isNullable) - .hasSize(2) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); + assertThat(check) + .executing(ctx) + .hasSize(10) + .containsExactly( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_balance"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "account_number"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted"), + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "first_name"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "last_name"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name")) + .filteredOn(Column::isNullable) + .hasSize(2) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "info"), + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBlankCommentOnColumns(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(10) - .filteredOn(c -> "id".equalsIgnoreCase(c.getColumnName())) - .hasSize(2) - .containsExactly( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), - Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"))); + assertThat(check) + .executing(ctx) + .hasSize(10) + .filteredOn(c -> "id".equalsIgnoreCase(c.getColumnName())) + .hasSize(2) + .containsExactly( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "id"), + Column.ofNotNull(ctx.enrichWithSchema("clients"), "id"))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldIgnoreDroppedColumns(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDroppedInfoColumn(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(9) - .filteredOn(Column::isNullable) - .hasSize(1) - .containsExactly( - Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); + assertThat(check) + .executing(ctx) + .hasSize(9) + .filteredOn(Column::isNullable) + .hasSize(1) + .containsExactly( + Column.ofNullable(ctx.enrichWithSchema("clients"), "middle_name"))); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/DuplicatedIndexesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/DuplicatedIndexesCheckOnHostTest.java index c05726bd..86015211 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/DuplicatedIndexesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/DuplicatedIndexesCheckOnHostTest.java @@ -29,49 +29,49 @@ class DuplicatedIndexesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(DuplicatedIndexes.class) - .hasDiagnostic(Diagnostic.DUPLICATED_INDEXES) - .hasHost(getHost()); + .hasType(DuplicatedIndexes.class) + .hasDiagnostic(Diagnostic.DUPLICATED_INDEXES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDuplicatedIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L))) - .allMatch(d -> d.getTotalSize() >= 16_384L)); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("accounts_account_number_key"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L))) + .allMatch(d -> d.getTotalSize() >= 16_384L)); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withHashIndexShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDuplicatedHashIndex(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentOpclassShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDifferentOpclassIndexes(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentCollationShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withCustomCollation().withDuplicatedCustomCollationIndex(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ForeignKeysNotCoveredWithIndexCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ForeignKeysNotCoveredWithIndexCheckOnHostTest.java index d3abfacb..8492080a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ForeignKeysNotCoveredWithIndexCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/ForeignKeysNotCoveredWithIndexCheckOnHostTest.java @@ -29,55 +29,55 @@ class ForeignKeysNotCoveredWithIndexCheckOnHostTest extends DatabaseAwareTestBas @Test void shouldSatisfyContract() { assertThat(check) - .hasType(ForeignKey.class) - .hasDiagnostic(Diagnostic.FOREIGN_KEYS_WITHOUT_INDEX) - .hasHost(getHost()); + .hasType(ForeignKey.class) + .hasDiagnostic(Diagnostic.FOREIGN_KEYS_WITHOUT_INDEX) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withForeignKeyOnNullableColumn(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactlyInAnyOrder( - ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), - ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) - .flatExtracting(ForeignKey::getColumnsInConstraint) - .hasSize(2) - .containsExactlyInAnyOrder( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactlyInAnyOrder( + ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), + ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) + .flatExtracting(ForeignKey::getColumnsInConstraint) + .hasSize(2) + .containsExactlyInAnyOrder( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithNotSuitableIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withForeignKeyOnNullableColumn().withNonSuitableIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactlyInAnyOrder( - ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), - ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) - .flatExtracting(ForeignKey::getColumnsInConstraint) - .hasSize(2) - .containsExactlyInAnyOrder( - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), - Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactlyInAnyOrder( + ForeignKey.ofColumn(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id", + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id")), + ForeignKey.ofColumn(ctx.enrichWithSchema("bad_clients"), "c_bad_clients_fk_real_client_id", + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))) + .flatExtracting(ForeignKey::getColumnsInConstraint) + .hasSize(2) + .containsExactlyInAnyOrder( + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "client_id"), + Column.ofNullable(ctx.enrichWithSchema("bad_clients"), "real_client_id"))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithSuitableIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withSuitableIndex(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/FunctionsWithoutDescriptionCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/FunctionsWithoutDescriptionCheckOnHostTest.java index b0d0c06b..735db99a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/FunctionsWithoutDescriptionCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/FunctionsWithoutDescriptionCheckOnHostTest.java @@ -30,22 +30,22 @@ class FunctionsWithoutDescriptionCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(StoredFunction.class) - .hasDiagnostic(Diagnostic.FUNCTIONS_WITHOUT_DESCRIPTION) - .hasHost(getHost()); + .hasType(StoredFunction.class) + .hasDiagnostic(Diagnostic.FUNCTIONS_WITHOUT_DESCRIPTION) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withFunctions, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") - )); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") + )); } @DisabledIf("isProceduresNotSupported") @@ -53,37 +53,37 @@ void onDatabaseWithThem(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThemForProcedures(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withProcedures, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("insert_data"), - isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("insert_data"), - isOutParametersInProcedureSupported() ? "IN a integer, IN b integer, IN c integer" : "a integer, b integer, c integer") - )); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("insert_data"), + isOutParametersInProcedureSupported() ? "IN a integer, IN b integer" : "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("insert_data"), + isOutParametersInProcedureSupported() ? "IN a integer, IN b integer, IN c integer" : "a integer, b integer, c integer") + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withFunctions().withBlankCommentOnFunctions(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), - StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") - )); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer"), + StoredFunction.of(ctx.enrichWithSchema("add"), "a integer, b integer, c integer") + )); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldTakingIntoAccountNonBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withFunctions().withCommentOnFunctions(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty() + assertThat(check) + .executing(ctx) + .isEmpty() ); } @@ -92,9 +92,9 @@ void shouldTakingIntoAccountNonBlankComments(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldTakingIntoAccountNonBlankCommentsForProcedures(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withProcedures().withCommentOnProcedures(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty() + assertThat(check) + .executing(ctx) + .isEmpty() ); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBloatCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBloatCheckOnHostTest.java index f4e97d3a..853328ad 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBloatCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBloatCheckOnHostTest.java @@ -25,8 +25,8 @@ class IndexesWithBloatCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(IndexWithBloat.class) - .hasDiagnostic(Diagnostic.BLOATED_INDEXES) - .hasHost(getHost()); + .hasType(IndexWithBloat.class) + .hasDiagnostic(Diagnostic.BLOATED_INDEXES) + .hasHost(getHost()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBooleanCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBooleanCheckOnHostTest.java index bcdb138e..f34c7e2e 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBooleanCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithBooleanCheckOnHostTest.java @@ -29,21 +29,21 @@ class IndexesWithBooleanCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(IndexWithColumns.class) - .hasDiagnostic(Diagnostic.INDEXES_WITH_BOOLEAN) - .hasHost(getHost()); + .hasType(IndexWithColumns.class) + .hasDiagnostic(Diagnostic.INDEXES_WITH_BOOLEAN) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBooleanValuesInIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_deleted"), 0L, - Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted")) - )); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + IndexWithColumns.ofSingle(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_deleted"), 0L, + Column.ofNotNull(ctx.enrichWithSchema("accounts"), "deleted")) + )); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithNullValuesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithNullValuesCheckOnHostTest.java index 4b84e488..e7e86d4e 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithNullValuesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IndexesWithNullValuesCheckOnHostTest.java @@ -28,20 +28,20 @@ class IndexesWithNullValuesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(IndexWithNulls.class) - .hasDiagnostic(Diagnostic.INDEXES_WITH_NULL_VALUES) - .hasHost(getHost()); + .hasType(IndexWithNulls.class) + .hasDiagnostic(Diagnostic.INDEXES_WITH_NULL_VALUES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withNullValuesInIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - IndexWithNulls.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_middle_name"), 0L, "middle_name")) - .allMatch(i -> i.getNullableColumn().isNullable())); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + IndexWithNulls.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_middle_name"), 0L, "middle_name")) + .allMatch(i -> i.getNullableColumn().isNullable())); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IntersectedIndexesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IntersectedIndexesCheckOnHostTest.java index 27ed5823..07bf814b 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IntersectedIndexesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/IntersectedIndexesCheckOnHostTest.java @@ -29,49 +29,49 @@ class IntersectedIndexesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(DuplicatedIndexes.class) - .hasDiagnostic(Diagnostic.INTERSECTED_INDEXES) - .hasHost(getHost()); + .hasType(DuplicatedIndexes.class) + .hasDiagnostic(Diagnostic.INTERSECTED_INDEXES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L) - ), - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) - .allMatch(d -> d.getTotalSize() >= 106_496L)); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L) + ), + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) + .allMatch(d -> d.getTotalSize() >= 106_496L)); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldFindHashIndex(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedHashIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - DuplicatedIndexes.of( - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), - IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) - .allMatch(d -> d.getTotalSize() >= 106_496L)); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + DuplicatedIndexes.of( + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L), + IndexWithSize.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L))) + .allMatch(d -> d.getTotalSize() >= 106_496L)); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void withDifferentOpclassShouldReturnNothing(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withDifferentOpclassIndexes(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/InvalidIndexesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/InvalidIndexesCheckOnHostTest.java index ca1ba6fc..40fa9de7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/InvalidIndexesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/InvalidIndexesCheckOnHostTest.java @@ -28,19 +28,19 @@ class InvalidIndexesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Index.class) - .hasDiagnostic(Diagnostic.INVALID_INDEXES) - .hasHost(getHost()); + .hasType(Index.class) + .hasDiagnostic(Diagnostic.INVALID_INDEXES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withInvalidIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - Index.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name_first_name")))); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + Index.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name_first_name")))); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/NotValidConstraintsCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/NotValidConstraintsCheckOnHostTest.java index d90780f7..3a68a6f5 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/NotValidConstraintsCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/NotValidConstraintsCheckOnHostTest.java @@ -33,9 +33,9 @@ class NotValidConstraintsCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Constraint.class) - .hasDiagnostic(Diagnostic.NOT_VALID_CONSTRAINTS) - .hasHost(getHost()); + .hasType(Constraint.class) + .hasDiagnostic(Diagnostic.NOT_VALID_CONSTRAINTS) + .hasHost(getHost()); } @ParameterizedTest @@ -44,21 +44,21 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withNotValidConstraints().withUniqueConstraintOnSerialColumn(), ctx -> { final List notValidConstraints = check.check(ctx); Assertions.assertThat(notValidConstraints) - .hasSize(2) - .containsExactly( - Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_chk_client_id_not_validated_yet", ConstraintType.CHECK), - Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id_not_validated_yet", ConstraintType.FOREIGN_KEY)); + .hasSize(2) + .containsExactly( + Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_chk_client_id_not_validated_yet", ConstraintType.CHECK), + Constraint.ofType(ctx.enrichWithSchema("accounts"), "c_accounts_fk_client_id_not_validated_yet", ConstraintType.FOREIGN_KEY)); ExecuteUtils.executeOnDatabase(getDataSource(), statement -> { for (final Constraint constraint : notValidConstraints) { statement.execute(String.format("alter table %s validate constraint %s;", - constraint.getTableName(), constraint.getConstraintName())); + constraint.getTableName(), constraint.getConstraintName())); } }); assertThat(check) - .executing(ctx) - .isEmpty(); + .executing(ctx) + .isEmpty(); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithBloatCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithBloatCheckOnHostTest.java index f5b7d22e..9490da75 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithBloatCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithBloatCheckOnHostTest.java @@ -25,8 +25,8 @@ class TablesWithBloatCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(TableWithBloat.class) - .hasDiagnostic(Diagnostic.BLOATED_TABLES) - .hasHost(getHost()); + .hasType(TableWithBloat.class) + .hasDiagnostic(Diagnostic.BLOATED_TABLES) + .hasHost(getHost()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithMissingIndexesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithMissingIndexesCheckOnHostTest.java index b718c3fd..fa747394 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithMissingIndexesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithMissingIndexesCheckOnHostTest.java @@ -28,9 +28,9 @@ class TablesWithMissingIndexesCheckOnHostTest extends StatisticsAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(TableWithMissingIndex.class) - .hasDiagnostic(Diagnostic.TABLES_WITH_MISSING_INDEXES) - .hasHost(getHost()); + .hasType(TableWithMissingIndex.class) + .hasDiagnostic(Diagnostic.TABLES_WITH_MISSING_INDEXES) + .hasHost(getHost()); } @ParameterizedTest @@ -39,13 +39,13 @@ void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> { tryToFindAccountByClientId(schemaName); assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) - .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) - .allMatch(t -> t.getIndexScans() == 0) - .allMatch(t -> t.getTableSizeInBytes() > 1L); + .executing(ctx) + .hasSize(1) + .containsExactly( + TableWithMissingIndex.of(ctx.enrichWithSchema("accounts"), 0L, 0L, 0L)) + .allMatch(t -> t.getSeqScans() >= AMOUNT_OF_TRIES) + .allMatch(t -> t.getIndexScans() == 0) + .allMatch(t -> t.getTableSizeInBytes() > 1L); }); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHostTest.java index f66a206b..1f1c7f57 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutDescriptionCheckOnHostTest.java @@ -29,32 +29,32 @@ class TablesWithoutDescriptionCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Table.class) - .hasDiagnostic(Diagnostic.TABLES_WITHOUT_DESCRIPTION) - .hasHost(getHost()); + .hasType(Table.class) + .hasDiagnostic(Diagnostic.TABLES_WITHOUT_DESCRIPTION) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, DatabasePopulator::withReferences, ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - Table.of(ctx.enrichWithSchema("accounts"), 0L), - Table.of(ctx.enrichWithSchema("clients"), 0L))); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + Table.of(ctx.enrichWithSchema("accounts"), 0L), + Table.of(ctx.enrichWithSchema("clients"), 0L))); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldNotTakingIntoAccountBlankComments(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withBlankCommentOnTables(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(2) - .containsExactly( - Table.of(ctx.enrichWithSchema("accounts"), 0L), - Table.of(ctx.enrichWithSchema("clients"), 0L))); + assertThat(check) + .executing(ctx) + .hasSize(2) + .containsExactly( + Table.of(ctx.enrichWithSchema("accounts"), 0L), + Table.of(ctx.enrichWithSchema("clients"), 0L))); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutPrimaryKeyCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutPrimaryKeyCheckOnHostTest.java index 7a468e9f..be596e92 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutPrimaryKeyCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/TablesWithoutPrimaryKeyCheckOnHostTest.java @@ -28,29 +28,29 @@ class TablesWithoutPrimaryKeyCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(Table.class) - .hasDiagnostic(Diagnostic.TABLES_WITHOUT_PRIMARY_KEY) - .hasHost(getHost()); + .hasType(Table.class) + .hasDiagnostic(Diagnostic.TABLES_WITHOUT_PRIMARY_KEY) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withTableWithoutPrimaryKey(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(1) - .containsExactly( - Table.of(ctx.enrichWithSchema("bad_clients"), 0L)) - .allMatch(t -> t.getTableSizeInBytes() == 0L)); + assertThat(check) + .executing(ctx) + .hasSize(1) + .containsExactly( + Table.of(ctx.enrichWithSchema("bad_clients"), 0L)) + .allMatch(t -> t.getTableSizeInBytes() == 0L)); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldReturnNothingForMaterializedViews(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withMaterializedView(), ctx -> - assertThat(check) - .executing(ctx) - .isEmpty()); + assertThat(check) + .executing(ctx) + .isEmpty()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/UnusedIndexesCheckOnHostTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/UnusedIndexesCheckOnHostTest.java index f0e1a557..833d4ace 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/UnusedIndexesCheckOnHostTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/host/UnusedIndexesCheckOnHostTest.java @@ -28,26 +28,26 @@ class UnusedIndexesCheckOnHostTest extends DatabaseAwareTestBase { @Test void shouldSatisfyContract() { assertThat(check) - .hasType(UnusedIndex.class) - .hasDiagnostic(Diagnostic.UNUSED_INDEXES) - .hasHost(getHost()); + .hasType(UnusedIndex.class) + .hasDiagnostic(Diagnostic.UNUSED_INDEXES) + .hasHost(getHost()); } @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void onDatabaseWithThem(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withDuplicatedIndex(), ctx -> - assertThat(check) - .executing(ctx) - .hasSize(6) - .containsExactlyInAnyOrder( - UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), - UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) - .allMatch(i -> i.getIndexSizeInBytes() > 0L) - .allMatch(i -> i.getIndexScans() == 0)); + assertThat(check) + .executing(ctx) + .hasSize(6) + .containsExactlyInAnyOrder( + UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_first"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("clients"), ctx.enrichWithSchema("i_clients_last_name"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_number_balance_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_account_number_not_deleted"), 0L, 0), + UnusedIndex.of(ctx.enrichWithSchema("accounts"), ctx.enrichWithSchema("i_accounts_id_account_number_not_deleted"), 0L, 0)) + .allMatch(i -> i.getIndexSizeInBytes() > 0L) + .allMatch(i -> i.getIndexScans() == 0)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicateTest.java index c0f5ad0a..71b603ee 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterDuplicatedIndexesByNamePredicateTest.java @@ -34,54 +34,54 @@ class FilterDuplicatedIndexesByNamePredicateTest { @Test void shouldValidateArguments() { assertThatThrownBy(() -> FilterDuplicatedIndexesByNamePredicate.of((String) null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("objectName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("objectName cannot be null"); assertThatThrownBy(() -> FilterDuplicatedIndexesByNamePredicate.of("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("objectName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("objectName cannot be blank"); assertThatThrownBy(() -> FilterDuplicatedIndexesByNamePredicate.of(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("objectName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("objectName cannot be blank"); assertThatThrownBy(() -> FilterDuplicatedIndexesByNamePredicate.of((Collection) null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("exclusions cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("exclusions cannot be null"); } @Test void forSingleIndexName() { final Predicate predicate = FilterDuplicatedIndexesByNamePredicate.of("idx3"); assertThat(predicate) - .accepts(DuplicatedIndexes.of(FIRST, SECOND)) - .rejects(DuplicatedIndexes.of(SECOND, THIRD)) - .rejects(DuplicatedIndexes.of(THIRD, FIRST)); + .accepts(DuplicatedIndexes.of(FIRST, SECOND)) + .rejects(DuplicatedIndexes.of(SECOND, THIRD)) + .rejects(DuplicatedIndexes.of(THIRD, FIRST)); } @Test void caseShouldNotMatter() { final Predicate predicate = FilterDuplicatedIndexesByNamePredicate.of("IDX3"); assertThat(predicate) - .accepts(DuplicatedIndexes.of(FIRST, SECOND)) - .rejects(DuplicatedIndexes.of(SECOND, THIRD)) - .rejects(DuplicatedIndexes.of(THIRD, FIRST)); + .accepts(DuplicatedIndexes.of(FIRST, SECOND)) + .rejects(DuplicatedIndexes.of(SECOND, THIRD)) + .rejects(DuplicatedIndexes.of(THIRD, FIRST)); } @Test void forMultipleIndexNames() { final Predicate predicate = FilterDuplicatedIndexesByNamePredicate.of(List.of("idx3", "idx4", "idx5")); assertThat(predicate) - .accepts(DuplicatedIndexes.of(FIRST, SECOND)) - .rejects(DuplicatedIndexes.of(SECOND, THIRD)) - .rejects(DuplicatedIndexes.of(THIRD, FIRST)); + .accepts(DuplicatedIndexes.of(FIRST, SECOND)) + .rejects(DuplicatedIndexes.of(SECOND, THIRD)) + .rejects(DuplicatedIndexes.of(THIRD, FIRST)); } @Test void forEmpty() { final Predicate predicate = FilterDuplicatedIndexesByNamePredicate.of(List.of()); assertThat(predicate) - .accepts(DuplicatedIndexes.of(FIRST, SECOND)) - .accepts(DuplicatedIndexes.of(SECOND, THIRD)) - .accepts(DuplicatedIndexes.of(THIRD, FIRST)); + .accepts(DuplicatedIndexes.of(FIRST, SECOND)) + .accepts(DuplicatedIndexes.of(SECOND, THIRD)) + .accepts(DuplicatedIndexes.of(THIRD, FIRST)); } @Test @@ -91,11 +91,11 @@ void shouldCreateDefensiveCopy() { exclusions.clear(); assertThat(exclusions) - .isEmpty(); + .isEmpty(); assertThat(predicate) - .accepts(DuplicatedIndexes.of(FIRST, SECOND)) - .rejects(DuplicatedIndexes.of(SECOND, THIRD)) - .rejects(DuplicatedIndexes.of(THIRD, FIRST)); + .accepts(DuplicatedIndexes.of(FIRST, SECOND)) + .rejects(DuplicatedIndexes.of(SECOND, THIRD)) + .rejects(DuplicatedIndexes.of(THIRD, FIRST)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByBloatPredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByBloatPredicateTest.java index ecbb4499..9b2560cb 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByBloatPredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByBloatPredicateTest.java @@ -26,30 +26,30 @@ class FilterIndexesByBloatPredicateTest { @Test void shouldValidateArguments() { assertThatThrownBy(() -> FilterIndexesByBloatPredicate.of(-1L, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("sizeThresholdInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sizeThresholdInBytes cannot be less than zero"); assertThatThrownBy(() -> FilterIndexesByBloatPredicate.of(1L, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("percentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("percentageThreshold should be in the range from 0 to 100 inclusive"); assertThatThrownBy(() -> FilterIndexesByBloatPredicate.of(1L, 101)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("percentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("percentageThreshold should be in the range from 0 to 100 inclusive"); } @Test void shouldBeInclusive() { final Predicate predicate = FilterIndexesByBloatPredicate.of(10L, 20); assertThat(predicate) - .rejects(IndexWithBloat.of("t", "idx", 200L, 20L, 10)) - .rejects(IndexWithBloat.of("t", "idx", 18L, 9L, 50)) - .accepts(IndexWithBloat.of("t", "idx", 20L, 10L, 50)); + .rejects(IndexWithBloat.of("t", "idx", 200L, 20L, 10)) + .rejects(IndexWithBloat.of("t", "idx", 18L, 9L, 50)) + .accepts(IndexWithBloat.of("t", "idx", 20L, 10L, 50)); } @Test void forZero() { final Predicate predicate = FilterIndexesByBloatPredicate.of(0L, 0); assertThat(predicate) - .accepts(IndexWithBloat.of("t", "idx", 1L, 0L, 0)) - .accepts(IndexWithBloat.of("t", "idx", 11L, 11L, 100)); + .accepts(IndexWithBloat.of("t", "idx", 1L, 0L, 0)) + .accepts(IndexWithBloat.of("t", "idx", 11L, 11L, 100)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByNamePredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByNamePredicateTest.java index 59d26b9c..2ac03ca7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByNamePredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesByNamePredicateTest.java @@ -31,17 +31,17 @@ class FilterIndexesByNamePredicateTest { void caseShouldNotMatter() { final Predicate predicate = FilterIndexesByNamePredicate.of("idx3"); assertThat(predicate) - .accepts(FIRST) - .accepts(SECOND) - .rejects(THIRD); + .accepts(FIRST) + .accepts(SECOND) + .rejects(THIRD); } @Test void forEmpty() { final Predicate predicate = FilterIndexesByNamePredicate.of(List.of()); assertThat(predicate) - .accepts(FIRST) - .accepts(SECOND) - .accepts(THIRD); + .accepts(FIRST) + .accepts(SECOND) + .accepts(THIRD); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesBySizePredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesBySizePredicateTest.java index 44c0ee4d..27dd47c1 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesBySizePredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterIndexesBySizePredicateTest.java @@ -30,25 +30,25 @@ class FilterIndexesBySizePredicateTest { @Test void shouldValidateArguments() { assertThatThrownBy(() -> FilterIndexesBySizePredicate.of(-1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("thresholdInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("thresholdInBytes cannot be less than zero"); } @Test void shouldBeInclusive() { final Predicate predicate = FilterIndexesBySizePredicate.of(20L); assertThat(predicate) - .rejects(FIRST) - .accepts(SECOND) - .accepts(THIRD); + .rejects(FIRST) + .accepts(SECOND) + .accepts(THIRD); } @Test void forZero() { final Predicate predicate = FilterIndexesBySizePredicate.of(0L); assertThat(predicate) - .accepts(FIRST) - .accepts(SECOND) - .accepts(THIRD); + .accepts(FIRST) + .accepts(SECOND) + .accepts(THIRD); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByBloatPredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByBloatPredicateTest.java index e36f5084..299e0898 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByBloatPredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByBloatPredicateTest.java @@ -26,8 +26,8 @@ class FilterTablesByBloatPredicateTest { void shouldBeInclusive() { final Predicate predicate = FilterTablesByBloatPredicate.of(10L, 20); assertThat(predicate) - .rejects(TableWithBloat.of("t", 100L, 10L, 10)) - .rejects(TableWithBloat.of("t", 18L, 9L, 50)) - .accepts(TableWithBloat.of("t", 100L, 20L, 20)); + .rejects(TableWithBloat.of("t", 100L, 10L, 10)) + .rejects(TableWithBloat.of("t", 18L, 9L, 50)) + .accepts(TableWithBloat.of("t", 100L, 20L, 20)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByNamePredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByNamePredicateTest.java index 514326a4..1024e7b7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByNamePredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesByNamePredicateTest.java @@ -31,17 +31,17 @@ class FilterTablesByNamePredicateTest { void caseShouldNotMatter() { final Predicate predicate = FilterTablesByNamePredicate.of("table3"); assertThat(predicate) - .accepts(FIRST) - .accepts(SECOND) - .rejects(THIRD); + .accepts(FIRST) + .accepts(SECOND) + .rejects(THIRD); } @Test void forEmpty() { final Predicate predicate = FilterTablesByNamePredicate.of(List.of()); assertThat(predicate) - .accepts(FIRST) - .accepts(SECOND) - .accepts(THIRD); + .accepts(FIRST) + .accepts(SECOND) + .accepts(THIRD); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicateTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicateTest.java index d162d5c2..11826908 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicateTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/checks/predicates/FilterTablesBySizePredicateTest.java @@ -30,16 +30,16 @@ class FilterTablesBySizePredicateTest { @Test void shouldValidateArguments() { assertThatThrownBy(() -> FilterTablesBySizePredicate.of(-1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("thresholdInBytes cannot be less than zero"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("thresholdInBytes cannot be less than zero"); } @Test void shouldBeInclusive() { final Predicate predicate = FilterTablesBySizePredicate.of(12L); assertThat(predicate) - .rejects(FIRST) - .accepts(SECOND) - .accepts(THIRD); + .rejects(FIRST) + .accepts(SECOND) + .accepts(THIRD); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilderTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilderTest.java index b5ea8397..6a561d3f 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilderTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsBuilderTest.java @@ -21,10 +21,10 @@ class ExclusionsBuilderTest { @Test void toStringBuilderTest() { assertThat(Exclusions.builder()) - .hasToString("ExclusionsBuilder{duplicatedIndexesExclusions='', intersectedIndexesExclusions='', " + - "unusedIndexesExclusions='', tablesWithMissingIndexesExclusions='', tablesWithoutPrimaryKeyExclusions='', " + - "indexesWithNullValuesExclusions='', btreeIndexesOnArrayColumnsExclusions='', " + - "indexSizeThresholdInBytes=0, tableSizeThresholdInBytes=0, " + "indexBloatSizeThresholdInBytes=0, indexBloatPercentageThreshold=0, " + - "tableBloatSizeThresholdInBytes=0, tableBloatPercentageThreshold=0}"); + .hasToString("ExclusionsBuilder{duplicatedIndexesExclusions='', intersectedIndexesExclusions='', " + + "unusedIndexesExclusions='', tablesWithMissingIndexesExclusions='', tablesWithoutPrimaryKeyExclusions='', " + + "indexesWithNullValuesExclusions='', btreeIndexesOnArrayColumnsExclusions='', " + + "indexSizeThresholdInBytes=0, tableSizeThresholdInBytes=0, " + "indexBloatSizeThresholdInBytes=0, indexBloatPercentageThreshold=0, " + + "tableBloatSizeThresholdInBytes=0, tableBloatPercentageThreshold=0}"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsTest.java index ae87856d..395e437d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/ExclusionsTest.java @@ -23,60 +23,60 @@ class ExclusionsTest { @Test void parseTest() { final Exclusions e = Exclusions.builder() - .withDuplicatedIndexesExclusions("i1,i2,, i3, , i4 ") - .withIntersectedIndexesExclusions(", , ,, i5, i6") - .withUnusedIndexesExclusions(",i7,i8,,i9") - .withTablesWithMissingIndexesExclusions(", , , s.t1, s.t2") - .withTablesWithoutPrimaryKeyExclusions(" , , s.t3, s.t4, s.t5, t6") - .withIndexesWithNullValuesExclusions(",,s.i1, , , ,,,") - .withBtreeIndexesOnArrayColumnsExclusions(",s.i2, , ,s.i3") - .build(); + .withDuplicatedIndexesExclusions("i1,i2,, i3, , i4 ") + .withIntersectedIndexesExclusions(", , ,, i5, i6") + .withUnusedIndexesExclusions(",i7,i8,,i9") + .withTablesWithMissingIndexesExclusions(", , , s.t1, s.t2") + .withTablesWithoutPrimaryKeyExclusions(" , , s.t3, s.t4, s.t5, t6") + .withIndexesWithNullValuesExclusions(",,s.i1, , , ,,,") + .withBtreeIndexesOnArrayColumnsExclusions(",s.i2, , ,s.i3") + .build(); assertThat(e).isNotNull(); assertThat(e.getDuplicatedIndexesExclusions()) - .isNotNull() - .hasSize(4) - .containsExactlyInAnyOrder("i1", "i2", "i3", "i4"); + .isNotNull() + .hasSize(4) + .containsExactlyInAnyOrder("i1", "i2", "i3", "i4"); assertThat(e.getIntersectedIndexesExclusions()) - .isNotNull() - .hasSize(2) - .containsExactlyInAnyOrder("i5", "i6"); + .isNotNull() + .hasSize(2) + .containsExactlyInAnyOrder("i5", "i6"); assertThat(e.getUnusedIndexesExclusions()) - .isNotNull() - .hasSize(3) - .containsExactlyInAnyOrder("i7", "i8", "i9"); + .isNotNull() + .hasSize(3) + .containsExactlyInAnyOrder("i7", "i8", "i9"); assertThat(e.getTablesWithMissingIndexesExclusions()) - .isNotNull() - .hasSize(2) - .containsExactlyInAnyOrder("s.t1", "s.t2"); + .isNotNull() + .hasSize(2) + .containsExactlyInAnyOrder("s.t1", "s.t2"); assertThat(e.getTablesWithoutPrimaryKeyExclusions()) - .isNotNull() - .hasSize(4) - .containsExactlyInAnyOrder("s.t3", "s.t4", "s.t5", "t6"); + .isNotNull() + .hasSize(4) + .containsExactlyInAnyOrder("s.t3", "s.t4", "s.t5", "t6"); assertThat(e.getIndexesWithNullValuesExclusions()) - .isNotNull() - .hasSize(1) - .containsExactlyInAnyOrder("s.i1"); + .isNotNull() + .hasSize(1) + .containsExactlyInAnyOrder("s.i1"); assertThat(e.getBtreeIndexesOnArrayColumnsExclusions()) - .isNotNull() - .hasSize(2) - .containsExactlyInAnyOrder("s.i2", "s.i3"); + .isNotNull() + .hasSize(2) + .containsExactlyInAnyOrder("s.i2", "s.i3"); } @Test void sizeInBytesTest() { final Exclusions e = Exclusions.builder() - .withIndexSizeThreshold(11L) - .withTableSizeThreshold(22L) - .withIndexBloatSizeThreshold(33L) - .withTableBloatSizeThreshold(44L) - .build(); + .withIndexSizeThreshold(11L) + .withTableSizeThreshold(22L) + .withIndexBloatSizeThreshold(33L) + .withTableBloatSizeThreshold(44L) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexSizeThresholdInBytes()).isEqualTo(11L); assertThat(e.getTableSizeThresholdInBytes()).isEqualTo(22L); @@ -87,11 +87,11 @@ void sizeInBytesTest() { @Test void withMemoryUnitTest() { final Exclusions e = Exclusions.builder() - .withTableSizeThreshold(10, MemoryUnit.MB) - .withIndexSizeThreshold(2, MemoryUnit.GB) - .withIndexBloatSizeThreshold(4, MemoryUnit.KB) - .withTableBloatSizeThreshold(8, MemoryUnit.KB) - .build(); + .withTableSizeThreshold(10, MemoryUnit.MB) + .withIndexSizeThreshold(2, MemoryUnit.GB) + .withIndexBloatSizeThreshold(4, MemoryUnit.KB) + .withTableBloatSizeThreshold(8, MemoryUnit.KB) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexSizeThresholdInBytes()).isEqualTo(2_147_483_648L); assertThat(e.getTableSizeThresholdInBytes()).isEqualTo(10_485_760L); @@ -105,28 +105,28 @@ void emptyTest() { assertThat(e).isNotNull(); assertThat(e.getDuplicatedIndexesExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getIntersectedIndexesExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getUnusedIndexesExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getTablesWithMissingIndexesExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getTablesWithoutPrimaryKeyExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getIndexesWithNullValuesExclusions()) - .isNotNull() - .isEmpty(); + .isNotNull() + .isEmpty(); assertThat(e.getIndexSizeThresholdInBytes()).isZero(); assertThat(e.getTableSizeThresholdInBytes()).isZero(); @@ -140,21 +140,21 @@ void emptyTest() { void toStringTest() { final Exclusions e = Exclusions.empty(); assertThat(e) - .hasToString("Exclusions{duplicatedIndexesExclusions=[], " + "intersectedIndexesExclusions=[], unusedIndexesExclusions=[], " + - "tablesWithMissingIndexesExclusions=[], tablesWithoutPrimaryKeyExclusions=[], " + - "indexesWithNullValuesExclusions=[], btreeIndexesOnArrayColumnsExclusions=[], " + - "indexSizeThresholdInBytes=0, tableSizeThresholdInBytes=0, " + - "indexBloatSizeThresholdInBytes=0, indexBloatPercentageThreshold=0, " + "tableBloatSizeThresholdInBytes=0, tableBloatPercentageThreshold=0}"); + .hasToString("Exclusions{duplicatedIndexesExclusions=[], " + "intersectedIndexesExclusions=[], unusedIndexesExclusions=[], " + + "tablesWithMissingIndexesExclusions=[], tablesWithoutPrimaryKeyExclusions=[], " + + "indexesWithNullValuesExclusions=[], btreeIndexesOnArrayColumnsExclusions=[], " + + "indexSizeThresholdInBytes=0, tableSizeThresholdInBytes=0, " + + "indexBloatSizeThresholdInBytes=0, indexBloatPercentageThreshold=0, " + "tableBloatSizeThresholdInBytes=0, tableBloatPercentageThreshold=0}"); } @Test void builderWithZeroSizeInBytes() { final Exclusions e = Exclusions.builder() - .withIndexSizeThreshold(0L) - .withTableSizeThreshold(0L) - .withIndexBloatSizeThreshold(0L) - .withTableBloatSizeThreshold(0L) - .build(); + .withIndexSizeThreshold(0L) + .withTableSizeThreshold(0L) + .withIndexBloatSizeThreshold(0L) + .withTableBloatSizeThreshold(0L) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexSizeThresholdInBytes()).isZero(); assertThat(e.getTableSizeThresholdInBytes()).isZero(); @@ -165,11 +165,11 @@ void builderWithZeroSizeInBytes() { @Test void builderWithZeroSizeInMemoryUnits() { final Exclusions e = Exclusions.builder() - .withIndexSizeThreshold(0, MemoryUnit.KB) - .withTableSizeThreshold(0, MemoryUnit.KB) - .withIndexBloatSizeThreshold(0, MemoryUnit.KB) - .withTableBloatSizeThreshold(0, MemoryUnit.GB) - .build(); + .withIndexSizeThreshold(0, MemoryUnit.KB) + .withTableSizeThreshold(0, MemoryUnit.KB) + .withIndexBloatSizeThreshold(0, MemoryUnit.KB) + .withTableBloatSizeThreshold(0, MemoryUnit.GB) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexSizeThresholdInBytes()).isZero(); assertThat(e.getTableSizeThresholdInBytes()).isZero(); @@ -181,27 +181,27 @@ void builderWithZeroSizeInMemoryUnits() { void builderWithInvalidSize() { final ExclusionsBuilder builder = Exclusions.builder(); assertThatThrownBy(() -> builder.withIndexSizeThreshold(-1L)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withTableSizeThreshold(-1L)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withIndexBloatSizeThreshold(-1L)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withIndexSizeThreshold(-1, MemoryUnit.KB)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withTableSizeThreshold(-1, MemoryUnit.KB)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withIndexBloatSizeThreshold(-1, MemoryUnit.KB)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> builder.withTableBloatSizeThreshold(-1, MemoryUnit.MB)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } @Test void zeroPercentageThreshold() { final Exclusions e = Exclusions.builder() - .withIndexBloatPercentageThreshold(0) - .withTableBloatPercentageThreshold(0) - .build(); + .withIndexBloatPercentageThreshold(0) + .withTableBloatPercentageThreshold(0) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexBloatPercentageThreshold()).isZero(); assertThat(e.getTableBloatPercentageThreshold()).isZero(); @@ -210,9 +210,9 @@ void zeroPercentageThreshold() { @Test void maxPercentageThreshold() { final Exclusions e = Exclusions.builder() - .withIndexBloatPercentageThreshold(100) - .withTableBloatPercentageThreshold(100) - .build(); + .withIndexBloatPercentageThreshold(100) + .withTableBloatPercentageThreshold(100) + .build(); assertThat(e).isNotNull(); assertThat(e.getIndexBloatPercentageThreshold()).isEqualTo(100); assertThat(e.getTableBloatPercentageThreshold()).isEqualTo(100); @@ -222,16 +222,16 @@ void maxPercentageThreshold() { void invalidPercentageThreshold() { final ExclusionsBuilder builder = Exclusions.builder(); assertThatThrownBy(() -> builder.withIndexBloatPercentageThreshold(-1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); assertThatThrownBy(() -> builder.withIndexBloatPercentageThreshold(101)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("indexBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("indexBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); assertThatThrownBy(() -> builder.withTableBloatPercentageThreshold(-1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); assertThatThrownBy(() -> builder.withTableBloatPercentageThreshold(101)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("tableBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("tableBloatPercentageThreshold should be in the range from 0 to 100 inclusive"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/HealthLoggerTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/HealthLoggerTest.java index 0b21a843..f3406afb 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/HealthLoggerTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/HealthLoggerTest.java @@ -38,9 +38,9 @@ class HealthLoggerTest extends HealthLoggerTestBase { private static Clock originalClock; private final HealthLogger logger = new KeyValueFileHealthLogger( - getConnectionCredentials(), - new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), new PrimaryHostDeterminerImpl()), - DatabaseChecks::new); + getConnectionCredentials(), + new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), new PrimaryHostDeterminerImpl()), + DatabaseChecks::new); @BeforeAll static void setUp() { @@ -58,43 +58,43 @@ static void tearDown() { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void logAll(final String schemaName) { executeTestOnDatabase(schemaName, - dbp -> dbp.withReferences() - .withData() - .withInvalidIndex() - .withNullValuesInIndex() - .withBooleanValuesInIndex() - .withTableWithoutPrimaryKey() - .withDuplicatedIndex() - .withNonSuitableIndex() - .withJsonType() - .withSerialType() - .withFunctions() - .withNotValidConstraints() - .withBtreeIndexesOnArrayColumn(), - ctx -> { - collectStatistics(schemaName); - assertThat(logger.logAll(Exclusions.empty(), ctx)) - .hasSameSizeAs(Diagnostic.values()) - .containsExactlyInAnyOrder( - "1999-12-31T23:59:59Z\tdb_indexes_health\tinvalid_indexes\t1", - "1999-12-31T23:59:59Z\tdb_indexes_health\tduplicated_indexes\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\tforeign_keys_without_index\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_without_primary_key\t1", - "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_null_values\t1", - "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_bloat\t16", - "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_bloat\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\tintersected_indexes\t11", - "1999-12-31T23:59:59Z\tdb_indexes_health\tunused_indexes\t12", - "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_missing_indexes\t0", - "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_without_description\t4", - "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_without_description\t18", - "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_with_json_type\t1", - "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_with_serial_types\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\tfunctions_without_description\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_boolean\t1", - "1999-12-31T23:59:59Z\tdb_indexes_health\tnot_valid_constraints\t2", - "1999-12-31T23:59:59Z\tdb_indexes_health\tbtree_indexes_on_array_columns\t2"); - }); + dbp -> dbp.withReferences() + .withData() + .withInvalidIndex() + .withNullValuesInIndex() + .withBooleanValuesInIndex() + .withTableWithoutPrimaryKey() + .withDuplicatedIndex() + .withNonSuitableIndex() + .withJsonType() + .withSerialType() + .withFunctions() + .withNotValidConstraints() + .withBtreeIndexesOnArrayColumn(), + ctx -> { + collectStatistics(schemaName); + assertThat(logger.logAll(Exclusions.empty(), ctx)) + .hasSameSizeAs(Diagnostic.values()) + .containsExactlyInAnyOrder( + "1999-12-31T23:59:59Z\tdb_indexes_health\tinvalid_indexes\t1", + "1999-12-31T23:59:59Z\tdb_indexes_health\tduplicated_indexes\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\tforeign_keys_without_index\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_without_primary_key\t1", + "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_null_values\t1", + "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_bloat\t16", + "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_bloat\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\tintersected_indexes\t11", + "1999-12-31T23:59:59Z\tdb_indexes_health\tunused_indexes\t12", + "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_missing_indexes\t0", + "1999-12-31T23:59:59Z\tdb_indexes_health\ttables_without_description\t4", + "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_without_description\t18", + "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_with_json_type\t1", + "1999-12-31T23:59:59Z\tdb_indexes_health\tcolumns_with_serial_types\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\tfunctions_without_description\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\tindexes_with_boolean\t1", + "1999-12-31T23:59:59Z\tdb_indexes_health\tnot_valid_constraints\t2", + "1999-12-31T23:59:59Z\tdb_indexes_health\tbtree_indexes_on_array_columns\t2"); + }); } @ParameterizedTest @@ -104,10 +104,10 @@ void logTablesWithMissingIndexes(final String schemaName) { tryToFindAccountByClientId(schemaName); assertThat(logger.logAll(Exclusions.empty(), ctx)) - .hasSameSizeAs(Diagnostic.values()) - .filteredOn(ofKey(SimpleLoggingKey.TABLES_WITH_MISSING_INDEXES)) - .hasSize(1) - .containsExactly("1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_missing_indexes\t1"); + .hasSameSizeAs(Diagnostic.values()) + .filteredOn(ofKey(SimpleLoggingKey.TABLES_WITH_MISSING_INDEXES)) + .hasSize(1) + .containsExactly("1999-12-31T23:59:59Z\tdb_indexes_health\ttables_with_missing_indexes\t1"); }); } @@ -115,19 +115,19 @@ void logTablesWithMissingIndexes(final String schemaName) { void logAllWithDefaultSchema() { final List logs = logger.logAll(Exclusions.empty()); assertThat(logs) - .hasSameSizeAs(Diagnostic.values()); + .hasSameSizeAs(Diagnostic.values()); for (final SimpleLoggingKey key : SimpleLoggingKey.values()) { assertThat(logs) - .filteredOn(ofKey(key)) - .hasSize(1) - .containsExactly("1999-12-31T23:59:59Z\tdb_indexes_health\t" + key.getSubKeyName() + "\t0"); + .filteredOn(ofKey(key)) + .hasSize(1) + .containsExactly("1999-12-31T23:59:59Z\tdb_indexes_health\t" + key.getSubKeyName() + "\t0"); } } @Test void completenessTest() { assertThat(logger.logAll(Exclusions.empty())) - .as("All diagnostics must be logged") - .hasSameSizeAs(Diagnostic.values()); + .as("All diagnostics must be logged") + .hasSameSizeAs(Diagnostic.values()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/SimpleLoggingKeyTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/SimpleLoggingKeyTest.java index 6ad7aa68..daaf6db7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/SimpleLoggingKeyTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/SimpleLoggingKeyTest.java @@ -27,12 +27,12 @@ void getKeyName() { final Set keyNames = new HashSet<>(); for (final LoggingKey key : SimpleLoggingKey.values()) { assertThat(key.getKeyName()) - .isLowerCase() - .doesNotContainAnyWhitespaces(); + .isLowerCase() + .doesNotContainAnyWhitespaces(); keyNames.add(key.getKeyName()); } assertThat(keyNames) - .hasSize(1); + .hasSize(1); } @Test @@ -40,12 +40,12 @@ void getSubKeyName() { final Set subKeyNames = new HashSet<>(); for (final LoggingKey key : SimpleLoggingKey.values()) { assertThat(key.getSubKeyName()) - .isLowerCase() - .doesNotContainAnyWhitespaces(); + .isLowerCase() + .doesNotContainAnyWhitespaces(); subKeyNames.add(key.getSubKeyName()); } assertThat(subKeyNames) - .hasSize(SimpleLoggingKey.values().length); + .hasSize(SimpleLoggingKey.values().length); } @Test @@ -53,31 +53,31 @@ void descriptionShouldPresentAndBeUnique() { final Set descriptions = new HashSet<>(); for (final LoggingKey key : SimpleLoggingKey.values()) { assertThat(key.getDescription()) - .isLowerCase() - .containsWhitespaces(); + .isLowerCase() + .containsWhitespaces(); descriptions.add(key.getDescription()); } assertThat(descriptions) - .hasSize(SimpleLoggingKey.values().length); + .hasSize(SimpleLoggingKey.values().length); } @Test void descriptionCorrespondsToSubKeyName() { for (final LoggingKey key : SimpleLoggingKey.values()) { assertThat(key.getSubKeyName()) - .isEqualTo(key.getDescription().replace(' ', '_')); + .isEqualTo(key.getDescription().replace(' ', '_')); } } @Test void completenessTest() { assertThat(SimpleLoggingKey.values()) - .as("There must be logging key for each diagnostic") - .hasSameSizeAs(Diagnostic.values()); + .as("There must be logging key for each diagnostic") + .hasSameSizeAs(Diagnostic.values()); for (final SimpleLoggingKey key : SimpleLoggingKey.values()) { assertThat(Diagnostic.valueOf(key.toString())) - .as("Name of SimpleLoggingKey have to correspond to Diagnostic name") - .isNotNull(); + .as("Name of SimpleLoggingKey have to correspond to Diagnostic name") + .isNotNull(); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/StandardHealthLoggerTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/StandardHealthLoggerTest.java index 950912c5..f8788029 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/StandardHealthLoggerTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/health/logger/StandardHealthLoggerTest.java @@ -27,64 +27,64 @@ class StandardHealthLoggerTest extends HealthLoggerTestBase { private final HealthLogger logger = new StandardHealthLogger( - getConnectionCredentials(), - new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), new PrimaryHostDeterminerImpl()), - DatabaseChecks::new); + getConnectionCredentials(), + new HighAvailabilityPgConnectionFactoryImpl(new PgConnectionFactoryImpl(), new PrimaryHostDeterminerImpl()), + DatabaseChecks::new); @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void logAll(final String schemaName) { executeTestOnDatabase(schemaName, - dbp -> dbp.withReferences() - .withData() - .withInvalidIndex() - .withNullValuesInIndex() - .withBooleanValuesInIndex() - .withBtreeIndexesOnArrayColumn() - .withTableWithoutPrimaryKey() - .withDuplicatedIndex() - .withNonSuitableIndex() - .withJsonType() - .withSerialType() - .withFunctions() - .withNotValidConstraints(), - ctx -> { - collectStatistics(schemaName); - final List logs = logger.logAll(Exclusions.empty(), ctx); - assertThat(logs) - .hasSameSizeAs(Diagnostic.values()) - .containsExactlyInAnyOrder( - "invalid_indexes:1", - "duplicated_indexes:2", - "foreign_keys_without_index:2", - "tables_without_primary_key:1", - "indexes_with_null_values:1", - "indexes_with_bloat:16", - "tables_with_bloat:2", - "intersected_indexes:11", - "unused_indexes:12", - "tables_with_missing_indexes:0", - "tables_without_description:4", - "columns_without_description:18", - "columns_with_json_type:1", - "columns_with_serial_types:2", - "functions_without_description:2", - "indexes_with_boolean:1", - "not_valid_constraints:2", - "btree_indexes_on_array_columns:2"); - }); + dbp -> dbp.withReferences() + .withData() + .withInvalidIndex() + .withNullValuesInIndex() + .withBooleanValuesInIndex() + .withBtreeIndexesOnArrayColumn() + .withTableWithoutPrimaryKey() + .withDuplicatedIndex() + .withNonSuitableIndex() + .withJsonType() + .withSerialType() + .withFunctions() + .withNotValidConstraints(), + ctx -> { + collectStatistics(schemaName); + final List logs = logger.logAll(Exclusions.empty(), ctx); + assertThat(logs) + .hasSameSizeAs(Diagnostic.values()) + .containsExactlyInAnyOrder( + "invalid_indexes:1", + "duplicated_indexes:2", + "foreign_keys_without_index:2", + "tables_without_primary_key:1", + "indexes_with_null_values:1", + "indexes_with_bloat:16", + "tables_with_bloat:2", + "intersected_indexes:11", + "unused_indexes:12", + "tables_with_missing_indexes:0", + "tables_without_description:4", + "columns_without_description:18", + "columns_with_json_type:1", + "columns_with_serial_types:2", + "functions_without_description:2", + "indexes_with_boolean:1", + "not_valid_constraints:2", + "btree_indexes_on_array_columns:2"); + }); } @Test void logAllWithDefaultSchema() { final List logs = logger.logAll(Exclusions.empty()); assertThat(logs) - .hasSameSizeAs(Diagnostic.values()); + .hasSameSizeAs(Diagnostic.values()); for (final SimpleLoggingKey key : SimpleLoggingKey.values()) { assertThat(logs) - .filteredOn(ofKey(key)) - .hasSize(1) - .containsExactly(key.getSubKeyName() + ":0"); + .filteredOn(ofKey(key)) + .hasSize(1) + .containsExactly(key.getSubKeyName() + ":0"); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnClusterTest.java index 1566d8ea..563d3b19 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseCheckOnClusterTest.java @@ -26,23 +26,23 @@ class DatabaseCheckOnClusterTest { private static final Collection CONTEXTS = List.of( - PgContext.of("demo"), PgContext.of("test"), PgContext.ofPublic()); + PgContext.of("demo"), PgContext.of("test"), PgContext.ofPublic()); @SuppressWarnings("unchecked") @Test void check() { final DatabaseCheckOnCluster check = (DatabaseCheckOnCluster
) Mockito.spy(DatabaseCheckOnCluster.class); Mockito.when(check.check(any(PgContext.class), any())) - .thenAnswer(invocation -> { - final PgContext ctx = invocation.getArgument(0); - return List.of( - Table.of(ctx.enrichWithSchema("t1"), 1L), - Table.of(ctx.enrichWithSchema("t2"), 1L)); - }); + .thenAnswer(invocation -> { + final PgContext ctx = invocation.getArgument(0); + return List.of( + Table.of(ctx.enrichWithSchema("t1"), 1L), + Table.of(ctx.enrichWithSchema("t2"), 1L)); + }); final List
tables = check.check(CONTEXTS, item -> true); assertThat(tables) - .hasSize(6) - .extracting(Table::getTableName) - .containsExactlyInAnyOrder("t1", "demo.t1", "test.t1", "t2", "demo.t2", "test.t2"); + .hasSize(6) + .extracting(Table::getTableName) + .containsExactlyInAnyOrder("t1", "demo.t1", "test.t1", "t2", "demo.t2", "test.t2"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecksTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecksTest.java index f1ca3ba0..8c0ecbd8 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecksTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DatabaseChecksTest.java @@ -37,8 +37,8 @@ class DatabaseChecksTest extends DatabaseAwareTestBase { @Test void shouldThrowExceptionForInvalidType() { assertThatThrownBy(() -> checks.getCheck(Diagnostic.INVALID_INDEXES, Table.class)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Illegal type: class io.github.mfvanek.pg.model.table.Table"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Illegal type: class io.github.mfvanek.pg.model.table.Table"); } @ParameterizedTest @@ -46,9 +46,9 @@ void shouldThrowExceptionForInvalidType() { @DisplayName("For each diagnostic should exist check") void completenessTest(@Nonnull final Diagnostic diagnostic) { assertThat(checks.getCheck(diagnostic, DbObject.class)) - .isNotNull() - .satisfies(c -> assertThat(c.getDiagnostic()) - .isEqualTo(diagnostic)); + .isNotNull() + .satisfies(c -> assertThat(c.getDiagnostic()) + .isEqualTo(diagnostic)); } @Test @@ -61,8 +61,8 @@ void shouldThrowExceptionIfCheckNotFound() throws NoSuchFieldException, IllegalA clearMethod.invoke(fieldValue); assertThatThrownBy(() -> databaseChecks.getCheck(Diagnostic.INVALID_INDEXES, Index.class)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Check for diagnostic INVALID_INDEXES not found"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Check for diagnostic INVALID_INDEXES not found"); } @ParameterizedTest @@ -70,7 +70,7 @@ void shouldThrowExceptionIfCheckNotFound() throws NoSuchFieldException, IllegalA @DisplayName("Each check should return nothing on empty database") void onEmptyDatabaseCheckShouldReturnNothing(@Nonnull final Diagnostic diagnostic) { assertThat(checks.getCheck(diagnostic, DbObject.class).check()) - .isEmpty(); + .isEmpty(); } @ParameterizedTest @@ -78,8 +78,8 @@ void onEmptyDatabaseCheckShouldReturnNothing(@Nonnull final Diagnostic diagnosti void onDatabaseWithoutThemCheckShouldReturnNothing(@Nonnull final Diagnostic diagnostic) { for (final String schemaName : SCHEMAS) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData().withCommentOnColumns().withCommentOnTables(), ctx -> - assertThat(checks.getCheck(diagnostic, DbObject.class).check(ctx)) - .isEmpty()); + assertThat(checks.getCheck(diagnostic, DbObject.class).check(ctx)) + .isEmpty()); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DiagnosticTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DiagnosticTest.java index 8bd17de3..6b2be85a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DiagnosticTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/maintenance/DiagnosticTest.java @@ -50,19 +50,19 @@ void sqlQueryFileNameShouldHaveSqlExtension() { @Test void shouldBeAtLeastTwoChecksAcrossTheCluster() { final long countOfChecksAcrossTheCluster = Arrays.stream(Diagnostic.values()) - .peek(d -> { - assertThat(d.getQueryExecutor()).isNotNull(); - assertThat(d.getExecutionTopology()).isNotNull(); - }) - .filter(d -> d.getExecutionTopology() == Diagnostic.ExecutionTopology.ACROSS_CLUSTER) - .peek(d -> assertThat(d.isAcrossCluster()).isTrue()) - .count(); + .peek(d -> { + assertThat(d.getQueryExecutor()).isNotNull(); + assertThat(d.getExecutionTopology()).isNotNull(); + }) + .filter(d -> d.getExecutionTopology() == Diagnostic.ExecutionTopology.ACROSS_CLUSTER) + .peek(d -> assertThat(d.isAcrossCluster()).isTrue()) + .count(); assertThat(countOfChecksAcrossTheCluster).isEqualTo(2); } @Test void toStringTest() { assertThat(Diagnostic.UNUSED_INDEXES) - .hasToString("UNUSED_INDEXES"); + .hasToString("UNUSED_INDEXES"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplTest.java index 47522011..b74db2a6 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplTest.java @@ -29,7 +29,7 @@ class DatabaseManagementImplTest extends StatisticsAwareTestBase { private final DatabaseManagement databaseManagement = new DatabaseManagementImpl(getHaPgConnection(), - StatisticsMaintenanceOnHostImpl::new, ConfigurationMaintenanceOnHostImpl::new); + StatisticsMaintenanceOnHostImpl::new, ConfigurationMaintenanceOnHostImpl::new); @ParameterizedTest @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) @@ -38,17 +38,17 @@ void shouldResetCounters(final String schemaName) { final OffsetDateTime testStartTime = OffsetDateTime.now(ClockHolder.clock()); tryToFindAccountByClientId(schemaName); assertThat(getSeqScansForAccounts(ctx)) - .isGreaterThanOrEqualTo(AMOUNT_OF_TRIES); + .isGreaterThanOrEqualTo(AMOUNT_OF_TRIES); assertThat(databaseManagement.resetStatistics()) - .isTrue(); + .isTrue(); collectStatistics(schemaName); assertThat(getSeqScansForAccounts(ctx)) - .isZero(); + .isZero(); assertThat(databaseManagement.getLastStatsResetTimestamp()) - .isPresent() - .get() - .satisfies(t -> assertThat(t).isAfter(testStartTime)); + .isPresent() + .get() + .satisfies(t -> assertThat(t).isAfter(testStartTime)); }); } @@ -58,9 +58,9 @@ void shouldReturnParamsWithDefaultValues(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> { final ServerSpecification specification = ServerSpecification.builder().withCpuCores(2).withMemoryAmount(2, MemoryUnit.GB).withSSD().build(); assertThat(databaseManagement.getParamsWithDefaultValues(specification)) - .hasSize(5) - .extracting(PgParam::getName) - .containsExactlyInAnyOrder("log_min_duration_statement", "idle_in_transaction_session_timeout", "statement_timeout", "effective_cache_size", "temp_file_limit"); + .hasSize(5) + .extracting(PgParam::getName) + .containsExactlyInAnyOrder("log_min_duration_statement", "idle_in_transaction_session_timeout", "statement_timeout", "effective_cache_size", "temp_file_limit"); }); } @@ -68,8 +68,8 @@ void shouldReturnParamsWithDefaultValues(final String schemaName) { @ValueSource(strings = {PgContext.DEFAULT_SCHEMA_NAME, "custom"}) void shouldReturnParamsCurrentValues(final String schemaName) { executeTestOnDatabase(schemaName, dbp -> dbp.withReferences().withData(), ctx -> - assertThat(databaseManagement.getParamsCurrentValues()) - .hasSizeGreaterThan(ImportantParam.values().length) - .isUnmodifiable()); + assertThat(databaseManagement.getParamsCurrentValues()) + .hasSizeGreaterThan(ImportantParam.values().length) + .isUnmodifiable()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplUnitTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplUnitTest.java index be012582..225898f8 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplUnitTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/common/management/DatabaseManagementImplUnitTest.java @@ -36,17 +36,17 @@ class DatabaseManagementImplUnitTest { @Test void shouldThrowExceptionWhenInvalidArgumentsArePassed() { assertThatThrownBy(() -> new DatabaseManagementImpl(null, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("haPgConnection cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("haPgConnection cannot be null"); assertThatThrownBy(() -> new DatabaseManagementImpl(haPgConnectionMock, null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("statisticsOnHostFactory cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("statisticsOnHostFactory cannot be null"); final Function statisticsOnHostFactory = pgConnection -> Mockito.mock(StatisticsMaintenanceOnHost.class); assertThatThrownBy(() -> new DatabaseManagementImpl(haPgConnectionMock, statisticsOnHostFactory, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("configurationOnHostFactory cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("configurationOnHostFactory cannot be null"); } @Test @@ -64,13 +64,13 @@ void resetStatisticsShouldAggregateResultsFromAllHosts() { }; final DatabaseManagement management = new DatabaseManagementImpl(haPgConnectionMock, statisticsOnHostFactory, ConfigurationMaintenanceOnHostImpl::new); Mockito.when(haPgConnectionMock.getConnectionsToAllHostsInCluster()) - .thenReturn(Set.of(firstConnection, secondConnection)); + .thenReturn(Set.of(firstConnection, secondConnection)); // False on all hosts Mockito.when(firstStatisticsMock.resetStatistics()).thenReturn(Boolean.FALSE); Mockito.when(secondStatisticsMock.resetStatistics()).thenReturn(Boolean.FALSE); assertThat(management.resetStatistics()) - .isFalse(); + .isFalse(); Mockito.verify(firstStatisticsMock, Mockito.times(1)).resetStatistics(); Mockito.verify(secondStatisticsMock, Mockito.times(1)).resetStatistics(); Mockito.verifyNoMoreInteractions(firstStatisticsMock, secondStatisticsMock); @@ -79,7 +79,7 @@ void resetStatisticsShouldAggregateResultsFromAllHosts() { Mockito.when(firstStatisticsMock.resetStatistics()).thenReturn(Boolean.TRUE); Mockito.when(secondStatisticsMock.resetStatistics()).thenReturn(Boolean.TRUE); assertThat(management.resetStatistics()) - .isTrue(); + .isTrue(); Mockito.verify(firstStatisticsMock, Mockito.times(2)).resetStatistics(); Mockito.verify(secondStatisticsMock, Mockito.times(2)).resetStatistics(); Mockito.verifyNoMoreInteractions(firstStatisticsMock, secondStatisticsMock); diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/HighAvailabilityPgConnectionClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/HighAvailabilityPgConnectionClusterTest.java index 24a0b7a8..2def52e4 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/HighAvailabilityPgConnectionClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/HighAvailabilityPgConnectionClusterTest.java @@ -40,25 +40,25 @@ void standbyBecomesPrimaryOnPrimaryDownWithPredefinedDelay() { final HighAvailabilityPgConnection haPgConnection = HighAvailabilityPgConnectionImpl.of(firstConnection, pgConnections, 5_000L); assertThat(haPgConnection.getConnectionToPrimary()) - .as("First connection is primary") - .isEqualTo(firstConnection) - .as("Second connection is not primary") - .isNotEqualTo(secondConnection); + .as("First connection is primary") + .isEqualTo(firstConnection) + .as("Second connection is not primary") + .isNotEqualTo(secondConnection); postgresCluster.stopFirstContainer(); Awaitility - .await() - .atMost(PgConnectionAwareCluster.MAX_WAIT_INTERVAL_SECONDS) - .with() - .pollInterval(Duration.ofSeconds(2)) - .until(() -> haPgConnection.getConnectionToPrimary().equals(secondConnection)); + .await() + .atMost(PgConnectionAwareCluster.MAX_WAIT_INTERVAL_SECONDS) + .with() + .pollInterval(Duration.ofSeconds(2)) + .until(() -> haPgConnection.getConnectionToPrimary().equals(secondConnection)); assertThat(haPgConnection.getConnectionToPrimary()) - .as("Second connection is primary") - .isEqualTo(secondConnection) - .as("First connection is not primary") - .isNotEqualTo(firstConnection); + .as("Second connection is primary") + .isEqualTo(secondConnection) + .as("First connection is not primary") + .isNotEqualTo(firstConnection); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/PrimaryHostDeterminerClusterTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/PrimaryHostDeterminerClusterTest.java index 8f369631..f69ad5d2 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/PrimaryHostDeterminerClusterTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/e2e/PrimaryHostDeterminerClusterTest.java @@ -39,25 +39,25 @@ void correctPrimaryDetection() { final PgConnection secondConnection = postgresCluster.getSecondPgConnection(); assertThat(primaryHostDeterminer.isPrimary(firstConnection)) - .as("First connection is primary") - .isTrue(); + .as("First connection is primary") + .isTrue(); assertThat(primaryHostDeterminer.isPrimary(secondConnection)) - .as("Second connection is not primary") - .isFalse(); + .as("Second connection is not primary") + .isFalse(); postgresCluster.stopFirstContainer(); Awaitility - .await("Second node becomes primary") - .atMost(PgConnectionAwareCluster.MAX_WAIT_INTERVAL_SECONDS) - .with() - .pollInterval(Duration.ofSeconds(2)) - .until(() -> primaryHostDeterminer.isPrimary(secondConnection)); + .await("Second node becomes primary") + .atMost(PgConnectionAwareCluster.MAX_WAIT_INTERVAL_SECONDS) + .with() + .pollInterval(Duration.ofSeconds(2)) + .until(() -> primaryHostDeterminer.isPrimary(secondConnection)); assertThat(primaryHostDeterminer.isPrimary(secondConnection)) - .as("Second connection is primary") - .isTrue(); + .as("Second connection is primary") + .isTrue(); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImplTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImplTest.java index df05c561..ef899d59 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImplTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/settings/maintenance/ConfigurationMaintenanceOnHostImplTest.java @@ -33,32 +33,32 @@ class ConfigurationMaintenanceOnHostImplTest extends DatabaseAwareTestBase { @Test void getHostShouldReturnPrimary() { assertThat(configurationMaintenance.getHost()) - .isEqualTo(getHost()); + .isEqualTo(getHost()); } @Test void getParamsWithDefaultValues() { final ServerSpecification specification = ServerSpecification.builder() - .withCpuCores(2) - .withMemoryAmount(2, MemoryUnit.GB) - .withSSD() - .build(); + .withCpuCores(2) + .withMemoryAmount(2, MemoryUnit.GB) + .withSSD() + .build(); final Set paramsWithDefaultValues = configurationMaintenance.getParamsWithDefaultValues(specification); assertThat(paramsWithDefaultValues) - .hasSize(5) - .extracting(PgParam::getName) - .containsExactlyInAnyOrder("log_min_duration_statement", "idle_in_transaction_session_timeout", "statement_timeout", "effective_cache_size", "temp_file_limit"); + .hasSize(5) + .extracting(PgParam::getName) + .containsExactlyInAnyOrder("log_min_duration_statement", "idle_in_transaction_session_timeout", "statement_timeout", "effective_cache_size", "temp_file_limit"); } @Test void getParamsCurrentValues() { final Set currentValues = configurationMaintenance.getParamsCurrentValues(); assertThat(currentValues) - .hasSizeGreaterThan(200) - .isUnmodifiable(); + .hasSizeGreaterThan(200) + .isUnmodifiable(); final Set allParamNames = currentValues.stream() - .map(PgParam::getName) - .collect(Collectors.toUnmodifiableSet()); + .map(PgParam::getName) + .collect(Collectors.toUnmodifiableSet()); for (final ImportantParam importantParam : ImportantParam.values()) { assertThat(allParamNames).contains(importantParam.getName()); } @@ -68,17 +68,17 @@ void getParamsCurrentValues() { void getParamCurrentValue() { final PgParam currentValue = configurationMaintenance.getParamCurrentValue(ImportantParam.LOG_MIN_DURATION_STATEMENT); assertThat(currentValue) - .isNotNull() - .extracting(PgParam::getValue) - .isEqualTo(ImportantParam.LOG_MIN_DURATION_STATEMENT.getDefaultValue()); + .isNotNull() + .extracting(PgParam::getValue) + .isEqualTo(ImportantParam.LOG_MIN_DURATION_STATEMENT.getDefaultValue()); } @Test void getCurrentValueForUnknownParam() { final PgParam pgParam = PgParamImpl.of("unknown_param", ""); assertThatThrownBy(() -> configurationMaintenance.getParamCurrentValue(pgParam)) - .isInstanceOf(PgSqlException.class) - .hasCauseInstanceOf(SQLException.class) - .hasMessageContaining("unknown_param"); + .isInstanceOf(PgSqlException.class) + .hasCauseInstanceOf(SQLException.class) + .hasMessageContaining("unknown_param"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplTest.java index 78da98f4..c44aa916 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplTest.java @@ -28,7 +28,7 @@ class StatisticsMaintenanceOnHostImplTest extends StatisticsAwareTestBase { @Test void resetStatisticsOnEmptyDatabaseShouldExecuteCorrectly() { assertThat(statisticsMaintenance.resetStatistics()) - .isTrue(); + .isTrue(); } @ParameterizedTest @@ -39,23 +39,23 @@ void shouldResetCounters(final String schemaName) { tryToFindAccountByClientId(schemaName); final PgContext pgContext = PgContext.of(schemaName); assertThat(getSeqScansForAccounts(pgContext)) - .isGreaterThanOrEqualTo(AMOUNT_OF_TRIES); + .isGreaterThanOrEqualTo(AMOUNT_OF_TRIES); assertThat(statisticsMaintenance.resetStatistics()) - .isTrue(); + .isTrue(); collectStatistics(schemaName); assertThat(getSeqScansForAccounts(pgContext)) - .isZero(); + .isZero(); assertThat(statisticsMaintenance.getLastStatsResetTimestamp()) - .isPresent() - .get() - .satisfies(t -> assertThat(t).isAfter(testStartTime)); + .isPresent() + .get() + .satisfies(t -> assertThat(t).isAfter(testStartTime)); }); } @Test void getHostShouldWork() { assertThat(statisticsMaintenance.getHost()) - .isEqualTo(getHost()); + .isEqualTo(getHost()); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplUnitTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplUnitTest.java index 1dd3770a..5bd64a9f 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplUnitTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/statistics/maintenance/StatisticsMaintenanceOnHostImplUnitTest.java @@ -28,13 +28,13 @@ class StatisticsMaintenanceOnHostImplUnitTest { @Test void shouldFailOnNullArguments() { assertThatThrownBy(() -> new StatisticsMaintenanceOnHostImpl(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("pgConnection cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("pgConnection cannot be null"); final PgConnection connectionMock = Mockito.mock(PgConnection.class); assertThatThrownBy(() -> new StatisticsMaintenanceOnHostImpl(connectionMock, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("queryExecutor cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("queryExecutor cannot be null"); } @Test @@ -43,9 +43,9 @@ void resetStatisticsShouldReturnFalseOnEmptyResultSet() { final StatisticsQueryExecutor executorMock = Mockito.mock(StatisticsQueryExecutor.class); final StatisticsMaintenanceOnHost maintenance = new StatisticsMaintenanceOnHostImpl(connectionMock, executorMock); Mockito.when(executorMock.executeQuery(any(), any(), any())) - .thenReturn(List.of()); + .thenReturn(List.of()); assertThat(maintenance.resetStatistics()) - .isFalse(); + .isFalse(); } @Test @@ -54,8 +54,8 @@ void resetStatisticsShouldReturnFalseWhenFirstRowIsFalse() { final StatisticsQueryExecutor executorMock = Mockito.mock(StatisticsQueryExecutor.class); final StatisticsMaintenanceOnHost maintenance = new StatisticsMaintenanceOnHostImpl(connectionMock, executorMock); Mockito.when(executorMock.executeQuery(any(), any(), any())) - .thenReturn(List.of(Boolean.FALSE, Boolean.TRUE)); + .thenReturn(List.of(Boolean.FALSE, Boolean.TRUE)); assertThat(maintenance.resetStatistics()) - .isFalse(); + .isFalse(); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabaseAwareTestBase.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabaseAwareTestBase.java index 3e592609..9f37b952 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabaseAwareTestBase.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabaseAwareTestBase.java @@ -58,7 +58,7 @@ protected void executeTestOnDatabase(@Nonnull final String schemaName, @Nonnull final Consumer testExecutor) { try (DatabasePopulator databasePopulator = DatabasePopulator.builder(getDataSource(), schemaName, isProceduresSupported())) { databaseConfigurer.configure(databasePopulator) - .populate(); + .populate(); testExecutor.accept(PgContext.of(schemaName, 0)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabasePopulator.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabasePopulator.java index 9bdf2129..27e58bef 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabasePopulator.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/DatabasePopulator.java @@ -232,7 +232,7 @@ public DatabasePopulator withUniqueConstraintOnSerialColumn() { public DatabasePopulator withSerialPrimaryKeyReferencesToAnotherTable() { statementsToExecuteInSameTransaction.putIfAbsent(82, new CreateTableWithSerialPrimaryKeyReferencesToAnotherTable(schemaName)); return withCheckConstraintOnSerialPrimaryKey() - .withUniqueConstraintOnSerialColumn(); + .withUniqueConstraintOnSerialColumn(); } @Nonnull @@ -289,7 +289,7 @@ private void createInvalidIndex() { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.execute(String.format("create unique index concurrently if not exists " + - "i_clients_last_name_first_name on %s.clients (last_name, first_name)", schemaName)); + "i_clients_last_name_first_name on %s.clients (last_name, first_name)", schemaName)); } catch (SQLException ignored) { // do nothing, just skip error } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/StatisticsAwareTestBase.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/StatisticsAwareTestBase.java index 13c4c7d9..31b2378d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/StatisticsAwareTestBase.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/StatisticsAwareTestBase.java @@ -28,9 +28,9 @@ public abstract class StatisticsAwareTestBase extends DatabaseAwareTestBase { protected long getSeqScansForAccounts(@Nonnull final PgContext pgContext) { final String sqlQuery = - "select psat.relname::text as table_name, coalesce(psat.seq_scan, 0) as seq_scan\n" + - "from pg_catalog.pg_stat_all_tables psat\n" + - "where psat.schemaname = ?::text and psat.relname = 'accounts'::text;"; + "select psat.relname::text as table_name, coalesce(psat.seq_scan, 0) as seq_scan\n" + + "from pg_catalog.pg_stat_all_tables psat\n" + + "where psat.schemaname = ?::text and psat.relname = 'accounts'::text;"; try (Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(sqlQuery)) { statement.setString(1, pgContext.getSchemaName()); @@ -45,8 +45,8 @@ protected long getSeqScansForAccounts(@Nonnull final PgContext pgContext) { protected boolean existsStatisticsForTable(@Nonnull final String schemaName, @Nonnull final String tableName) { final String sqlQuery = - "select exists (select 1 from pg_catalog.pg_stats ps " + - "where ps.schemaname = ?::text and ps.tablename = ?::text);"; + "select exists (select 1 from pg_catalog.pg_stats ps " + + "where ps.schemaname = ?::text and ps.tablename = ?::text);"; try (Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(sqlQuery)) { statement.setString(1, schemaName); diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AbstractDbStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AbstractDbStatement.java index 93ea997b..d546af56 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AbstractDbStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AbstractDbStatement.java @@ -26,13 +26,13 @@ protected AbstractDbStatement(@Nonnull final String schemaName) { protected void throwExceptionIfTableDoesNotExist(@Nonnull final Statement statement, @Nonnull final String tableName) throws SQLException { final String checkQuery = String.format("select exists (%n" + - " select 1 %n" + - " from pg_catalog.pg_class c%n" + - " join pg_catalog.pg_namespace n on n.oid = c.relnamespace%n" + - " where n.nspname = '%s'%n" + - " and c.relname = '%s'%n" + - " and c.relkind = 'r'%n" + - " );", schemaName, tableName); + " select 1 %n" + + " from pg_catalog.pg_class c%n" + + " join pg_catalog.pg_namespace n on n.oid = c.relnamespace%n" + + " where n.nspname = '%s'%n" + + " and c.relname = '%s'%n" + + " and c.relkind = 'r'%n" + + " );", schemaName, tableName); try (ResultSet rs = statement.executeQuery(checkQuery)) { if (rs.next()) { final boolean schemaExists = rs.getBoolean(1); diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnColumnsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnColumnsStatement.java index dd7f7f50..1746546a 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnColumnsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnColumnsStatement.java @@ -23,6 +23,6 @@ public AddBlankCommentOnColumnsStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on column %1$s.clients.id is '';" + - "comment on column %1$s.accounts.id is ' ';", schemaName)); + "comment on column %1$s.accounts.id is ' ';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnFunctionsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnFunctionsStatement.java index 8d99e528..9dee3fa4 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnFunctionsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnFunctionsStatement.java @@ -23,6 +23,6 @@ public AddBlankCommentOnFunctionsStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on function %1$s.add(a integer, b integer) is ' ';" + - "comment on function %1$s.add(a int, b int, c int) is '';", schemaName)); + "comment on function %1$s.add(a int, b int, c int) is '';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnTablesStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnTablesStatement.java index f1f8d147..15522dc7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnTablesStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddBlankCommentOnTablesStatement.java @@ -23,6 +23,6 @@ public AddBlankCommentOnTablesStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on table %1$s.clients is ' ';" + - "comment on table %1$s.accounts is '';", schemaName)); + "comment on table %1$s.accounts is '';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnColumnsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnColumnsStatement.java index 43252fdf..0e20bc83 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnColumnsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnColumnsStatement.java @@ -23,14 +23,14 @@ public AddCommentOnColumnsStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on column %1$s.clients.id is 'Unique record ID';" + - "comment on column %1$s.clients.last_name is 'Customer''s last name';" + - "comment on column %1$s.clients.first_name is 'Customer''s given name';" + - "comment on column %1$s.clients.middle_name is 'Patronymic of the customer';" + - "comment on column %1$s.clients.info is 'Raw client data';" + - "comment on column %1$s.accounts.id is 'Unique record ID';" + - "comment on column %1$s.accounts.client_id is 'Customer record ID';" + - "comment on column %1$s.accounts.account_number is 'Customer''s account number';" + - "comment on column %1$s.accounts.account_balance is 'The balance on the customer''s account';" + - "comment on column %1$s.accounts.deleted is 'Indicates that the account has been deleted';", schemaName)); + "comment on column %1$s.clients.last_name is 'Customer''s last name';" + + "comment on column %1$s.clients.first_name is 'Customer''s given name';" + + "comment on column %1$s.clients.middle_name is 'Patronymic of the customer';" + + "comment on column %1$s.clients.info is 'Raw client data';" + + "comment on column %1$s.accounts.id is 'Unique record ID';" + + "comment on column %1$s.accounts.client_id is 'Customer record ID';" + + "comment on column %1$s.accounts.account_number is 'Customer''s account number';" + + "comment on column %1$s.accounts.account_balance is 'The balance on the customer''s account';" + + "comment on column %1$s.accounts.deleted is 'Indicates that the account has been deleted';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnFunctionsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnFunctionsStatement.java index 1843e33c..7eb65911 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnFunctionsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnFunctionsStatement.java @@ -23,6 +23,6 @@ public AddCommentOnFunctionsStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on function %1$s.add(a integer, b integer) is 'Sums two given arguments';" + - "comment on function %1$s.add(a int, b int, c int) is 'Sums three given arguments';", schemaName)); + "comment on function %1$s.add(a int, b int, c int) is 'Sums three given arguments';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnProceduresStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnProceduresStatement.java index 0ffacdc8..2369fab9 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnProceduresStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnProceduresStatement.java @@ -23,6 +23,6 @@ public AddCommentOnProceduresStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on procedure %1$s.insert_data(a integer, b integer) is 'Inserts two rows into clients';" + - "comment on procedure %1$s.insert_data(a int, b int, c int) is 'Inserts three rows into clients';", schemaName)); + "comment on procedure %1$s.insert_data(a int, b int, c int) is 'Inserts three rows into clients';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnTablesStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnTablesStatement.java index de7b23d7..fe5a9971 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnTablesStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddCommentOnTablesStatement.java @@ -23,6 +23,6 @@ public AddCommentOnTablesStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("comment on table %1$s.clients is 'Customer Information';" + - "comment on table %1$s.accounts is 'Information about customer accounts';", schemaName)); + "comment on table %1$s.accounts is 'Information about customer accounts';", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddInvalidForeignKeyStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddInvalidForeignKeyStatement.java index 7504422a..a5c5365c 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddInvalidForeignKeyStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddInvalidForeignKeyStatement.java @@ -23,10 +23,10 @@ public AddInvalidForeignKeyStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("alter table if exists %1$s.accounts " + - "add constraint c_accounts_fk_client_id_not_validated_yet foreign key (client_id) references %1$s.clients (id) not valid;", - schemaName)); + "add constraint c_accounts_fk_client_id_not_validated_yet foreign key (client_id) references %1$s.clients (id) not valid;", + schemaName)); statement.execute(String.format("alter table if exists %1$s.accounts " + - "add constraint c_accounts_chk_client_id_not_validated_yet check (client_id > 0) not valid;", - schemaName)); + "add constraint c_accounts_chk_client_id_not_validated_yet check (client_id > 0) not valid;", + schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddLinksBetweenAccountsAndClientsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddLinksBetweenAccountsAndClientsStatement.java index 2e23ec0c..ab8db686 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddLinksBetweenAccountsAndClientsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/AddLinksBetweenAccountsAndClientsStatement.java @@ -23,7 +23,7 @@ public AddLinksBetweenAccountsAndClientsStatement(@Nonnull final String schemaNa @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("alter table if exists %1$s.accounts " + - "add constraint c_accounts_fk_client_id foreign key (client_id) references %1$s.clients (id);", - schemaName)); + "add constraint c_accounts_fk_client_id foreign key (client_id) references %1$s.clients (id);", + schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateAccountsTableStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateAccountsTableStatement.java index 65190128..718f5c72 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateAccountsTableStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateAccountsTableStatement.java @@ -24,10 +24,10 @@ public CreateAccountsTableStatement(@Nonnull final String schemaName) { public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create sequence if not exists %s.accounts_seq", schemaName)); statement.execute(String.format("create table if not exists %1$s.accounts (" + - "id bigint not null primary key default nextval('%1$s.accounts_seq')," + - "client_id bigint not null," + - "account_number varchar(50) not null unique," + - "account_balance numeric(22,2) not null default 0," + - "deleted boolean not null default false)", schemaName)); + "id bigint not null primary key default nextval('%1$s.accounts_seq')," + + "client_id bigint not null," + + "account_number varchar(50) not null unique," + + "account_balance numeric(22,2) not null default 0," + + "deleted boolean not null default false)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateClientsTableStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateClientsTableStatement.java index 506e97b4..5637f78b 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateClientsTableStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateClientsTableStatement.java @@ -24,10 +24,10 @@ public CreateClientsTableStatement(@Nonnull final String schemaName) { public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create sequence if not exists %s.clients_seq", schemaName)); statement.execute(String.format("create table if not exists %1$s.clients (" + - "id bigint not null primary key default nextval('%1$s.clients_seq')," + - "last_name varchar(255) not null," + - "first_name varchar(255) not null," + - "middle_name varchar(255)," + - "info jsonb)", schemaName)); + "id bigint not null primary key default nextval('%1$s.clients_seq')," + + "last_name varchar(255) not null," + + "first_name varchar(255) not null," + + "middle_name varchar(255)," + + "info jsonb)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedCustomCollationIndexStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedCustomCollationIndexStatement.java index b02dd375..67c04e7d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedCustomCollationIndexStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedCustomCollationIndexStatement.java @@ -23,6 +23,6 @@ public CreateDuplicatedCustomCollationIndexStatement(@Nonnull final String schem @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists i_accounts_account_number " + - "on %1$s.accounts (account_number collate %1$s.\"C.UTF-8\")", schemaName)); + "on %1$s.accounts (account_number collate %1$s.\"C.UTF-8\")", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedIndexStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedIndexStatement.java index 68ab4f76..5cfbfeda 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedIndexStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateDuplicatedIndexStatement.java @@ -23,16 +23,16 @@ public CreateDuplicatedIndexStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists i_accounts_account_number " + - "on %s.accounts (account_number)", schemaName)); + "on %s.accounts (account_number)", schemaName)); statement.execute(String.format("create index if not exists i_accounts_account_number_not_deleted " + - "on %s.accounts (account_number) where not deleted", schemaName)); + "on %s.accounts (account_number) where not deleted", schemaName)); statement.execute(String.format("create index if not exists i_accounts_number_balance_not_deleted " + - "on %s.accounts (account_number, account_balance) where not deleted", schemaName)); + "on %s.accounts (account_number, account_balance) where not deleted", schemaName)); statement.execute(String.format("create index if not exists i_clients_last_first " + - "on %s.clients (last_name, first_name)", schemaName)); + "on %s.clients (last_name, first_name)", schemaName)); statement.execute(String.format("create index if not exists i_clients_last_name " + - "on %s.clients (last_name)", schemaName)); + "on %s.clients (last_name)", schemaName)); statement.execute(String.format("create index if not exists i_accounts_id_account_number_not_deleted " + - "on %s.accounts (id, account_number) where not deleted", schemaName)); + "on %s.accounts (id, account_number) where not deleted", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateForeignKeyOnNullableColumnStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateForeignKeyOnNullableColumnStatement.java index 5d5dbf3d..016f1153 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateForeignKeyOnNullableColumnStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateForeignKeyOnNullableColumnStatement.java @@ -23,6 +23,6 @@ public CreateForeignKeyOnNullableColumnStatement(@Nonnull final String schemaNam @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("alter table if exists %1$s.bad_clients " + - "add constraint c_bad_clients_fk_real_client_id foreign key (real_client_id) references %1$s.clients (id);", schemaName)); + "add constraint c_bad_clients_fk_real_client_id foreign key (real_client_id) references %1$s.clients (id);", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateFunctionsStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateFunctionsStatement.java index cbd20b85..6b0ee29f 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateFunctionsStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateFunctionsStatement.java @@ -23,14 +23,14 @@ public CreateFunctionsStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create or replace function %s.add(a integer, b integer) returns integer " + - "as 'select $1 + $2;' " + - "language sql " + - "immutable " + - "returns null on null input;", schemaName)); + "as 'select $1 + $2;' " + + "language sql " + + "immutable " + + "returns null on null input;", schemaName)); statement.execute(String.format("create or replace function %s.add(a int, b int, c int) returns int " + - "as 'select $1 + $2 + $3;' " + - "language sql " + - "immutable " + - "returns null on null input;", schemaName)); + "as 'select $1 + $2 + $3;' " + + "language sql " + + "immutable " + + "returns null on null input;", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithBooleanValues.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithBooleanValues.java index bb3efd69..aeb4ddb7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithBooleanValues.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithBooleanValues.java @@ -23,8 +23,8 @@ public CreateIndexWithBooleanValues(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists i_accounts_deleted " + - "on %s.accounts (deleted)", schemaName)); + "on %s.accounts (deleted)", schemaName)); statement.execute(String.format("create unique index if not exists i_accounts_account_number_deleted " + - "on %s.accounts (account_number, deleted)", schemaName)); + "on %s.accounts (account_number, deleted)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithNullValues.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithNullValues.java index 04f8cc01..efd451a1 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithNullValues.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexWithNullValues.java @@ -23,6 +23,6 @@ public CreateIndexWithNullValues(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists i_clients_middle_name " + - "on %s.clients (middle_name)", schemaName)); + "on %s.clients (middle_name)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexesWithDifferentOpclassStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexesWithDifferentOpclassStatement.java index d367fb70..039446a4 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexesWithDifferentOpclassStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateIndexesWithDifferentOpclassStatement.java @@ -23,8 +23,8 @@ public CreateIndexesWithDifferentOpclassStatement(@Nonnull final String schemaNa @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists i_clients_last_name " + - "on %s.clients using btree(lower(last_name))", schemaName)); + "on %s.clients using btree(lower(last_name))", schemaName)); statement.execute(String.format("create index if not exists i_clients_last_name_ops " + - "on %s.clients using btree(lower(last_name) text_pattern_ops)", schemaName)); + "on %s.clients using btree(lower(last_name) text_pattern_ops)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateMaterializedViewStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateMaterializedViewStatement.java index 9397f336..6c27ffcc 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateMaterializedViewStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateMaterializedViewStatement.java @@ -23,6 +23,6 @@ public CreateMaterializedViewStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create materialized view if not exists %1$s.accounts_mat_view as (" + - "select client_id, account_number from %1$s.accounts);", schemaName)); + "select client_id, account_number from %1$s.accounts);", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateNotSuitableIndexForForeignKeyStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateNotSuitableIndexForForeignKeyStatement.java index 67a1334b..5d31482d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateNotSuitableIndexForForeignKeyStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateNotSuitableIndexForForeignKeyStatement.java @@ -23,6 +23,6 @@ public CreateNotSuitableIndexForForeignKeyStatement(@Nonnull final String schema @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists " + - "i_accounts_account_number_client_id on %s.accounts (account_number, client_id)", schemaName)); + "i_accounts_account_number_client_id on %s.accounts (account_number, client_id)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateProceduresStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateProceduresStatement.java index 1effff5a..a32ac361 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateProceduresStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateProceduresStatement.java @@ -23,17 +23,17 @@ public CreateProceduresStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create or replace procedure %1$s.insert_data(a integer, b integer) " + - " language sql " + - "as $$ " + - "insert into %1$s.clients values (a); " + - "insert into %1$s.clients values (b); " + - "$$;", schemaName)); + " language sql " + + "as $$ " + + "insert into %1$s.clients values (a); " + + "insert into %1$s.clients values (b); " + + "$$;", schemaName)); statement.execute(String.format("create or replace procedure %1$s.insert_data(a int, b int, c int) " + - "language sql " + - "as $$ " + - "insert into %1$s.clients values (a); " + - "insert into %1$s.clients values (b); " + - "insert into %1$s.clients values (c); " + - "$$;", schemaName)); + "language sql " + + "as $$ " + + "insert into %1$s.clients values (a); " + + "insert into %1$s.clients values (b); " + + "insert into %1$s.clients values (c); " + + "$$;", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSchemaStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSchemaStatement.java index a0df6d00..64c256af 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSchemaStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSchemaStatement.java @@ -25,7 +25,7 @@ public CreateSchemaStatement(@Nonnull final String schemaName) { public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute("create schema if not exists " + schemaName); final String checkQuery = String.format( - "select exists(select 1 from information_schema.schemata where schema_name = '%s')", schemaName); + "select exists(select 1 from information_schema.schemata where schema_name = '%s')", schemaName); try (ResultSet rs = statement.executeQuery(checkQuery)) { if (rs.next()) { final boolean schemaExists = rs.getBoolean(1); diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSuitableIndexForForeignKeyStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSuitableIndexForForeignKeyStatement.java index e3a2b58b..c503f606 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSuitableIndexForForeignKeyStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateSuitableIndexForForeignKeyStatement.java @@ -23,6 +23,6 @@ public CreateSuitableIndexForForeignKeyStatement(@Nonnull final String schemaNam @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create index if not exists " + - "i_accounts_client_id_account_number on %s.accounts (client_id, account_number)", schemaName)); + "i_accounts_client_id_account_number on %s.accounts (client_id, account_number)", schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithCheckConstraintOnSerialPrimaryKey.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithCheckConstraintOnSerialPrimaryKey.java index 10ec7bc4..75b31de3 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithCheckConstraintOnSerialPrimaryKey.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithCheckConstraintOnSerialPrimaryKey.java @@ -23,9 +23,9 @@ public CreateTableWithCheckConstraintOnSerialPrimaryKey(@Nonnull final String sc @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create table if not exists %1$s.another_table(" + - "id bigserial primary key, " + - "constraint not_reserved_id check (id > 1000), " + - "constraint less_than_million check (id < 1000000));", - schemaName)); + "id bigserial primary key, " + + "constraint not_reserved_id check (id > 1000), " + + "constraint less_than_million check (id < 1000000));", + schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithColumnOfBigSerialTypeStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithColumnOfBigSerialTypeStatement.java index 167e693b..cfd8024e 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithColumnOfBigSerialTypeStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithColumnOfBigSerialTypeStatement.java @@ -23,11 +23,11 @@ public CreateTableWithColumnOfBigSerialTypeStatement(@Nonnull final String schem @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create table if not exists %s.bad_accounts (" + - "id bigserial not null primary key, " + - "name varchar(255) not null," + - // not null constraint will be added for all serial columns - "real_client_id bigserial," + - "real_account_id bigserial)", schemaName)); + "id bigserial not null primary key, " + + "name varchar(255) not null," + + // not null constraint will be added for all serial columns + "real_client_id bigserial," + + "real_account_id bigserial)", schemaName)); throwExceptionIfTableDoesNotExist(statement, "bad_accounts"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithSerialPrimaryKeyReferencesToAnotherTable.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithSerialPrimaryKeyReferencesToAnotherTable.java index 5e21c982..e94c3953 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithSerialPrimaryKeyReferencesToAnotherTable.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithSerialPrimaryKeyReferencesToAnotherTable.java @@ -23,11 +23,11 @@ public CreateTableWithSerialPrimaryKeyReferencesToAnotherTable(@Nonnull final St @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create table if not exists %1$s.test_table(" + - "id bigserial, " + - "num bigserial, " + - "constraint test_table_pkey_id primary key (id), " + - "constraint test_table_fkey_other_id foreign key (id) references %1$s.another_table (id), " + - "constraint test_table_fkey_one_more_id foreign key (id) references %1$s.one_more_table (id));", - schemaName)); + "id bigserial, " + + "num bigserial, " + + "constraint test_table_pkey_id primary key (id), " + + "constraint test_table_fkey_other_id foreign key (id) references %1$s.another_table (id), " + + "constraint test_table_fkey_one_more_id foreign key (id) references %1$s.one_more_table (id));", + schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithUniqueSerialColumn.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithUniqueSerialColumn.java index 103a06df..b786d960 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithUniqueSerialColumn.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithUniqueSerialColumn.java @@ -23,10 +23,10 @@ public CreateTableWithUniqueSerialColumn(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create table if not exists %1$s.one_more_table(" + - "id bigserial, " + - "constraint unique_id unique (id), " + - "constraint not_reserved_id check (id > 1000), " + - "constraint less_than_million check (id < 1000000));", - schemaName)); + "id bigserial, " + + "constraint unique_id unique (id), " + + "constraint not_reserved_id check (id > 1000), " + + "constraint less_than_million check (id < 1000000));", + schemaName)); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithoutPrimaryKeyStatement.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithoutPrimaryKeyStatement.java index 93082d32..f5f29a64 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithoutPrimaryKeyStatement.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/CreateTableWithoutPrimaryKeyStatement.java @@ -23,9 +23,9 @@ public CreateTableWithoutPrimaryKeyStatement(@Nonnull final String schemaName) { @Override public void execute(@Nonnull final Statement statement) throws SQLException { statement.execute(String.format("create table if not exists %s.bad_clients (" + - "id bigint not null, " + - "name varchar(255) not null," + - "real_client_id bigint)", schemaName)); + "id bigint not null, " + + "name varchar(255) not null," + + "real_client_id bigint)", schemaName)); throwExceptionIfTableDoesNotExist(statement, "bad_clients"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/InsertDataIntoTablesAction.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/InsertDataIntoTablesAction.java index c9002c75..81c3afa8 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/InsertDataIntoTablesAction.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/support/statements/InsertDataIntoTablesAction.java @@ -38,9 +38,9 @@ public InsertDataIntoTablesAction(@Nonnull final DataSource dataSource, @Nonnull public void run() { final int clientsCountToCreate = 1_000; final String insertClientSql = String.format( - "insert into %s.clients (id, first_name, last_name, info) values (?, ?, ?, ?)", schemaName); + "insert into %s.clients (id, first_name, last_name, info) values (?, ?, ?, ?)", schemaName); final String insertAccountSql = String.format( - "insert into %s.accounts (client_id, account_number) values (?, ?)", schemaName); + "insert into %s.accounts (client_id, account_number) values (?, ?)", schemaName); try (Connection connection = dataSource.getConnection(); PreparedStatement insertClientStatement = connection.prepareStatement(insertClientSql); PreparedStatement insertAccountStatement = connection.prepareStatement(insertAccountSql)) { diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ClockHolderTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ClockHolderTest.java index ccf7e028..b8ae0a62 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ClockHolderTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ClockHolderTest.java @@ -28,14 +28,14 @@ class ClockHolderTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(ClockHolder.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void clockDefaultValue() { assertThat(ClockHolder.clock()) - .isNotNull() - .isEqualTo(Clock.systemUTC()); + .isNotNull() + .isEqualTo(Clock.systemUTC()); } @Test @@ -45,11 +45,11 @@ void setClockShouldWork() { final Clock oldClock = ClockHolder.setClock(fixed); try { assertThat(ClockHolder.clock()) - .isNotNull() - .isSameAs(fixed); + .isNotNull() + .isSameAs(fixed); assertThat(LocalDateTime.now(ClockHolder.clock())) - .isNotNull() - .isEqualTo(dateTime); + .isNotNull() + .isEqualTo(dateTime); } finally { ClockHolder.setClock(oldClock); } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/CollectionUtilsTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/CollectionUtilsTest.java index 18d3afca..0063c46d 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/CollectionUtilsTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/CollectionUtilsTest.java @@ -26,43 +26,43 @@ class CollectionUtilsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(CollectionUtils.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @SuppressWarnings("ConstantConditions") @Test void intersectionShouldThrowExceptionOnInvalidArguments() { assertThatThrownBy(() -> CollectionUtils.intersection(null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("first cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("first cannot be null"); final List empty = List.of(); assertThatThrownBy(() -> CollectionUtils.intersection(empty, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("second cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("second cannot be null"); } @Test void intersectionShouldWorkWithEmptyCollections() { assertThat(CollectionUtils.intersection(List.of(), Set.of(1))) - .isEmpty(); + .isEmpty(); assertThat(CollectionUtils.intersection(Set.of(1), List.of())) - .isEmpty(); + .isEmpty(); } @Test void intersectionShouldRemoveDuplicates() { assertThat(CollectionUtils.intersection(List.of(10, 10, 11, 12), Set.of(10, 12, 14))) - .hasSize(2) - .containsExactly(10, 12); + .hasSize(2) + .containsExactly(10, 12); assertThat(CollectionUtils.intersection(Set.of(44, 90, 33, 12), List.of(21, 44, 12, 33, 34, 12, 44, 33))) - .hasSize(3) - .containsExactlyInAnyOrder(44, 33, 12); // ordering based on first argument and not guaranteed for Set + .hasSize(3) + .containsExactlyInAnyOrder(44, 33, 12); // ordering based on first argument and not guaranteed for Set } @Test void intersectionShouldRemainOrderingFromFirstIfPossible() { assertThat(CollectionUtils.intersection(List.of(7, 1, -1, 0, 3), List.of(0, 3, 7))) - .hasSize(3) - .containsExactly(7, 0, 3); + .hasSize(3) + .containsExactly(7, 0, 3); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParserTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParserTest.java index f9f038e0..ac7c02b7 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParserTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/ColumnsInForeignKeyParserTest.java @@ -24,34 +24,34 @@ class ColumnsInForeignKeyParserTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(ColumnsInForeignKeyParser.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @SuppressWarnings("ConstantConditions") @Test void shouldThrowExceptionWhenPassedInvalidData() { assertThatThrownBy(() -> ColumnsInForeignKeyParser.parseRawColumnData(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("tableName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("tableName cannot be null"); assertThatThrownBy(() -> ColumnsInForeignKeyParser.parseRawColumnData("t")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Columns array cannot be empty"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Columns array cannot be empty"); assertThatThrownBy(() -> ColumnsInForeignKeyParser.parseRawColumnData("t", "abracadabra")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Cannot parse column info from abracadabra"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot parse column info from abracadabra"); assertThatThrownBy(() -> ColumnsInForeignKeyParser.parseRawColumnData("t", "a, b, c")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Cannot parse column info from a, b, c"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot parse column info from a, b, c"); } @Test void shouldWorkWhenValidDataPassed() { assertThat(ColumnsInForeignKeyParser.parseRawColumnData("t", "c1, true", "c2, false", "c3, abracadabra")) - .hasSize(3) - .containsExactly( - Column.ofNotNull("t", "c1"), - Column.ofNullable("t", "c2"), - Column.ofNullable("t", "c3")) - .isUnmodifiable(); + .hasSize(3) + .containsExactly( + Column.ofNotNull("t", "c1"), + Column.ofNullable("t", "c2"), + Column.ofNullable("t", "c3")) + .isUnmodifiable(); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/NamedParametersParserTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/NamedParametersParserTest.java index 88e2eb22..3376950e 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/NamedParametersParserTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/NamedParametersParserTest.java @@ -24,91 +24,91 @@ class NamedParametersParserTest { @Test void withInvalidArguments() { assertThatThrownBy(() -> parse(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("originalSqlQuery cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("originalSqlQuery cannot be null"); assertThatThrownBy(() -> parse("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("originalSqlQuery cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("originalSqlQuery cannot be blank"); assertThatThrownBy(() -> parse(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("originalSqlQuery cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("originalSqlQuery cannot be blank"); } @Test void parseWithoutNamedParams() { assertThat(parse("select * from orders;")) - .isEqualTo("select * from orders;"); + .isEqualTo("select * from orders;"); assertThat(parse("select * from accounts where account_number = ?")) - .isEqualTo("select * from accounts where account_number = ?"); + .isEqualTo("select * from accounts where account_number = ?"); } @Test void parseWithSingleLineComment() { assertThat(parse("select * from accounts --test")) - .isEqualTo("select * from accounts --test"); + .isEqualTo("select * from accounts --test"); assertThat(parse("select * from accounts where account_number = ? --test")) - .isEqualTo("select * from accounts where account_number = ? --test"); + .isEqualTo("select * from accounts where account_number = ? --test"); assertThat(parse("select * from clients where id = :p_id --test\n and name = :p_name")) - .isEqualTo("select * from clients where id = ? --test\n and name = ?"); + .isEqualTo("select * from clients where id = ? --test\n and name = ?"); } @Test void parseWithMultiLineComment() { assertThat(parse("select * from /* test \ncomment */ accounts")) - .isEqualTo("select * from /* test \ncomment */ accounts"); + .isEqualTo("select * from /* test \ncomment */ accounts"); assertThat(parse("select * from /* test \n:comment */ accounts where id = :p_id;")) - .isEqualTo("select * from /* test \n:comment */ accounts where id = ?;"); + .isEqualTo("select * from /* test \n:comment */ accounts where id = ?;"); } @Test void parseWithQuotes() { assertThat(parse("select id as \"counter\" from orders where name = 'test';")) - .isEqualTo("select id as \"counter\" from orders where name = 'test';"); + .isEqualTo("select id as \"counter\" from orders where name = 'test';"); assertThat(parse("select id as \"counter\" from orders where name = :p_name;")) - .isEqualTo("select id as \"counter\" from orders where name = ?;"); + .isEqualTo("select id as \"counter\" from orders where name = ?;"); } @Test void parseWithDoubleColon() { assertThat(parse("select id::text from orders where id < 10::bigint")) - .isEqualTo("select id::text from orders where id < 10::bigint"); + .isEqualTo("select id::text from orders where id < 10::bigint"); assertThat(parse("select * from accounts where account_number = ?::text")) - .isEqualTo("select * from accounts where account_number = ?::text"); + .isEqualTo("select * from accounts where account_number = ?::text"); assertThat(parse("select * from accounts where account_number = :p_num::text")) - .isEqualTo("select * from accounts where account_number = ?::text"); + .isEqualTo("select * from accounts where account_number = ?::text"); assertThat(parse("select c.* from clients c where c.first_name = :p_name::text and c.last_name = :p_surname::text;")) - .isEqualTo("select c.* from clients c where c.first_name = ?::text and c.last_name = ?::text;"); + .isEqualTo("select c.* from clients c where c.first_name = ?::text and c.last_name = ?::text;"); } @Test void parseWithInvalidNameAfterDoubleColon() { assertThat(parse("select * from accounts where account_number = :p_num:::text")) - .isEqualTo("select * from accounts where account_number = ?::?"); + .isEqualTo("select * from accounts where account_number = ?::?"); } @Test void parseWithInvalidNameAfterColon() { assertThat(parse("select * from accounts where account_number = :p%num::text")) - .isEqualTo("select * from accounts where account_number = ?%num::text"); + .isEqualTo("select * from accounts where account_number = ?%num::text"); } @Test void parseWithColonInTheEnd() { assertThat(parse("select * from accounts where account_number = :")) - .isEqualTo("select * from accounts where account_number = :"); + .isEqualTo("select * from accounts where account_number = :"); assertThat(parse("select * from accounts where account_number = :%")) - .isEqualTo("select * from accounts where account_number = :%"); + .isEqualTo("select * from accounts where account_number = :%"); } @Test void parseWithArraySlice() { assertThat(parse("select schedule[1:2][1:1] from sal_emp where name = 'Bill';")) - .isEqualTo("select schedule[1:2][1:1] from sal_emp where name = 'Bill';"); + .isEqualTo("select schedule[1:2][1:1] from sal_emp where name = 'Bill';"); assertThat(parse("select schedule[1:2][1:1] from sal_emp where name = :name_param::text;")) - .isEqualTo("select schedule[1:2][1:1] from sal_emp where name = ?::text;"); + .isEqualTo("select schedule[1:2][1:1] from sal_emp where name = ?::text;"); assertThat(parse("inner join pg_catalog.pg_attribute as col on i.indrelid = col.attrelid and col.attnum = any((string_to_array(i.indkey::text, ' ')::int2[])[:i.indnkeyatts])")) - .isEqualTo("inner join pg_catalog.pg_attribute as col on i.indrelid = col.attrelid and col.attnum = any((string_to_array(i.indkey::text, ' ')::int2[])[:i.indnkeyatts])"); + .isEqualTo("inner join pg_catalog.pg_attribute as col on i.indrelid = col.attrelid and col.attnum = any((string_to_array(i.indkey::text, ' ')::int2[])[:i.indnkeyatts])"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/PostgresVersionTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/PostgresVersionTest.java index 0bb5ff59..fb76a69b 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/PostgresVersionTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/PostgresVersionTest.java @@ -28,6 +28,6 @@ void checkPgVersion() { final String requiredPgVersionString = (pgVersionFromEnv == null) ? "16.2 (Debian 16.2-" : pgVersionFromEnv.split("-")[0]; final String actualPgVersionString = PostgresVersionReader.readVersion(getDataSource()); assertThat(actualPgVersionString) - .startsWith(requiredPgVersionString); + .startsWith(requiredPgVersionString); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/QueryExecutorsTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/QueryExecutorsTest.java index 93dcbace..d6387b56 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/QueryExecutorsTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/QueryExecutorsTest.java @@ -34,7 +34,7 @@ class QueryExecutorsTest extends DatabaseAwareTestBase { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(QueryExecutors.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @SuppressWarnings("ConstantConditions") @@ -43,8 +43,8 @@ void executeInvalidQuery() { final String invalidSql = "select unknown_field from unknown_table"; final PgConnection pgConnection = getPgConnection(); assertThatThrownBy(() -> QueryExecutors.executeQuery(pgConnection, invalidSql, rs -> null)) - .isInstanceOf(PgSqlException.class) - .hasCauseInstanceOf(SQLException.class); + .isInstanceOf(PgSqlException.class) + .hasCauseInstanceOf(SQLException.class); } @SuppressWarnings("ConstantConditions") @@ -54,8 +54,8 @@ void executeInvalidQueryWithSchema() { final PgContext context = PgContext.of("s"); final PgConnection pgConnection = getPgConnection(); assertThatThrownBy(() -> QueryExecutors.executeQueryWithSchema(pgConnection, context, invalidSqlWithParam, rs -> null)) - .isInstanceOf(PgSqlException.class) - .hasCauseInstanceOf(SQLException.class); + .isInstanceOf(PgSqlException.class) + .hasCauseInstanceOf(SQLException.class); } @SuppressWarnings("ConstantConditions") @@ -63,8 +63,8 @@ void executeInvalidQueryWithSchema() { void executeNullQuery() { final PgConnection pgConnection = getPgConnection(); assertThatThrownBy(() -> QueryExecutors.executeQuery(pgConnection, null, rs -> null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("sqlQuery cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("sqlQuery cannot be null"); } @Test @@ -80,10 +80,10 @@ void executeQueryWithSchemaWithExecutionError() throws SQLException { final PgConnection pgConnection = PgConnectionImpl.of(dataSource, PgHostImpl.ofUrl("jdbc:postgresql://localhost:6432")); final PgContext context = PgContext.ofPublic(); assertThatThrownBy(() -> QueryExecutors.executeQueryWithSchema(pgConnection, context, "select version()", rs -> rs.getString(1))) - .isInstanceOf(PgSqlException.class) - .hasMessage("bad parameter") - .hasCauseInstanceOf(SQLException.class) - .hasRootCauseMessage("bad parameter"); + .isInstanceOf(PgSqlException.class) + .hasMessage("bad parameter") + .hasCauseInstanceOf(SQLException.class) + .hasRootCauseMessage("bad parameter"); } } @@ -100,10 +100,10 @@ void executeQueryWithBloatThresholdWithExecutionError() throws SQLException { final PgConnection pgConnection = PgConnectionImpl.of(dataSource, PgHostImpl.ofUrl("jdbc:postgresql://localhost:6432")); final PgContext context = PgContext.ofPublic(); assertThatThrownBy(() -> QueryExecutors.executeQueryWithBloatThreshold(pgConnection, context, "select version()", rs -> rs.getString(1))) - .isInstanceOf(PgSqlException.class) - .hasMessage("bad parameter") - .hasCauseInstanceOf(SQLException.class) - .hasRootCauseMessage("bad parameter"); + .isInstanceOf(PgSqlException.class) + .hasMessage("bad parameter") + .hasCauseInstanceOf(SQLException.class) + .hasRootCauseMessage("bad parameter"); } } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/SqlQueryReaderTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/SqlQueryReaderTest.java index 3c9c8540..2647d4ae 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/SqlQueryReaderTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/utils/SqlQueryReaderTest.java @@ -25,47 +25,47 @@ class SqlQueryReaderTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(SqlQueryReader.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } @Test void getQueryFromFileShouldFindFileAndReadIt() { final String query = SqlQueryReader.getQueryFromFile("bloated_tables.sql"); assertThat(query) - .isNotNull() - .hasSizeGreaterThan(1_000); + .isNotNull() + .hasSizeGreaterThan(1_000); } @Test void getQueryFromFileShouldFindFileInUppercase() { final String query = SqlQueryReader.getQueryFromFile("BLOATED_TABLES.SQL"); assertThat(query) - .isNotNull() - .hasSizeGreaterThan(1_000); + .isNotNull() + .hasSizeGreaterThan(1_000); } @Test void getQueryFromFileShouldFailWithFileNotFound() { assertThatThrownBy(() -> SqlQueryReader.getQueryFromFile("unknown_file.sql")) - .isInstanceOf(RuntimeException.class) - .hasCauseInstanceOf(FileNotFoundException.class) - .hasMessage("java.io.FileNotFoundException: unknown_file.sql"); + .isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(FileNotFoundException.class) + .hasMessage("java.io.FileNotFoundException: unknown_file.sql"); } @SuppressWarnings("ConstantConditions") @Test void withInvalidFileName() { assertThatThrownBy(() -> SqlQueryReader.getQueryFromFile(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("sqlFileName cannot be null"); + .isInstanceOf(NullPointerException.class) + .hasMessage("sqlFileName cannot be null"); assertThatThrownBy(() -> SqlQueryReader.getQueryFromFile("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("sqlFileName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sqlFileName cannot be blank"); assertThatThrownBy(() -> SqlQueryReader.getQueryFromFile(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("sqlFileName cannot be blank"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("sqlFileName cannot be blank"); assertThatThrownBy(() -> SqlQueryReader.getQueryFromFile("file.txt")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("only *.sql files are supported"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("only *.sql files are supported"); } } diff --git a/pg-index-health/src/test/java/io/github/mfvanek/pg/validation/AdditionalValidatorsTest.java b/pg-index-health/src/test/java/io/github/mfvanek/pg/validation/AdditionalValidatorsTest.java index 42bc293b..30cbbb1c 100644 --- a/pg-index-health/src/test/java/io/github/mfvanek/pg/validation/AdditionalValidatorsTest.java +++ b/pg-index-health/src/test/java/io/github/mfvanek/pg/validation/AdditionalValidatorsTest.java @@ -22,6 +22,6 @@ class AdditionalValidatorsTest { @Test void privateConstructor() { assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(AdditionalValidators.class)) - .isInstanceOf(UnsupportedOperationException.class); + .isInstanceOf(UnsupportedOperationException.class); } } diff --git a/spring-boot-integration/pg-index-health-test-starter/src/main/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfiguration.java b/spring-boot-integration/pg-index-health-test-starter/src/main/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfiguration.java index 75d26c5d..3441045a 100644 --- a/spring-boot-integration/pg-index-health-test-starter/src/main/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfiguration.java +++ b/spring-boot-integration/pg-index-health-test-starter/src/main/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfiguration.java @@ -73,7 +73,7 @@ public class DatabaseStructureHealthAutoConfiguration { /** * {@link PgConnection} bean. * - * @param dataSource {@link DataSource} instance + * @param dataSource {@link DataSource} instance * @param databaseUrl connection string to database * @return {@link PgConnection} instance */ diff --git a/spring-boot-integration/pg-index-health-test-starter/src/main/resources/META-INF/spring.factories b/spring-boot-integration/pg-index-health-test-starter/src/main/resources/META-INF/spring.factories index 14705038..f44d1052 100644 --- a/spring-boot-integration/pg-index-health-test-starter/src/main/resources/META-INF/spring.factories +++ b/spring-boot-integration/pg-index-health-test-starter/src/main/resources/META-INF/spring.factories @@ -1 +1 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration = io.github.mfvanek.pg.spring.DatabaseStructureHealthAutoConfiguration +org.springframework.boot.autoconfigure.EnableAutoConfiguration=io.github.mfvanek.pg.spring.DatabaseStructureHealthAutoConfiguration diff --git a/spring-boot-integration/pg-index-health-test-starter/src/test/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfigurationFilteringTest.java b/spring-boot-integration/pg-index-health-test-starter/src/test/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfigurationFilteringTest.java index e258d72c..3e560218 100644 --- a/spring-boot-integration/pg-index-health-test-starter/src/test/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfigurationFilteringTest.java +++ b/spring-boot-integration/pg-index-health-test-starter/src/test/java/io/github/mfvanek/pg/spring/DatabaseStructureHealthAutoConfigurationFilteringTest.java @@ -28,39 +28,34 @@ import io.github.mfvanek.pg.checks.host.TablesWithoutDescriptionCheckOnHost; import io.github.mfvanek.pg.checks.host.TablesWithoutPrimaryKeyCheckOnHost; import io.github.mfvanek.pg.checks.host.UnusedIndexesCheckOnHost; +import io.github.mfvanek.pg.common.maintenance.Diagnostic; import io.github.mfvanek.pg.settings.maintenance.ConfigurationMaintenanceOnHost; import io.github.mfvanek.pg.statistics.maintenance.StatisticsMaintenanceOnHost; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.boot.test.context.FilteredClassLoader; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; class DatabaseStructureHealthAutoConfigurationFilteringTest extends AutoConfigurationTestBase { + private static final int ADDITIONAL_BEANS = 3; // pgConnection + statisticsMaintenanceOnHost + configurationMaintenanceOnHost + + @Test + void beansCompleteness() { + assertThat(EXPECTED_BEANS) + .as("All checks should be added to the starter") + .hasSize(Diagnostic.values().length + ADDITIONAL_BEANS); + + assertThat(getCheckTypes()) + .hasSize(Diagnostic.values().length + 2); // statisticsMaintenanceOnHost + configurationMaintenanceOnHost + } + @ParameterizedTest - @ValueSource(classes = { - DuplicatedIndexesCheckOnHost.class, - ForeignKeysNotCoveredWithIndexCheckOnHost.class, - IndexesWithBloatCheckOnHost.class, - IndexesWithNullValuesCheckOnHost.class, - IntersectedIndexesCheckOnHost.class, - InvalidIndexesCheckOnHost.class, - TablesWithBloatCheckOnHost.class, - TablesWithMissingIndexesCheckOnHost.class, - TablesWithoutPrimaryKeyCheckOnHost.class, - UnusedIndexesCheckOnHost.class, - TablesWithoutDescriptionCheckOnHost.class, - ColumnsWithoutDescriptionCheckOnHost.class, - ColumnsWithJsonTypeCheckOnHost.class, - ColumnsWithSerialTypesCheckOnHost.class, - FunctionsWithoutDescriptionCheckOnHost.class, - IndexesWithBooleanCheckOnHost.class, - NotValidConstraintsCheckOnHost.class, - BtreeIndexesOnArrayColumnsCheckOnHost.class, - StatisticsMaintenanceOnHost.class, - ConfigurationMaintenanceOnHost.class}) + @MethodSource("getCheckTypes") void withoutClass(final Class type) { assertWithTestConfig() .withPropertyValues("spring.datasource.url=jdbc:postgresql://localhost:5432") @@ -93,4 +88,28 @@ void withDataSourceAndEmptyConnectionStringAndWithoutDriver() { .isEmpty(); }); } + + private static List> getCheckTypes() { + return List.of( + DuplicatedIndexesCheckOnHost.class, + ForeignKeysNotCoveredWithIndexCheckOnHost.class, + IndexesWithBloatCheckOnHost.class, + IndexesWithNullValuesCheckOnHost.class, + IntersectedIndexesCheckOnHost.class, + InvalidIndexesCheckOnHost.class, + TablesWithBloatCheckOnHost.class, + TablesWithMissingIndexesCheckOnHost.class, + TablesWithoutPrimaryKeyCheckOnHost.class, + UnusedIndexesCheckOnHost.class, + TablesWithoutDescriptionCheckOnHost.class, + ColumnsWithoutDescriptionCheckOnHost.class, + ColumnsWithJsonTypeCheckOnHost.class, + ColumnsWithSerialTypesCheckOnHost.class, + FunctionsWithoutDescriptionCheckOnHost.class, + IndexesWithBooleanCheckOnHost.class, + NotValidConstraintsCheckOnHost.class, + BtreeIndexesOnArrayColumnsCheckOnHost.class, + StatisticsMaintenanceOnHost.class, + ConfigurationMaintenanceOnHost.class); + } }