diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ColumnNamesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ColumnNamesTest.java index 7e1a79e1f2a3..5018d1744f8b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ColumnNamesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ColumnNamesTest.java @@ -7,94 +7,96 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; +import java.util.List; + import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.ServiceRegistryFunctionalTesting; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.JdbcMetadataAccessStrategy; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.cfg.MappingSettings.KEYWORD_AUTO_QUOTING_ENABLED; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY; /** * @author Andrea Boriero */ -@RunWith(Parameterized.class) -public class ColumnNamesTest { - @Parameterized.Parameters - public static Collection parameters() { - return Arrays.asList( - new String[] {JdbcMetadataAccessStrategy.GROUPED.toString(), JdbcMetadataAccessStrategy.INDIVIDUALLY.toString()} +@ParameterizedClass +@MethodSource("parameters") +@TestInstance( TestInstance.Lifecycle.PER_METHOD ) +@ServiceRegistryFunctionalTesting +@DomainModel(annotatedClasses = ColumnNamesTest.Employee.class) +public class ColumnNamesTest implements ServiceRegistryProducer { + public static Collection parameters() { + return List.of( + JdbcMetadataAccessStrategy.GROUPED, + JdbcMetadataAccessStrategy.INDIVIDUALLY ); } - @Parameterized.Parameter - public String jdbcMetadataExtractorStrategy; + private final File output; + private final JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy; - private StandardServiceRegistry ssr; - private Metadata metadata; - private File output; + public ColumnNamesTest( + JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy, + @TempDir File outputDir) { + this.jdbcMetadataExtractorStrategy = jdbcMetadataExtractorStrategy; + this.output = new File( outputDir, "update_script.sql" ); + } - @Before - public void setUp() throws IOException { - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, "true" ) - .applySetting( AvailableSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) + @Override + public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { + return ServiceRegistryUtil.serviceRegistryBuilder() + .applySetting( KEYWORD_AUTO_QUOTING_ENABLED, "true" ) + .applySetting( HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) .build(); - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + } - metadata = new MetadataSources( ssr ) - .addAnnotatedClass( Employee.class ) - .buildMetadata(); - new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), metadata ); + @BeforeEach + public void setUp(DomainModelScope modelScope) { + new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } - @After - public void tearDown() { - try { - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + @AfterEach + public void tearDown(DomainModelScope modelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } @Test - public void testSchemaUpdateWithQuotedColumnNames() throws Exception { + public void testSchemaUpdateWithQuotedColumnNames(DomainModelScope modelScope) throws IOException { new SchemaUpdate() .setOutputFile( output.getAbsolutePath() ) - .execute( - EnumSet.of( TargetType.SCRIPT ), - metadata - ); + .execute( EnumSet.of( TargetType.SCRIPT ), modelScope.getDomainModel() ); final String fileContent = new String( Files.readAllBytes( output.toPath() ) ); - assertThat( "The update output file should be empty", fileContent, is( "" ) ); + assertThat( fileContent ).as( "The update output file should be empty" ).isEmpty(); } @Entity @Table(name = "Employee") - public class Employee { + public static class Employee { @Id private long id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/CreateCharDiscriminatorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/CreateCharDiscriminatorTest.java index 13527475747d..fba02127b73b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/CreateCharDiscriminatorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/CreateCharDiscriminatorTest.java @@ -4,13 +4,6 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.Map; - -import org.hibernate.mapping.PersistentClass; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.orm.junit.JiraKey; - import jakarta.persistence.Column; import jakarta.persistence.DiscriminatorColumn; import jakarta.persistence.DiscriminatorValue; @@ -18,32 +11,28 @@ import jakarta.persistence.Id; import jakarta.persistence.Inheritance; import jakarta.persistence.Table; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; import static jakarta.persistence.DiscriminatorType.CHAR; import static jakarta.persistence.InheritanceType.SINGLE_TABLE; import static org.junit.jupiter.api.Assertions.assertEquals; +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey("HHH-16551") -public class CreateCharDiscriminatorTest extends BaseNonConfigCoreFunctionalTestCase { +@ServiceRegistry(settings = @Setting(name="jakarta.persistence.validation.mode", value = "ddl")) +@DomainModel(annotatedClasses = CreateCharDiscriminatorTest.Parent.class) +public class CreateCharDiscriminatorTest { - @org.junit.Test - @JiraKey("HHH-16551") - public void testCreateDiscriminatorCharColumnSize() { - PersistentClass classMapping = metadata().getEntityBinding( Parent.class.getName() ); + @Test + public void testCreateDiscriminatorCharColumnSize(DomainModelScope modelScope) { + final var classMapping = modelScope.getEntityBinding( Parent.class ); final var discriminatorColumn = classMapping.getDiscriminator().getColumns().get( 0 ); - assertEquals( discriminatorColumn.getLength(), 1L ); - } - - @Override - protected void addSettings(Map settings) { - settings.put( "jakarta.persistence.validation.mode", "ddl" ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Parent.class - }; + assertEquals( 1L, discriminatorColumn.getLength() ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ExportIdentifierTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ExportIdentifierTest.java index 25a425492221..72d1ac6eebe7 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ExportIdentifierTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ExportIdentifierTest.java @@ -4,12 +4,6 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.hibernate.boot.internal.BootstrapContextImpl; import org.hibernate.boot.internal.MetadataBuilderImpl; import org.hibernate.boot.model.naming.Identifier; @@ -19,32 +13,39 @@ import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Sequence; import org.hibernate.boot.model.relational.SimpleAuxiliaryDatabaseObject; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.Index; import org.hibernate.mapping.PrimaryKey; import org.hibernate.mapping.Table; import org.hibernate.mapping.UniqueKey; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; -@RequiresDialectFeature(DialectChecks.SupportsSequences.class) -public class ExportIdentifierTest extends BaseUnitTestCase { +@SuppressWarnings("JUnitMalformedDeclaration") +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) +@ServiceRegistry +public class ExportIdentifierTest { @Test @JiraKey( value = "HHH-12935" ) - public void testUniqueExportableIdentifier() { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - final MetadataBuilderImpl.MetadataBuildingOptionsImpl options = new MetadataBuilderImpl.MetadataBuildingOptionsImpl( ssr ); - options.setBootstrapContext( new BootstrapContextImpl( ssr, options ) ); - final Database database = new Database( options ); + public void testUniqueExportableIdentifier(ServiceRegistryScope scope) { + final var registry = scope.getRegistry(); + final var options = new MetadataBuilderImpl.MetadataBuildingOptionsImpl( registry ); + options.setBootstrapContext( new BootstrapContextImpl( registry, options ) ); + + final var database = new Database( options ); database.locateNamespace( null, null ); database.locateNamespace( Identifier.toIdentifier( "catalog1" ), null ); @@ -63,19 +64,14 @@ public void testUniqueExportableIdentifier() { final List exportIdentifierList = new ArrayList<>(); final Set exportIdentifierSet = new HashSet<>(); - try { - addTables( "aTable" , database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); - addSimpleAuxiliaryDatabaseObject( database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); - addNamedAuxiliaryDatabaseObjects( - "aNamedAuxiliaryDatabaseObject", database.getNamespaces(), exportIdentifierList, exportIdentifierSet - ); - addSequences( "aSequence", database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); + addTables( "aTable" , database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); + addSimpleAuxiliaryDatabaseObject( database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); + addNamedAuxiliaryDatabaseObjects( + "aNamedAuxiliaryDatabaseObject", database.getNamespaces(), exportIdentifierList, exportIdentifierSet + ); + addSequences( "aSequence", database.getNamespaces(), exportIdentifierList, exportIdentifierSet ); - assertEquals( exportIdentifierList.size(), exportIdentifierSet.size() ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + assertEquals( exportIdentifierList.size(), exportIdentifierSet.size() ); } private void addTables( @@ -84,7 +80,6 @@ private void addTables( List exportIdentifierList, Set exportIdentifierSet) { for ( Namespace namespace : namespaces ) { - final Table table = new Table( "orm", namespace, Identifier.toIdentifier( name ), false ); addExportIdentifier( table, exportIdentifierList, exportIdentifierSet ); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/H2DialectDataBaseToUpperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/H2DialectDataBaseToUpperTest.java index 094d26e1886c..2ebace128d6c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/H2DialectDataBaseToUpperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/H2DialectDataBaseToUpperTest.java @@ -4,60 +4,39 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; - +import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Test; +import java.util.EnumSet; @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-13597") -public class H2DialectDataBaseToUpperTest extends BaseUnitTestCase { - - private StandardServiceRegistry ssr; - private MetadataImplementor metadata; - - @Test - public void hibernateShouldStartUpWithH2AutoUpdateAndDatabaseToUpperFalse() { - setUp( "false" ); - new SchemaUpdate().setHaltOnError( true ) - .execute( EnumSet.of( TargetType.DATABASE ), metadata ); - } - - @Test - public void hibernateShouldStartUpWithH2AutoUpdateAndDatabaseToUpperTrue() { - setUp( "true" ); - new SchemaUpdate().setHaltOnError( true ) - .execute( EnumSet.of( TargetType.DATABASE ), metadata ); +public class H2DialectDataBaseToUpperTest { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testToUpper(boolean toUpper) { + try (var registry = createServiceRegistry(toUpper)) { + final Metadata metadata = new MetadataSources( registry ).buildMetadata(); + new SchemaUpdate().setHaltOnError( true ).execute( EnumSet.of( TargetType.DATABASE ), metadata ); + } } - private void setUp(String databaseToUpper) { - ssr = ServiceRegistryUtil.serviceRegistryBuilder() + private StandardServiceRegistry createServiceRegistry(boolean toUpper) { + return ServiceRegistryUtil.serviceRegistryBuilder() .applySetting( AvailableSettings.URL, - "jdbc:h2:mem:databaseToUpper;DATABASE_TO_UPPER=" + databaseToUpper + ";DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE" + "jdbc:h2:mem:databaseToUpper;DATABASE_TO_UPPER=" + toUpper + ";DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE" ) .build(); - final MetadataSources metadataSources = new MetadataSources( ssr ); - metadata = (MetadataImplementor) metadataSources.buildMetadata(); - } - - @After - public void tearDown() { - if ( ssr != null ) { - StandardServiceRegistryBuilder.destroy( ssr ); - } } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/Hbm2ddlCreateOnlyTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/Hbm2ddlCreateOnlyTest.java index 4632410f2c23..682284074acd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/Hbm2ddlCreateOnlyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/Hbm2ddlCreateOnlyTest.java @@ -10,7 +10,7 @@ import org.hibernate.testing.orm.jpa.PersistenceUnitDescriptorAdapter; import org.hibernate.testing.orm.junit.JiraKey; import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/IdentifierHelperTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/IdentifierHelperTest.java index 22d7f83f540b..2bd3951f4a39 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/IdentifierHelperTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/IdentifierHelperTest.java @@ -4,49 +4,39 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.Collections; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.service.ServiceRegistry; - -import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.boot.ServiceRegistryTestingImpl; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; +import org.hibernate.testing.orm.junit.BaseUnitTest; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hibernate.cfg.MappingSettings.KEYWORD_AUTO_QUOTING_ENABLED; /** * @author Steve Ebersole */ -@RequiresDialect( H2Dialect.class ) -public class IdentifierHelperTest extends BaseUnitTestCase { - @Test - public void testAutoQuotingDisabled() { - ServiceRegistry sr = ServiceRegistryTestingImpl.forUnitTesting( - Collections.singletonMap( - AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, - // true is the default, but to be sure... - true - ) - ); - Identifier identifier = sr.getService( JdbcEnvironment.class ).getIdentifierHelper().toIdentifier( "select" ); - assertTrue( identifier.isQuoted() ); - StandardServiceRegistryBuilder.destroy( sr ); +@RequiresDialect(H2Dialect.class) +@BaseUnitTest +public class IdentifierHelperTest { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testAutoQuotingDisabled(boolean useQuoting) { + try (var registry = createServiceRegistry( useQuoting )) { + var jdbcEnvironment = registry.requireService( JdbcEnvironment.class ); + var identifier = jdbcEnvironment.getIdentifierHelper().toIdentifier( "select" ); + assertThat( identifier.isQuoted() ).isEqualTo( useQuoting ); + } + } - sr = ServiceRegistryTestingImpl.forUnitTesting( - Collections.singletonMap( - AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, - false - ) + private static ServiceRegistry createServiceRegistry(boolean useQuoting) { + return ServiceRegistryTestingImpl.forUnitTesting( + Collections.singletonMap( KEYWORD_AUTO_QUOTING_ENABLED, useQuoting ) ); - identifier = sr.getService( JdbcEnvironment.class ).getIdentifierHelper().toIdentifier( "select" ); - assertFalse( identifier.isQuoted() ); - StandardServiceRegistryBuilder.destroy( sr ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ImplicitCompositeKeyJoinTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ImplicitCompositeKeyJoinTest.java index c168ac381347..b48d9faa0926 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ImplicitCompositeKeyJoinTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ImplicitCompositeKeyJoinTest.java @@ -4,8 +4,6 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.Serializable; -import java.util.List; import jakarta.persistence.Column; import jakarta.persistence.Embeddable; import jakarta.persistence.EmbeddedId; @@ -14,63 +12,52 @@ import jakarta.persistence.JoinColumns; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.tool.schema.internal.SchemaCreatorImpl; - +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; - +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.tool.schema.internal.SchemaCreatorImpl; import org.jboss.logging.Logger; +import org.junit.jupiter.api.Test; + +import java.io.Serializable; +import java.util.List; import static jakarta.persistence.ConstraintMode.NO_CONSTRAINT; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-9865") +@ServiceRegistry +@DomainModel(annotatedClasses = ImplicitCompositeKeyJoinTest.Employee.class) public class ImplicitCompositeKeyJoinTest { private static final Logger LOGGER = Logger.getLogger( ImplicitCompositeKeyJoinTest.class ); @Test - public void testSchemaCreationSQLCommandIsGeneratedWithTheCorrectColumnSizeValues() throws Exception { - final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - final org.hibernate.boot.Metadata metadata = new MetadataSources( ssr ) - .addAnnotatedClass( Employee.class ) - .buildMetadata(); - - boolean createTableEmployeeFound = false; - - final List commands = new SchemaCreatorImpl( ssr ).generateCreationCommands( - metadata, - false - ); - - for ( String command : commands ) { - LOGGER.info( command ); - if ( command.toLowerCase().matches( "^create( (column|row))? table employee.+" ) ) { - final String[] columnsDefinition = getColumnsDefinition( command ); - - for ( String columnsDefinition1 : columnsDefinition ) { - checkColumnSize( columnsDefinition1 ); - } - createTableEmployeeFound = true; + public void testCorrectColumnSizeValues(ServiceRegistryScope registryScope, DomainModelScope modelScope) { + boolean createTableEmployeeFound = false; + + final List commands = new SchemaCreatorImpl( registryScope.getRegistry() ) + .generateCreationCommands( modelScope.getDomainModel(), false ); + + for ( String command : commands ) { + LOGGER.info( command ); + if ( command.toLowerCase().matches( "^create( (column|row))? table employee.+" ) ) { + final String[] columnsDefinition = getColumnsDefinition( command ); + + for ( String columnsDefinition1 : columnsDefinition ) { + checkColumnSize( columnsDefinition1 ); } + createTableEmployeeFound = true; } - assertTrue( - "Expected create table command for Employee entity not found", - createTableEmployeeFound - ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); } + assertTrue( createTableEmployeeFound, + "Expected create table command for Employee entity not found" ); } private String[] getColumnsDefinition(String command) { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MigrationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MigrationTest.java index 6ace0fc14cf7..102d0fa1ef7c 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MigrationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MigrationTest.java @@ -4,53 +4,36 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; - import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.EnumSet; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Max Rydahl Andersen * @author Brett Meyer */ -public class MigrationTest extends BaseUnitTestCase { - private ServiceRegistry serviceRegistry; - - @Before - public void setUp() { - serviceRegistry = ServiceRegistryUtil.serviceRegistry(); - } - - @After - public void tearDown() { - StandardServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; - } - +@SuppressWarnings("JUnitMalformedDeclaration") +@org.hibernate.testing.orm.junit.ServiceRegistry +public class MigrationTest { @Test - public void testSimpleColumnAddition() { + public void testSimpleColumnAddition(ServiceRegistryScope registryScope) { String resource1 = "org/hibernate/orm/test/schemaupdate/1_Version.hbm.xml"; String resource2 = "org/hibernate/orm/test/schemaupdate/2_Version.hbm.xml"; - MetadataImplementor v1metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + MetadataImplementor v1metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addResource( resource1 ) .buildMetadata(); @@ -68,7 +51,7 @@ public void testSimpleColumnAddition() { assertEquals( 0, v1schemaUpdate.getExceptions().size() ); - MetadataImplementor v2metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + MetadataImplementor v2metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addResource( resource2 ) .buildMetadata(); @@ -89,11 +72,11 @@ public void testSimpleColumnAddition() { } @Test - public void testSimpleColumnTypeChange() { + public void testSimpleColumnTypeChange(ServiceRegistryScope registryScope) { String resource1 = "org/hibernate/orm/test/schemaupdate/1_Version.hbm.xml"; String resource4 = "org/hibernate/orm/test/schemaupdate/4_Version.hbm.xml"; - MetadataImplementor v1metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + MetadataImplementor v1metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addResource( resource1 ) .buildMetadata(); @@ -111,7 +94,7 @@ public void testSimpleColumnTypeChange() { assertEquals( 0, v1schemaUpdate.getExceptions().size() ); - MetadataImplementor v2metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + MetadataImplementor v2metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addResource( resource4 ) .buildMetadata(); @@ -131,59 +114,10 @@ public void testSimpleColumnTypeChange() { } -// /** -// * 3_Version.hbm.xml contains a named unique constraint and an un-named -// * unique constraint (will receive a randomly-generated name). Create -// * the original schema with 2_Version.hbm.xml. Then, run SchemaUpdate -// * TWICE using 3_Version.hbm.xml. Neither RECREATE_QUIETLY nor SKIP should -// * generate any exceptions. -// */ -// @Test -// @JiraKey( value = "HHH-8162" ) -// public void testConstraintUpdate() { -// doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY); -// doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.RECREATE_QUIETLY); -// doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.SKIP); -// } -// -// private void doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy strategy) { -// // original -// String resource1 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml"; -// // adds unique constraint -// String resource2 = "org/hibernate/test/schemaupdate/3_Version.hbm.xml"; -// -// MetadataImplementor v1metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) -// .addResource( resource1 ) -// .buildMetadata(); -// MetadataImplementor v2metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) -// .addResource( resource2 ) -// .buildMetadata(); -// -// new SchemaExport( v1metadata ).execute( false, true, true, false ); -// -// // adds unique constraint -// Configuration v2cfg = new Configuration(); -// v2cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy ); -// v2cfg.addResource( resource2 ); -// SchemaUpdate v2schemaUpdate = new SchemaUpdate( serviceRegistry, v2cfg ); -// v2schemaUpdate.execute( true, true ); -// assertEquals( 0, v2schemaUpdate.getExceptions().size() ); -// -// Configuration v3cfg = new Configuration(); -// v3cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy ); -// v3cfg.addResource( resource2 ); -// SchemaUpdate v3schemaUpdate = new SchemaUpdate( serviceRegistry, v3cfg ); -// v3schemaUpdate.execute( true, true ); -// assertEquals( 0, v3schemaUpdate.getExceptions().size() ); -// -// new SchemaExport( serviceRegistry, v3cfg ).drop( false, true ); -// } - - @Test @JiraKey( value = "HHH-9713" ) - public void testIndexCreationViaSchemaUpdate() { - MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + public void testIndexCreationViaSchemaUpdate(ServiceRegistryScope registryScope) { + MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClass( EntityWithIndex.class ) .buildMetadata(); @@ -210,8 +144,8 @@ public static class EntityWithIndex { @Test @JiraKey( value = "HHH-9550" ) - public void testSameTableNameDifferentExplicitSchemas() { - MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + public void testSameTableNameDifferentExplicitSchemas(ServiceRegistryScope registryScope) { + MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addAnnotatedClass( CustomerInfo.class ) .addAnnotatedClass( PersonInfo.class ) .buildMetadata(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MixedFieldPropertyAnnotationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MixedFieldPropertyAnnotationTest.java index b87c6cda19a1..3e5759678c7b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MixedFieldPropertyAnnotationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/MixedFieldPropertyAnnotationTest.java @@ -4,43 +4,39 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.Environment; import org.hibernate.dialect.MySQLDialect; import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.CustomRunner; -import org.hibernate.testing.util.ServiceRegistryUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; + +import java.util.EnumSet; /** * @author Andrea Boriero */ @JiraKey(value = "HHH-9849") -@RunWith(CustomRunner.class) @RequiresDialect(MySQLDialect.class) public class MixedFieldPropertyAnnotationTest { protected ServiceRegistry serviceRegistry; protected MetadataImplementor metadata; @Test - public void testUpdateSchema() throws Exception { + public void testUpdateSchema() { new SchemaUpdate().execute( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java index 087a262434b5..434cf2655234 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/PostgreSQLMultipleSchemaSequenceTest.java @@ -4,167 +4,165 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.EnumSet; -import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; - import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.tool.schema.TargetType; - -import org.hibernate.testing.RequiresDialect; +import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; import org.hibernate.testing.util.ServiceRegistryUtil; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.orm.test.util.DdlTransactionIsolatorTestingImpl; -import org.junit.Before; -import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.EnumSet; +import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.hibernate.cfg.JdbcSettings.URL; /** * @author Vlad Mihalcea */ @RequiresDialect(PostgreSQLDialect.class) -@RequiresDialectFeature(DialectChecks.SupportSchemaCreation.class) -public class PostgreSQLMultipleSchemaSequenceTest extends BaseUnitTestCase { - - private File output; - - @Before - public void setUp() throws IOException { - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - } +@RequiresDialectFeature(feature = DialectFeatureChecks.SupportSchemaCreation.class) +public class PostgreSQLMultipleSchemaSequenceTest { + private static final String extraSchemaName = "extra_schema_sequence_validation"; @Test - @JiraKey( value = "HHH-5538" ) - public void test() { - StandardServiceRegistry ssr1 = ServiceRegistryUtil.serviceRegistry(); - - final String extraSchemaName = "extra_schema_sequence_validation"; - - try { - final MetadataImplementor metadata1 = (MetadataImplementor) new MetadataSources( ssr1 ) + @JiraKey("HHH-5538") + public void test(@TempDir File tempDir) throws IOException { + final File output = new File( tempDir, "update_script.sql" ); + + // roughly: + // 1) Using "main" connection provider - + // a) Export (drop & create) the model to both the database and script file + // b) Create a schema named $extraSchemaName + // c) Verify the initial value of the SEQ_TEST sequence + // 2) Using a separate connection connecting to the $extraSchemaName schema - + // a) Export (drop & create) the model to both the database and script file + // b) Verify the initial value of + // the SEQ_TEST sequence + // c) Verify we had 2 "create sequence" commands + // + // ¯_(ツ)_/¯ + + // 1 + try (var registry1 = primaryServiceRegistry()) { + final var metadata1 = new MetadataSources( registry1 ) .addAnnotatedClass( Box.class ) .buildMetadata(); try { + // 1.a new SchemaExport() .setOutputFile( output.getAbsolutePath() ) .create( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata1 ); - final ConnectionProvider connectionProvider1 = ssr1.getService( ConnectionProvider.class ); + // 1.b + final ConnectionProvider connectionProvider1 = registry1.requireService( ConnectionProvider.class ); DdlTransactionIsolatorTestingImpl ddlTransactionIsolator1 = new DdlTransactionIsolatorTestingImpl( - ssr1, + registry1, new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess( connectionProvider1 ) ); try(Statement statement = ddlTransactionIsolator1.getIsolatedConnection().createStatement()) { statement.execute( String.format( "DROP SCHEMA IF EXISTS %s CASCADE", extraSchemaName ) ); statement.execute( String.format( "CREATE SCHEMA %s;", extraSchemaName ) ); + // 1.c try(ResultSet resultSet = statement.executeQuery( "SELECT NEXTVAL('SEQ_TEST')" )) { while ( resultSet.next() ) { Long sequenceValue = resultSet.getLong( 1 ); - assertEquals( Long.valueOf( 1L ), sequenceValue ); + Assertions.assertEquals( Long.valueOf( 1L ), sequenceValue ); } } } catch (SQLException e) { - fail(e.getMessage()); - } - - String existingUrl = (String) Environment.getProperties().get( AvailableSettings.URL ); - if ( existingUrl.indexOf( '?' ) == -1 ) { - existingUrl += "?"; - } - else { - existingUrl += "&"; + Assertions.fail( e.getMessage() ); } - StandardServiceRegistry ssr2 = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.URL, existingUrl + "currentSchema=" + extraSchemaName ) - .build(); - try { + // 2 + try (var ssr2 = secondaryServiceRegistry()) { final MetadataImplementor metadata2 = (MetadataImplementor) new MetadataSources( ssr2 ) .addAnnotatedClass( Box.class ) .buildMetadata(); try { + // 2.a new SchemaExport() .setOutputFile( output.getAbsolutePath() ) .create( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata2 ); - } - finally { - final ConnectionProvider connectionProvider2 = ssr2.getService( ConnectionProvider.class ); - DdlTransactionIsolatorTestingImpl ddlTransactionIsolator2 = new DdlTransactionIsolatorTestingImpl( + + var connectionProvider2 = ssr2.requireService( ConnectionProvider.class ); + var ddlTransactionIsolator2 = new DdlTransactionIsolatorTestingImpl( ssr2, new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess( connectionProvider2 ) ); - try(Statement statement = ddlTransactionIsolator2.getIsolatedConnection().createStatement()) { - try(ResultSet resultSet = statement.executeQuery( "SELECT NEXTVAL('SEQ_TEST')" )) { + try(var statement = ddlTransactionIsolator2.getIsolatedConnection().createStatement()) { + try(var resultSet = statement.executeQuery( "SELECT NEXTVAL('SEQ_TEST')" )) { while ( resultSet.next() ) { - Long sequenceValue = resultSet.getLong( 1 ); - assertEquals( Long.valueOf( 1L ), sequenceValue ); + var sequenceValue = resultSet.getLong( 1 ); + Assertions.assertEquals( Long.valueOf( 1L ), sequenceValue ); } } statement.execute( String.format( "DROP SCHEMA IF EXISTS %s CASCADE", extraSchemaName ) ); } catch (SQLException e) { - fail(e.getMessage()); + Assertions.fail( e.getMessage() ); } - + } + finally { new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata2 ); } } - finally { - StandardServiceRegistryBuilder.destroy( ssr2 ); - } - } finally { - // clean up new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata1 ); } final List sqlLines = Files.readAllLines( output.toPath(), Charset.defaultCharset() ); - assertEquals( 2 , - sqlLines - .stream() - .filter( s -> s.equalsIgnoreCase( "create sequence SEQ_TEST start with 1 increment by 1;" ) ) - .count() - ); + Assertions.assertEquals( 2, sqlLines + .stream() + .filter( s -> s.equalsIgnoreCase( "create sequence SEQ_TEST start with 1 increment by 1;" ) ) + .count() ); } - catch (IOException e) { - fail(e.getMessage()); + } + + private ServiceRegistry primaryServiceRegistry() { + return ServiceRegistryUtil.serviceRegistry(); + } + + private ServiceRegistry secondaryServiceRegistry() { + String existingUrl = (String) Environment.getProperties().get( URL ); + if ( existingUrl.indexOf( '?' ) == -1 ) { + existingUrl += "?"; } - finally { - StandardServiceRegistryBuilder.destroy( ssr1 ); + else { + existingUrl += "&"; } + return ServiceRegistryUtil.serviceRegistryBuilder() + .applySetting( URL, existingUrl + "currentSchema=" + extraSchemaName ) + .build(); } @Entity(name = "Box") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameSchemaUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameSchemaUpdateTest.java index f07f46a72fe2..0d8629be7536 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameSchemaUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameSchemaUpdateTest.java @@ -4,68 +4,51 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.Skip; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.io.File; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.SchemaToolingSettings.JAKARTA_HBM2DDL_CREATE_SCHEMAS; /** * @author Andrea Boriero */ - -public class QuotedTableNameSchemaUpdateTest extends BaseUnitTestCase { - - private File output; - private StandardServiceRegistry ssr; - - @Before - public void setUp() throws IOException { - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.HBM2DDL_CREATE_SCHEMAS, "true" ) - .build(); - } - - @After - public void tearsDown() { - StandardServiceRegistryBuilder.destroy( ssr ); - } - +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry(settings = @Setting(name = JAKARTA_HBM2DDL_CREATE_SCHEMAS, value = "true")) +public class QuotedTableNameSchemaUpdateTest { @Test @JiraKey(value = "HHH-10820") - @Skip(condition = Skip.OperatingSystem.Windows.class, message = "On Windows, MySQL is case insensitive!") - public void testSchemaUpdateWithQuotedTableName() throws Exception { - final MetadataSources metadataSources = new MetadataSources( ssr ); - metadataSources.addAnnotatedClass( QuotedTable.class ); - - MetadataImplementor metadata = (MetadataImplementor) metadataSources.buildMetadata(); + @DisabledOnOs(value = OS.WINDOWS, disabledReason = "On Windows, MySQL is case insensitive!") + public void testSchemaUpdateWithQuotedTableName( + ServiceRegistryScope registryScope, + @TempDir File tempDir) throws Exception { + var output = new File( tempDir, "update_script.sql" ); + + var metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) + .addAnnotatedClass( QuotedTable.class ) + .buildMetadata(); metadata.orderColumns( false ); metadata.validate(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameWithForeignKeysSchemaUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameWithForeignKeysSchemaUpdateTest.java index d935288be7a8..569fc6d629ac 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameWithForeignKeysSchemaUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/QuotedTableNameWithForeignKeysSchemaUpdateTest.java @@ -4,87 +4,49 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.spi.MetadataImplementor; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.EnumSet; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-10197") -public class QuotedTableNameWithForeignKeysSchemaUpdateTest extends BaseUnitTestCase { - - @Before - public void setUp() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addResource( "org/hibernate/orm/test/schemaupdate/UserGroup.hbm.xml" ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } +@ServiceRegistry +@DomainModel(xmlMappings = "org/hibernate/orm/test/schemaupdate/UserGroup.hbm.xml") +public class QuotedTableNameWithForeignKeysSchemaUpdateTest { + + @BeforeEach + public void setUp(DomainModelScope modelScope) { + final MetadataImplementor domainModel = modelScope.getDomainModel(); + domainModel.orderColumns( false ); + domainModel.validate(); + new SchemaExport().create( EnumSet.of( TargetType.DATABASE ), domainModel ); } - @Test - public void testUpdateExistingSchema() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addResource( "org/hibernate/orm/test/schemaupdate/UserGroup.hbm.xml" ) - .buildMetadata(); - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + @AfterEach + public void tearDown(DomainModelScope modelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), modelScope.getDomainModel() ); } @Test - public void testGeneratingUpdateScript() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addResource( "org/hibernate/orm/test/schemaupdate/UserGroup.hbm.xml" ) - .buildMetadata(); - new SchemaUpdate().execute( EnumSet.of( TargetType.STDOUT ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + public void testUpdateExistingSchema(DomainModelScope modelScope) { + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } - @After - public void tearDown() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); - try { - - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addResource( "org/hibernate/orm/test/schemaupdate/UserGroup.hbm.xml" ) - .buildMetadata(); - new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); - - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + @Test + public void testGeneratingUpdateScript(DomainModelScope modelScope) { + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaDropTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaDropTest.java index 5dbbde37bdbf..a2542d57726f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaDropTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaDropTest.java @@ -8,15 +8,14 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import java.util.EnumSet; -import java.util.Map; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.HSQLDialect; import org.hibernate.engine.config.spi.ConfigurationService; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.hibernate.tool.schema.SourceType; import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.spi.CommandAcceptanceException; @@ -29,46 +28,60 @@ import org.hibernate.tool.schema.spi.ScriptTargetOutput; import org.hibernate.tool.schema.spi.SourceDescriptor; import org.hibernate.tool.schema.spi.TargetDescriptor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; +import java.util.EnumSet; +import java.util.Map; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-10605") @RequiresDialect(value = HSQLDialect.class) -public class SchemaDropTest extends BaseUnitTestCase implements ExecutionOptions, ExceptionHandler { - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - - @Before - public void setUp() { - serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( MyEntity.class ).buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); +@ServiceRegistry +@DomainModel(annotatedClasses = SchemaDropTest.MyEntity.class) +public class SchemaDropTest implements ExceptionHandler { + @BeforeEach + public void setUp(DomainModelScope modelScope) throws Exception { + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); } @Test - public void testDropSequence() { - getSchemaDropper().doDrop( - metadata, - this, + public void testDropSequence(ServiceRegistryScope registryScope, DomainModelScope modelScope) { + getSchemaDropper( registryScope ).doDrop( + modelScope.getDomainModel(), + options( registryScope ), ContributableMatcher.ALL, getSourceDescriptor(), getTargetDescriptor() ); } - private SchemaDropper getSchemaDropper() { - return serviceRegistry.getService( SchemaManagementTool.class ).getSchemaDropper( null ); + private SchemaDropper getSchemaDropper(ServiceRegistryScope registryScope) { + return registryScope.getRegistry().requireService( SchemaManagementTool.class ).getSchemaDropper( null ); + } + + private ExecutionOptions options(ServiceRegistryScope registryScope) { + return new ExecutionOptions() { + @Override + public Map getConfigurationValues() { + return registryScope.getRegistry().requireService( ConfigurationService.class ).getSettings(); + } + + @Override + public boolean shouldManageNamespaces() { + return false; + } + + @Override + public ExceptionHandler getExceptionHandler() { + return SchemaDropTest.this; + } + }; } private TargetDescriptor getTargetDescriptor() { @@ -99,21 +112,6 @@ public ScriptSourceInput getScriptSourceInput() { }; } - @Override - public Map getConfigurationValues() { - return serviceRegistry.getService( ConfigurationService.class ).getSettings(); - } - - @Override - public boolean shouldManageNamespaces() { - return false; - } - - @Override - public ExceptionHandler getExceptionHandler() { - return this; - } - @Override public void handleException(CommandAcceptanceException exception) { throw exception; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java index 76786dfe5b89..99d35bc875c2 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportTest.java @@ -4,87 +4,84 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import org.hamcrest.MatcherAssert; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; -import org.hibernate.dialect.Dialect; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.hibernate.testing.orm.junit.DialectFeatureChecks; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialectFeature; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.ServiceRegistryBuilder; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Gail Badner */ -public class SchemaExportTest extends BaseUnitTestCase { - private boolean doesDialectSupportDropTableIfExist() { - final Dialect dialect = metadata.getDatabase().getDialect(); +@SuppressWarnings("JUnitMalformedDeclaration") +@org.hibernate.testing.orm.junit.ServiceRegistry +@DomainModel(xmlMappings = "org/hibernate/orm/test/schemaupdate/mapping.hbm.xml") +public class SchemaExportTest { + private boolean doesDialectSupportDropTableIfExist(ServiceRegistryScope registryScope) { + var dialect = registryScope.getRegistry().requireService( JdbcEnvironment.class ).getDialect(); return dialect.supportsIfExistsAfterTableName() || dialect.supportsIfExistsBeforeTableName(); } - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - - @Before - public void setUp() { - serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addResource( "org/hibernate/orm/test/schemaupdate/mapping.hbm.xml" ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + @BeforeEach + public void setUp(DomainModelScope modelScope) throws Exception { + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), model ); } - @After - public void tearDown() { - ServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; + @AfterEach + public void tearDown(DomainModelScope modelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } @Test - public void testCreateAndDropOnlyType() { - final SchemaExport schemaExport = new SchemaExport(); + public void testCreateAndDropOnlyType(DomainModelScope modelScope) { + final var schemaExport = new SchemaExport(); + final var model = modelScope.getDomainModel(); // create w/o dropping first; (OK because tables don't exist yet - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, metadata ); + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, model ); assertEquals( 0, schemaExport.getExceptions().size() ); // create w/o dropping again; should cause an exception because the tables exist already - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, metadata ); + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.CREATE, model ); assertEquals( 1, schemaExport.getExceptions().size() ); // drop tables only - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, model ); assertEquals( 0, schemaExport.getExceptions().size() ); } @Test - public void testBothType() { - final SchemaExport schemaExport = new SchemaExport(); + public void testBothType(ServiceRegistryScope registryScope, DomainModelScope modelScope) { + final var schemaExport = new SchemaExport(); + final var model = modelScope.getDomainModel(); // drop before create (nothing to drop yeT) - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); - if ( doesDialectSupportDropTableIfExist() ) { + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, model ); + if ( doesDialectSupportDropTableIfExist( registryScope ) ) { assertEquals( 0, schemaExport.getExceptions().size() ); } else { @@ -92,45 +89,48 @@ public void testBothType() { } // drop before create again (this time drops the tables before re-creating) - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.BOTH, metadata ); + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.BOTH, model ); int exceptionCount = schemaExport.getExceptions().size(); - if ( doesDialectSupportDropTableIfExist() ) { - assertEquals( 0, exceptionCount); + if ( doesDialectSupportDropTableIfExist( registryScope ) ) { + assertEquals( 0, exceptionCount ); } // drop tables - schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, metadata ); + schemaExport.execute( EnumSet.of( TargetType.DATABASE ), SchemaExport.Action.DROP, model ); assertEquals( 0, schemaExport.getExceptions().size() ); } @Test - public void testCreateAndDrop() { - final SchemaExport schemaExport = new SchemaExport(); + public void testCreateAndDrop(ServiceRegistryScope registryScope, DomainModelScope modelScope) { + final var schemaExport = new SchemaExport(); + final var model = modelScope.getDomainModel(); // should drop before creating, but tables don't exist yet - schemaExport.create( EnumSet.of( TargetType.DATABASE ), metadata ); - if ( doesDialectSupportDropTableIfExist() ) { + schemaExport.create( EnumSet.of( TargetType.DATABASE ), model ); + if ( doesDialectSupportDropTableIfExist( registryScope ) ) { assertEquals( 0, schemaExport.getExceptions().size() ); } else { assertEquals( 1, schemaExport.getExceptions().size() ); } // call create again; it should drop tables before re-creating - schemaExport.create( EnumSet.of( TargetType.DATABASE ), metadata ); + schemaExport.create( EnumSet.of( TargetType.DATABASE ), model ); assertEquals( 0, schemaExport.getExceptions().size() ); + // drop the tables - schemaExport.drop( EnumSet.of( TargetType.DATABASE ), metadata ); + schemaExport.drop( EnumSet.of( TargetType.DATABASE ), model ); assertEquals( 0, schemaExport.getExceptions().size() ); } @Test @JiraKey(value = "HHH-10678") - @RequiresDialectFeature( value = DialectChecks.SupportSchemaCreation.class) - public void testHibernateMappingSchemaPropertyIsNotIgnored() throws Exception { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + @RequiresDialectFeature(feature = DialectFeatureChecks.SupportSchemaCreation.class) + public void testHibernateMappingSchemaPropertyIsNotIgnored( + ServiceRegistryScope registryScope, + @TempDir File tempDir) throws Exception { + var output = new File( tempDir, "update_script.sql" ); - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) + final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( registryScope.getRegistry() ) .addResource( "org/hibernate/orm/test/schemaupdate/mapping2.hbm.xml" ) .buildMetadata(); metadata.orderColumns( false ); @@ -143,6 +143,6 @@ public void testHibernateMappingSchemaPropertyIsNotIgnored() throws Exception { String fileContent = new String( Files.readAllBytes( output.toPath() ) ); Pattern fileContentPattern = Pattern.compile( "create( (column|row))? table schema1.version" ); Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); - assertThat( fileContent, fileContentMatcher.find(), is( true ) ); + MatcherAssert.assertThat( fileContent, fileContentMatcher.find(), is( true ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithGlobalQuotingEnabledTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithGlobalQuotingEnabledTest.java index ff6d7031b801..679de592527a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithGlobalQuotingEnabledTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithGlobalQuotingEnabledTest.java @@ -4,80 +4,64 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.sql.SQLException; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.MySQLDialect; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.CustomRunner; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.sql.SQLException; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.MappingSettings.GLOBALLY_QUOTED_IDENTIFIERS; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-9866") -@RunWith(CustomRunner.class) @RequiresDialect(MySQLDialect.class) +@org.hibernate.testing.orm.junit.ServiceRegistry(settings = @Setting(name = GLOBALLY_QUOTED_IDENTIFIERS, value = "true")) +@DomainModel(annotatedClasses = {SchemaExportWithGlobalQuotingEnabledTest.MyEntity.class, SchemaExportWithGlobalQuotingEnabledTest.Role.class}) public class SchemaExportWithGlobalQuotingEnabledTest { - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - @Test - public void testSchemaExport() throws Exception { + public void testSchemaExport(DomainModelScope modelScope) { SchemaExport schemaExport = new SchemaExport(); - schemaExport.create( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); + schemaExport.create( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), modelScope.getDomainModel() ); + //noinspection unchecked List exceptions = schemaExport.getExceptions(); for ( SQLException exception : exceptions ) { assertThat( exception.getMessage(), exception.getSQLState(), not( "42000" ) ); } } - @Before - public void setUp() { - serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.GLOBALLY_QUOTED_IDENTIFIERS, "true" ) - .build(); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( MyEntity.class ) - .addAnnotatedClass( Role.class ) - .buildMetadata(); - + @BeforeEach + public void setUp(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport for START-UP *************************" ); - new SchemaExport().create( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); + new SchemaExport().create( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport for START-UP *************************" ); } - @After - public void tearDown() { + @AfterEach + public void tearDown(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport (drop) for TEAR-DOWN *************************" ); - new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); + new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport (drop) for TEAR-DOWN *************************" ); - - StandardServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchema.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchemaTests.java similarity index 53% rename from hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchema.java rename to hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchemaTests.java index 7689ed995e90..d0eba75ab0b9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchema.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaExportWithIndexAndDefaultSchemaTests.java @@ -4,74 +4,62 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; +import org.hamcrest.MatcherAssert; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.CustomRunner; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.EnumSet; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.MappingSettings.DEFAULT_SCHEMA; +import static org.hibernate.cfg.MappingSettings.GLOBALLY_QUOTED_IDENTIFIERS; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-9866") -@RunWith(CustomRunner.class) @RequiresDialect(PostgreSQLDialect.class) -public class SchemaExportWithIndexAndDefaultSchema { - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - +@ServiceRegistry(settings = { + @Setting(name = GLOBALLY_QUOTED_IDENTIFIERS, value = "true"), + @Setting(name = DEFAULT_SCHEMA, value = "public") +}) +@DomainModel(annotatedClasses = SchemaExportWithIndexAndDefaultSchemaTests.MyEntity.class) +public class SchemaExportWithIndexAndDefaultSchemaTests { @Test - public void shouldCreateIndex() { + public void shouldCreateIndex(DomainModelScope modelScope) { SchemaExport schemaExport = new SchemaExport(); - schemaExport.create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); - assertThat( schemaExport.getExceptions().size(), is( 0 ) ); + schemaExport.create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); + MatcherAssert.assertThat( schemaExport.getExceptions().size(), is( 0 ) ); } - @Before - public void setUp() { - serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.GLOBALLY_QUOTED_IDENTIFIERS, "true" ) - .applySetting( Environment.DEFAULT_SCHEMA, "public" ) - .build(); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( MyEntity.class ) - .buildMetadata(); - + @BeforeEach + public void setUp(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport for START-UP *************************" ); - new SchemaExport().create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaExport().create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport for START-UP *************************" ); } - @After - public void tearDown() { + @AfterEach + public void tearDown(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport (drop) for TEAR-DOWN *************************" ); - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport (drop) for TEAR-DOWN *************************" ); - - StandardServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigrationTargetScriptCreationTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigrationTargetScriptCreationTest.java index 30f0faa91623..a644aa563ec1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigrationTargetScriptCreationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigrationTargetScriptCreationTest.java @@ -8,89 +8,68 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; import java.io.File; -import java.io.IOException; import java.nio.file.Files; import java.util.EnumSet; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.service.ServiceRegistry; +import org.hamcrest.MatcherAssert; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.ServiceRegistryFunctionalTesting; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; -import org.junit.After; -import org.junit.Test; - -import org.hibernate.testing.ServiceRegistryBuilder; import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hibernate.cfg.SchemaToolingSettings.JAKARTA_HBM2DDL_DATABASE_ACTION; +import static org.hibernate.cfg.SchemaToolingSettings.JAKARTA_HBM2DDL_SCRIPTS_ACTION; +import static org.hibernate.cfg.SchemaToolingSettings.JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET; /** * @author Andrea Boriero */ -public class SchemaMigrationTargetScriptCreationTest extends BaseCoreFunctionalTestCase { - private File output; +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistryFunctionalTesting +@DomainModel(annotatedClasses = SchemaMigrationTargetScriptCreationTest.TestEntity.class) +@SessionFactory(exportSchema = false) +public class SchemaMigrationTargetScriptCreationTest implements ServiceRegistryProducer { + private final File output; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {TestEntity.class}; - } - - @Override - protected boolean createSchema() { - return false; + public SchemaMigrationTargetScriptCreationTest(@TempDir File outputDir) { + this.output = new File( outputDir, "update_script.sql" ); } @Override - protected void configure(Configuration configuration) { - try { - output = File.createTempFile( "update_script", ".sql" ); - } - catch (IOException e) { - fail( e.getMessage() ); - } - output.deleteOnExit(); - configuration.setProperty( Environment.JAKARTA_HBM2DDL_DATABASE_ACTION, "update" ); - configuration.setProperty( Environment.JAKARTA_HBM2DDL_SCRIPTS_ACTION, "update" ); - configuration.setProperty( Environment.JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, output.getAbsolutePath() ); + public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { + return builder.applySetting( JAKARTA_HBM2DDL_DATABASE_ACTION, "update" ) + .applySetting( JAKARTA_HBM2DDL_SCRIPTS_ACTION, "update" ) + .applySetting( JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, output.getAbsolutePath() ) + .build(); } - @After - public void tearDown() { - ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); - try { - MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( TestEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); - } - finally { - ServiceRegistryBuilder.destroy( serviceRegistry ); - } + @AfterEach + public void tearDown(DomainModelScope modelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } @Test @JiraKey(value = "HHH-10684") - public void testTargetScriptIsCreated() throws Exception { + public void testTargetScriptIsCreated(SessionFactoryScope factoryScope) throws Exception { + factoryScope.getSessionFactory(); String fileContent = new String( Files.readAllBytes( output.toPath() ) ); Pattern fileContentPattern = Pattern.compile( "create( (column|row))? table test_entity" ); Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); - assertThat( - "Script file : " + fileContent.toLowerCase(), - fileContentMatcher.find(), - is( true ) - ); + MatcherAssert.assertThat( "Script file : " + fileContent.toLowerCase(), fileContentMatcher.find(), is( true ) ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigratorHaltOnErrorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigratorHaltOnErrorTest.java index fbb1a9449a6e..b1046ec5f8d3 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigratorHaltOnErrorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaMigratorHaltOnErrorTest.java @@ -4,68 +4,63 @@ */ package org.hibernate.orm.test.schemaupdate; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_HALT_ON_ERROR; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.community.dialect.AltibaseDialect; import org.hibernate.community.dialect.FirebirdDialect; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.DB2Dialect; import org.hibernate.community.dialect.DerbyDialect; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.tool.schema.spi.SchemaManagementException; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @author Vlad Mihalcea */ -@SkipForDialect(value = DB2Dialect.class, comment = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.") -@SkipForDialect(value = DerbyDialect.class, comment = "Derby is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = FirebirdDialect.class, comment = "FirebirdDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = AltibaseDialect.class, comment = "AltibaseDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = InformixDialect.class, comment = "Informix is far more resistant to the reserved keyword usage.") -public class SchemaMigratorHaltOnErrorTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - From.class - }; - } - - @Override - protected Map buildSettings() { - Map settings = super.buildSettings(); - settings.put( AvailableSettings.HBM2DDL_AUTO, "update" ); - settings.put( AvailableSettings.HBM2DDL_HALT_ON_ERROR, true ); - return settings; - } - - @Override - public void buildEntityManagerFactory() { +@SuppressWarnings("JUnitMalformedDeclaration") +@SkipForDialect(dialectClass = DB2Dialect.class, + matchSubTypes = true, + reason = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.") +@SkipForDialect(dialectClass = DerbyDialect.class, + reason = "Derby is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = FirebirdDialect.class, + reason = "FirebirdDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = AltibaseDialect.class, + reason = "AltibaseDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = InformixDialect.class, + reason = "Informix is far more resistant to the reserved keyword usage.") +@Jpa( + annotatedClasses = SchemaMigratorHaltOnErrorTest.From.class, + integrationSettings = { + @Setting(name = HBM2DDL_AUTO, value = "update"), + @Setting(name = HBM2DDL_HALT_ON_ERROR, value = "true") + } +) +public class SchemaMigratorHaltOnErrorTest { + @Test + void testHaltOnError(EntityManagerFactoryScope factoryScope) { try { - super.buildEntityManagerFactory(); - fail("Should halt on error!"); + factoryScope.getEntityManagerFactory(); + Assertions.fail( "Expecting this to fail" ); } - catch ( Exception e ) { + catch (Exception e) { SchemaManagementException cause = (SchemaManagementException) e.getCause(); - assertTrue( cause.getMessage().startsWith( "Halting on error : Error executing DDL" ) ); + Assertions.assertTrue( cause.getMessage().startsWith( "Halting on error : Error executing DDL" ) ); } } - @Test - public void testHaltOnError() { - } - @Entity(name = "From") - public class From { + public static class From { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateDelimiterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateDelimiterTest.java index b8d2f7ca24c0..7fef20904732 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateDelimiterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateDelimiterTest.java @@ -4,71 +4,59 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; +import org.hamcrest.MatcherAssert; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.EnumSet; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-1122") +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = SchemaUpdateDelimiterTest.TestEntity.class) public class SchemaUpdateDelimiterTest { - public static final String EXPECTED_DELIMITER = ";"; @Test - public void testSchemaUpdateApplyDelimiterToGeneratedSQL() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + public void testSchemaUpdateApplyDelimiterToGeneratedSQL( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( TestEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( EXPECTED_DELIMITER ) - .setFormat( false ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( EXPECTED_DELIMITER ) + .setFormat( false ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); - List sqlLines = Files.readAllLines( output.toPath(), Charset.defaultCharset() ); - for ( String line : sqlLines ) { - assertThat( - "The expected delimiter is not applied " + line, - line.endsWith( EXPECTED_DELIMITER ), - is( true ) - ); - } - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); + var sqlLines = Files.readAllLines( output.toPath(), Charset.defaultCharset() ); + for ( var line : sqlLines ) { + MatcherAssert.assertThat( "The expected delimiter is not applied " + line, + line.endsWith( EXPECTED_DELIMITER ), is( true ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateFormatterTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateFormatterTest.java index 6ecaf45f6d41..b139c0099e8a 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateFormatterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateFormatterTest.java @@ -4,36 +4,37 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.regex.Pattern; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Assert; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.regex.Pattern; + +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; /** * @author Koen Aers */ @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-10158") -public class SchemaUpdateFormatterTest extends BaseUnitTestCase { +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = SchemaUpdateFormatterTest.TestEntity.class) +public class SchemaUpdateFormatterTest { private static final String AFTER_FORMAT = "\n\\s+create table test_entity \\(\n" + @@ -43,38 +44,29 @@ public class SchemaUpdateFormatterTest extends BaseUnitTestCase { private static final String DELIMITER = ";"; @Test - public void testSetFormat() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + public void testSetFormat( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( TestEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( DELIMITER ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( DELIMITER ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); - String outputContent = new String(Files.readAllBytes(output.toPath())); - //Old Macs use \r as a new line delimiter - outputContent = outputContent.replaceAll( "\r", "\n"); - //On Windows, \r\n would become \n\n, so we eliminate duplicates - outputContent = outputContent.replaceAll( "\n\n", "\n"); + String outputContent = new String(Files.readAllBytes(output.toPath())); + //Old Macs use \r as a new line delimiter + outputContent = outputContent.replaceAll( "\r", "\n"); + //On Windows, \r\n would become \n\n, so we eliminate duplicates + outputContent = outputContent.replaceAll( "\n\n", "\n"); - Assert.assertTrue( Pattern.compile( AFTER_FORMAT ).matcher( outputContent ).matches() ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + Assertions.assertTrue( Pattern.compile( AFTER_FORMAT ).matcher( outputContent ).matches() ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateGeneratingOnlyScriptFileTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateGeneratingOnlyScriptFileTest.java index 8f40a20a8cdd..3fdaea5e5ac9 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateGeneratingOnlyScriptFileTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateGeneratingOnlyScriptFileTest.java @@ -4,67 +4,58 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "10180") +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = SchemaUpdateGeneratingOnlyScriptFileTest.TestEntity.class) public class SchemaUpdateGeneratingOnlyScriptFileTest { @Test - public void testSchemaUpdateScriptGeneration() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + public void testSchemaUpdateScriptGeneration( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( TestEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( ";" ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( ";" ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); - String fileContent = new String( Files.readAllBytes( output.toPath() ) ); - Pattern fileContentPattern = Pattern.compile( "create( (column|row))? table test_entity" ); - Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); - assertThat( fileContentMatcher.find(), is( true ) ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + String fileContent = new String( Files.readAllBytes( output.toPath() ) ); + Pattern fileContentPattern = Pattern.compile( "create( (column|row))? table test_entity" ); + Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); + assertTrue( fileContentMatcher.find() ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateHaltOnErrorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateHaltOnErrorTest.java index 0df6fd97b84d..75b87ba7c421 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateHaltOnErrorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateHaltOnErrorTest.java @@ -4,84 +4,63 @@ */ package org.hibernate.orm.test.schemaupdate; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.util.EnumSet; - import jakarta.persistence.Entity; import jakarta.persistence.Id; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.community.dialect.AltibaseDialect; +import org.hibernate.community.dialect.DerbyDialect; import org.hibernate.community.dialect.FirebirdDialect; import org.hibernate.community.dialect.InformixDialect; import org.hibernate.dialect.DB2Dialect; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.junit4.CustomRunner; -import org.hibernate.testing.util.ServiceRegistryUtil; - -import org.hibernate.community.dialect.DerbyDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.spi.SchemaManagementException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.EnumSet; /** * @author Vlad Mihalcea * @author Gail Badner */ -@SkipForDialect(value = DB2Dialect.class, comment = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.") -@SkipForDialect(value = DerbyDialect.class, comment = "Derby is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = FirebirdDialect.class, comment = "FirebirdDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = AltibaseDialect.class, comment = "AltibaseDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") -@SkipForDialect(value = InformixDialect.class, comment = "Informix is far more resistant to the reserved keyword usage.") -@RunWith(CustomRunner.class) +@SuppressWarnings("JUnitMalformedDeclaration") +@SkipForDialect(dialectClass = DB2Dialect.class, + reason = "DB2 is far more resistant to the reserved keyword usage. See HHH-12832.") +@SkipForDialect(dialectClass = DerbyDialect.class, + reason = "Derby is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = FirebirdDialect.class, + reason = "FirebirdDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = AltibaseDialect.class, + reason = "AltibaseDialect has autoQuoteKeywords enabled, so it is far more resistant to the reserved keyword usage.") +@SkipForDialect(dialectClass = InformixDialect.class, + reason = "Informix is far more resistant to the reserved keyword usage.") +@ServiceRegistry +@DomainModel(annotatedClasses = SchemaUpdateHaltOnErrorTest.From.class) public class SchemaUpdateHaltOnErrorTest { - - private StandardServiceRegistry ssr; - private MetadataImplementor metadata; - - @Before - public void setUp() throws IOException { - File output = File.createTempFile("update_script", ".sql"); - output.deleteOnExit(); - ssr = ServiceRegistryUtil.serviceRegistry(); - - final MetadataSources metadataSources = new MetadataSources( ssr ) - .addAnnotatedClass( From.class ); - metadata = (MetadataImplementor) metadataSources.buildMetadata(); - } - - @After - public void tearsDown() { - // there shouldn't be anything to clean up - StandardServiceRegistryBuilder.destroy( ssr ); - } - @Test - public void testHaltOnError() { + public void testHaltOnError(DomainModelScope modelScope) { + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); + try { - new SchemaUpdate().setHaltOnError( true ) - .execute( EnumSet.of( TargetType.DATABASE ), metadata ); - fail( "Should halt on error!" ); + new SchemaUpdate() + .setHaltOnError( true ) + .execute( EnumSet.of( TargetType.DATABASE ), model ); + Assertions.fail( "Should halt on error!" ); } catch ( Exception e ) { SchemaManagementException cause = (SchemaManagementException) e; - assertTrue( cause.getMessage().startsWith( "Halting on error : Error executing DDL" ) ); + Assertions.assertTrue( cause.getMessage().startsWith( "Halting on error : Error executing DDL" ) ); } } @Entity(name = "From") - public class From { + public static class From { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.java index 15dcef81710a..1689a28905a4 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.java @@ -4,82 +4,74 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; import jakarta.persistence.ConstraintMode; import jakarta.persistence.Entity; import jakarta.persistence.ForeignKey; import jakarta.persistence.Id; import jakarta.persistence.SecondaryTable; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; -import static org.junit.Assert.assertFalse; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-8805") -public class SchemaUpdateJoinColumnNoConstraintSecondaryTableTest extends BaseUnitTestCase { +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = SchemaUpdateJoinColumnNoConstraintSecondaryTableTest.Parent.class) +public class SchemaUpdateJoinColumnNoConstraintSecondaryTableTest { + + // Expected script: + // + // create table Child ( + // id bigint not null, + // some_fk bigint, + // primary key (id) + // ); + // + // create table Parent ( + // id bigint not null, + // primary key (id) + // ); - private static final String EXPECTED_SCRIPT = - " create table Child ( " + - " id bigint not null, " + - " some_fk bigint, " + - " primary key (id) " + - " ); " + - " " + - " create table Parent ( " + - " id bigint not null, " + - " primary key (id) " + - " ); "; private static final String DELIMITER = ";"; @Test - public void test() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( Parent.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( DELIMITER ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); - - String outputContent = new String(Files.readAllBytes(output.toPath())); - - assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); - - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + public void test( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); + + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); + + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( DELIMITER ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); + + String outputContent = new String(Files.readAllBytes(output.toPath())); + Assertions.assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); } @Entity(name = "Parent") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest.java index 865ce1936edb..f5847d3529bd 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest.java @@ -4,83 +4,76 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; import jakarta.persistence.ConstraintMode; import jakarta.persistence.Entity; import jakarta.persistence.ForeignKey; import jakarta.persistence.Id; import jakarta.persistence.SecondaryTable; import jakarta.persistence.SecondaryTables; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; -import static org.junit.Assert.assertFalse; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-8805") -public class SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest extends BaseUnitTestCase { +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest.Parent.class) +public class SchemaUpdateJoinColumnNoConstraintSecondaryTablesTest { + + // Expected script: + // + // create table Child ( + // id bigint not null, + // some_fk bigint, + // primary key (id) + // ); + // + // create table Parent ( + // id bigint not null, + // primary key (id) + // ); - private static final String EXPECTED_SCRIPT = - " create table Child ( " + - " id bigint not null, " + - " some_fk bigint, " + - " primary key (id) " + - " ); " + - " " + - " create table Parent ( " + - " id bigint not null, " + - " primary key (id) " + - " ); "; private static final String DELIMITER = ";"; @Test - public void test() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); + public void test( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( Parent.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( DELIMITER ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( DELIMITER ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); - String outputContent = new String(Files.readAllBytes(output.toPath())); + String outputContent = new String(Files.readAllBytes(output.toPath())); - assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); - - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + Assertions.assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); } @Entity(name = "Parent") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintTest.java index 81e6cb6f131d..bbd094a3cdab 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateJoinColumnNoConstraintTest.java @@ -4,73 +4,64 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.nio.file.Files; -import java.util.EnumSet; import jakarta.persistence.ConstraintMode; import jakarta.persistence.Entity; import jakarta.persistence.ForeignKey; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; - -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.nio.file.Files; +import java.util.EnumSet; -import static org.junit.Assert.assertFalse; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @RequiresDialect(H2Dialect.class) @JiraKey(value = "HHH-8805") -public class SchemaUpdateJoinColumnNoConstraintTest extends BaseUnitTestCase { - +@ServiceRegistry(settings = @Setting(name = HBM2DDL_AUTO, value = "none")) +@DomainModel(annotatedClasses = { + SchemaUpdateJoinColumnNoConstraintTest.Parent.class, + SchemaUpdateJoinColumnNoConstraintTest.Child.class +}) +public class SchemaUpdateJoinColumnNoConstraintTest { private static final String DELIMITER = ";"; @Test - public void test() throws Exception { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.HBM2DDL_AUTO, "none" ) - .build(); - try { - File output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( Parent.class ) - .addAnnotatedClass( Child.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( DELIMITER ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.SCRIPT ), metadata ); - - String outputContent = new String(Files.readAllBytes(output.toPath())); - - assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); - - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + public void test( + DomainModelScope modelScope, + @TempDir File tmpDir) throws Exception { + var output = new File( tmpDir, "update_script.sql" ); + + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); + + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( DELIMITER ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.SCRIPT ), model ); + + String outputContent = new String(Files.readAllBytes(output.toPath())); + Assertions.assertFalse( outputContent.toLowerCase().contains( "foreign key" ) ); } @Entity(name = "Parent") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateProceedOnErrorTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateProceedOnErrorTest.java index d4aaabd13d19..4087b4836d6e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateProceedOnErrorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateProceedOnErrorTest.java @@ -4,52 +4,38 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.Map; import jakarta.persistence.Entity; import jakarta.persistence.Id; +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; +import org.hibernate.testing.orm.junit.Jpa; +import org.hibernate.testing.orm.junit.Setting; +import org.junit.jupiter.api.Test; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.orm.test.jpa.BaseEntityManagerFunctionalTestCase; - -import org.junit.Test; - -import static org.junit.Assert.fail; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_AUTO; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Vlad Mihalcea */ -public class SchemaUpdateProceedOnErrorTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - From.class - }; - } - - @Override - protected Map buildSettings() { - Map settings = super.buildSettings(); - settings.put( AvailableSettings.HBM2DDL_AUTO, "update" ); - return settings; - } +@SuppressWarnings("JUnitMalformedDeclaration") +@Jpa( + annotatedClasses = SchemaUpdateProceedOnErrorTest.From.class, + integrationSettings = @Setting(name = HBM2DDL_AUTO, value = "update") +) +public class SchemaUpdateProceedOnErrorTest { - @Override - public void buildEntityManagerFactory() { + @Test + public void testHaltOnError(EntityManagerFactoryScope factoryScope) { try { - super.buildEntityManagerFactory(); + factoryScope.getEntityManagerFactory(); } catch ( Exception e ) { - fail("Should not halt on error: " + e.getMessage()); + fail( "Should not halt on error: " + e.getMessage() ); } } - @Test - public void testHaltOnError() { - } - @Entity(name = "From") - public class From { + public static class From { @Id private Integer id; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java index 2f4552052816..dd44773f6581 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java @@ -4,18 +4,6 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; @@ -32,69 +20,100 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; +import org.hamcrest.MatcherAssert; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.SQLServerDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistryFunctionalTesting; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.transaction.TransactionUtil; +import org.hibernate.testing.util.ServiceRegistryUtil; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.hbm2ddl.SchemaValidator; import org.hibernate.tool.schema.JdbcMetadataAccessStrategy; import org.hibernate.tool.schema.TargetType; +import org.jboss.logging.Logger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.hibernate.testing.orm.junit.DialectContext; -import org.hibernate.testing.transaction.TransactionUtil; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.io.File; +import java.nio.file.Files; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Collection; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import static org.hibernate.cfg.MappingSettings.KEYWORD_AUTO_QUOTING_ENABLED; +import static org.hibernate.cfg.SchemaToolingSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY; /** * @author Andrea Boriero */ -@RunWith(Parameterized.class) @RequiresDialect(SQLServerDialect.class) -public class SchemaUpdateSQLServerTest extends BaseUnitTestCase { - - @Parameterized.Parameters - public static Collection parameters() { - return Arrays.asList( - new String[] {JdbcMetadataAccessStrategy.GROUPED.toString(), JdbcMetadataAccessStrategy.INDIVIDUALLY.toString()} +@ParameterizedClass +@MethodSource("parameters") +@TestInstance( TestInstance.Lifecycle.PER_METHOD ) +@ServiceRegistryFunctionalTesting +@DomainModel(annotatedClasses = { + SchemaUpdateSQLServerTest.LowercaseTableNameEntity.class, + SchemaUpdateSQLServerTest.TestEntity.class, + SchemaUpdateSQLServerTest.UppercaseTableNameEntity.class, + SchemaUpdateSQLServerTest.MixedCaseTableNameEntity.class, + SchemaUpdateSQLServerTest.Match.class, + SchemaUpdateSQLServerTest.InheritanceRootEntity.class, + SchemaUpdateSQLServerTest.InheritanceChildEntity.class, + SchemaUpdateSQLServerTest.InheritanceSecondChildEntity.class +}) +public class SchemaUpdateSQLServerTest implements ServiceRegistryProducer { + private static final Logger log = Logger.getLogger( SchemaUpdateSQLServerTest.class ); + + public static Collection parameters() { + return List.of( + JdbcMetadataAccessStrategy.GROUPED, + JdbcMetadataAccessStrategy.INDIVIDUALLY ); } - @Parameterized.Parameter - public String jdbcMetadataExtractorStrategy; - - private File output; - private StandardServiceRegistry ssr; - private MetadataImplementor metadata; + public JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy; + private final File output; - @Before - public void setUp() throws IOException { - if(!SQLServerDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() )) { - return; - } + public SchemaUpdateSQLServerTest( + JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy, + @TempDir File outputDir) { + this.jdbcMetadataExtractorStrategy = jdbcMetadataExtractorStrategy; + this.output = new File( outputDir, "update_script.sql" ); + } - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, "true" ) - .applySetting( AvailableSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) + @Override + public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { + return ServiceRegistryUtil.serviceRegistryBuilder() + .applySetting( KEYWORD_AUTO_QUOTING_ENABLED, "true" ) + .applySetting( HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) .build(); + } + + @BeforeEach + void prepare(ServiceRegistryScope registryScope, DomainModelScope modelScope) { + var registry = registryScope.getRegistry(); try { - TransactionUtil.doWithJDBC( ssr, connection -> { + TransactionUtil.doWithJDBC( registry, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); statement.executeUpdate( "DROP DATABASE hibernate_orm_test_collation" ); @@ -105,7 +124,7 @@ public void setUp() throws IOException { log.debug( e.getMessage() ); } try { - TransactionUtil.doWithJDBC( ssr, connection -> { + TransactionUtil.doWithJDBC( registry, connection -> { try (Statement statement = connection.createStatement()) { connection.setAutoCommit( true ); statement.executeUpdate( "CREATE DATABASE hibernate_orm_test_collation COLLATE Latin1_General_CS_AS" ); @@ -117,52 +136,35 @@ public void setUp() throws IOException { log.debug( e.getMessage() ); } - final MetadataSources metadataSources = new MetadataSources( ssr ); - metadataSources.addAnnotatedClass( LowercaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( TestEntity.class ); - metadataSources.addAnnotatedClass( UppercaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( MixedCaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( Match.class ); - metadataSources.addAnnotatedClass( InheritanceRootEntity.class ); - metadataSources.addAnnotatedClass( InheritanceChildEntity.class ); - metadataSources.addAnnotatedClass( InheritanceSecondChildEntity.class ); - - metadata = (MetadataImplementor) metadataSources.buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); } - @After - public void tearsDown() { - if(!SQLServerDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() )) { - return; - } - + @AfterEach + void tearsDown(DomainModelScope modelScope) { new SchemaExport().setHaltOnError( true ) .setOutputFile( output.getAbsolutePath() ) .setFormat( false ) - .drop( EnumSet.of( TargetType.DATABASE ), metadata ); - StandardServiceRegistryBuilder.destroy( ssr ); + .drop( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } @Test - public void testSchemaUpdateAndValidation() throws Exception { - if(!SQLServerDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() )) { - return; - } - - new SchemaUpdate().setHaltOnError( true ) - .execute( EnumSet.of( TargetType.DATABASE ), metadata ); + public void testSchemaUpdateAndValidation(DomainModelScope modelScope) throws Exception { + new SchemaUpdate() + .setHaltOnError( true ) + .execute( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); - new SchemaValidator().validate( metadata ); + new SchemaValidator().validate( modelScope.getDomainModel() ); - new SchemaUpdate().setHaltOnError( true ) + new SchemaUpdate() + .setHaltOnError( true ) .setOutputFile( output.getAbsolutePath() ) .setFormat( false ) - .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); + .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), modelScope.getDomainModel() ); final String fileContent = new String( Files.readAllBytes( output.toPath() ) ); - assertThat( "The update output file should be empty", fileContent, is( "" ) ); + MatcherAssert.assertThat( "The update output file should be empty", fileContent, is( "" ) ); } @Entity(name = "TestEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java index 8bf8ab0c83cd..9b22e0edeae1 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java @@ -4,16 +4,6 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; @@ -29,137 +19,133 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; +import org.hamcrest.MatcherAssert; import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.community.dialect.TiDBDialect; import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SybaseDialect; -import org.hibernate.community.dialect.TiDBDialect; import org.hibernate.engine.jdbc.env.spi.IdentifierHelper; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.hibernate.testing.SkipLog; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.ServiceRegistryFunctionalTesting; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.SkipForDialect; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.hbm2ddl.SchemaValidator; import org.hibernate.tool.schema.JdbcMetadataAccessStrategy; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -import org.hibernate.testing.SkipLog; -import org.hibernate.testing.orm.junit.DialectContext; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.io.File; +import java.nio.file.Files; +import java.util.Collection; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; /** * @author Andrea Boriero */ -@RunWith(Parameterized.class) -public class SchemaUpdateTest { - - private boolean skipTest; - - @Parameterized.Parameters - public static Collection parameters() { - return Arrays.asList( - new String[] {JdbcMetadataAccessStrategy.GROUPED.toString(), JdbcMetadataAccessStrategy.INDIVIDUALLY.toString()} +@SkipForDialect(dialectClass = SQLServerDialect.class) +@SkipForDialect(dialectClass = SybaseDialect.class) +@SkipForDialect(dialectClass = TiDBDialect.class) +@ParameterizedClass +@MethodSource("parameters") +@TestInstance( TestInstance.Lifecycle.PER_METHOD ) +@ServiceRegistryFunctionalTesting +@DomainModel(annotatedClasses = { + SchemaUpdateTest.LowercaseTableNameEntity.class, + SchemaUpdateTest.TestEntity.class, + SchemaUpdateTest.UppercaseTableNameEntity.class, + SchemaUpdateTest.MixedCaseTableNameEntity.class, + SchemaUpdateTest.Match.class, + SchemaUpdateTest.InheritanceRootEntity.class, + SchemaUpdateTest.InheritanceChildEntity.class, + SchemaUpdateTest.InheritanceSecondChildEntity.class +}) +public class SchemaUpdateTest implements ServiceRegistryProducer { + public static Collection parameters() { + return List.of( + JdbcMetadataAccessStrategy.GROUPED, + JdbcMetadataAccessStrategy.INDIVIDUALLY ); } - @Parameterized.Parameter - public String jdbcMetadataExtractorStrategy; - - private File output; - private StandardServiceRegistry ssr; - private MetadataImplementor metadata; + public JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy; + private final File output; - @Before - public void setUp() throws IOException { - if ( SQLServerDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() ) - || SybaseDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() ) - || TiDBDialect.class.isAssignableFrom( DialectContext.getDialect().getClass() ) ) { - // SQLServerDialect, SybaseDialect and TiDB store case-insensitive quoted identifiers in mixed case, - // so the checks at the end of this method won't work. - // For TiDB, only 'lower_case_table_names=2' is supported. - skipTest = true; - return; - } - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, "true" ) - .applySetting( AvailableSettings.HBM2DDL_JDBC_METADATA_EXTRACTOR_STRATEGY, jdbcMetadataExtractorStrategy ) - .build(); + private boolean skip; - final MetadataSources metadataSources = new MetadataSources( ssr ); - metadataSources.addAnnotatedClass( LowercaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( TestEntity.class ); - metadataSources.addAnnotatedClass( UppercaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( MixedCaseTableNameEntity.class ); - metadataSources.addAnnotatedClass( Match.class ); - metadataSources.addAnnotatedClass( InheritanceRootEntity.class ); - metadataSources.addAnnotatedClass( InheritanceChildEntity.class ); - metadataSources.addAnnotatedClass( InheritanceSecondChildEntity.class ); - - metadata = (MetadataImplementor) metadataSources.buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + public SchemaUpdateTest( + JdbcMetadataAccessStrategy jdbcMetadataExtractorStrategy, + @TempDir File outputDir) { + this.jdbcMetadataExtractorStrategy = jdbcMetadataExtractorStrategy; + this.output = new File( outputDir, "update_script.sql" ); + } + @BeforeEach + void prepare(ServiceRegistryScope registryScope) { // Databases that use case-insensitive quoted identifiers need to be skipped. // The following checks will work for checking those dialects that store case-insensitive // quoted identifiers as upper-case or lower-case. It does not work for dialects that // store case-insensitive identifiers in mixed case (like SQL Server). - final IdentifierHelper identifierHelper = ssr.getService( JdbcEnvironment.class ).getIdentifierHelper(); + final IdentifierHelper identifierHelper = registryScope.getRegistry().requireService( JdbcEnvironment.class ).getIdentifierHelper(); final String lowerCaseName = identifierHelper.toMetaDataObjectName( Identifier.toIdentifier( "testentity", true ) ); final String upperCaseName = identifierHelper.toMetaDataObjectName( Identifier.toIdentifier("TESTENTITY", true ) ); final String mixedCaseName = identifierHelper.toMetaDataObjectName( Identifier.toIdentifier("TESTentity", true ) ); if ( lowerCaseName.equals( upperCaseName ) || - lowerCaseName.equals( mixedCaseName ) || - upperCaseName.equals( mixedCaseName ) ) { - StandardServiceRegistryBuilder.destroy( ssr ); - skipTest = true; + lowerCaseName.equals( mixedCaseName ) || + upperCaseName.equals( mixedCaseName ) ) { + skip = true; } } - @After - public void tearsDown() { - if ( skipTest ) { + @AfterEach + public void tearsDown(DomainModelScope modelScope) { + if ( skip ) { return; } + new SchemaExport().setHaltOnError( true ) .setOutputFile( output.getAbsolutePath() ) .setFormat( false ) - .drop( EnumSet.of( TargetType.DATABASE ), metadata ); - StandardServiceRegistryBuilder.destroy( ssr ); + .drop( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); } @Test - public void testSchemaUpdateAndValidation() throws Exception { - if ( skipTest ) { + public void testSchemaUpdateAndValidation(DomainModelScope modelScope) throws Exception { + if ( skip ) { SkipLog.reportSkip( "skipping test because quoted names are not case-sensitive." ); return; } new SchemaUpdate().setHaltOnError( true ) - .execute( EnumSet.of( TargetType.DATABASE ), metadata ); + .execute( EnumSet.of( TargetType.DATABASE ), modelScope.getDomainModel() ); - new SchemaValidator().validate( metadata ); + new SchemaValidator().validate( modelScope.getDomainModel() ); new SchemaUpdate().setHaltOnError( true ) .setOutputFile( output.getAbsolutePath() ) .setFormat( false ) - .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); + .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), modelScope.getDomainModel() ); final String fileContent = new String( Files.readAllBytes( output.toPath() ) ); - assertThat( "The update output file should be empty", fileContent, is( "" ) ); + MatcherAssert.assertThat( "The update output file should be empty", fileContent, is( "" ) ); } @Entity(name = "TestEntity") diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithFunctionIndexTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithFunctionIndexTest.java index c1bffc7968b4..3a467c88db19 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithFunctionIndexTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithFunctionIndexTest.java @@ -4,105 +4,72 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; - import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.EnumSet; + +import static org.hibernate.cfg.MappingSettings.DEFAULT_SCHEMA; +import static org.hibernate.cfg.MappingSettings.GLOBALLY_QUOTED_IDENTIFIERS; /** * @author Yoann Rodiere */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-10191") @RequiresDialect(PostgreSQLDialect.class) -public class SchemaUpdateWithFunctionIndexTest extends BaseNonConfigCoreFunctionalTestCase { - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; +@ServiceRegistry(settings = { + @Setting(name= GLOBALLY_QUOTED_IDENTIFIERS, value = "false"), + @Setting(name = DEFAULT_SCHEMA, value = "public") +}) +@DomainModel(annotatedClasses = SchemaUpdateWithFunctionIndexTest.MyEntity.class) +@SessionFactory +public class SchemaUpdateWithFunctionIndexTest { @Test - public void testUpdateSchema() { - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); - } - - @Before - public void setUp() { - dropFunctionIndex(); - dropTable(); - createTable(); - createFunctionIndex(); - serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.GLOBALLY_QUOTED_IDENTIFIERS, "false" ) - .applySetting( Environment.DEFAULT_SCHEMA, "public" ) - .build(); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( MyEntity.class ) - .buildMetadata(); - } - - private void createTable() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "CREATE TABLE MyEntity(id bigint, name varchar(255));" ); - query.executeUpdate(); - transaction.commit(); - session.close(); - } - - private void createFunctionIndex() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "CREATE UNIQUE INDEX uk_MyEntity_name_lowercase ON MyEntity (lower(name));" ); - query.executeUpdate(); - transaction.commit(); - session.close(); - } - - private void dropTable() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "DROP TABLE IF EXISTS MyEntity;" ); - query.executeUpdate(); - transaction.commit(); - session.close(); + public void testUpdateSchema(DomainModelScope modelScope) { + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } - private void dropFunctionIndex() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "DROP INDEX IF EXISTS uk_MyEntity_name_lowercase;" ); - query.executeUpdate(); - transaction.commit(); - session.close(); + @BeforeEach + public void setUp(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "DROP INDEX IF EXISTS uk_MyEntity_name_lowercase;" ); + statement.execute( "DROP TABLE IF EXISTS MyEntity;" ); + statement.execute( "CREATE TABLE MyEntity(id bigint, name varchar(255));" ); + statement.execute( "CREATE UNIQUE INDEX uk_MyEntity_name_lowercase ON MyEntity (lower(name));" ); + } + } ) ); } - @After - public void tearDown() { - dropFunctionIndex(); - dropTable(); - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); - StandardServiceRegistryBuilder.destroy( serviceRegistry ); + @AfterEach + public void tearDown(DomainModelScope modelScope, SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "DROP INDEX IF EXISTS uk_MyEntity_name_lowercase;" ); + statement.execute( "DROP TABLE IF EXISTS MyEntity;" ); + } + } ) ); + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } @Entity diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithViewsTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithViewsTest.java index b435aef7597d..54990a4b287f 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithViewsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateWithViewsTest.java @@ -4,93 +4,69 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.IOException; -import java.util.EnumSet; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.Table; - -import org.hibernate.dialect.CockroachDialect; import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.Environment; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.testing.SkipForDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.util.EnumSet; + +import static org.hibernate.cfg.MappingSettings.DEFAULT_SCHEMA; +import static org.hibernate.cfg.MappingSettings.GLOBALLY_QUOTED_IDENTIFIERS; /** * @author Andrea Boriero */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey(value = "HHH-1872") @RequiresDialect(PostgreSQLDialect.class) -@SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/24897") -public class SchemaUpdateWithViewsTest extends BaseNonConfigCoreFunctionalTestCase { - - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - +@ServiceRegistry(settings = { + @Setting(name= GLOBALLY_QUOTED_IDENTIFIERS, value = "false"), + @Setting(name = DEFAULT_SCHEMA, value = "public") +}) +@DomainModel(annotatedClasses = SchemaUpdateWithViewsTest.MyEntity.class) +@SessionFactory +public class SchemaUpdateWithViewsTest { @Test - public void testUpdateSchema() { - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + public void testUpdateSchema(DomainModelScope modelScope) { + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } - @Before - public void setUp() throws IOException { - createViewWithSameNameOfEntityTable(); - serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( Environment.GLOBALLY_QUOTED_IDENTIFIERS, "false" ) - .applySetting( Environment.DEFAULT_SCHEMA, "public" ) - .build(); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( MyEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + @BeforeEach + public void setUp(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "CREATE OR REPLACE VIEW MyEntity AS SELECT 'Hello World' " ); + } + } ) ); } - private void createViewWithSameNameOfEntityTable() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "CREATE OR REPLACE VIEW MyEntity AS SELECT 'Hello World' " ); - query.executeUpdate(); - transaction.commit(); - session.close(); - } + @AfterEach + public void tearDown(DomainModelScope modelScope, SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "DROP VIEW IF EXISTS MyEntity " ); + } + } ) ); - @After - public void tearDown() { - dropView(); System.out.println( "********* Starting SchemaExport (drop) for TEAR-DOWN *************************" ); - new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), metadata ); + new SchemaExport().drop( EnumSet.of( TargetType.STDOUT, TargetType.DATABASE ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport (drop) for TEAR-DOWN *************************" ); - - StandardServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; - } - - private void dropView() { - Session session = openSession(); - Transaction transaction = session.beginTransaction(); - Query query = session.createNativeQuery( "DROP VIEW IF EXISTS MyEntity " ); - query.executeUpdate(); - transaction.commit(); - session.close(); } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SequenceReadingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SequenceReadingTest.java index d5d8dc307506..b12e8b9a0143 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SequenceReadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SequenceReadingTest.java @@ -4,28 +4,28 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.util.EnumSet; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - -import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistryFunctionalTesting; +import org.hibernate.testing.orm.junit.ServiceRegistryProducer; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorNoOpImpl; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.util.EnumSet; + +import static org.hibernate.cfg.JdbcSettings.DIALECT; /** * Regression test fr a bug in org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorNoOpImpl @@ -34,38 +34,35 @@ * * @see */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-9745" ) @RequiresDialect( H2Dialect.class ) -public class SequenceReadingTest extends BaseCoreFunctionalTestCase { +@ServiceRegistryFunctionalTesting +@DomainModel(annotatedClasses = SequenceReadingTest.MyEntity.class) +public class SequenceReadingTest implements ServiceRegistryProducer { + @Override + public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { + return builder.applySetting( DIALECT, MyExtendedH2Dialect.class ).build(); + } @Test - public void testSequenceReading() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.DIALECT, MyExtendedH2Dialect.class ) - .build(); - try { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( MyEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); + public void testSequenceReading(DomainModelScope modelScope) { + var model = modelScope.getDomainModel(); + model.orderColumns( false ); + model.validate(); + try { + // try to update the schema + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), model ); + } + finally { try { - // try to update the schema - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE ), metadata ); + // clean up + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), model ); } - finally { - try { - // clean up - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata ); - } - catch (Exception ignore) { - } + catch (Exception ignore) { } } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } } /** diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SqlServerQuoteSchemaTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SqlServerQuoteSchemaTest.java index bb0518232465..88ab01315157 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SqlServerQuoteSchemaTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SqlServerQuoteSchemaTest.java @@ -4,160 +4,113 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; - +import org.hamcrest.MatcherAssert; import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.dialect.SQLServerDialect; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.RequiresDialect; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.ServiceRegistryScope; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; +import org.hibernate.testing.orm.junit.Setting; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import static org.hamcrest.core.Is.is; -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hibernate.cfg.MappingSettings.GLOBALLY_QUOTED_IDENTIFIERS; /** * @author Vlad Mihalcea */ +@SuppressWarnings("JUnitMalformedDeclaration") @JiraKey( value = "HHH-12106" ) @RequiresDialect( SQLServerDialect.class ) -public class SqlServerQuoteSchemaTest extends BaseCoreFunctionalTestCase { - - private File output; - - @Override - protected void afterSessionFactoryBuilt() { - try { - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - } - catch (IOException ignore) { - } - try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( - "DROP TABLE [my-schema].my_entity" ) - .executeUpdate(); - }); - } - catch (Exception ignore) { - } - try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( - "DROP SCHEMA [my-schema]" ) - .executeUpdate(); - }); - } - catch (Exception ignore) { - } - try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( - "CREATE SCHEMA [my-schema]" ) - .executeUpdate(); - }); - } - catch (Exception ignore) { - } +@ServiceRegistry(settings = @Setting(name = GLOBALLY_QUOTED_IDENTIFIERS, value = "true")) +@DomainModel +@SessionFactory(exportSchema = false) +public class SqlServerQuoteSchemaTest { + @BeforeEach + void setUp(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "DROP TABLE [my-schema].my_entity" ); + statement.execute( "DROP SCHEMA [my-schema]" ); + statement.execute( "CREATE SCHEMA [my-schema]" ); + } + } ) ); } - @Override - protected void cleanupTest() { - try { - doInHibernate( this::sessionFactory, session -> { - session.createNativeQuery( - "DROP SCHEMA [my-schema]" ) - .executeUpdate(); - } ); - } - catch (Exception ignore) { - } + @AfterEach + void tearDown(SessionFactoryScope factoryScope) { + factoryScope.inTransaction( (session) -> session.doWork( (connection) -> { + try (var statement = connection.createStatement()) { + statement.execute( "DROP SCHEMA [my-schema]" ); + } + } ) ); } @Test - public void test() { - StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, Boolean.TRUE.toString() ) - .build(); - - try { - output.deleteOnExit(); - - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( MyEntity.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( ";" ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } - + public void test(ServiceRegistryScope registryScope, @TempDir File tmpDir) { + var output = new File( tmpDir, "update_script.sql" ); + + // first, export the schema... + var model = new MetadataSources( registryScope.getRegistry() ) + .addAnnotatedClass( MyEntity.class ) + .buildMetadata(); + + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( ";" ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), model ); try { String fileContent = new String( Files.readAllBytes( output.toPath() ) ); Pattern fileContentPattern = Pattern.compile( "create table \\[my\\-schema\\]\\.\\[my_entity\\]" ); Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); - assertThat( fileContentMatcher.find(), is( true ) ); + MatcherAssert.assertThat( fileContentMatcher.find(), is( true ) ); } catch (IOException e) { - fail(e.getMessage()); + Assertions.fail( e.getMessage() ); } - ssr = ServiceRegistryUtil.serviceRegistryBuilder() - .applySetting( AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, Boolean.TRUE.toString() ) - .build(); - try { - final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) - .addAnnotatedClass( MyEntityUpdated.class ) - .buildMetadata(); - metadata.orderColumns( false ); - metadata.validate(); - - new SchemaUpdate() - .setHaltOnError( true ) - .setOutputFile( output.getAbsolutePath() ) - .setDelimiter( ";" ) - .setFormat( true ) - .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata ); - } - finally { - StandardServiceRegistryBuilder.destroy( ssr ); - } + // then, update the schema... + model = new MetadataSources( registryScope.getRegistry() ) + .addAnnotatedClass( MyEntityUpdated.class ) + .buildMetadata(); + + new SchemaUpdate() + .setHaltOnError( true ) + .setOutputFile( output.getAbsolutePath() ) + .setDelimiter( ";" ) + .setFormat( true ) + .execute( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), model ); try { String fileContent = new String( Files.readAllBytes( output.toPath() ) ); Pattern fileContentPattern = Pattern.compile( "alter table \\[my\\-schema\\]\\.\\[my_entity\\]" ); Matcher fileContentMatcher = fileContentPattern.matcher( fileContent.toLowerCase() ); - assertThat( fileContentMatcher.find(), is( true ) ); + MatcherAssert.assertThat( fileContentMatcher.find(), is( true ) ); } catch (IOException e) { - fail(e.getMessage()); + Assertions.fail( e.getMessage() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TableCommentTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TableCommentTest.java index a5ee28a84bc2..076347eefb9b 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TableCommentTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TableCommentTest.java @@ -4,85 +4,91 @@ */ package org.hibernate.orm.test.schemaupdate; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.EnumSet; -import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.Id; - import jakarta.persistence.Table; -import org.hibernate.boot.MetadataSources; +import org.hamcrest.MatcherAssert; +import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.persister.entity.AbstractEntityPersister; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; +import org.hibernate.testing.orm.junit.JiraKey; +import org.hibernate.testing.orm.junit.ServiceRegistry; +import org.hibernate.testing.orm.junit.SessionFactory; +import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import org.hibernate.testing.orm.junit.JiraKey; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.EnumSet; +import java.util.List; -import static junit.framework.TestCase.fail; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; /** * @author Andrea Boriero */ -public class TableCommentTest extends BaseNonConfigCoreFunctionalTestCase { - - private File output; - - @Before - public void setUp() throws IOException { - output = File.createTempFile( "update_script", ".sql" ); - output.deleteOnExit(); - } - - @After - public void tearDown() { - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata() ); +@SuppressWarnings("JUnitMalformedDeclaration") +@ServiceRegistry +@DomainModel(annotatedClasses = TableCommentTest.TableWithComment.class) +@SessionFactory(exportSchema = false) +public class TableCommentTest { + + @AfterEach + public void tearDown(DomainModelScope modelScope) { + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); } @Test @JiraKey(value = "HHH-10451") - public void testCommentOnTableStatementIsGenerated() throws IOException { - createSchema( new Class[] {TableWithComment.class} ); + public void testCommentOnTableStatementIsGenerated( + DomainModelScope modelScope, + SessionFactoryScope factoryScope, + @TempDir File tmpDir) throws IOException { + var output = new File( tmpDir, "update_script.sql" ); + + createSchema( modelScope, output); + + var dialect = factoryScope.getSessionFactory().getJdbcServices().getDialect(); final List sqlLines = Files.readAllLines( output.toPath(), Charset.defaultCharset() ); boolean found = false; - final String tableName = getTableName(); + final String tableName = getTableName( factoryScope ); for ( String sqlStatement : sqlLines ) { if ( sqlStatement.toLowerCase() .equals( "comment on table " + tableName.toLowerCase() + " is 'comment snippet';" ) ) { - if ( getDialect().supportsCommentOn() ) { + if ( dialect.supportsCommentOn() ) { found = true; } else { - fail( "Generated " + sqlStatement + " statement, but Dialect does not support it" ); + Assertions.fail( "Generated " + sqlStatement + " statement, but Dialect does not support it" ); } } - if ( containsCommentInCreateTableStatement( sqlStatement ) ) { - if ( getDialect().supportsCommentOn() || getDialect().getTableComment( "comment snippet" ).isEmpty() ) { + if ( containsCommentInCreateTableStatement( sqlStatement, dialect ) ) { + if ( dialect.supportsCommentOn() || dialect.getTableComment( "comment snippet" ).isEmpty() ) { found = true; } else { - fail( "Generated comment on create table statement, but Dialect does not support it" ); + Assertions.fail( "Generated comment on create table statement, but Dialect does not support it" ); } } } - assertThat( "Table Comment Statement not correctly generated", found, is( true ) ); + MatcherAssert.assertThat( "Table Comment Statement not correctly generated", found, is( true ) ); } - private boolean containsCommentInCreateTableStatement(String sqlStatement) { - return sqlStatement.toLowerCase().contains( getDialect().getCreateTableString() ) - && sqlStatement.toLowerCase().contains( getDialect().getTableComment( "comment snippet" ).toLowerCase() ); + private boolean containsCommentInCreateTableStatement(String sqlStatement, Dialect dialect) { + return sqlStatement.toLowerCase().contains( dialect.getCreateTableString() ) + && sqlStatement.toLowerCase().contains( dialect.getTableComment( "comment snippet" ).toLowerCase() ); } @Entity(name = "TableWithComment") @@ -93,8 +99,8 @@ public static class TableWithComment { private int id; } - private String getTableName() { - final SessionFactoryImplementor sessionFactory = sessionFactory(); + private String getTableName(SessionFactoryScope factoryScope) { + final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory(); final EntityMappingType entityMappingType = sessionFactory .getRuntimeMetamodels() .getEntityMappingType( TableWithComment.class ); @@ -102,19 +108,10 @@ private String getTableName() { return ( (AbstractEntityPersister) entityMappingType ).getTableName(); } - private void createSchema(Class[] annotatedClasses) { + private void createSchema(DomainModelScope modelScope, File output) { new SchemaExport() .setOutputFile( output.getAbsolutePath() ) .setFormat( false ) - .create( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), metadata() ); - } - - protected void afterMetadataSourcesApplied(MetadataSources metadataSources) { - metadataSources.addAnnotatedClass( TableWithComment.class ); - } - - @Override - protected boolean createSchema() { - return false; + .create( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), modelScope.getDomainModel() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TestFkUpdating.java b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TestFkUpdating.java index f2d837ecf663..68f060222826 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TestFkUpdating.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TestFkUpdating.java @@ -13,54 +13,43 @@ import jakarta.persistence.Table; import org.hibernate.annotations.GenericGenerator; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.service.ServiceRegistry; +import org.hibernate.testing.orm.junit.DomainModel; +import org.hibernate.testing.orm.junit.DomainModelScope; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.hibernate.testing.util.ServiceRegistryUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; /** * @author Steve Ebersole */ +@SuppressWarnings("JUnitMalformedDeclaration") +@DomainModel(annotatedClasses = { + TestFkUpdating.User.class, + TestFkUpdating.Role.class +}) public class TestFkUpdating { - protected ServiceRegistry serviceRegistry; - protected MetadataImplementor metadata; - - @Before - public void setUp() { - serviceRegistry = ServiceRegistryUtil.serviceRegistry(); - metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ) - .addAnnotatedClass( User.class ) - .addAnnotatedClass(Role.class) - .buildMetadata(); - + @BeforeEach + public void setUp(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport for START-UP *************************" ); - new SchemaExport().create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaExport().create( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport for START-UP *************************" ); } - @After - public void tearDown() { + @AfterEach + public void tearDown(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaExport (drop) for TEAR-DOWN *************************" ); - new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaExport().drop( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaExport (drop) for TEAR-DOWN *************************" ); - - - StandardServiceRegistryBuilder.destroy( serviceRegistry ); - serviceRegistry = null; } @Test - public void testUpdate() { + public void testUpdate(DomainModelScope modelScope) { System.out.println( "********* Starting SchemaUpdate for TEST *************************" ); - new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), metadata ); + new SchemaUpdate().execute( EnumSet.of( TargetType.DATABASE, TargetType.STDOUT ), modelScope.getDomainModel() ); System.out.println( "********* Completed SchemaUpdate for TEST *************************" ); }