Search in sources :

Example 91 with MetadataImplementor

use of org.hibernate.boot.spi.MetadataImplementor in project hibernate-orm by hibernate.

the class MigrationTest method testIndexCreationViaSchemaUpdate.

// /**
// * 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
// @TestForIssue( jiraKey = "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
@TestForIssue(jiraKey = "HHH-9713")
public void testIndexCreationViaSchemaUpdate() {
    MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(serviceRegistry).addAnnotatedClass(EntityWithIndex.class).buildMetadata();
    // drop and then create the schema
    new SchemaExport().execute(EnumSet.of(TargetType.DATABASE), SchemaExport.Action.BOTH, metadata);
    try {
        // update the schema
        new SchemaUpdate().execute(EnumSet.of(TargetType.DATABASE), metadata);
    } finally {
        // drop the schema
        new SchemaExport().drop(EnumSet.of(TargetType.DATABASE), metadata);
    }
}
Also used : MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 92 with MetadataImplementor

use of org.hibernate.boot.spi.MetadataImplementor in project hibernate-orm by hibernate.

the class PostgreSQLMultipleSchemaSequenceTest method test.

@Test
@TestForIssue(jiraKey = "HHH-5538")
public void test() {
    StandardServiceRegistry ssr1 = new StandardServiceRegistryBuilder().build();
    final String extraSchemaName = "extra_schema_sequence_validation";
    try {
        final MetadataImplementor metadata1 = (MetadataImplementor) new MetadataSources(ssr1).addAnnotatedClass(Box.class).buildMetadata();
        try {
            new SchemaExport().setOutputFile(output.getAbsolutePath()).create(EnumSet.of(TargetType.DATABASE, TargetType.SCRIPT), metadata1);
            final ConnectionProvider connectionProvider1 = ssr1.getService(ConnectionProvider.class);
            DdlTransactionIsolatorTestingImpl ddlTransactionIsolator1 = new DdlTransactionIsolatorTestingImpl(ssr1, 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));
                try (ResultSet resultSet = statement.executeQuery("SELECT NEXTVAL('SEQ_TEST')")) {
                    while (resultSet.next()) {
                        Long sequenceValue = resultSet.getLong(1);
                        assertEquals(Long.valueOf(1L), sequenceValue);
                    }
                }
            } catch (SQLException e) {
                fail(e.getMessage());
            }
            StandardServiceRegistry ssr2 = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.URL, Environment.getProperties().get(AvailableSettings.URL) + "?currentSchema=" + extraSchemaName).build();
            try {
                final MetadataImplementor metadata2 = (MetadataImplementor) new MetadataSources(ssr2).addAnnotatedClass(Box.class).buildMetadata();
                try {
                    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(ssr2, new JdbcEnvironmentInitiator.ConnectionProviderJdbcConnectionAccess(connectionProvider2));
                    try (Statement statement = ddlTransactionIsolator2.getIsolatedConnection().createStatement()) {
                        try (ResultSet resultSet = statement.executeQuery("SELECT NEXTVAL('SEQ_TEST')")) {
                            while (resultSet.next()) {
                                Long sequenceValue = resultSet.getLong(1);
                                assertEquals(Long.valueOf(1L), sequenceValue);
                            }
                        }
                        statement.execute(String.format("DROP SCHEMA IF EXISTS %s CASCADE", extraSchemaName));
                    } catch (SQLException e) {
                        fail(e.getMessage());
                    }
                    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<String> sqlLines = Files.readAllLines(output.toPath(), Charset.defaultCharset());
        assertEquals(2, sqlLines.stream().filter(s -> s.equalsIgnoreCase("create sequence SEQ_TEST start 1 increment 1")).count());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr1);
    }
}
Also used : JdbcEnvironmentInitiator(org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) SQLException(java.sql.SQLException) Statement(java.sql.Statement) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) IOException(java.io.IOException) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider) DdlTransactionIsolatorTestingImpl(org.hibernate.test.util.DdlTransactionIsolatorTestingImpl) ResultSet(java.sql.ResultSet) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 93 with MetadataImplementor

use of org.hibernate.boot.spi.MetadataImplementor in project hibernate-orm by hibernate.

the class NumericValidationTest method testValidation.

@Test
public void testValidation() {
    MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addAnnotatedClass(TestEntity.class).buildMetadata();
    metadata.validate();
    // create the schema
    createSchema(metadata);
    try {
        doValidation(metadata);
    } finally {
        dropSchema(metadata);
    }
}
Also used : MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) Test(org.junit.Test)

Example 94 with MetadataImplementor

use of org.hibernate.boot.spi.MetadataImplementor in project hibernate-orm by hibernate.

the class CrossSchemaForeignKeyGenerationTest method testSchemaMigrationForeignKeysAreGeneratedAfterAllTheTablesAreCreated.

