Search in sources :

Example 1 with SchemaUpdate

use of org.hibernate.tool.hbm2ddl.SchemaUpdate in project midpoint by Evolveum.

the class OrgClosureManager method autoUpdateClosureTableStructure.

// TEMPORARY and quite BRUTAL HACK
// Originally in midPoint 3.0, m_org_closure has 5 columns, a non-null ID among them.
// In 3.1, it has 3, and no ID. Unfortunately, hibernate's hbm2ddl tool does not automatically remove ID column,
// so people can expect quite hard-to-understand error messages when running midPoint after upgrade.
//
// This code removes and re-creates the m_org_closure table if hbm2ddl is set to "update".
//
// returns true if the table was re-created
private boolean autoUpdateClosureTableStructure() {
    if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) {
        LOGGER.debug("Skipping org closure structure check.");
        return false;
    }
    SessionFactory sf = baseHelper.getSessionFactory();
    if (sf instanceof SessionFactoryImpl) {
        SessionFactoryImpl sfi = ((SessionFactoryImpl) sf);
        LOGGER.debug("SessionFactoryImpl.getSettings() = {}; auto update schema = {}", sfi.getSettings(), sfi.getSettings() != null ? sfi.getSettings().isAutoUpdateSchema() : null);
        if (sfi.getSettings() != null && sfi.getSettings().isAutoUpdateSchema()) {
            LOGGER.info("Checking the closure table structure.");
            final Session session = baseHelper.getSessionFactory().openSession();
            final Holder<Boolean> wrongNumberOfColumns = new Holder<>(false);
            session.doWork(new Work() {

                @Override
                public void execute(Connection connection) throws SQLException {
                    DatabaseMetaData meta = connection.getMetaData();
                    if (meta == null) {
                        LOGGER.warn("No database metadata found.");
                    } else {
                        ResultSet rsColumns = meta.getColumns(null, null, CLOSURE_TABLE_NAME, null);
                        int columns = 0;
                        while (rsColumns.next()) {
                            LOGGER.debug("Column: {} {}", rsColumns.getString("TYPE_NAME"), rsColumns.getString("COLUMN_NAME"));
                            columns++;
                        }
                        if (columns > 0) {
                            LOGGER.debug("There are {} columns in {} (obtained via DatabaseMetaData)", columns, CLOSURE_TABLE_NAME);
                            if (columns != 3) {
                                wrongNumberOfColumns.setValue(true);
                            }
                            return;
                        }
                        // perhaps some problem here... let's try another way out
                        try {
                            Statement stmt = connection.createStatement();
                            ResultSet rs = stmt.executeQuery("select * from " + CLOSURE_TABLE_NAME);
                            int cols = rs.getMetaData().getColumnCount();
                            if (cols > 0) {
                                LOGGER.debug("There are {} columns in {} (obtained via resultSet.getMetaData())", cols, CLOSURE_TABLE_NAME);
                                if (cols != 3) {
                                    wrongNumberOfColumns.setValue(true);
                                }
                            } else {
                                LOGGER.warn("Couldn't determine the number of columns in {}. In case of problems, please fix your database structure manually using DB scripts in 'config' folder.", CLOSURE_TABLE_NAME);
                            }
                            // don't care about closing them in case of failure
                            rs.close();
                            stmt.close();
                        } catch (RuntimeException e) {
                            LoggingUtils.logException(LOGGER, "Couldn't obtain the number of columns in {}. In case of problems running midPoint, please fix your database structure manually using DB scripts in 'config' folder.", e, CLOSURE_TABLE_NAME);
                        }
                    }
                }
            });
            if (wrongNumberOfColumns.getValue()) {
                session.getTransaction().begin();
                LOGGER.info("Wrong number of columns detected; dropping table " + CLOSURE_TABLE_NAME);
                Query q = session.createSQLQuery("drop table " + CLOSURE_TABLE_NAME);
                q.executeUpdate();
                session.getTransaction().commit();
                LOGGER.info("Calling hibernate hbm2ddl SchemaUpdate tool to create the table in the necessary form.");
                new SchemaUpdate(sfi.getServiceRegistry(), baseHelper.getSessionFactoryBean().getConfiguration()).execute(false, true);
                LOGGER.info("Done, table was (hopefully) created. If not, please fix your database structure manually using DB scripts in 'config' folder.");
                return true;
            }
        } else {
        // auto schema update is disabled
        }
    } else {
        LOGGER.warn("SessionFactory is not of type SessionFactoryImpl; it is {}", sf != null ? sf.getClass() : "null");
    }
    return false;
}
Also used : SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Holder(com.evolveum.midpoint.util.Holder) Connection(java.sql.Connection) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) DatabaseMetaData(java.sql.DatabaseMetaData) Work(org.hibernate.jdbc.Work) ResultSet(java.sql.ResultSet) SessionFactoryImpl(org.hibernate.internal.SessionFactoryImpl) Session(org.hibernate.Session)

