some cleanups to AbstractInformationExtractorImpl

This commit is contained in:
Gavin King 2024-11-14 10:35:35 +01:00
parent 26cd62ff6d
commit 12e17ed870
3 changed files with 225 additions and 324 deletions

View File

@ -203,6 +203,7 @@ import jakarta.xml.bind.Marshaller;
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 @@ public class HbmXmlTransformer {
}
}
}
else if ( StringHelper.isNotEmpty( tableName ) ) {
else if ( isNotEmpty( tableName ) ) {
// this is the case of transforming a <join/> 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 class HbmXmlTransformer {
}
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
);
mappingXmlBinding.getRoot().getEmbeddables().add( jaxbEmbeddable );
if ( StringHelper.isNotEmpty( embeddableClassName ) ) {
if ( isNotEmpty( embeddableClassName ) ) {
jaxbEmbeddableByClassName.put( embeddableClassName, jaxbEmbeddable );
}
@ -1668,7 +1669,7 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
}
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
}
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;
}
}
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 @@ public class HbmXmlTransformer {
final ComponentTypeInfo componentTypeInfo = transformationState.getEmbeddableInfoByRole().get( partRole );
target.setTarget( embeddableName );
if ( StringHelper.isNotEmpty( embeddableClassName ) ) {
if ( isNotEmpty( embeddableClassName ) ) {
target.setTargetClass( embeddableClassName );
}
@ -2217,7 +2212,7 @@ public class HbmXmlTransformer {
}
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 class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
PluralAttributeInfo hbmAttributeInfo,
Property bootModelProperty,
Collection bootModelValue) {
if ( StringHelper.isNotEmpty( bootModelValue.getMappedByProperty() ) ) {
if ( isNotEmpty( bootModelValue.getMappedByProperty() ) ) {
return bootModelValue.getMappedByProperty();
}
@ -2369,8 +2364,8 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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 class HbmXmlTransformer {
);
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 class HbmXmlTransformer {
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 @@ public class HbmXmlTransformer {
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;

View File

@ -9,7 +9,6 @@ import java.sql.ResultSet;
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.Objects;
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.JdbcEnvironment;
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.SchemaExtractionException;
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 abstract class AbstractInformationExtractorImpl implements InformationExt
)
);
final List<String> 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 abstract class AbstractInformationExtractorImpl implements InformationExt
final List<String> 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,18 +221,14 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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;
} );
}
@ -313,13 +308,17 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
}
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 abstract class AbstractInformationExtractorImpl implements InformationExt
// 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 abstract class AbstractInformationExtractorImpl implements InformationExt
// 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 abstract class AbstractInformationExtractorImpl implements InformationExt
}
}
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 abstract class AbstractInformationExtractorImpl implements InformationExt
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 abstract class AbstractInformationExtractorImpl implements InformationExt
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 abstract class AbstractInformationExtractorImpl implements InformationExt
"%",
tableTypes,
resultSet -> {
final NameSpaceTablesInformation tablesInformation = extractNameSpaceTablesInformation( resultSet );
final NameSpaceTablesInformation tablesInformation =
extractNameSpaceTablesInformation( resultSet );
populateTablesWithColumns( catalogFilter, schemaFilter, tablesInformation );
return tablesInformation;
} );
@ -665,10 +645,7 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
);
}
catch (SQLException e) {
throw convertSQLException(
e,
"Error accessing tables metadata"
);
throw convertSQLException( e, "Error accessing tables metadata" );
}
}
@ -676,7 +653,7 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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() ) {
String defaultCatalog;
try {
defaultCatalog = extractionContext.getJdbcConnection().getCatalog();
}
catch (SQLException ignore) {
}
defaultCatalog = "";
}
catalogToUse = null;
catalogFilter = defaultCatalog;
@ -780,7 +757,7 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
catalogFilter = null;
}
if ( extractionContext.getJdbcEnvironment().getNameQualifierSupport().supportsSchemas() ) {
if ( nameQualifierSupport.supportsSchemas() ) {
if ( schema == null ) {
schemaToUse = null;
schemaFilter = "";
@ -817,6 +794,10 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
}
private NameQualifierSupport getNameQualifierSupport() {
return getJdbcEnvironment().getNameQualifierSupport();
}
private TableInformation extractTableInformation(
Identifier catalog,
Identifier schema,
@ -825,23 +806,19 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
catch (SQLException e) {
throw convertSQLException(
e,
"Error accessing tables metadata"
);
throw convertSQLException( e, "Error accessing tables metadata" );
}
}
@ -942,34 +911,18 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
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 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
throw new SchemaExtractionException( "Primary Key information was missing for KEY_SEQ = " + ( i+1) );
}
}
// build the return
return new PrimaryKeyInformationImpl( pkIdentifier, pkColumns );
}
@ -1110,54 +1058,34 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
@Override
public Iterable<IndexInformation> getIndexes(TableInformation tableInformation) {
final Map<Identifier, IndexInformationImpl.Builder> 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<Identifier, IndexInformationImpl.Builder> 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() )
);
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 = DatabaseIdentifier.toIdentifier(
resultSet.getString( getResultSetColumnNameLabel() )
);
final ColumnInformation columnInformation = tableInformation.getColumn( columnIdentifier );
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(
@ -1167,16 +1095,17 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
}
builder.addColumn( columnInformation );
}
}
return null;
}
);
}
catch (SQLException e) {
throw convertSQLException(
e,
"Error accessing index information: " + tableInformation.getName().toString()
);
throw convertSQLException( e,
"Error accessing index information: "
+ tableInformation.getName() );
}
final List<IndexInformation> indexes = new ArrayList<>();
@ -1348,74 +1277,22 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
@Override
public Iterable<ForeignKeyInformation> getForeignKeys(TableInformation tableInformation) {
final Map<Identifier, ForeignKeyBuilder> 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<Identifier, ForeignKeyBuilder> fkBuilders = new HashMap<>();
try {
ExtractionContext.ResultSetProcessor<Void> 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 )
);
}
final String table = tableInformation.getName().getTableName().getText();
processImportedKeysResultSet( catalogFilter, schemaFilter, table,
resultSet -> {
process( tableInformation, resultSet, fkBuilders );
return null;
};
processImportedKeysResultSet(
catalogFilter,
schemaFilter,
tableInformation.getName().getTableName().getText(),
processor);
final Dialect dialect = extractionContext.getJdbcEnvironment().getDialect();
} );
final Dialect dialect = getJdbcEnvironment().getDialect();
if ( dialect.useCrossReferenceForeignKeys() ) {
processCrossReferenceResultSet(
null,
@ -1423,16 +1300,18 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
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<ForeignKeyInformation> fks = new ArrayList<>();
@ -1443,6 +1322,37 @@ public abstract class AbstractInformationExtractorImpl implements InformationExt
return fks;
}
private void process(TableInformation tableInformation, ResultSet resultSet, Map<Identifier, ForeignKeyBuilder> 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 abstract class AbstractInformationExtractorImpl implements InformationExt
}
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() ) )
);
}
}

