From 14c464caa742ecd25c7e274ba3a0121d4f82a071 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 09:40:49 +0100 Subject: [PATCH 1/6] move Caching to spi package as planned clean it up a bit --- .../org/hibernate/boot/model/TruthValue.java | 21 +++--- .../AbstractPluralAttributeSourceImpl.java | 2 +- .../hbm/EntityHierarchySourceImpl.java | 2 +- .../model/source/internal/hbm/Helper.java | 43 ++++++------- .../source/internal/hbm/ModelBinder.java | 9 ++- .../boot/model/{ => source/spi}/Caching.java | 64 ++++++++++--------- .../source/spi/EntityHierarchySource.java | 1 - .../source/spi/PluralAttributeSource.java | 1 - 8 files changed, 70 insertions(+), 73 deletions(-) rename hibernate-core/src/main/java/org/hibernate/boot/model/{ => source/spi}/Caching.java (57%) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java b/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java index d244d5c0adc8..0b54f4ac41ba 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java @@ -18,17 +18,22 @@ public enum TruthValue { FALSE, UNKNOWN; + public static TruthValue of(boolean bool) { + return bool ? TRUE : FALSE; + } + public boolean toBoolean(boolean defaultValue) { - switch (this) { - case TRUE: - return true; - case FALSE: - return false; - default: - return defaultValue; - } + return switch ( this ) { + case TRUE -> true; + case FALSE -> false; + default -> defaultValue; + }; } + /** + * @deprecated No longer used + */ + @Deprecated(since = "7", forRemoval = true) public static boolean toBoolean(TruthValue value, boolean defaultValue) { return value != null ? value.toBoolean( defaultValue ) : defaultValue; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractPluralAttributeSourceImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractPluralAttributeSourceImpl.java index a92a4a991325..86797c5ce989 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractPluralAttributeSourceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractPluralAttributeSourceImpl.java @@ -17,7 +17,7 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmRootEntityType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmSynchronizeType; import org.hibernate.boot.jaxb.hbm.spi.PluralAttributeInfo; -import org.hibernate.boot.model.Caching; +import org.hibernate.boot.model.source.spi.Caching; import org.hibernate.boot.model.CustomSql; import org.hibernate.boot.model.source.spi.AttributePath; import org.hibernate.boot.model.source.spi.AttributeRole; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchySourceImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchySourceImpl.java index afadcf922112..44ebac02055b 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchySourceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchySourceImpl.java @@ -18,7 +18,7 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmPolymorphismEnum; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmRootEntityType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmSimpleIdType; -import org.hibernate.boot.model.Caching; +import org.hibernate.boot.model.source.spi.Caching; import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.naming.EntityNaming; import org.hibernate.boot.model.source.spi.DiscriminatorSource; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/Helper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/Helper.java index 204c7d253371..f5ecc25ec542 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/Helper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/Helper.java @@ -20,9 +20,8 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmUnionSubclassEntityType; import org.hibernate.boot.jaxb.hbm.spi.TableInformationContainer; import org.hibernate.boot.jaxb.hbm.spi.ToolingHintContainer; -import org.hibernate.boot.model.Caching; +import org.hibernate.boot.model.source.spi.Caching; import org.hibernate.boot.model.CustomSql; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.source.spi.InheritanceType; import org.hibernate.boot.model.source.spi.SizeSource; import org.hibernate.boot.model.source.spi.TableSpecificationSource; @@ -75,32 +74,26 @@ public static CustomSql buildCustomSql(JaxbHbmCustomSqlDmlType customSqlElement) } public static Caching createCaching(JaxbHbmCacheType cacheElement) { - if ( cacheElement == null ) { - return new Caching( TruthValue.UNKNOWN ); - } - else { - return new Caching( - cacheElement.getRegion(), - cacheElement.getUsage(), - cacheElement.getInclude() == null - || !"non-lazy".equals( cacheElement.getInclude().value() ), - TruthValue.TRUE - ); - } + return cacheElement == null + ? new Caching() + : new Caching( + cacheElement.getRegion(), + cacheElement.getUsage(), + cacheElement.getInclude() == null + || !"non-lazy".equals( cacheElement.getInclude().value() ), + true + ); } public static Caching createNaturalIdCaching(JaxbHbmNaturalIdCacheType cacheElement) { - if ( cacheElement == null ) { - return new Caching( TruthValue.UNKNOWN ); - } - else { - return new Caching( - nullIfEmpty( cacheElement.getRegion() ), - null, - false, - TruthValue.TRUE - ); - } + return cacheElement == null + ? new Caching() + : new Caching( + nullIfEmpty( cacheElement.getRegion() ), + null, + false, + true + ); } public static String getPropertyAccessorName(String access, boolean isEmbedded, String defaultAccess) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java index c1f92c945d77..8132e017cd37 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java @@ -22,9 +22,8 @@ import org.hibernate.boot.jaxb.Origin; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNamedNativeQueryType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNamedQueryType; -import org.hibernate.boot.model.Caching; +import org.hibernate.boot.model.source.spi.Caching; import org.hibernate.boot.model.IdentifierGeneratorDefinition; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.TypeDefinition; import org.hibernate.boot.model.internal.FkSecondPass; import org.hibernate.boot.model.internal.SimpleToOneFkSecondPass; @@ -278,7 +277,7 @@ private void bindRootEntity(EntityHierarchySourceImpl hierarchySource, RootClass ); if ( hierarchySource.getNaturalIdCaching() != null ) { - if ( hierarchySource.getNaturalIdCaching().getRequested() == TruthValue.TRUE ) { + if ( hierarchySource.getNaturalIdCaching().isRequested() ) { rootEntityDescriptor.setNaturalIdCacheRegionName( hierarchySource.getNaturalIdCaching().getRegion() ); } } @@ -303,7 +302,7 @@ private static boolean isCacheEnabled(MappingDocument mappingDocument, Caching c return switch ( mappingDocument.getBuildingOptions().getSharedCacheMode() ) { case UNSPECIFIED, ENABLE_SELECTIVE -> // this is default behavior for hbm.xml - caching != null && caching.getRequested().toBoolean(false); + caching != null && caching.isRequested(false); case NONE -> // this option is actually really useful false; @@ -314,7 +313,7 @@ private static boolean isCacheEnabled(MappingDocument mappingDocument, Caching c case DISABLE_SELECTIVE -> // makes no sense for hbm.xml, and also goes against our // ideology, and so it hurts me to support it here - caching == null || caching.getRequested().toBoolean(true); + caching == null || caching.isRequested(true); }; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/Caching.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java similarity index 57% rename from hibernate-core/src/main/java/org/hibernate/boot/model/Caching.java rename to hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java index 691b80327e0c..eef99363a6de 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/Caching.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java @@ -2,21 +2,20 @@ * SPDX-License-Identifier: LGPL-2.1-or-later * Copyright Red Hat Inc. and Hibernate Authors */ -package org.hibernate.boot.model; +package org.hibernate.boot.model.source.spi; import org.hibernate.boot.CacheRegionDefinition; +import org.hibernate.boot.model.TruthValue; import org.hibernate.cache.spi.access.AccessType; -import org.hibernate.internal.util.StringHelper; + +import static org.hibernate.internal.util.StringHelper.isEmpty; /** * Models the caching options for an entity, natural id, or collection. * * @author Steve Ebersole * @author Hardy Ferentschik - * - * @deprecated will move to {@link org.hibernate.boot.model.source.spi}, where its only uses are */ -@Deprecated(since = "6") // because it is moving packages public class Caching { // NOTE : TruthValue for now because I need to look at how JPA's SharedCacheMode concept is handled private TruthValue requested; @@ -24,16 +23,19 @@ public class Caching { private AccessType accessType; private boolean cacheLazyProperties; - public Caching(TruthValue requested) { - this.requested = requested; + public Caching() { + this.requested = TruthValue.UNKNOWN; } public Caching(String region, AccessType accessType, boolean cacheLazyProperties) { - this( region, accessType, cacheLazyProperties, TruthValue.UNKNOWN ); + this.requested = TruthValue.UNKNOWN; + this.region = region; + this.accessType = accessType; + this.cacheLazyProperties = cacheLazyProperties; } - public Caching(String region, AccessType accessType, boolean cacheLazyProperties, TruthValue requested) { - this.requested = requested; + public Caching(String region, AccessType accessType, boolean cacheLazyProperties, boolean requested) { + this.requested = TruthValue.of( requested ); this.region = region; this.accessType = accessType; this.cacheLazyProperties = cacheLazyProperties; @@ -63,37 +65,37 @@ public void setCacheLazyProperties(boolean cacheLazyProperties) { this.cacheLazyProperties = cacheLazyProperties; } - public TruthValue getRequested() { - return requested; + public boolean isRequested() { + return requested == TruthValue.TRUE; } - public void setRequested(TruthValue requested) { - this.requested = requested; + public boolean isRequested(boolean defaultValue) { + return requested == TruthValue.UNKNOWN ? defaultValue : isRequested(); } - public void overlay(CacheRegionDefinition overrides) { - if ( overrides == null ) { - return; - } + public void setRequested(boolean requested) { + this.requested = TruthValue.of(requested); + } - requested = TruthValue.TRUE; - accessType = AccessType.fromExternalName( overrides.getUsage() ); - if ( StringHelper.isEmpty( overrides.getRegion() ) ) { - region = overrides.getRegion(); + public void overlay(CacheRegionDefinition overrides) { + if ( overrides != null ) { + requested = TruthValue.TRUE; + accessType = AccessType.fromExternalName( overrides.getUsage() ); + if ( isEmpty( overrides.getRegion() ) ) { + region = overrides.getRegion(); + } + // ugh, primitive boolean + cacheLazyProperties = overrides.isCacheLazy(); } - // ugh, primitive boolean - cacheLazyProperties = overrides.isCacheLazy(); } public void overlay(Caching overrides) { - if ( overrides == null ) { - return; + if ( overrides != null ) { + this.requested = overrides.requested; + this.accessType = overrides.accessType; + this.region = overrides.region; + this.cacheLazyProperties = overrides.cacheLazyProperties; } - - this.requested = overrides.requested; - this.accessType = overrides.accessType; - this.region = overrides.region; - this.cacheLazyProperties = overrides.cacheLazyProperties; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntityHierarchySource.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntityHierarchySource.java index 2922dcfa8be8..172e8be9eb55 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntityHierarchySource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntityHierarchySource.java @@ -4,7 +4,6 @@ */ package org.hibernate.boot.model.source.spi; -import org.hibernate.boot.model.Caching; import org.hibernate.engine.OptimisticLockStyle; /** diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/PluralAttributeSource.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/PluralAttributeSource.java index 7798a186e336..a0b0a2c84374 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/PluralAttributeSource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/PluralAttributeSource.java @@ -4,7 +4,6 @@ */ package org.hibernate.boot.model.source.spi; -import org.hibernate.boot.model.Caching; import org.hibernate.boot.model.CustomSql; /** From 7895d80b3601704470cdc75ce4f546924b9ab3b7 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 09:58:21 +0100 Subject: [PATCH 2/6] get rid of TruthValue and use Boolean clean it up a bit --- .../org/hibernate/boot/model/TruthValue.java | 40 ------------------- .../hbm/AbstractEntitySourceImpl.java | 7 ---- .../hbm/ColumnAttributeSourceImpl.java | 13 +++--- .../source/internal/hbm/ColumnSourceImpl.java | 31 +++++--------- .../internal/hbm/RelationalObjectBinder.java | 13 +----- .../hbm/RelationalValueSourceHelper.java | 39 +++++++----------- .../boot/model/source/spi/Caching.java | 20 ++++------ .../boot/model/source/spi/ColumnSource.java | 4 +- .../boot/model/source/spi/EntitySource.java | 4 -- .../java/org/hibernate/mapping/Column.java | 5 +-- .../AbstractInformationExtractorImpl.java | 32 +++++++-------- .../internal/ColumnInformationImpl.java | 7 ++-- .../schema/extract/spi/ColumnInformation.java | 9 +++-- .../extract/spi/ColumnTypeInformation.java | 13 +++--- .../descriptor/jdbc/spi/JdbcTypeRegistry.java | 11 ++--- .../CheckForExistingForeignKeyTest.java | 7 +--- .../internal/AbstractSchemaMigratorTest.java | 5 +-- 17 files changed, 82 insertions(+), 178 deletions(-) delete mode 100644 hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java b/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java deleted file mode 100644 index 0b54f4ac41ba..000000000000 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/TruthValue.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SPDX-License-Identifier: LGPL-2.1-or-later - * Copyright Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.boot.model; - -/** - * An enumeration of truth values. - * - * @implNote Sure, this could be handled with {@code Boolean}, but - * that option is vulnerable to unwanted auto-unboxing - * and {@link NullPointerException}s. - * - * @author Steve Ebersole - */ -public enum TruthValue { - TRUE, - FALSE, - UNKNOWN; - - public static TruthValue of(boolean bool) { - return bool ? TRUE : FALSE; - } - - public boolean toBoolean(boolean defaultValue) { - return switch ( this ) { - case TRUE -> true; - case FALSE -> false; - default -> defaultValue; - }; - } - - /** - * @deprecated No longer used - */ - @Deprecated(since = "7", forRemoval = true) - public static boolean toBoolean(TruthValue value, boolean defaultValue) { - return value != null ? value.toBoolean( defaultValue ) : defaultValue; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractEntitySourceImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractEntitySourceImpl.java index 39d9074d6587..6c1d56719749 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractEntitySourceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AbstractEntitySourceImpl.java @@ -22,7 +22,6 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmSecondaryTableType; import org.hibernate.boot.jaxb.hbm.spi.SecondaryTableContainer; import org.hibernate.boot.model.CustomSql; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.source.spi.AttributePath; import org.hibernate.boot.model.source.spi.AttributeRole; import org.hibernate.boot.model.source.spi.AttributeSource; @@ -391,10 +390,4 @@ public List getNamedNativeQueries() { return jaxbEntityMapping.getSqlQuery(); } - @Override - public TruthValue quoteIdentifiersLocalToEntity() { - // HBM does not allow for this - return TruthValue.UNKNOWN; - } - } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnAttributeSourceImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnAttributeSourceImpl.java index 5670434f6a8a..77ee07d48ab3 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnAttributeSourceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnAttributeSourceImpl.java @@ -6,7 +6,6 @@ import java.util.Set; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.source.spi.ColumnSource; import org.hibernate.boot.model.source.spi.JdbcDataType; import org.hibernate.boot.model.source.spi.SizeSource; @@ -24,8 +23,8 @@ class ColumnAttributeSourceImpl private final String tableName; private final String columnName; private final SizeSource sizeSource; - private final TruthValue nullable; - private final TruthValue unique; + private final Boolean nullable; + private final Boolean unique; private final Set indexConstraintNames; private final Set ukConstraintNames; @@ -34,8 +33,8 @@ class ColumnAttributeSourceImpl String tableName, String columnName, SizeSource sizeSource, - TruthValue nullable, - TruthValue unique, + Boolean nullable, + Boolean unique, Set indexConstraintNames, Set ukConstraintNames) { super( mappingDocument ); @@ -64,7 +63,7 @@ public String getName() { } @Override - public TruthValue isNullable() { + public Boolean isNullable() { return nullable; } @@ -100,7 +99,7 @@ public String getWriteFragment() { @Override public boolean isUnique() { - return unique == TruthValue.TRUE; + return unique == Boolean.TRUE; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnSourceImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnSourceImpl.java index eb6d7c2d66a1..c78830fefc17 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnSourceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ColumnSourceImpl.java @@ -5,16 +5,15 @@ package org.hibernate.boot.model.source.internal.hbm; -import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmColumnType; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.source.spi.ColumnSource; import org.hibernate.boot.model.source.spi.JdbcDataType; import org.hibernate.boot.model.source.spi.SizeSource; +import static java.util.Collections.addAll; import static org.hibernate.internal.util.StringHelper.splitAtCommas; /** @@ -25,7 +24,7 @@ class ColumnSourceImpl implements ColumnSource { private final String tableName; private final JaxbHbmColumnType columnElement; - private final TruthValue nullable; + private final Boolean nullable; private final Set indexConstraintNames; private final Set ukConstraintNames; @@ -39,27 +38,19 @@ class ColumnSourceImpl mappingDocument, tableName, columnElement, - interpretNotNullToNullability( columnElement.isNotNull() ), + columnElement.isNotNull() == null + ? null + : !columnElement.isNotNull(), indexConstraintNames, ukConstraintNames ); } - private static TruthValue interpretNotNullToNullability(Boolean notNull) { - if ( notNull == null ) { - return TruthValue.UNKNOWN; - } - else { - // not-null == nullable, so the booleans are reversed - return notNull ? TruthValue.FALSE : TruthValue.TRUE; - } - } - ColumnSourceImpl( MappingDocument mappingDocument, String tableName, JaxbHbmColumnType columnElement, - TruthValue nullable, + Boolean nullable, Set indexConstraintNames, Set ukConstraintNames) { super( mappingDocument ); @@ -86,7 +77,7 @@ public String getName() { } @Override - public TruthValue isNullable() { + public Boolean isNullable() { return nullable; } @@ -126,8 +117,8 @@ public String getWriteFragment() { @Override public boolean isUnique() { - // TODO: should TruthValue be returned instead of boolean? - return columnElement.isUnique() != null && columnElement.isUnique().booleanValue(); + return columnElement.isUnique() != null + && columnElement.isUnique(); } @Override @@ -160,8 +151,8 @@ public static Set splitAndCombine(Set stringSet, String values) return stringSet; } else { - HashSet set = new HashSet<>( stringSet ); - Collections.addAll( set, splitAtCommas( values ) ); + final HashSet set = new HashSet<>( stringSet ); + addAll( set, splitAtCommas( values ) ); return set; } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalObjectBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalObjectBinder.java index 9d875071407d..81cdcd0eacab 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalObjectBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalObjectBinder.java @@ -7,7 +7,6 @@ import java.util.Collections; import java.util.List; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.PhysicalNamingStrategy; import org.hibernate.boot.model.relational.Database; @@ -150,7 +149,8 @@ public void bindColumn( } } - column.setNullable( interpretNullability( columnSource.isNullable(), areColumnsNullableByDefault ) ); + final Boolean nullable = columnSource.isNullable(); + column.setNullable( nullable == null ? areColumnsNullableByDefault : nullable ); column.setUnique( columnSource.isUnique() ); if ( columnSource.isUnique() && table != null ) { @@ -182,15 +182,6 @@ public void bindColumn( } } - private static boolean interpretNullability(TruthValue nullable, boolean areColumnsNullableByDefault) { - if ( nullable == null || nullable == TruthValue.UNKNOWN ) { - return areColumnsNullableByDefault; - } - else { - return nullable == TruthValue.TRUE; - } - } - public void bindFormulas( MappingDocument sourceDocument, List formulaSources, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalValueSourceHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalValueSourceHelper.java index 6677873686fd..a51201f43fbd 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalValueSourceHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/RelationalValueSourceHelper.java @@ -12,14 +12,14 @@ import org.hibernate.boot.MappingException; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmColumnType; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.source.spi.ColumnSource; import org.hibernate.boot.model.source.spi.DerivedValueSource; import org.hibernate.boot.model.source.spi.RelationalValueSource; import org.hibernate.boot.model.source.spi.SizeSource; -import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.CollectionHelper; +import static org.hibernate.internal.util.StringHelper.isNotEmpty; + /** * @author Steve Ebersole */ @@ -152,7 +152,7 @@ public static RelationalValueSource buildValueSource( if ( sources.size() > 1 ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "Expecting just a single formula/column in context of <%s name=\"%s\"/>", @@ -197,7 +197,7 @@ public static ColumnSource buildColumnSource( if ( sources.size() > 1 ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "Expecting just a single formula/column in context of <%s name=\"%s\"/>", @@ -219,7 +219,7 @@ public static ColumnSource buildColumnSource( if ( !(result instanceof ColumnSource) ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "Expecting single column in context of <%s name=\"%s\"/>, but found formula [%s]", @@ -267,7 +267,7 @@ public static List buildColumnSources( if ( !(source instanceof ColumnSource) ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "Expecting only columns in context of <%s name=\"%s\"/>, but found formula [%s]", @@ -307,7 +307,7 @@ public static List buildValueSources( ColumnsAndFormulasSource columnsAndFormulasSource) { List result = new ArrayList<>(); - if ( StringHelper.isNotEmpty( columnsAndFormulasSource.getFormulaAttribute() ) ) { + if ( isNotEmpty( columnsAndFormulasSource.getFormulaAttribute() ) ) { // we have an explicit formula attribute (i.e., ) validateUseOfFormulaAttribute( mappingDocument, columnsAndFormulasSource ); @@ -359,8 +359,8 @@ else if ( selectable instanceof String ) { containingTableName, columnsAndFormulasSource.getColumnAttribute(), columnsAndFormulasSource.getSizeSource(), - interpretNullabilityToTruthValue( columnsAndFormulasSource.isNullable() ), - columnsAndFormulasSource.isUnique() ? TruthValue.TRUE : TruthValue.FALSE, + columnsAndFormulasSource.isNullable(), + columnsAndFormulasSource.isUnique(), columnsAndFormulasSource.getIndexConstraintNames(), columnsAndFormulasSource.getUniqueKeyConstraintNames() ) @@ -370,23 +370,14 @@ else if ( selectable instanceof String ) { return result; } - private static TruthValue interpretNullabilityToTruthValue(Boolean nullable) { - if ( nullable == null ) { - return TruthValue.UNKNOWN; - } - else { - return nullable ? TruthValue.TRUE : TruthValue.FALSE; - } - } - private static void validateUseOfFormulaAttribute( MappingDocument sourceDocument, ColumnsAndFormulasSource columnsAndFormulasSource) { // 1) make sure there is no column attribute - if ( StringHelper.isNotEmpty( columnsAndFormulasSource.getColumnAttribute() ) ) { + if ( isNotEmpty( columnsAndFormulasSource.getColumnAttribute() ) ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "column attribute and formula attribute may not be specified together near <%s name=\"%s\" column=\"%s\" formula=\"%s\" />", @@ -411,7 +402,7 @@ private static void validateUseOfFormulaAttribute( if ( CollectionHelper.isNotEmpty( columnsAndFormulasSource.getColumnOrFormulaElements() ) ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "formula attribute may not be specified along with or subelement(s) near <%s name=\"%s\" formula=\"%s\" />", @@ -435,10 +426,10 @@ private static void validateUseOfFormulaAttribute( private static void validateUseOfColumnOrFormulaNestedElements( MappingDocument sourceDocument, ColumnsAndFormulasSource columnsAndFormulasSource) { - if ( StringHelper.isNotEmpty( columnsAndFormulasSource.getColumnAttribute() ) ) { + if ( isNotEmpty( columnsAndFormulasSource.getColumnAttribute() ) ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "column attribute may not be specified along with or subelement(s) near <%s name=\"%s\" column=\"%s\" />", @@ -467,7 +458,7 @@ private static void validateCustomWriteFragment( if ( customWrite != null && !customWrite.matches("[^?]*\\?[^?]*") ) { final String errorMessage; if ( columnsAndFormulasSource.getSourceType().canBeNamed() - && StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { + && isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) { errorMessage = String.format( Locale.ENGLISH, "write expression must contain exactly one value placeholder ('?') character near for <%s name=\"%s\" />", diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java index eef99363a6de..a9ff645d1899 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/Caching.java @@ -5,7 +5,6 @@ package org.hibernate.boot.model.source.spi; import org.hibernate.boot.CacheRegionDefinition; -import org.hibernate.boot.model.TruthValue; import org.hibernate.cache.spi.access.AccessType; import static org.hibernate.internal.util.StringHelper.isEmpty; @@ -17,25 +16,21 @@ * @author Hardy Ferentschik */ public class Caching { - // NOTE : TruthValue for now because I need to look at how JPA's SharedCacheMode concept is handled - private TruthValue requested; + private Boolean requested; private String region; private AccessType accessType; private boolean cacheLazyProperties; - public Caching() { - this.requested = TruthValue.UNKNOWN; - } + public Caching() {} public Caching(String region, AccessType accessType, boolean cacheLazyProperties) { - this.requested = TruthValue.UNKNOWN; this.region = region; this.accessType = accessType; this.cacheLazyProperties = cacheLazyProperties; } public Caching(String region, AccessType accessType, boolean cacheLazyProperties, boolean requested) { - this.requested = TruthValue.of( requested ); + this.requested = requested; this.region = region; this.accessType = accessType; this.cacheLazyProperties = cacheLazyProperties; @@ -66,20 +61,20 @@ public void setCacheLazyProperties(boolean cacheLazyProperties) { } public boolean isRequested() { - return requested == TruthValue.TRUE; + return requested == Boolean.TRUE; } public boolean isRequested(boolean defaultValue) { - return requested == TruthValue.UNKNOWN ? defaultValue : isRequested(); + return requested == null ? defaultValue : isRequested(); } public void setRequested(boolean requested) { - this.requested = TruthValue.of(requested); + this.requested = requested; } public void overlay(CacheRegionDefinition overrides) { if ( overrides != null ) { - requested = TruthValue.TRUE; + requested = true; accessType = AccessType.fromExternalName( overrides.getUsage() ); if ( isEmpty( overrides.getRegion() ) ) { region = overrides.getRegion(); @@ -105,5 +100,4 @@ public String toString() { + ", cacheLazyProperties=" + cacheLazyProperties + ", requested=" + requested + '}'; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/ColumnSource.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/ColumnSource.java index 415034f1c6c3..61a62db8d9c8 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/ColumnSource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/ColumnSource.java @@ -6,8 +6,6 @@ import java.util.Set; -import org.hibernate.boot.model.TruthValue; - /** * Contract for source information pertaining to a physical column definition specific to a particular attribute * context. @@ -44,7 +42,7 @@ public interface ColumnSource extends RelationalValueSource { * * @return {@code true} indicates it is nullable; {@code false} non-nullable. */ - TruthValue isNullable(); + Boolean isNullable(); /** * Obtain a specified default value for the column diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntitySource.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntitySource.java index 7f9684606821..222e2871a3f3 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntitySource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/EntitySource.java @@ -10,7 +10,6 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNamedNativeQueryType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNamedQueryType; import org.hibernate.boot.model.CustomSql; -import org.hibernate.boot.model.TruthValue; /** * Contract describing source of information related to mapping an entity. @@ -146,7 +145,4 @@ public interface EntitySource extends IdentifiableTypeSource, ToolingHintContext List getNamedQueries(); List getNamedNativeQueries(); - - TruthValue quoteIdentifiersLocalToEntity(); - } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Column.java b/hibernate-core/src/main/java/org/hibernate/mapping/Column.java index 9d423ae61733..954bbb4b1ce1 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Column.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Column.java @@ -14,7 +14,6 @@ import org.hibernate.Internal; import org.hibernate.MappingException; import org.hibernate.boot.Metadata; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.spi.MetadataBuildingContext; @@ -435,8 +434,8 @@ public String getTypeName() { } @Override - public TruthValue getNullable() { - return nullable ? TruthValue.TRUE : TruthValue.FALSE; + public Boolean getNullable() { + return nullable; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java index 554f7fe97209..8bd332ea2fa0 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java @@ -18,7 +18,6 @@ import java.util.StringTokenizer; import org.hibernate.JDBCException; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.DatabaseIdentifier; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.QualifiedTableName; @@ -50,7 +49,7 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt private final String[] tableTypes; - private String[] extraPhysicalTableTypes; + private final String[] extraPhysicalTableTypes; private final ExtractionContext extractionContext; @@ -430,8 +429,8 @@ private Identifier getCurrentSchema(JdbcEnvironment jdbcEnvironment) { .getIdentifierHelper() .toIdentifier( extractionContext.getJdbcConnection().getSchema() ); } - catch (SQLException ignore) { - LOG.sqlWarning( ignore.getErrorCode(), ignore.getSQLState() ); + catch (SQLException sqle) { + LOG.sqlWarning( sqle.getErrorCode(), sqle.getSQLState() ); } catch (AbstractMethodError ignore) { // jConnect and jTDS report that they "support" schemas, but they don't really @@ -911,25 +910,24 @@ protected void addColumns(TableInformation tableInformation) { } } - protected TruthValue interpretNullable(int nullable) { - switch ( nullable ) { - case ResultSetMetaData.columnNullable: - return TruthValue.TRUE; - case ResultSetMetaData.columnNoNulls: - return TruthValue.FALSE; - default: - return TruthValue.UNKNOWN; - } + protected Boolean interpretNullable(int nullable) { + return switch ( nullable ) { + case ResultSetMetaData.columnNullable -> Boolean.TRUE; + case ResultSetMetaData.columnNoNulls -> Boolean.FALSE; + default -> null; + }; } - private TruthValue interpretTruthValue(String nullable) { + private Boolean interpretTruthValue(String nullable) { if ( "yes".equalsIgnoreCase( nullable ) ) { - return TruthValue.TRUE; + return Boolean.TRUE; } else if ( "no".equalsIgnoreCase( nullable ) ) { - return TruthValue.FALSE; + return Boolean.FALSE; + } + else { + return null; } - return TruthValue.UNKNOWN; } // This method is not currently used. diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/ColumnInformationImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/ColumnInformationImpl.java index ce1d92817dc1..c6028d15f6e8 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/ColumnInformationImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/ColumnInformationImpl.java @@ -4,7 +4,6 @@ */ package org.hibernate.tool.schema.extract.internal; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.tool.schema.extract.spi.ColumnInformation; import org.hibernate.tool.schema.extract.spi.TableInformation; @@ -23,7 +22,7 @@ public class ColumnInformationImpl implements ColumnInformation { private final String typeName; private final int columnSize; private final int decimalDigits; - private final TruthValue nullable; + private final Boolean nullable; public ColumnInformationImpl( TableInformation containingTableInformation, @@ -32,7 +31,7 @@ public ColumnInformationImpl( String typeName, int columnSize, int decimalDigits, - TruthValue nullable) { + Boolean nullable) { this.containingTableInformation = containingTableInformation; this.columnIdentifier = columnIdentifier; this.typeCode = typeCode; @@ -73,7 +72,7 @@ public int getDecimalDigits() { } @Override - public TruthValue getNullable() { + public Boolean getNullable() { return nullable; } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java index 01337a9a913f..69c5e13b0bd6 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java @@ -4,7 +4,6 @@ */ package org.hibernate.tool.schema.extract.spi; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; /** @@ -29,11 +28,13 @@ public interface ColumnInformation extends ColumnTypeInformation { Identifier getColumnIdentifier(); /** - * Is the column nullable. The database is allowed to report unknown, hence the use of TruthValue + * Is the column nullable. + *

+ * The database is allowed to report unknown, hence the use of {@link Boolean}. * - * @return nullability. + * @return nullability, if known */ - TruthValue getNullable(); + Boolean getNullable(); /** * The JDBC type-code. diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java index aef06b47850b..16f645e9e23a 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java @@ -7,7 +7,6 @@ import java.sql.Types; import org.hibernate.Incubating; -import org.hibernate.boot.model.TruthValue; /** * Provides access to information about existing table columns @@ -20,8 +19,8 @@ public interface ColumnTypeInformation { ColumnTypeInformation EMPTY = new ColumnTypeInformation() { @Override - public TruthValue getNullable() { - return TruthValue.UNKNOWN; + public Boolean getNullable() { + return null; } @Override @@ -46,11 +45,13 @@ public int getDecimalDigits() { }; /** - * Is the column nullable. The database is allowed to report unknown, hence the use of TruthValue + * Is the column nullable. + *

+ * The database is allowed to report unknown, hence the use of {@link Boolean}. * - * @return nullability. + * @return nullability, if known */ - TruthValue getNullable(); + Boolean getNullable(); /** * The JDBC type-code. diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java index 0f370d5d0919..29a56dedcad9 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/spi/JdbcTypeRegistry.java @@ -10,7 +10,6 @@ import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; -import org.hibernate.boot.model.TruthValue; import org.hibernate.dialect.Dialect; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.spi.RuntimeModelCreationContext; @@ -165,7 +164,7 @@ public AggregateJdbcType resolveAggregateDescriptor( registrationKey = null; } final JdbcType descriptor = getDescriptor( jdbcTypeCode ); - if ( !( descriptor instanceof AggregateJdbcType ) ) { + if ( !(descriptor instanceof AggregateJdbcType aggregateJdbcType) ) { throw new IllegalArgumentException( String.format( "Tried to resolve the JdbcType [%s] as AggregateJdbcType but it does not implement that interface!", @@ -173,7 +172,6 @@ public AggregateJdbcType resolveAggregateDescriptor( ) ); } - final AggregateJdbcType aggregateJdbcType = (AggregateJdbcType) descriptor; final AggregateJdbcType resolvedJdbcType = aggregateJdbcType.resolveAggregateJdbcType( embeddableMappingType, typeName, @@ -181,8 +179,7 @@ public AggregateJdbcType resolveAggregateDescriptor( ); if ( registrationKey != null ) { aggregateDescriptorMap.put( registrationKey, resolvedJdbcType ); - if ( resolvedJdbcType instanceof SqlTypedJdbcType ) { - final SqlTypedJdbcType sqlTypedJdbcType = (SqlTypedJdbcType) resolvedJdbcType; + if ( resolvedJdbcType instanceof SqlTypedJdbcType sqlTypedJdbcType ) { sqlTypedDescriptorMap.put( sqlTypedJdbcType.getSqlTypeName().toLowerCase( Locale.ROOT ), sqlTypedJdbcType ); } } @@ -295,7 +292,7 @@ public void addTypeConstructorIfAbsent(JdbcTypeConstructor jdbcTypeConstructor) private static final class TypeConstructedJdbcTypeKey { private final int typeConstructorTypeCode; private final Object jdbcTypeOrBasicType; - private final TruthValue nullable; + private final Boolean nullable; private final int typeCode; private final @Nullable String typeName; private final int columnSize; @@ -308,7 +305,7 @@ public TypeConstructedJdbcTypeKey( this.typeConstructorTypeCode = typeConstructorTypeCode; this.jdbcTypeOrBasicType = jdbcTypeOrBasicType; if ( columnTypeInformation == null ) { - this.nullable = TruthValue.UNKNOWN; + this.nullable = null; this.typeCode = Types.OTHER; this.typeName = null; this.columnSize = 0; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/internal/CheckForExistingForeignKeyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/internal/CheckForExistingForeignKeyTest.java index 5959f80f6e9e..2cd64dfd1ca2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/internal/CheckForExistingForeignKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/internal/CheckForExistingForeignKeyTest.java @@ -11,7 +11,6 @@ import java.util.Set; import org.hibernate.boot.Metadata; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Namespace.Name; @@ -362,9 +361,7 @@ private ColumnInformation getColumnInformation(String tableName, String columnNa String typeName = null; int columnSize = 0; int decimalDigits = 0; - TruthValue nullable = null; - ColumnInformationImpl columnInformation = new ColumnInformationImpl( containingTableInformation, columnIdentifier, typeCode, typeName, columnSize, - decimalDigits, nullable ); - return columnInformation; + return new ColumnInformationImpl( containingTableInformation, columnIdentifier, typeCode, typeName, columnSize, + decimalDigits, null ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java b/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java index 9c4c25ccb1e3..bd1295e21b1f 100644 --- a/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/tool/schema/internal/AbstractSchemaMigratorTest.java @@ -8,7 +8,6 @@ import java.util.Set; import org.hibernate.boot.Metadata; -import org.hibernate.boot.model.TruthValue; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.QualifiedTableName; @@ -62,8 +61,8 @@ protected NameSpaceTablesInformation performTablesMigration(Metadata metadata, .when(destinationTableInformation).getName(); columnReferenceMappings.add(new ForeignKeyInformationImpl.ColumnReferenceMappingImpl( new ColumnInformationImpl(null, toIdentifier("referencing_column"), // column name is lower case - 0, "typeName", 255, 0, TruthValue.TRUE), - new ColumnInformationImpl(destinationTableInformation, null, 1, "typeName", 0, 0, TruthValue.TRUE))); + 0, "typeName", 255, 0, true), + new ColumnInformationImpl(destinationTableInformation, null, 1, "typeName", 0, 0, true))); doReturn(singletonList(new ForeignKeyInformationImpl(toIdentifier("FKp8mpamfw2inhj88hwhty1eipm"), columnReferenceMappings))) .when(existingTableInformation).getForeignKeys(); From 0f0a89d0a5c139a17f8a8afe886975c37c75fd2c Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 10:35:35 +0100 Subject: [PATCH 3/6] some cleanups to AbstractInformationExtractorImpl --- .../jaxb/hbm/transform/HbmXmlTransformer.java | 75 ++- .../AbstractInformationExtractorImpl.java | 449 +++++++----------- ...tionExtractorJdbcDatabaseMetaDataImpl.java | 25 +- 3 files changed, 225 insertions(+), 324 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java index 0a6da850295b..c0c50c5792e8 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java @@ -203,6 +203,7 @@ import static org.hibernate.boot.jaxb.hbm.transform.HbmTransformationLogging.TRANSFORMATION_LOGGER; import static org.hibernate.internal.util.StringHelper.isNotEmpty; +import static org.hibernate.internal.util.StringHelper.nullIfEmpty; /** * Transforms {@code hbm.xml} {@linkplain JaxbHbmHibernateMapping JAXB} bindings into @@ -1205,7 +1206,7 @@ else if ( !source.getColumnOrFormula().isEmpty() ) { } } } - else if ( StringHelper.isNotEmpty( tableName ) ) { + else if ( isNotEmpty( tableName ) ) { // this is the case of transforming a where the property did not specify columns or formula. // we need to create a column still to pass along the secondary table name final TargetColumnAdapter column = target.makeColumnAdapter( columnDefaults ); @@ -1590,7 +1591,7 @@ public Boolean isUpdateable() { } private JaxbUserTypeImpl interpretBasicType(String typeName, JaxbHbmConfigParameterContainer typeLocalParams, JaxbHbmTypeDefinitionType typeDef) { - assert StringHelper.isNotEmpty( typeName ); + assert isNotEmpty( typeName ); final JaxbUserTypeImpl typeNode = new JaxbUserTypeImpl(); @@ -1624,7 +1625,7 @@ private JaxbEmbeddableImpl applyEmbeddable( JaxbHbmCompositeAttributeType hbmComponent, ComponentTypeInfo componentTypeInfo) { final String embeddableClassName = componentTypeInfo.getComponent().getComponentClassName(); - if ( StringHelper.isNotEmpty( embeddableClassName ) ) { + if ( isNotEmpty( embeddableClassName ) ) { final JaxbEmbeddableImpl existing = jaxbEmbeddableByClassName.get( embeddableClassName ); if ( existing != null ) { return existing; @@ -1641,7 +1642,7 @@ private JaxbEmbeddableImpl applyEmbeddable( ); mappingXmlBinding.getRoot().getEmbeddables().add( jaxbEmbeddable ); - if ( StringHelper.isNotEmpty( embeddableClassName ) ) { + if ( isNotEmpty( embeddableClassName ) ) { jaxbEmbeddableByClassName.put( embeddableClassName, jaxbEmbeddable ); } @@ -1668,7 +1669,7 @@ private JaxbEmbeddableImpl convertEmbeddable( private int counter = 1; private String determineEmbeddableName(String componentClassName, String attributeName) { - if ( StringHelper.isNotEmpty( componentClassName ) ) { + if ( isNotEmpty( componentClassName ) ) { return componentClassName; } return attributeName + "_" + counter++; @@ -1692,7 +1693,7 @@ private void transferOneToOne(JaxbHbmOneToOneType hbmOneToOne, PropertyInfo prop oneToOne.setOrphanRemoval( isOrphanRemoval( hbmOneToOne.getCascade() ) ); oneToOne.setForeignKey( new JaxbForeignKeyImpl() ); oneToOne.getForeignKey().setName( hbmOneToOne.getForeignKey() ); - if ( StringHelper.isNotEmpty( hbmOneToOne.getPropertyRef() ) ) { + if ( isNotEmpty( hbmOneToOne.getPropertyRef() ) ) { oneToOne.setPropertyRef( new JaxbPropertyRefImpl() ); oneToOne.getPropertyRef().setName( hbmOneToOne.getPropertyRef() ); } @@ -1736,7 +1737,7 @@ private JaxbManyToOneImpl transformManyToOne(JaxbHbmManyToOneType hbmNode, Prope jaxbManyToOne.setAttributeAccessor( hbmNode.getAccess() ); jaxbManyToOne.setCascade( convertCascadeType( hbmNode.getCascade() ) ); - if ( StringHelper.isNotEmpty( hbmNode.getPropertyRef() ) ) { + if ( isNotEmpty( hbmNode.getPropertyRef() ) ) { jaxbManyToOne.setPropertyRef( new JaxbPropertyRefImpl() ); jaxbManyToOne.getPropertyRef().setName( hbmNode.getPropertyRef() ); } @@ -1905,7 +1906,7 @@ private void transferCollectionCommonInfo(PluralAttributeInfo source, JaxbPlural target.setFetchMode( convert( source.getFetch() ) ); target.setFetch( convert( source.getLazy() ) ); - if ( StringHelper.isNotEmpty( source.getCollectionType() ) ) { + if ( isNotEmpty( source.getCollectionType() ) ) { final JaxbCollectionUserTypeImpl jaxbCollectionUserType = new JaxbCollectionUserTypeImpl(); target.setCollectionType( jaxbCollectionUserType ); jaxbCollectionUserType.setType( source.getCollectionType() ); @@ -1913,7 +1914,7 @@ private void transferCollectionCommonInfo(PluralAttributeInfo source, JaxbPlural if ( source instanceof JaxbHbmSetType set ) { final String sort = set.getSort(); - if ( StringHelper.isNotEmpty( sort ) && !"unsorted".equals( sort ) ) { + if ( isNotEmpty( sort ) && !"unsorted".equals( sort ) ) { target.setSort( sort ); } target.setOrderBy( set.getOrderBy() ); @@ -1921,7 +1922,7 @@ private void transferCollectionCommonInfo(PluralAttributeInfo source, JaxbPlural } else if ( source instanceof JaxbHbmMapType map ) { final String sort = map.getSort(); - if ( StringHelper.isNotEmpty( sort ) && !"unsorted".equals( sort ) ) { + if ( isNotEmpty( sort ) && !"unsorted".equals( sort ) ) { target.setSort( sort ); } target.setOrderBy( map.getOrderBy() ); @@ -2025,7 +2026,7 @@ else if ( source.getMapKey() != null ) { return; } - if ( StringHelper.isNotEmpty( source.getMapKey().getNode() ) ) { + if ( isNotEmpty( source.getMapKey().getNode() ) ) { handleUnsupported( "Transformation of `node` attribute is not supported - %s", origin() @@ -2040,7 +2041,7 @@ else if ( source.getMapKey() != null ) { jaxbMapKeyType.setValue( mapKeyType ); } - if ( StringHelper.isNotEmpty( source.getMapKey().getColumnAttribute() ) ) { + if ( isNotEmpty( source.getMapKey().getColumnAttribute() ) ) { final JaxbMapKeyColumnImpl mapKeyColumn = new JaxbMapKeyColumnImpl(); mapKeyColumn.setName( source.getMapKey().getColumnAttribute() ); target.setMapKeyColumn( mapKeyColumn ); @@ -2049,38 +2050,32 @@ else if ( source.getMapKey() != null ) { } private String resolveMapKeyType(JaxbHbmMapKeyBasicType mapKey) { - if ( StringHelper.isNotEmpty( mapKey.getTypeAttribute() ) ) { + if ( isNotEmpty( mapKey.getTypeAttribute() ) ) { return mapKey.getTypeAttribute(); } - - if ( mapKey.getType() != null ) { - return StringHelper.nullIfEmpty( mapKey.getType().getName() ); + else if ( mapKey.getType() != null ) { + return nullIfEmpty( mapKey.getType().getName() ); + } + else { + return null; } - - return null; } private Boolean invert(Boolean value) { - return invert( value, null ); - } - - private Boolean invert(Boolean value, Boolean defaultValue) { - if ( value == null ) { - return defaultValue; - } - return !value; + return value == null ? null : !value; } private JaxbPluralFetchModeImpl convert(JaxbHbmFetchStyleWithSubselectEnum fetch) { - if ( fetch != null ) { + if ( fetch == null ) { + return null; + } + else { return switch ( fetch ) { case SELECT -> JaxbPluralFetchModeImpl.SELECT; case JOIN -> JaxbPluralFetchModeImpl.JOIN; case SUBSELECT -> JaxbPluralFetchModeImpl.SUBSELECT; }; } - - return null; } @@ -2181,7 +2176,7 @@ private void transferElementInfo( final ComponentTypeInfo componentTypeInfo = transformationState.getEmbeddableInfoByRole().get( partRole ); target.setTarget( embeddableName ); - if ( StringHelper.isNotEmpty( embeddableClassName ) ) { + if ( isNotEmpty( embeddableClassName ) ) { target.setTargetClass( embeddableClassName ); } @@ -2217,7 +2212,7 @@ private void transferOneToManyInfo( } transferCollectionCommonInfo( hbmAttributeInfo, target ); - target.setTargetEntity( StringHelper.isNotEmpty( hbmOneToMany.getClazz() ) ? hbmOneToMany.getClazz() : hbmOneToMany.getEntityName() ); + target.setTargetEntity( isNotEmpty( hbmOneToMany.getClazz() ) ? hbmOneToMany.getClazz() : hbmOneToMany.getEntityName() ); final Property bootModelProperty = propertyInfo.bootModelProperty(); final Collection bootModelValue = (Collection) bootModelProperty.getValue(); @@ -2291,7 +2286,7 @@ public void addFormula(String formula) { target.getFilters().add( convert( hbmFilter ) ); } - if ( StringHelper.isNotEmpty( hbmAttributeInfo.getWhere() ) ) { + if ( isNotEmpty( hbmAttributeInfo.getWhere() ) ) { target.setSqlRestriction( hbmAttributeInfo.getWhere() ); } if ( hbmAttributeInfo.getSqlInsert() != null ) { @@ -2320,7 +2315,7 @@ private String resolveMappedBy( PluralAttributeInfo hbmAttributeInfo, Property bootModelProperty, Collection bootModelValue) { - if ( StringHelper.isNotEmpty( bootModelValue.getMappedByProperty() ) ) { + if ( isNotEmpty( bootModelValue.getMappedByProperty() ) ) { return bootModelValue.getMappedByProperty(); } @@ -2369,8 +2364,8 @@ private boolean matches(KeyValue collectionKey, List candidate) { final Column collectionKeyColumn = (Column) collectionKeySelectable; final Column candidateColumn = (Column) candidateSelectable; - assert StringHelper.isNotEmpty( collectionKeyColumn.getCanonicalName() ); - assert StringHelper.isNotEmpty( candidateColumn.getCanonicalName() ); + assert isNotEmpty( collectionKeyColumn.getCanonicalName() ); + assert isNotEmpty( candidateColumn.getCanonicalName() ); if ( !collectionKeyColumn.getCanonicalName().equals( candidateColumn.getCanonicalName() ) ) { return false; } @@ -2400,7 +2395,7 @@ private void transferManyToManyInfo( if ( manyToMany.isEmbedXml() != null ) { handleUnsupported( "`embed-xml` no longer supported" ); } - if ( StringHelper.isNotEmpty( manyToMany.getNode() ) ) { + if ( isNotEmpty( manyToMany.getNode() ) ) { handleUnsupported( "`node` no longer supported" ); } @@ -2409,7 +2404,7 @@ private void transferManyToManyInfo( final JaxbJoinTableImpl joinTable = new JaxbJoinTableImpl(); final String tableName = hbmCollection.getTable(); - if ( StringHelper.isNotEmpty( tableName ) ) { + if ( isNotEmpty( tableName ) ) { joinTable.setName( tableName ); } target.setJoinTable( joinTable ); @@ -2503,7 +2498,7 @@ public void addFormula(String formula) { ); transferCollectionCommonInfo( hbmCollection, target ); - target.setTargetEntity( StringHelper.isNotEmpty( manyToMany.getClazz() ) ? manyToMany.getClazz() : manyToMany.getEntityName() ); + target.setTargetEntity( isNotEmpty( manyToMany.getClazz() ) ? manyToMany.getClazz() : manyToMany.getEntityName() ); if ( manyToMany.getNotFound() == JaxbHbmNotFoundEnum.IGNORE ) { target.setNotFound( NotFoundAction.IGNORE ); @@ -2513,7 +2508,7 @@ public void addFormula(String formula) { target.getFilters().add( convert( hbmFilter ) ); } - if ( StringHelper.isNotEmpty( hbmCollection.getWhere() ) ) { + if ( isNotEmpty( hbmCollection.getWhere() ) ) { target.setSqlRestriction( hbmCollection.getWhere() ); } if ( hbmCollection.getSqlInsert() != null ) { @@ -2664,7 +2659,7 @@ private JaxbEmbeddableImpl transformEmbeddedIdEmbeddable( EntityTypeInfo bootEntityInfo, Property idProperty) { final String embeddableClassName = hbmCompositeId.getClazz(); - if ( StringHelper.isNotEmpty( embeddableClassName ) ) { + if ( isNotEmpty( embeddableClassName ) ) { final JaxbEmbeddableImpl existing = jaxbEmbeddableByClassName.get( embeddableClassName ); if ( existing != null ) { return existing; diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java index 8bd332ea2fa0..89c53310aafc 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java @@ -9,7 +9,6 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -18,7 +17,6 @@ import java.util.StringTokenizer; import org.hibernate.JDBCException; -import org.hibernate.boot.model.naming.DatabaseIdentifier; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.QualifiedTableName; import org.hibernate.cfg.AvailableSettings; @@ -31,8 +29,6 @@ import org.hibernate.engine.jdbc.env.spi.NameQualifierSupport; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.tool.schema.extract.spi.ColumnInformation; import org.hibernate.tool.schema.extract.spi.ExtractionContext; import org.hibernate.tool.schema.extract.spi.ForeignKeyInformation; @@ -44,6 +40,12 @@ import org.hibernate.tool.schema.extract.spi.TableInformation; import org.hibernate.tool.schema.spi.SchemaManagementException; +import static java.util.Collections.addAll; +import static org.hibernate.boot.model.naming.DatabaseIdentifier.toIdentifier; +import static org.hibernate.internal.util.StringHelper.isBlank; +import static org.hibernate.internal.util.StringHelper.splitTrimmingTokens; +import static org.hibernate.internal.util.config.ConfigurationHelper.getBoolean; + public abstract class AbstractInformationExtractorImpl implements InformationExtractor { private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractInformationExtractorImpl.class ); @@ -65,7 +67,7 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt public AbstractInformationExtractorImpl(ExtractionContext extractionContext) { this.extractionContext = extractionContext; - ConfigurationService configService = + final ConfigurationService configService = extractionContext.getServiceRegistry().requireService( ConfigurationService.class ); useJdbcMetadataDefaultsSetting = configService.getSetting( @@ -84,15 +86,8 @@ public AbstractInformationExtractorImpl(ExtractionContext extractionContext) { ) ); final List physicalTableTypesList = new ArrayList<>(); - if ( ! StringHelper.isBlank( extraPhysicalTableTypesConfig ) ) { - Collections.addAll( - physicalTableTypesList, - StringHelper.splitTrimmingTokens( - ",;", - extraPhysicalTableTypesConfig, - false - ) - ); + if ( !isBlank( extraPhysicalTableTypesConfig ) ) { + addAll( physicalTableTypesList, splitTrimmingTokens( ",;", extraPhysicalTableTypesConfig, false ) ); } final Dialect dialect = extractionContext.getJdbcEnvironment().getDialect(); dialect.augmentPhysicalTableTypes( physicalTableTypesList ); @@ -101,34 +96,38 @@ public AbstractInformationExtractorImpl(ExtractionContext extractionContext) { final List tableTypesList = new ArrayList<>(); tableTypesList.add( "TABLE" ); tableTypesList.add( "VIEW" ); - if ( ConfigurationHelper.getBoolean( AvailableSettings.ENABLE_SYNONYMS, configService.getSettings() ) ) { + if ( getBoolean( AvailableSettings.ENABLE_SYNONYMS, configService.getSettings() ) ) { if ( dialect instanceof DB2Dialect ) { tableTypesList.add( "ALIAS" ); } tableTypesList.add( "SYNONYM" ); } - Collections.addAll( tableTypesList, extraPhysicalTableTypes ); + addAll( tableTypesList, extraPhysicalTableTypes ); dialect.augmentRecognizedTableTypes( tableTypesList ); this.tableTypes = tableTypesList.toArray( new String[0] ); } protected IdentifierHelper identifierHelper() { - return extractionContext.getJdbcEnvironment().getIdentifierHelper(); + return getIdentifierHelper(); } protected JDBCException convertSQLException(SQLException sqlException, String message) { - return extractionContext.getJdbcEnvironment().getSqlExceptionHelper().convert( sqlException, message ); + return getJdbcEnvironment().getSqlExceptionHelper().convert( sqlException, message ); } protected String toMetaDataObjectName(Identifier identifier) { - return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataObjectName( identifier ); + return getIdentifierHelper().toMetaDataObjectName( identifier ); } protected ExtractionContext getExtractionContext() { return extractionContext; } + protected JdbcEnvironment getJdbcEnvironment() { + return extractionContext.getJdbcEnvironment(); + } + // The following methods purposely return the column labels that are defined by // DatabaseMetaData methods that return a ResultSet. Subclasses that do not rely // on DatabaseMetaData may override these methods to use different column labels. @@ -222,20 +221,16 @@ protected String getResultSetForeignKeyColumnNameLabel() { public boolean catalogExists(Identifier catalog) { try { return processCatalogsResultSet( resultSet -> { - while ( resultSet.next() ) { final String existingCatalogName = resultSet.getString( getResultSetCatalogLabel() ); - // todo : hmm.. case sensitive or insensitive match... // for now, match any case... - if ( catalog.getText().equalsIgnoreCase( existingCatalogName ) ) { return true; } } - return false; - }); + } ); } catch (SQLException sqlException) { throw convertSQLException( sqlException, "Unable to query ResultSet for existing catalogs" ); @@ -313,13 +308,17 @@ public boolean schemaExists(Identifier catalog, Identifier schema) { } } + private IdentifierHelper getIdentifierHelper() { + return getJdbcEnvironment().getIdentifierHelper(); + } + protected String determineCatalogFilter(Identifier catalog) { Identifier identifierToUse = catalog; if ( identifierToUse == null ) { identifierToUse = extractionContext.getDefaultCatalog(); } - return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataCatalogName( identifierToUse ); + return getIdentifierHelper().toMetaDataCatalogName( identifierToUse ); } protected String determineSchemaFilter(Identifier schema) { @@ -328,16 +327,14 @@ protected String determineSchemaFilter(Identifier schema) { identifierToUse = extractionContext.getDefaultSchema(); } - return extractionContext.getJdbcEnvironment().getIdentifierHelper().toMetaDataSchemaName( identifierToUse ); + return getIdentifierHelper().toMetaDataSchemaName( identifierToUse ); } private TableInformation extractTableInformation(ResultSet resultSet) throws SQLException { - final QualifiedTableName tableName = extractTableName( resultSet ); - return new TableInformationImpl( this, identifierHelper(), - tableName, + extractTableName( resultSet ), isPhysicalTableType( resultSet.getString( getResultSetTableTypeLabel() ) ), resultSet.getString( getResultSetRemarksLabel() ) ); @@ -357,33 +354,24 @@ public TableInformation getTable(Identifier catalog, Identifier schema, Identifi // 2) look in default namespace // 3) look in all namespaces - multiple hits is considered an error - TableInformation tableInfo; - // 1) look in current namespace - final JdbcEnvironment jdbcEnvironment = extractionContext.getJdbcEnvironment(); - final Identifier currentSchema = getCurrentSchema( jdbcEnvironment ); - final Identifier currentCatalog = getCurrentCatalog( jdbcEnvironment ); - if ( currentCatalog != null - || currentSchema != null ) { - tableInfo = locateTableInNamespace( - currentCatalog, - currentSchema, - tableName - ); - + final Identifier currentSchema = getCurrentSchema(); + final Identifier currentCatalog = getCurrentCatalog(); + if ( currentCatalog != null || currentSchema != null ) { + final TableInformation tableInfo = + locateTableInNamespace( currentCatalog, currentSchema, tableName ); if ( tableInfo != null ) { return tableInfo; } } // 2) look in default namespace - if ( extractionContext.getDefaultCatalog() != null || extractionContext.getDefaultSchema() != null ) { - tableInfo = locateTableInNamespace( - extractionContext.getDefaultCatalog(), - extractionContext.getDefaultSchema(), - tableName - ); - + final Identifier defaultCatalog = extractionContext.getDefaultCatalog(); + final Identifier defaultSchema = extractionContext.getDefaultSchema(); + if ( defaultCatalog != null + || defaultSchema != null ) { + final TableInformation tableInfo = + locateTableInNamespace( defaultCatalog, defaultSchema, tableName ); if ( tableInfo != null ) { return tableInfo; } @@ -391,19 +379,12 @@ public TableInformation getTable(Identifier catalog, Identifier schema, Identifi // 3) look in all namespaces try { - final String tableNameFilter = toMetaDataObjectName( tableName ); - return processTableResultSet( null, null, - tableNameFilter, + toMetaDataObjectName( tableName ), tableTypes, - resultSet -> extractTableInformation( - null, - null, - tableName, - resultSet - ) + resultSet -> extractTableInformation( null, null, tableName, resultSet ) ); } catch (SQLException sqlException) { @@ -412,21 +393,20 @@ public TableInformation getTable(Identifier catalog, Identifier schema, Identifi } } - private Identifier getCurrentSchema(JdbcEnvironment jdbcEnvironment) { - if ( jdbcEnvironment.getNameQualifierSupport() == NameQualifierSupport.CATALOG ) { + private Identifier getCurrentSchema() { + if ( getNameQualifierSupport() == NameQualifierSupport.CATALOG ) { return null; } if ( currentSchema != null ) { return currentSchema; } - final Identifier schema = jdbcEnvironment.getCurrentSchema(); + final Identifier schema = getJdbcEnvironment().getCurrentSchema(); if ( schema != null ) { currentSchema = schema; } if ( !useJdbcMetadataDefaultsSetting ) { try { - currentSchema = extractionContext.getJdbcEnvironment() - .getIdentifierHelper() + currentSchema = getIdentifierHelper() .toIdentifier( extractionContext.getJdbcConnection().getSchema() ); } catch (SQLException sqle) { @@ -439,25 +419,24 @@ private Identifier getCurrentSchema(JdbcEnvironment jdbcEnvironment) { return currentSchema; } - private Identifier getCurrentCatalog(JdbcEnvironment jdbcEnvironment) { - if ( jdbcEnvironment.getNameQualifierSupport() == NameQualifierSupport.SCHEMA ) { + private Identifier getCurrentCatalog() { + if ( getNameQualifierSupport() == NameQualifierSupport.SCHEMA ) { return null; } if ( currentCatalog != null ) { return currentCatalog; } - final Identifier catalog = jdbcEnvironment.getCurrentCatalog(); + final Identifier catalog = getJdbcEnvironment().getCurrentCatalog(); if ( catalog != null ) { currentCatalog = catalog; } if ( !useJdbcMetadataDefaultsSetting ) { try { - currentCatalog = extractionContext.getJdbcEnvironment() - .getIdentifierHelper() + currentCatalog = getIdentifierHelper() .toIdentifier( extractionContext.getJdbcConnection().getCatalog() ); } - catch (SQLException ignore) { - LOG.sqlWarning( ignore.getErrorCode(), ignore.getSQLState() ); + catch (SQLException sqle) { + LOG.sqlWarning( sqle.getErrorCode(), sqle.getSQLState() ); } } return currentCatalog; @@ -475,8 +454,8 @@ private String getCurrentCatalogFilter(JdbcEnvironment jdbcEnvironment) { try { currentCatalogFilter = extractionContext.getJdbcConnection().getCatalog(); } - catch (SQLException ignore) { - LOG.sqlWarning( ignore.getErrorCode(), ignore.getSQLState() ); + catch (SQLException sqle) { + LOG.sqlWarning( sqle.getErrorCode(), sqle.getSQLState() ); } } return currentCatalogFilter; @@ -495,8 +474,8 @@ private String getCurrentSchemaFilter(JdbcEnvironment jdbcEnvironment) { try { currentSchemaFilter = extractionContext.getJdbcConnection().getSchema(); } - catch (SQLException ignore) { - LOG.sqlWarning( ignore.getErrorCode(), ignore.getSQLState() ); + catch (SQLException sqle) { + LOG.sqlWarning( sqle.getErrorCode(), sqle.getSQLState() ); } catch (AbstractMethodError ignore) { // jConnect and jTDS report that they "support" schemas, but they don't really @@ -511,12 +490,12 @@ public NameSpaceTablesInformation getTables(Identifier catalog, Identifier schem final String catalogFilter; final String schemaFilter; - final JdbcEnvironment jdbcEnvironment = extractionContext.getJdbcEnvironment(); - final NameQualifierSupport nameQualifierSupport = jdbcEnvironment.getNameQualifierSupport(); + final NameQualifierSupport nameQualifierSupport = getNameQualifierSupport(); + if ( nameQualifierSupport.supportsCatalogs() ) { if ( catalog == null ) { // look in the current namespace - final String currentCatalogFilter = getCurrentCatalogFilter(jdbcEnvironment); + final String currentCatalogFilter = getCurrentCatalogFilter( getJdbcEnvironment() ); if ( currentCatalogFilter != null ) { catalogFilter = currentCatalogFilter; } @@ -541,7 +520,7 @@ public NameSpaceTablesInformation getTables(Identifier catalog, Identifier schem if ( nameQualifierSupport.supportsSchemas() ) { if ( schema == null ) { // 1) look in current namespace - final String currentSchemaFilter = getCurrentSchemaFilter( jdbcEnvironment ); + final String currentSchemaFilter = getCurrentSchemaFilter( getJdbcEnvironment() ); if ( currentSchemaFilter != null ) { schemaFilter = currentSchemaFilter; } @@ -570,7 +549,8 @@ public NameSpaceTablesInformation getTables(Identifier catalog, Identifier schem "%", tableTypes, resultSet -> { - final NameSpaceTablesInformation tablesInformation = extractNameSpaceTablesInformation( resultSet ); + final NameSpaceTablesInformation tablesInformation = + extractNameSpaceTablesInformation( resultSet ); populateTablesWithColumns( catalogFilter, schemaFilter, tablesInformation ); return tablesInformation; } ); @@ -665,10 +645,7 @@ private void populateTablesWithColumns( ); } catch (SQLException e) { - throw convertSQLException( - e, - "Error accessing tables metadata" - ); + throw convertSQLException( e, "Error accessing tables metadata" ); } } @@ -676,7 +653,7 @@ protected void addExtractedColumnInformation(TableInformation tableInformation, throws SQLException { final ColumnInformation columnInformation = new ColumnInformationImpl( tableInformation, - DatabaseIdentifier.toIdentifier( resultSet.getString( getResultSetColumnNameLabel() ) ), + toIdentifier( resultSet.getString( getResultSetColumnNameLabel() ) ), resultSet.getInt( getResultSetSqlTypeCodeLabel() ), new StringTokenizer( resultSet.getString( getResultSetTypeNameLabel() ), "()" ).nextToken(), resultSet.getInt( getResultSetColumnSizeLabel() ), @@ -687,7 +664,7 @@ protected void addExtractedColumnInformation(TableInformation tableInformation, } private NameSpaceTablesInformation extractNameSpaceTablesInformation(ResultSet resultSet) throws SQLException { - NameSpaceTablesInformation tables = new NameSpaceTablesInformation(identifierHelper()); + final NameSpaceTablesInformation tables = new NameSpaceTablesInformation( identifierHelper() ); while ( resultSet.next() ) { final TableInformation tableInformation = extractTableInformation( resultSet ); tables.addTableInformation( tableInformation ); @@ -757,15 +734,15 @@ private TableInformation locateTableInNamespace( final String catalogFilter; final String schemaFilter; - if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs() ) { + final NameQualifierSupport nameQualifierSupport = getNameQualifierSupport(); + if ( nameQualifierSupport.supportsCatalogs() ) { if ( catalog == null ) { - String defaultCatalog = ""; - if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsCatalogs() ) { - try { - defaultCatalog = extractionContext.getJdbcConnection().getCatalog(); - } - catch (SQLException ignore) { - } + String defaultCatalog; + try { + defaultCatalog = extractionContext.getJdbcConnection().getCatalog(); + } + catch (SQLException ignore) { + defaultCatalog = ""; } catalogToUse = null; catalogFilter = defaultCatalog; @@ -780,7 +757,7 @@ private TableInformation locateTableInNamespace( catalogFilter = null; } - if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas() ) { + if ( nameQualifierSupport.supportsSchemas() ) { if ( schema == null ) { schemaToUse = null; schemaFilter = ""; @@ -817,6 +794,10 @@ private TableInformation locateTableInNamespace( } } + private NameQualifierSupport getNameQualifierSupport() { + return getJdbcEnvironment().getNameQualifierSupport(); + } + private TableInformation extractTableInformation( Identifier catalog, Identifier schema, @@ -825,23 +806,19 @@ private TableInformation extractTableInformation( boolean found = false; TableInformation tableInformation = null; - while ( resultSet.next() ) { - if ( tableName.equals( Identifier.toIdentifier( resultSet.getString( getResultSetTableNameLabel() ), tableName.isQuoted() ) ) ) { if ( found ) { LOG.multipleTablesFound( tableName.render() ); - final String catalogName = catalog == null ? "" : catalog.render(); - final String schemaName = schema == null ? "" : schema.render(); throw new SchemaExtractionException( String.format( Locale.ENGLISH, "More than one table found in namespace (%s, %s) : %s", - catalogName, - schemaName, + catalog == null ? "" : catalog.render(), + schema == null ? "" : schema.render(), tableName.render() ) ); @@ -882,18 +859,13 @@ protected void addColumns(TableInformation tableInformation) { final QualifiedTableName tableName = tableInformation.getName(); final Identifier catalog = tableName.getCatalogName(); final Identifier schema = tableName.getSchemaName(); - - final String catalogFilter = catalog == null ? "" : catalog.getText(); - final String schemaFilter = schema == null ? "" : schema.getText(); - try { processColumnsResultSet( - catalogFilter, - schemaFilter, + catalog == null ? "" : catalog.getText(), + schema == null ? "" : schema.getText(), tableName.getTableName().getText(), "%", resultSet -> { - while ( resultSet.next() ) { addExtractedColumnInformation( tableInformation, resultSet ); } @@ -903,10 +875,7 @@ protected void addColumns(TableInformation tableInformation) { } catch (SQLException e) { - throw convertSQLException( - e, - "Error accessing tables metadata" - ); + throw convertSQLException( e, "Error accessing tables metadata" ); } } @@ -942,34 +911,18 @@ public PrimaryKeyInformation getPrimaryKey(TableInformationImpl tableInformation final QualifiedTableName tableName = tableInformation.getName(); final Identifier catalog = tableName.getCatalogName(); final Identifier schema = tableName.getSchemaName(); - - final String catalogFilter; - final String schemaFilter; - - if ( catalog == null ) { - catalogFilter = ""; - } - else { - catalogFilter = catalog.getText(); - } - - if ( schema == null ) { - schemaFilter = ""; - } - else { - schemaFilter = schema.getText(); - } - try { return processPrimaryKeysResultSet( - catalogFilter, - schemaFilter, + catalog == null ? "" : catalog.getText(), + schema == null ? "" : schema.getText(), tableInformation.getName().getTableName(), resultSet -> extractPrimaryKeyInformation( tableInformation, resultSet ) ); } catch (SQLException e) { - throw convertSQLException( e, "Error while reading primary key meta data for " + tableInformation.getName().toString() ); + throw convertSQLException( e, + "Error while reading primary key meta data for " + + tableInformation.getName() ); } } @@ -984,9 +937,7 @@ private PrimaryKeyInformation extractPrimaryKeyInformation( while ( resultSet.next() ) { final String currentPkName = resultSet.getString( getResultSetPrimaryKeyNameLabel() ); - final Identifier currentPkIdentifier = currentPkName == null - ? null - : DatabaseIdentifier.toIdentifier( currentPkName ); + final Identifier currentPkIdentifier = currentPkName == null ? null : toIdentifier( currentPkName ); if ( firstPass ) { pkIdentifier = currentPkIdentifier; firstPass = false; @@ -1003,15 +954,13 @@ private PrimaryKeyInformation extractPrimaryKeyInformation( } final int columnPosition = resultSet.getInt( getResultSetColumnPositionColumn() ); - final int index = columnPosition - 1; // Fill up the array list with nulls up to the desired index, because some JDBC drivers don't return results ordered by column position while ( pkColumns.size() <= index ) { pkColumns.add( null ); } - final Identifier columnIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetColumnNameLabel() ) - ); + final Identifier columnIdentifier = + toIdentifier( resultSet.getString( getResultSetColumnNameLabel() ) ); pkColumns.set( index, tableInformation.getColumn( columnIdentifier ) ); } if ( firstPass ) { @@ -1025,7 +974,6 @@ private PrimaryKeyInformation extractPrimaryKeyInformation( throw new SchemaExtractionException( "Primary Key information was missing for KEY_SEQ = " + ( i+1) ); } } - // build the return return new PrimaryKeyInformationImpl( pkIdentifier, pkColumns ); } @@ -1110,62 +1058,44 @@ protected abstract T processIndexInfoResultSet( @Override public Iterable getIndexes(TableInformation tableInformation) { - final Map builders = new HashMap<>(); final QualifiedTableName tableName = tableInformation.getName(); final Identifier catalog = tableName.getCatalogName(); final Identifier schema = tableName.getSchemaName(); - final String catalogFilter; - final String schemaFilter; - - if ( catalog == null ) { - catalogFilter = ""; - } - else { - catalogFilter = catalog.getText(); - } - - if ( schema == null ) { - schemaFilter = ""; - } - else { - schemaFilter = schema.getText(); - } - + final Map builders = new HashMap<>(); try { processIndexInfoResultSet( - catalogFilter, - schemaFilter, + catalog == null ? "" : catalog.getText(), + schema == null ? "" : schema.getText(), tableName.getTableName().getText(), false, // DO NOT limit to just unique true, // DO require up-to-date results resultSet -> { while ( resultSet.next() ) { - if ( resultSet.getShort( getResultSetIndexTypeLabel() ) == DatabaseMetaData.tableIndexStatistic ) { - continue; - } - - final Identifier indexIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetIndexNameLabel() ) - ); - IndexInformationImpl.Builder builder = builders.get( indexIdentifier ); - if ( builder == null ) { - builder = IndexInformationImpl.builder( indexIdentifier ); - builders.put( indexIdentifier, builder ); + if ( resultSet.getShort( getResultSetIndexTypeLabel() ) + != DatabaseMetaData.tableIndexStatistic ) { + final Identifier indexIdentifier = + toIdentifier( resultSet.getString( getResultSetIndexNameLabel() ) ); + IndexInformationImpl.Builder builder = builders.get( indexIdentifier ); + if ( builder == null ) { + builder = IndexInformationImpl.builder( indexIdentifier ); + builders.put( indexIdentifier, builder ); + } + + final Identifier columnIdentifier = + toIdentifier( resultSet.getString( getResultSetColumnNameLabel() ) ); + final ColumnInformation columnInformation = + tableInformation.getColumn( columnIdentifier ); + if ( columnInformation == null ) { + // See HHH-10191: this may happen when dealing with Oracle/PostgreSQL function indexes + LOG.logCannotLocateIndexColumnInformation( + columnIdentifier.getText(), + indexIdentifier.getText() + ); + } + builder.addColumn( columnInformation ); } - final Identifier columnIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetColumnNameLabel() ) - ); - final ColumnInformation columnInformation = tableInformation.getColumn( columnIdentifier ); - if ( columnInformation == null ) { - // See HHH-10191: this may happen when dealing with Oracle/PostgreSQL function indexes - LOG.logCannotLocateIndexColumnInformation( - columnIdentifier.getText(), - indexIdentifier.getText() - ); - } - builder.addColumn( columnInformation ); } return null; } @@ -1173,10 +1103,9 @@ public Iterable getIndexes(TableInformation tableInformation) } catch (SQLException e) { - throw convertSQLException( - e, - "Error accessing index information: " + tableInformation.getName().toString() - ); + throw convertSQLException( e, + "Error accessing index information: " + + tableInformation.getName() ); } final List indexes = new ArrayList<>(); @@ -1348,91 +1277,41 @@ protected abstract T processCrossReferenceResultSet( @Override public Iterable getForeignKeys(TableInformation tableInformation) { - final Map fkBuilders = new HashMap<>(); final QualifiedTableName tableName = tableInformation.getName(); final Identifier catalog = tableName.getCatalogName(); final Identifier schema = tableName.getSchemaName(); - final String catalogFilter; - final String schemaFilter; - - if ( catalog == null ) { - catalogFilter = ""; - } - else { - catalogFilter = catalog.getText(); - } - - if ( schema == null ) { - schemaFilter = ""; - } - else { - schemaFilter = schema.getText(); - } + final String catalogFilter = catalog == null ? "" : catalog.getText(); + final String schemaFilter = schema == null ? "" : schema.getText(); + final Map fkBuilders = new HashMap<>(); try { - ExtractionContext.ResultSetProcessor processor = resultSet -> { - while ( resultSet.next() ) { - // IMPL NOTE : The builder is mainly used to collect the column reference mappings - final Identifier fkIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetForeignKeyLabel() ) - ); - ForeignKeyBuilder fkBuilder = fkBuilders.get( fkIdentifier ); - if ( fkBuilder == null ) { - fkBuilder = generateForeignKeyBuilder( fkIdentifier ); - fkBuilders.put( fkIdentifier, fkBuilder ); - } - - final QualifiedTableName incomingPkTableName = extractPrimaryKeyTableName( resultSet ); - - final TableInformation pkTableInformation = extractionContext.getDatabaseObjectAccess() - .locateTableInformation( incomingPkTableName ); - - if ( pkTableInformation == null ) { - // the assumption here is that we have not seen this table already based on fully-qualified name - // during previous step of building all table metadata so most likely this is - // not a match based solely on schema/catalog and that another row in this result set - // should match. - continue; - } - - final Identifier fkColumnIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetForeignKeyColumnNameLabel() ) - ); - final Identifier pkColumnIdentifier = DatabaseIdentifier.toIdentifier( - resultSet.getString( getResultSetPrimaryKeyColumnNameLabel() ) - ); - - fkBuilder.addColumnMapping( - tableInformation.getColumn( fkColumnIdentifier ), - pkTableInformation.getColumn( pkColumnIdentifier ) - ); - } - return null; - }; - processImportedKeysResultSet( - catalogFilter, - schemaFilter, - tableInformation.getName().getTableName().getText(), - processor); - final Dialect dialect = extractionContext.getJdbcEnvironment().getDialect(); - if (dialect.useCrossReferenceForeignKeys()) { + final String table = tableInformation.getName().getTableName().getText(); + processImportedKeysResultSet( catalogFilter, schemaFilter, table, + resultSet -> { + process( tableInformation, resultSet, fkBuilders ); + return null; + } ); + final Dialect dialect = getJdbcEnvironment().getDialect(); + if ( dialect.useCrossReferenceForeignKeys() ) { processCrossReferenceResultSet( null, null, dialect.getCrossReferenceParentTableFilter(), catalogFilter, schemaFilter, - tableInformation.getName().getTableName().getText(), - processor + table, + resultSet -> { + process( tableInformation, resultSet, fkBuilders ); + return null; + } ); } } catch (SQLException e) { - throw convertSQLException( - e, - "Error accessing column metadata: " + tableInformation.getName().toString() - ); + throw convertSQLException( e, + "Error accessing column metadata: " + + tableInformation.getName() ); } final List fks = new ArrayList<>(); @@ -1443,6 +1322,37 @@ public Iterable getForeignKeys(TableInformation tableInfo return fks; } + private void process(TableInformation tableInformation, ResultSet resultSet, Map fkBuilders) + throws SQLException { + while ( resultSet.next() ) { + // IMPL NOTE : The builder is mainly used to collect the column reference mappings + final Identifier fkIdentifier = toIdentifier( resultSet.getString( getResultSetForeignKeyLabel() ) ); + ForeignKeyBuilder fkBuilder = fkBuilders.get( fkIdentifier ); + if ( fkBuilder == null ) { + fkBuilder = generateForeignKeyBuilder( fkIdentifier ); + fkBuilders.put( fkIdentifier, fkBuilder ); + } + + final TableInformation pkTableInformation = extractionContext.getDatabaseObjectAccess() + .locateTableInformation( extractPrimaryKeyTableName( resultSet ) ); + if ( pkTableInformation != null ) { + // the assumption here is that we have not seen this table already based on fully-qualified name + // during previous step of building all table metadata so most likely this is + // not a match based solely on schema/catalog and that another row in this result set + // should match. + final Identifier fkColumnIdentifier = + toIdentifier( resultSet.getString( getResultSetForeignKeyColumnNameLabel() ) ); + final Identifier pkColumnIdentifier = + toIdentifier( resultSet.getString( getResultSetPrimaryKeyColumnNameLabel() ) ); + fkBuilder.addColumnMapping( + tableInformation.getColumn( fkColumnIdentifier ), + pkTableInformation.getColumn( pkColumnIdentifier ) + ); + } + + } + } + private ForeignKeyBuilder generateForeignKeyBuilder(Identifier fkIdentifier) { return new ForeignKeyBuilderImpl( fkIdentifier ); } @@ -1480,27 +1390,18 @@ public ForeignKeyInformationImpl build() { } private QualifiedTableName extractPrimaryKeyTableName(ResultSet resultSet) throws SQLException { - final String incomingCatalogName = resultSet.getString( getResultSetPrimaryKeyCatalogLabel() ); - final String incomingSchemaName = resultSet.getString( getResultSetPrimaryKeySchemaLabel() ); - final String incomingTableName = resultSet.getString( getResultSetPrimaryKeyTableLabel() ); - - final DatabaseIdentifier catalog = DatabaseIdentifier.toIdentifier( incomingCatalogName ); - final DatabaseIdentifier schema = DatabaseIdentifier.toIdentifier( incomingSchemaName ); - final DatabaseIdentifier table = DatabaseIdentifier.toIdentifier( incomingTableName ); - - return new QualifiedTableName( catalog, schema, table ); + return new QualifiedTableName( + toIdentifier( resultSet.getString( getResultSetPrimaryKeyCatalogLabel() ) ), + toIdentifier( resultSet.getString( getResultSetPrimaryKeySchemaLabel() ) ), + toIdentifier( resultSet.getString( getResultSetPrimaryKeyTableLabel() ) ) ); } private QualifiedTableName extractTableName(ResultSet resultSet) throws SQLException { - final String incomingCatalogName = resultSet.getString( getResultSetCatalogLabel() ); - final String incomingSchemaName = resultSet.getString( getResultSetSchemaLabel() ); - final String incomingTableName = resultSet.getString( getResultSetTableNameLabel() ); - - final DatabaseIdentifier catalog = DatabaseIdentifier.toIdentifier( incomingCatalogName ); - final DatabaseIdentifier schema = DatabaseIdentifier.toIdentifier( incomingSchemaName ); - final DatabaseIdentifier table = DatabaseIdentifier.toIdentifier( incomingTableName ); - - return new QualifiedTableName( catalog, schema, table ); + return new QualifiedTableName( + toIdentifier( resultSet.getString( getResultSetCatalogLabel() ) ), + toIdentifier( resultSet.getString( getResultSetSchemaLabel() ) ), + toIdentifier( resultSet.getString( getResultSetTableNameLabel() ) ) + ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java index 0eddf5a1926c..5306139a2c8d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java @@ -4,6 +4,7 @@ */ package org.hibernate.tool.schema.extract.internal; +import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -28,6 +29,10 @@ public InformationExtractorJdbcDatabaseMetaDataImpl(ExtractionContext extraction super( extractionContext ); } + private DatabaseMetaData getJdbcDatabaseMetaData() { + return getExtractionContext().getJdbcDatabaseMetaData(); + } + @Override protected String getResultSetTableTypesPhysicalTableConstant() { return "TABLE"; @@ -35,7 +40,7 @@ protected String getResultSetTableTypesPhysicalTableConstant() { @Override public T processCatalogsResultSet(ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getCatalogs() ) { + try (ResultSet resultSet = getJdbcDatabaseMetaData().getCatalogs() ) { return processor.process( resultSet ); } } @@ -45,7 +50,7 @@ protected T processSchemaResultSet( String catalog, String schemaPattern, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getSchemas( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getSchemas( catalog, schemaPattern ) ) { return processor.process( resultSet ); @@ -60,7 +65,7 @@ protected T processTableResultSet( String[] types, ExtractionContext.ResultSetProcessor processor ) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getTables( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getTables( catalog, schemaPattern, tableNamePattern, @@ -76,7 +81,7 @@ protected T processColumnsResultSet( String tableNamePattern, String columnNamePattern, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getColumns( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getColumns( catalog, schemaPattern, tableNamePattern, @@ -91,7 +96,7 @@ protected T processPrimaryKeysResultSet( String schemaFilter, Identifier tableName, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try( ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getPrimaryKeys( + try( ResultSet resultSet = getJdbcDatabaseMetaData().getPrimaryKeys( catalogFilter, schemaFilter, tableName.getText() ) ) { @@ -108,7 +113,7 @@ protected T processIndexInfoResultSet( boolean approximate, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getIndexInfo( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getIndexInfo( catalog, schema, table, @@ -124,7 +129,7 @@ protected T processImportedKeysResultSet( String schema, String table, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getImportedKeys( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getImportedKeys( catalog, schema, table ) ) { @@ -141,7 +146,7 @@ protected T processCrossReferenceResultSet( String foreignSchema, String foreignTable, ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getCrossReference( + try (ResultSet resultSet = getJdbcDatabaseMetaData().getCrossReference( parentCatalog, parentSchema, parentTable, @@ -153,9 +158,9 @@ protected T processCrossReferenceResultSet( } protected void addColumns(TableInformation tableInformation) { - final Dialect dialect = getExtractionContext().getJdbcEnvironment().getDialect(); - + final Dialect dialect = getJdbcEnvironment().getDialect(); final ExtractionContext extractionContext = getExtractionContext(); + // We use this dummy query to retrieve the table information through the ResultSetMetaData // This is significantly better than to use the DatabaseMetaData especially on Oracle with synonyms enabled final String tableName = extractionContext.getSqlStringGenerationContext().format( From 2abaeb1fd52ca7286d38cf0ea34fd8a4c860de35 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 10:40:27 +0100 Subject: [PATCH 4/6] clean up unused instance variables --- .../hbm/transform/BootModelPreprocessor.java | 13 ++----------- .../jaxb/hbm/transform/HbmXmlTransformer.java | 19 +++---------------- 2 files changed, 5 insertions(+), 27 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/BootModelPreprocessor.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/BootModelPreprocessor.java index d79d54292056..6a26a37d8094 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/BootModelPreprocessor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/BootModelPreprocessor.java @@ -5,13 +5,10 @@ package org.hibernate.boot.jaxb.hbm.transform; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import org.hibernate.MappingException; -import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmHibernateMapping; -import org.hibernate.boot.jaxb.spi.Binding; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Component; @@ -21,7 +18,6 @@ import org.hibernate.mapping.RootClass; import org.hibernate.mapping.Table; import org.hibernate.mapping.ToOne; -import org.hibernate.service.ServiceRegistry; /** * @author Steve Ebersole @@ -29,25 +25,20 @@ public class BootModelPreprocessor { private static final Map entityByNameMap = new HashMap<>(); - static void preprocessBooModel( - List> hbmXmlBindings, - MetadataImplementor bootModel, - ServiceRegistry serviceRegistry, - TransformationState transformationState) { + static void preprocessBooModel(MetadataImplementor bootModel, TransformationState transformationState) { entityByNameMap.clear(); bootModel.getEntityBindings().forEach( (persistentClass) -> { final Table table = TransformationHelper.determineEntityTable( persistentClass ); final EntityTypeInfo entityTypeInfo = new EntityTypeInfo( table, persistentClass ); transformationState.getEntityInfoByName().put( persistentClass.getEntityName(), entityTypeInfo ); - buildPersistentClassPropertyInfos( persistentClass, entityTypeInfo, bootModel, transformationState ); + buildPersistentClassPropertyInfos( persistentClass, entityTypeInfo, transformationState ); } ); } private static void buildPersistentClassPropertyInfos( PersistentClass persistentClass, EntityTypeInfo entityTypeInfo, - MetadataImplementor bootModel, TransformationState transformationState) { if ( persistentClass.getClassName() != null ) { final String previous = entityByNameMap.put( persistentClass.getClassName(), persistentClass.getEntityName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java index c0c50c5792e8..842ca4feb8cb 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/hbm/transform/HbmXmlTransformer.java @@ -231,12 +231,7 @@ public static List> transform( final List> transformations = XmlPreprocessor.preprocessHbmXml( hbmXmlBindings, transformationState ); // build and perform a pass over the boot model building the rest of the transformation-state - BootModelPreprocessor.preprocessBooModel( - hbmXmlBindings, - bootModel, - serviceRegistry, - transformationState - ); + BootModelPreprocessor.preprocessBooModel( bootModel, transformationState ); // now we are ready to fully build the mapping.xml transformations for ( int i = 0; i < hbmXmlBindings.size(); i++ ) { @@ -244,9 +239,7 @@ public static List> transform( hbmXmlBindings.get( i ), transformations.get( i ), transformationState, - bootModel, - unsupportedFeatureHandling, - serviceRegistry + unsupportedFeatureHandling ); hbmXmlTransformer.performTransformation(); @@ -260,10 +253,8 @@ public static List> transform( private final Binding mappingXmlBinding; private final TransformationState transformationState; - private final MetadataImplementor bootModel; private final UnsupportedFeatureHandling unsupportedFeatureHandling; - private final ServiceRegistry serviceRegistry; // todo (7.0) : use transformation-state instead private final Map jaxbEmbeddableByClassName = new HashMap<>(); @@ -274,15 +265,11 @@ private HbmXmlTransformer( Binding hbmXmlBinding, Binding mappingXmlBinding, TransformationState transformationState, - MetadataImplementor bootModel, - UnsupportedFeatureHandling unsupportedFeatureHandling, - ServiceRegistry serviceRegistry) { + UnsupportedFeatureHandling unsupportedFeatureHandling) { this.hbmXmlBinding = hbmXmlBinding; this.mappingXmlBinding = mappingXmlBinding; this.transformationState = transformationState; - this.bootModel = bootModel; this.unsupportedFeatureHandling = unsupportedFeatureHandling; - this.serviceRegistry = serviceRegistry; } From 9cdf06ef8e320b3bb34ea1aef94a2b4c63b5951d Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 11:43:07 +0100 Subject: [PATCH 5/6] cleanups to InformationExtractorJdbcDatabaseMetaDataImpl and more to AbstractInformationExtractorImpl --- .../AbstractInformationExtractorImpl.java | 147 +++++++--------- ...tionExtractorJdbcDatabaseMetaDataImpl.java | 159 +++++++++--------- .../internal/TableInformationImpl.java | 2 +- 3 files changed, 146 insertions(+), 162 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java index 89c53310aafc..5fd9a9b8dd2d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/AbstractInformationExtractorImpl.java @@ -6,7 +6,6 @@ import java.sql.DatabaseMetaData; import java.sql.ResultSet; -import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; @@ -42,6 +41,7 @@ import static java.util.Collections.addAll; import static org.hibernate.boot.model.naming.DatabaseIdentifier.toIdentifier; +import static org.hibernate.internal.util.StringHelper.EMPTY_STRINGS; import static org.hibernate.internal.util.StringHelper.isBlank; import static org.hibernate.internal.util.StringHelper.splitTrimmingTokens; import static org.hibernate.internal.util.config.ConfigurationHelper.getBoolean; @@ -85,31 +85,37 @@ public AbstractInformationExtractorImpl(ExtractionContext extractionContext) { "" ) ); + final Dialect dialect = extractionContext.getJdbcEnvironment().getDialect(); + this.extraPhysicalTableTypes = getPhysicalTableTypes( extraPhysicalTableTypesConfig, dialect ); + this.tableTypes = getTableTypes( configService, dialect ); + } + + private String[] getPhysicalTableTypes(String extraPhysicalTableTypesConfig, Dialect dialect) { final List physicalTableTypesList = new ArrayList<>(); if ( !isBlank( extraPhysicalTableTypesConfig ) ) { addAll( physicalTableTypesList, splitTrimmingTokens( ",;", extraPhysicalTableTypesConfig, false ) ); } - final Dialect dialect = extractionContext.getJdbcEnvironment().getDialect(); dialect.augmentPhysicalTableTypes( physicalTableTypesList ); - this.extraPhysicalTableTypes = physicalTableTypesList.toArray( new String[0] ); + return physicalTableTypesList.toArray( EMPTY_STRINGS ); + } + private String[] getTableTypes(ConfigurationService configService, Dialect dialect) { final List tableTypesList = new ArrayList<>(); tableTypesList.add( "TABLE" ); tableTypesList.add( "VIEW" ); if ( getBoolean( AvailableSettings.ENABLE_SYNONYMS, configService.getSettings() ) ) { - if ( dialect instanceof DB2Dialect ) { + if ( dialect instanceof DB2Dialect ) { //TODO: should not use Dialect types directly! tableTypesList.add( "ALIAS" ); } tableTypesList.add( "SYNONYM" ); } addAll( tableTypesList, extraPhysicalTableTypes ); dialect.augmentRecognizedTableTypes( tableTypesList ); - - this.tableTypes = tableTypesList.toArray( new String[0] ); + return tableTypesList.toArray( EMPTY_STRINGS ); } - protected IdentifierHelper identifierHelper() { - return getIdentifierHelper(); + private IdentifierHelper getIdentifierHelper() { + return getJdbcEnvironment().getIdentifierHelper(); } protected JDBCException convertSQLException(SQLException sqlException, String message) { @@ -272,13 +278,17 @@ public boolean catalogExists(Identifier catalog) { protected abstract T processSchemaResultSet( String catalog, String schemaPattern, - ExtractionContext.ResultSetProcessor processor) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; @Override public boolean schemaExists(Identifier catalog, Identifier schema) { - final String catalogFilter = determineCatalogFilter( catalog ); - final String schemaFilter = determineSchemaFilter( schema ); - + final String catalogFilter = + getIdentifierHelper() + .toMetaDataCatalogName( catalog == null ? extractionContext.getDefaultCatalog() : catalog ); + final String schemaFilter = + getIdentifierHelper() + .toMetaDataSchemaName( schema == null ? extractionContext.getDefaultSchema() : schema ); try { return processSchemaResultSet( catalogFilter, @@ -308,32 +318,10 @@ public boolean schemaExists(Identifier catalog, Identifier schema) { } } - private IdentifierHelper getIdentifierHelper() { - return getJdbcEnvironment().getIdentifierHelper(); - } - - protected String determineCatalogFilter(Identifier catalog) { - Identifier identifierToUse = catalog; - if ( identifierToUse == null ) { - identifierToUse = extractionContext.getDefaultCatalog(); - } - - return getIdentifierHelper().toMetaDataCatalogName( identifierToUse ); - } - - protected String determineSchemaFilter(Identifier schema) { - Identifier identifierToUse = schema; - if ( identifierToUse == null ) { - identifierToUse = extractionContext.getDefaultSchema(); - } - - return getIdentifierHelper().toMetaDataSchemaName( identifierToUse ); - } - private TableInformation extractTableInformation(ResultSet resultSet) throws SQLException { return new TableInformationImpl( this, - identifierHelper(), + getIdentifierHelper(), extractTableName( resultSet ), isPhysicalTableType( resultSet.getString( getResultSetTableTypeLabel() ) ), resultSet.getString( getResultSetRemarksLabel() ) @@ -616,7 +604,8 @@ protected abstract T processColumnsResultSet( String schemaPattern, String tableNamePattern, String columnNamePattern, - ExtractionContext.ResultSetProcessor processor) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; private void populateTablesWithColumns( String catalogFilter, @@ -637,7 +626,7 @@ private void populateTablesWithColumns( currentTable = tables.getTableInformation( currentTableName ); } if ( currentTable != null ) { - addExtractedColumnInformation( currentTable, resultSet ); + currentTable.addColumn( columnInformation( currentTable, resultSet ) ); } } return null; @@ -649,9 +638,9 @@ private void populateTablesWithColumns( } } - protected void addExtractedColumnInformation(TableInformation tableInformation, ResultSet resultSet) + private ColumnInformationImpl columnInformation(TableInformation tableInformation, ResultSet resultSet) throws SQLException { - final ColumnInformation columnInformation = new ColumnInformationImpl( + return new ColumnInformationImpl( tableInformation, toIdentifier( resultSet.getString( getResultSetColumnNameLabel() ) ), resultSet.getInt( getResultSetSqlTypeCodeLabel() ), @@ -660,14 +649,13 @@ protected void addExtractedColumnInformation(TableInformation tableInformation, resultSet.getInt( getResultSetDecimalDigitsLabel() ), interpretTruthValue( resultSet.getString( getResultSetIsNullableLabel() ) ) ); - tableInformation.addColumn( columnInformation ); } - private NameSpaceTablesInformation extractNameSpaceTablesInformation(ResultSet resultSet) throws SQLException { - final NameSpaceTablesInformation tables = new NameSpaceTablesInformation( identifierHelper() ); + private NameSpaceTablesInformation extractNameSpaceTablesInformation(ResultSet resultSet) + throws SQLException { + final NameSpaceTablesInformation tables = new NameSpaceTablesInformation( getIdentifierHelper() ); while ( resultSet.next() ) { - final TableInformation tableInformation = extractTableInformation( resultSet ); - tables.addTableInformation( tableInformation ); + tables.addTableInformation( extractTableInformation( resultSet ) ); } return tables; } @@ -721,8 +709,8 @@ protected abstract T processTableResultSet( String schemaPattern, String tableNamePattern, String[] types, - ExtractionContext.ResultSetProcessor processor - ) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; private TableInformation locateTableInNamespace( Identifier catalog, @@ -735,6 +723,7 @@ private TableInformation locateTableInNamespace( final String schemaFilter; final NameQualifierSupport nameQualifierSupport = getNameQualifierSupport(); + if ( nameQualifierSupport.supportsCatalogs() ) { if ( catalog == null ) { String defaultCatalog; @@ -780,12 +769,7 @@ private TableInformation locateTableInNamespace( schemaFilter, tableNameFilter, tableTypes, - resultSet -> extractTableInformation( - catalogToUse, - schemaToUse, - tableName, - resultSet - ) + resultSet -> extractTableInformation( catalogToUse, schemaToUse, tableName, resultSet ) ); } @@ -802,15 +786,16 @@ private TableInformation extractTableInformation( Identifier catalog, Identifier schema, Identifier tableName, - ResultSet resultSet) throws SQLException { + ResultSet resultSet) + throws SQLException { boolean found = false; TableInformation tableInformation = null; while ( resultSet.next() ) { - if ( tableName.equals( Identifier.toIdentifier( - resultSet.getString( getResultSetTableNameLabel() ), - tableName.isQuoted() - ) ) ) { + final Identifier identifier = + toIdentifier( resultSet.getString( getResultSetTableNameLabel() ), + tableName.isQuoted() ); + if ( tableName.equals( identifier ) ) { if ( found ) { LOG.multipleTablesFound( tableName.render() ); throw new SchemaExtractionException( @@ -867,7 +852,7 @@ protected void addColumns(TableInformation tableInformation) { "%", resultSet -> { while ( resultSet.next() ) { - addExtractedColumnInformation( tableInformation, resultSet ); + tableInformation.addColumn( columnInformation( tableInformation, resultSet ) ); } return null; } @@ -879,14 +864,6 @@ protected void addColumns(TableInformation tableInformation) { } } - protected Boolean interpretNullable(int nullable) { - return switch ( nullable ) { - case ResultSetMetaData.columnNullable -> Boolean.TRUE; - case ResultSetMetaData.columnNoNulls -> Boolean.FALSE; - default -> null; - }; - } - private Boolean interpretTruthValue(String nullable) { if ( "yes".equalsIgnoreCase( nullable ) ) { return Boolean.TRUE; @@ -904,7 +881,8 @@ protected abstract T processPrimaryKeysResultSet( String catalogFilter, String schemaFilter, Identifier tableName, - ExtractionContext.ResultSetProcessor processor) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; @Override public PrimaryKeyInformation getPrimaryKey(TableInformationImpl tableInformation) { @@ -926,10 +904,8 @@ public PrimaryKeyInformation getPrimaryKey(TableInformationImpl tableInformation } } - private PrimaryKeyInformation extractPrimaryKeyInformation( - TableInformation tableInformation, - ResultSet resultSet - ) throws SQLException { + private PrimaryKeyInformation extractPrimaryKeyInformation(TableInformation tableInformation, ResultSet resultSet) + throws SQLException { final List pkColumns = new ArrayList<>(); boolean firstPass = true; @@ -937,19 +913,16 @@ private PrimaryKeyInformation extractPrimaryKeyInformation( while ( resultSet.next() ) { final String currentPkName = resultSet.getString( getResultSetPrimaryKeyNameLabel() ); - final Identifier currentPkIdentifier = currentPkName == null ? null : toIdentifier( currentPkName ); + final Identifier currentPkIdentifier = + currentPkName == null ? null : toIdentifier( currentPkName ); if ( firstPass ) { pkIdentifier = currentPkIdentifier; firstPass = false; } else { if ( !Objects.equals( pkIdentifier, currentPkIdentifier ) ) { - throw new SchemaExtractionException( - String.format( - "Encountered primary keys differing name on table %s", - tableInformation.getName().toString() - ) - ); + throw new SchemaExtractionException( "Encountered primary keys differing name on table " + + tableInformation.getName().toString() ); } } @@ -1054,7 +1027,8 @@ protected abstract T processIndexInfoResultSet( String table, boolean unique, boolean approximate, - ExtractionContext.ResultSetProcessor processor) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; @Override public Iterable getIndexes(TableInformation tableInformation) { @@ -1186,8 +1160,8 @@ protected abstract T processImportedKeysResultSet( String catalog, String schema, String table, - ExtractionContext.ResultSetProcessor processor - ) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; /** * Must do the following: @@ -1271,8 +1245,8 @@ protected abstract T processCrossReferenceResultSet( String foreignCatalog, String foreignSchema, String foreignTable, - ExtractionContext.ResultSetProcessor processor - ) throws SQLException; + ExtractionContext.ResultSetProcessor processor) + throws SQLException; @Override @@ -1322,8 +1296,11 @@ public Iterable getForeignKeys(TableInformation tableInfo return fks; } - private void process(TableInformation tableInformation, ResultSet resultSet, Map fkBuilders) - throws SQLException { + private void process( + TableInformation tableInformation, + ResultSet resultSet, + Map fkBuilders) + throws SQLException { while ( resultSet.next() ) { // IMPL NOTE : The builder is mainly used to collect the column reference mappings final Identifier fkIdentifier = toIdentifier( resultSet.getString( getResultSetForeignKeyLabel() ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java index 5306139a2c8d..02740dcaf1f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/InformationExtractorJdbcDatabaseMetaDataImpl.java @@ -39,8 +39,9 @@ protected String getResultSetTableTypesPhysicalTableConstant() { } @Override - public T processCatalogsResultSet(ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getCatalogs() ) { + public T processCatalogsResultSet(ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = getJdbcDatabaseMetaData().getCatalogs() ) { return processor.process( resultSet ); } } @@ -49,10 +50,11 @@ public T processCatalogsResultSet(ExtractionContext.ResultSetProcessor pr protected T processSchemaResultSet( String catalog, String schemaPattern, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getSchemas( - catalog, - schemaPattern ) ) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getSchemas( catalog, schemaPattern ) ) { return processor.process( resultSet ); } } @@ -63,13 +65,11 @@ protected T processTableResultSet( String schemaPattern, String tableNamePattern, String[] types, - ExtractionContext.ResultSetProcessor processor - ) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getTables( - catalog, - schemaPattern, - tableNamePattern, - types)) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getTables( catalog, schemaPattern, tableNamePattern, types) ) { return processor.process( resultSet ); } } @@ -80,12 +80,11 @@ protected T processColumnsResultSet( String schemaPattern, String tableNamePattern, String columnNamePattern, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getColumns( - catalog, - schemaPattern, - tableNamePattern, - columnNamePattern )) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getColumns( catalog, schemaPattern, tableNamePattern, columnNamePattern ) ) { return processor.process( resultSet ); } } @@ -95,11 +94,11 @@ protected T processPrimaryKeysResultSet( String catalogFilter, String schemaFilter, Identifier tableName, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - try( ResultSet resultSet = getJdbcDatabaseMetaData().getPrimaryKeys( - catalogFilter, - schemaFilter, - tableName.getText() ) ) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getPrimaryKeys( catalogFilter, schemaFilter, tableName.getText() ) ) { return processor.process( resultSet ); } } @@ -111,14 +110,11 @@ protected T processIndexInfoResultSet( String table, boolean unique, boolean approximate, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - - try (ResultSet resultSet = getJdbcDatabaseMetaData().getIndexInfo( - catalog, - schema, - table, - unique, - approximate ) ) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getIndexInfo( catalog, schema, table, unique, approximate ) ) { return processor.process( resultSet ); } } @@ -128,11 +124,11 @@ protected T processImportedKeysResultSet( String catalog, String schema, String table, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getImportedKeys( - catalog, - schema, - table ) ) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getImportedKeys( catalog, schema, table ) ) { return processor.process( resultSet ); } } @@ -145,14 +141,12 @@ protected T processCrossReferenceResultSet( String foreignCatalog, String foreignSchema, String foreignTable, - ExtractionContext.ResultSetProcessor processor) throws SQLException { - try (ResultSet resultSet = getJdbcDatabaseMetaData().getCrossReference( - parentCatalog, - parentSchema, - parentTable, - foreignCatalog, - foreignSchema, - foreignTable) ) { + ExtractionContext.ResultSetProcessor processor) + throws SQLException { + try ( ResultSet resultSet = + getJdbcDatabaseMetaData() + .getCrossReference( parentCatalog, parentSchema, parentTable, + foreignCatalog, foreignSchema, foreignTable) ) { return processor.process( resultSet ); } } @@ -162,12 +156,12 @@ protected void addColumns(TableInformation tableInformation) { final ExtractionContext extractionContext = getExtractionContext(); // We use this dummy query to retrieve the table information through the ResultSetMetaData - // This is significantly better than to use the DatabaseMetaData especially on Oracle with synonyms enabled - final String tableName = extractionContext.getSqlStringGenerationContext().format( - // The name comes from the database, so the case is correct - // But we quote here to avoid issues with reserved words - tableInformation.getName().quote() - ); + // Significantly better than using DatabaseMetaData especially on Oracle with synonyms enabled + final String tableName = + extractionContext.getSqlStringGenerationContext() + // The name comes from the database, so the case is correct + // But we quote here to avoid issues with reserved words + .format( tableInformation.getName().quote() ); try { extractionContext.getQueryResults( @@ -176,38 +170,51 @@ protected void addColumns(TableInformation tableInformation) { resultSet -> { final ResultSetMetaData metaData = resultSet.getMetaData(); final int columnCount = metaData.getColumnCount(); - for ( int i = 1; i <= columnCount; i++ ) { - final String columnName = metaData.getColumnName( i ); - final int columnType = metaData.getColumnType( i ); - final String typeName = new StringTokenizer( metaData.getColumnTypeName( i ), "()" ).nextToken(); - final int scale = metaData.getScale( i ); - final ColumnInformationImpl columnInformation = new ColumnInformationImpl( - tableInformation, - DatabaseIdentifier.toIdentifier( columnName ), - columnType, - typeName, - dialect.resolveSqlTypeLength( - typeName, - columnType, - metaData.getPrecision( i ), - scale, - metaData.getColumnDisplaySize( i ) - ), - scale, - interpretNullable( metaData.isNullable( i ) ) - ); - tableInformation.addColumn( columnInformation ); + tableInformation.addColumn( columnInformation( tableInformation, metaData, i, dialect ) ); } return null; } ); } catch (SQLException e) { - throw convertSQLException( - e, - "Error accessing column metadata: " + tableInformation.getName().toString() - ); + throw convertSQLException( e, + "Error accessing column metadata: " + + tableInformation.getName().toString() ); } } + + private static Boolean interpretNullable(int nullable) { + return switch ( nullable ) { + case ResultSetMetaData.columnNullable -> Boolean.TRUE; + case ResultSetMetaData.columnNoNulls -> Boolean.FALSE; + default -> null; + }; + } + + private static ColumnInformationImpl columnInformation( + TableInformation tableInformation, ResultSetMetaData metaData, int i, Dialect dialect) + throws SQLException { + final String columnName = metaData.getColumnName( i ); + final int columnType = metaData.getColumnType( i ); + final String typeName = + new StringTokenizer( metaData.getColumnTypeName( i ), "()" ) + .nextToken(); + final int scale = metaData.getScale( i ); + return new ColumnInformationImpl( + tableInformation, + DatabaseIdentifier.toIdentifier( columnName ), + columnType, + typeName, + dialect.resolveSqlTypeLength( + typeName, + columnType, + metaData.getPrecision( i ), + scale, + metaData.getColumnDisplaySize( i ) + ), + scale, + interpretNullable( metaData.isNullable( i ) ) + ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/TableInformationImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/TableInformationImpl.java index 4ca77c3c2820..8be137646f5d 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/TableInformationImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/TableInformationImpl.java @@ -35,7 +35,7 @@ public class TableInformationImpl implements TableInformation { private PrimaryKeyInformation primaryKey; private Map foreignKeys; private Map indexes; - private Map columns = new HashMap<>( ); + private final Map columns = new HashMap<>(); private boolean wasPrimaryKeyLoaded = false; // to avoid multiple db reads since primary key can be null. From 1fd237e125337fa428d0a842a000533b10fa8c4c Mon Sep 17 00:00:00 2001 From: Gavin King Date: Thu, 14 Nov 2024 11:51:49 +0100 Subject: [PATCH 6/6] remove dupe method declarations --- .../schema/extract/spi/ColumnInformation.java | 39 ------------------- .../extract/spi/ColumnTypeInformation.java | 6 +-- 2 files changed, 3 insertions(+), 42 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java index 69c5e13b0bd6..e48867bc6958 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnInformation.java @@ -26,43 +26,4 @@ public interface ColumnInformation extends ColumnTypeInformation { * @return The column simple identifier. */ Identifier getColumnIdentifier(); - - /** - * Is the column nullable. - *

- * The database is allowed to report unknown, hence the use of {@link Boolean}. - * - * @return nullability, if known - */ - Boolean getNullable(); - - /** - * The JDBC type-code. - * - * @return JDBC type-code - */ - int getTypeCode(); - - /** - * The database specific type name. - * - * @return Type name - */ - String getTypeName(); - - // todo : wrap these in org.hibernate.metamodel.spi.relational.Size ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - /** - * The column size (length). - * - * @return The column length - */ - int getColumnSize(); - - /** - * The precision, for numeric types - * - * @return The numeric precision - */ - int getDecimalDigits(); } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java index 16f645e9e23a..91944704696f 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/extract/spi/ColumnTypeInformation.java @@ -45,7 +45,7 @@ public int getDecimalDigits() { }; /** - * Is the column nullable. + * Is the column nullable? *

* The database is allowed to report unknown, hence the use of {@link Boolean}. * @@ -65,9 +65,9 @@ public int getDecimalDigits() { * * @return Type name */ - public String getTypeName(); + String getTypeName(); - // todo : wrap these in org.hibernate.metamodel.spi.relational.Size ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // todo : wrap these in org.hibernate.metamodel.spi.relational.Size /** * The column size (length).