Example 2 with SchemaUpdate

use of org.hibernate.tool.hbm2ddl.SchemaUpdate in project hibernate-orm by hibernate.

the class DisabledForeignKeyTest method expandedTests.

@Test
@TestForIssue(jiraKey = "HHH-9704")
public void expandedTests() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
    StandardServiceRegistry standardRegistry = registryBuilder.build();
    try {
        final MetadataSources sources = new MetadataSources(standardRegistry);
        sources.addAnnotatedClass(ManyToManyOwner.class);
        sources.addAnnotatedClass(ManyToManyTarget.class);
        final MetadataImplementor metadata = (MetadataImplementor) sources.buildMetadata();
        metadata.validate();
        // export 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().execute(EnumSet.of(TargetType.DATABASE), SchemaExport.Action.DROP, metadata);
        }
    } finally {
        StandardServiceRegistryBuilder.destroy(standardRegistry);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 3 with SchemaUpdate

use of org.hibernate.tool.hbm2ddl.SchemaUpdate in project hibernate-orm by hibernate.

the class SequenceReadingTest method testSequenceReading.

@Test
public void testSequenceReading() {
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.DIALECT, MyExtendedH2Dialect.class).build();
    try {
        final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addAnnotatedClass(MyEntity.class).buildMetadata();
        metadata.validate();
        try {
            // try to update the schema
            new SchemaUpdate().execute(EnumSet.of(TargetType.DATABASE), metadata);
        } finally {
            try {
                // clean up
                new SchemaExport().drop(EnumSet.of(TargetType.DATABASE), metadata);
            } catch (Exception ignore) {
            }
        }
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test)

Example 4 with SchemaUpdate

use of org.hibernate.tool.hbm2ddl.SchemaUpdate in project hibernate-orm by hibernate.

the class CommentGenerationTest method testSchemaUpdateScriptGeneration.

@Test
public void testSchemaUpdateScriptGeneration() throws Exception {
    final String resource = "org/hibernate/test/schemaupdate/CommentGeneration.hbm.xml";
    StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().applySetting(Environment.HBM2DDL_AUTO, "none").applySetting(Environment.DIALECT, SupportCommentDialect.class.getName()).build();
    try {
        File output = File.createTempFile("update_script", ".sql");
        output.deleteOnExit();
        final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(ssr).addResource(resource).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()));
        assertThat(fileContent.contains("comment on column version.description "), is(true));
    } finally {
        StandardServiceRegistryBuilder.destroy(ssr);
    }
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) 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)

Example 5 with SchemaUpdate

use of org.hibernate.tool.hbm2ddl.SchemaUpdate in project hibernate-orm by hibernate.

the class ConnectionsReleaseTest method testSchemaUpdateReleasesAllConnections.

@Test
public void testSchemaUpdateReleasesAllConnections() throws SQLException {
    new SchemaUpdate().execute(EnumSet.of(TargetType.DATABASE), metadata);
    assertThat(connectionProvider.getOpenConnection(), is(0));
}
Also used : SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) Test(org.junit.Test)

Aggregations

SchemaUpdate (org.hibernate.tool.hbm2ddl.SchemaUpdate)25 Test (org.junit.Test)23 MetadataSources (org.hibernate.boot.MetadataSources)20 MetadataImplementor (org.hibernate.boot.spi.MetadataImplementor)20 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)15 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)15 SchemaExport (org.hibernate.tool.hbm2ddl.SchemaExport)9 File (java.io.File)7 TestForIssue (org.hibernate.testing.TestForIssue)7 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 SchemaValidator (org.hibernate.tool.hbm2ddl.SchemaValidator)2 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)1 Holder (com.evolveum.midpoint.util.Holder)1 IOException (java.io.IOException)1 Connection (java.sql.Connection)1 DatabaseMetaData (java.sql.DatabaseMetaData)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Statement (java.sql.Statement)1