View File

@ -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 class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
super( extractionContext );
}
private DatabaseMetaData getJdbcDatabaseMetaData() {
return getExtractionContext().getJdbcDatabaseMetaData();
}
@Override
protected String getResultSetTableTypesPhysicalTableConstant() {
return "TABLE";
@ -35,7 +40,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
@Override
public <T> T processCatalogsResultSet(ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getCatalogs() ) {
try (ResultSet resultSet = getJdbcDatabaseMetaData().getCatalogs() ) {
return processor.process( resultSet );
}
}
@ -45,7 +50,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String catalog,
String schemaPattern,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getSchemas(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getSchemas(
catalog,
schemaPattern ) ) {
return processor.process( resultSet );
@ -60,7 +65,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String[] types,
ExtractionContext.ResultSetProcessor<T> processor
) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getTables(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getTables(
catalog,
schemaPattern,
tableNamePattern,
@ -76,7 +81,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String tableNamePattern,
String columnNamePattern,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getColumns(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getColumns(
catalog,
schemaPattern,
tableNamePattern,
@ -91,7 +96,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String schemaFilter,
Identifier tableName,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try( ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getPrimaryKeys(
try( ResultSet resultSet = getJdbcDatabaseMetaData().getPrimaryKeys(
catalogFilter,
schemaFilter,
tableName.getText() ) ) {
@ -108,7 +113,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
boolean approximate,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getIndexInfo(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getIndexInfo(
catalog,
schema,
table,
@ -124,7 +129,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String schema,
String table,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getImportedKeys(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getImportedKeys(
catalog,
schema,
table ) ) {
@ -141,7 +146,7 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
String foreignSchema,
String foreignTable,
ExtractionContext.ResultSetProcessor<T> processor) throws SQLException {
try (ResultSet resultSet = getExtractionContext().getJdbcDatabaseMetaData().getCrossReference(
try (ResultSet resultSet = getJdbcDatabaseMetaData().getCrossReference(
parentCatalog,
parentSchema,
parentTable,
@ -153,9 +158,9 @@ public class InformationExtractorJdbcDatabaseMetaDataImpl extends AbstractInform
}
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(