@Test
@TestForIssue(jiraKey = "HHH-10420")
public void testSchemaMigrationForeignKeysAreGeneratedAfterAllTheTablesAreCreated() throws Exception {
    final MetadataSources metadataSources = new MetadataSources(ssr);
    metadataSources.addAnnotatedClass(SchemaOneEntity.class);
    metadataSources.addAnnotatedClass(SchemaTwoEntity.class);
    MetadataImplementor metadata = (MetadataImplementor) metadataSources.buildMetadata();
    metadata.validate();
    final Database database = metadata.getDatabase();
    final HibernateSchemaManagementTool tool = (HibernateSchemaManagementTool) ssr.getService(SchemaManagementTool.class);
    final Map configurationValues = ssr.getService(ConfigurationService.class).getSettings();
    final ExecutionOptions options = new ExecutionOptions() {

        @Override
        public boolean shouldManageNamespaces() {
            return true;
        }

        @Override
        public Map getConfigurationValues() {
            return configurationValues;
        }

        @Override
        public ExceptionHandler getExceptionHandler() {
            return ExceptionHandlerLoggedImpl.INSTANCE;
        }
    };
    new IndividuallySchemaMigratorImpl(tool, DefaultSchemaFilter.INSTANCE).doMigration(metadata, options, TargetDescriptorImpl.INSTANCE);
    new IndividuallySchemaMigratorImpl(tool, DefaultSchemaFilter.INSTANCE).doMigration(metadata, options, TargetDescriptorImpl.INSTANCE);
    new SchemaDropperImpl(tool).doDrop(metadata, options, ssr.getService(JdbcEnvironment.class).getDialect(), new SourceDescriptor() {

        @Override
        public SourceType getSourceType() {
            return SourceType.METADATA;
        }

        @Override
        public ScriptSourceInput getScriptSourceInput() {
            return null;
        }
    }, buildTargets());
}
Also used : HibernateSchemaManagementTool(org.hibernate.tool.schema.internal.HibernateSchemaManagementTool) SchemaManagementTool(org.hibernate.tool.schema.spi.SchemaManagementTool) SourceDescriptor(org.hibernate.tool.schema.spi.SourceDescriptor) ScriptSourceInput(org.hibernate.tool.schema.spi.ScriptSourceInput) SourceType(org.hibernate.tool.schema.SourceType) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) HibernateSchemaManagementTool(org.hibernate.tool.schema.internal.HibernateSchemaManagementTool) ExecutionOptions(org.hibernate.tool.schema.spi.ExecutionOptions) SchemaDropperImpl(org.hibernate.tool.schema.internal.SchemaDropperImpl) Database(org.hibernate.boot.model.relational.Database) ConfigurationService(org.hibernate.engine.config.spi.ConfigurationService) Map(java.util.Map) IndividuallySchemaMigratorImpl(org.hibernate.tool.schema.internal.IndividuallySchemaMigratorImpl) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 95 with MetadataImplementor

use of org.hibernate.boot.spi.MetadataImplementor in project hibernate-orm by hibernate.

the class SchemaUpdateGeneratingOnlyScriptFileTest method testSchemaUpdateScriptGeneration.

@Test
public void testSchemaUpdateScriptGeneration() throws Exception {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(Environment.HBM2DDL_AUTO, "none").build();
    try {
        File output = File.createTempFile("update_script", ".sql");
        output.deleteOnExit();
        final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addAnnotatedClass(TestEntity.class).buildMetadata();
        metadata.validate();
        new SchemaUpdate().setHaltOnError(true).setOutputFile(output.getAbsolutePath()).setDelimiter(";").setFormat(true).execute(EnumSet.of(TargetType.SCRIPT), metadata);
        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);
    }
}
Also used : Pattern(java.util.regex.Pattern) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Matcher(java.util.regex.Matcher) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) File(java.io.File) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) Test(org.junit.Test)

Aggregations

MetadataImplementor (org.hibernate.boot.spi.MetadataImplementor)113 MetadataSources (org.hibernate.boot.MetadataSources)80 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)62 Test (org.junit.Test)56 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)52 SimpleValue (org.hibernate.mapping.SimpleValue)32 RootClass (org.hibernate.mapping.RootClass)31 PersistentClass (org.hibernate.mapping.PersistentClass)27 TestForIssue (org.hibernate.testing.TestForIssue)26 Table (org.hibernate.mapping.Table)23 Test (org.junit.jupiter.api.Test)23 SchemaExport (org.hibernate.tool.hbm2ddl.SchemaExport)22 SchemaUpdate (org.hibernate.tool.hbm2ddl.SchemaUpdate)20 Column (org.hibernate.mapping.Column)17 ArrayList (java.util.ArrayList)15 ServiceRegistry (org.hibernate.service.ServiceRegistry)15 File (java.io.File)14 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)14 Configuration (org.hibernate.cfg.Configuration)12 Property (org.hibernate.mapping.Property)11