Search in sources :

Example 56 with Dialect

use of org.hibernate.dialect.Dialect in project xwiki-platform by xwiki.

the class XWikiHibernateStoreTest method createHibernateSequenceIfRequiredWhenNotInUpdateCommands.

@Test
public void createHibernateSequenceIfRequiredWhenNotInUpdateCommands() throws Exception {
    Session session = mock(Session.class);
    SessionFactoryImplementor sessionFactory = mock(SessionFactoryImplementor.class);
    Dialect dialect = mock(Dialect.class);
    when(session.getSessionFactory()).thenReturn(sessionFactory);
    when(sessionFactory.getDialect()).thenReturn(dialect);
    when(dialect.getNativeIdentifierGeneratorClass()).thenReturn(SequenceGenerator.class);
    SQLQuery sqlQuery = mock(SQLQuery.class);
    when(session.createSQLQuery("create sequence schema.hibernate_sequence")).thenReturn(sqlQuery);
    when(sqlQuery.executeUpdate()).thenReturn(0);
    this.store.createHibernateSequenceIfRequired(new String[] {}, "schema", session);
    verify(session).createSQLQuery("create sequence schema.hibernate_sequence");
    verify(sqlQuery).executeUpdate();
}
Also used : SessionFactoryImplementor(org.hibernate.engine.SessionFactoryImplementor) Dialect(org.hibernate.dialect.Dialect) SQLQuery(org.hibernate.SQLQuery) Session(org.hibernate.Session) Test(org.junit.Test)

Example 57 with Dialect

use of org.hibernate.dialect.Dialect in project xwiki-platform by xwiki.

the class XWikiHibernateBaseStore method createHibernateSequenceIfRequired.

/**
 * In the Hibernate mapping file for XWiki we use a "native" generator for some tables (deleted document and deleted
 * attachments for example - The reason we use generated ids and not custom computed ones is because we don't need
 * to address rows from these tables). For a lot of database the Dialect uses an Identity Generator (when the DB
 * supports it). PostgreSQL and Oracle don't support it and Hibernate defaults to a Sequence Generator which uses a
 * sequence named "hibernate_sequence" by default. Hibernate will normally create such a sequence automatically when
 * updating the schema (see #getSchemaUpdateScript). However the problem is that Hibernate maintains a cache of
 * sequence names per catalog and will only generate the sequence creation SQL if the sequence is not in this cache.
 * Since the main wiki is updated first the sequence named "hibernate_sequence" will be put in this cache, thus
 * preventing subwikis to automatically create sequence with the same name (see also
 * https://hibernate.atlassian.net/browse/HHH-1672). As a workaround, we create the required sequence here.
 *
 * @param schemaSQL the list of SQL commands to execute to update the schema, possibly containing the
 *            "hibernate_sequence" sequence creation
 * @param schemaName the schema name corresponding to the subwiki being updated
 * @param session the Hibernate session, used to get the Dialect object
 * @since 5.2RC1
 */
protected void createHibernateSequenceIfRequired(String[] schemaSQL, String schemaName, Session session) {
    // There's no issue when in database mode, only in schema mode.
    if (isInSchemaMode()) {
        Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect();
        if (dialect.getNativeIdentifierGeneratorClass().equals(SequenceGenerator.class)) {
            // We create the sequence only if it's not already in the SQL to execute as otherwise we would get an
            // error that the sequence already exists ("relation "hibernate_sequence" already exists").
            boolean hasSequence = false;
            String sequenceSQL = String.format("create sequence %s.hibernate_sequence", schemaName);
            for (String sql : schemaSQL) {
                if (sequenceSQL.equals(sql)) {
                    hasSequence = true;
                    break;
                }
            }
            if (!hasSequence) {
                // try to create the sequence and if it fails then we consider it already exists.
                try {
                    // Ignore errors in the log during the creation of the sequence since we know it can fail and we
                    // don't want to show false positives to the user.
                    this.loggerManager.pushLogListener(null);
                    session.createSQLQuery(sequenceSQL).executeUpdate();
                } catch (HibernateException e) {
                // Sequence failed to be created, we assume it already exists and that's why an exception was
                // raised!
                } finally {
                    this.loggerManager.popLogListener();
                }
            }
        }
    }
}
Also used : HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.SessionFactoryImplementor) Dialect(org.hibernate.dialect.Dialect)

Example 58 with Dialect

use of org.hibernate.dialect.Dialect in project xwiki-platform by xwiki.

the class AbstractDropNotNullDataMigration method getLiquibaseChangeLog.

@Override
public String getLiquibaseChangeLog() throws DataMigrationException {
    XWikiHibernateBaseStore store = getStore();
    Dialect dialect = store.getDialect();
    Configuration configuration = store.getConfiguration();
    Mapping mapping = configuration.buildMapping();
    PersistentClass pClass = configuration.getClassMapping(this.table.getName());
    Column column = ((Column) pClass.getProperty(this.property).getColumnIterator().next());
    String columnType = column.getSqlType(dialect, mapping);
    StringBuilder builder = new StringBuilder();
    builder.append("<changeSet author=\"xwiki\" id=\"R").append(this.getVersion().getVersion()).append("\">\n");
    builder.append("    <dropNotNullConstraint\n");
    builder.append("            columnDataType=\"").append(columnType).append('"').append('\n');
    builder.append("            columnName=\"").append(column.getName()).append('"').append('\n');
    builder.append("            tableName=\"").append(pClass.getTable().getName()).append("\"/>\n");
    builder.append("</changeSet>");
    return builder.toString();
}
Also used : Configuration(org.hibernate.cfg.Configuration) Column(org.hibernate.mapping.Column) Dialect(org.hibernate.dialect.Dialect) Mapping(org.hibernate.engine.Mapping) XWikiHibernateBaseStore(com.xpn.xwiki.store.XWikiHibernateBaseStore) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 59 with Dialect

use of org.hibernate.dialect.Dialect in project uPortal by Jasig.

the class DbTestImpl method printDbInfo.

@Override
public void printDbInfo() {
    boolean fail = false;
    logger.info("JDBC DataSources");
    for (final Entry<String, JdbcOperations> jdbcEntry : this.jdbcOperations.entrySet()) {
        final String jdbcName = jdbcEntry.getKey();
        try {
            logger.info("\t" + jdbcName);
            final JdbcOperations jdbcOps = jdbcEntry.getValue();
            jdbcOps.execute(new ConnectionCallback<Object>() {

                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    printInfo(con);
                    return null;
                }
            });
        } catch (Exception e) {
            logger.error("\t" + jdbcName + ": parse info", e);
            fail = true;
        }
        logger.info("");
    }
    logger.info("Hibernate Dialects");
    for (final Entry<String, HibernateConfiguration> configEntry : this.hibernateConfigurations.entrySet()) {
        final String persistenceUnit = configEntry.getKey();
        try {
            final HibernateConfiguration hibernateConfiguration = configEntry.getValue();
            final SessionFactoryImplementor sessionFactory = hibernateConfiguration.getSessionFactory();
            final Dialect dialect = sessionFactory.getDialect();
            logger.info("\t" + persistenceUnit + ": " + dialect);
        } catch (Exception e) {
            logger.error("\t" + persistenceUnit + ": Failed to resolve Dialect", e);
            fail = true;
        }
        logger.info("");
    }
    if (fail) {
        throw new RuntimeException("One or more of the portal data sources is not configured correctly or the target database is not available.");
    }
}
Also used : SQLException(java.sql.SQLException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Connection(java.sql.Connection) JdbcOperations(org.springframework.jdbc.core.JdbcOperations) DataAccessException(org.springframework.dao.DataAccessException) SQLException(java.sql.SQLException) Dialect(org.hibernate.dialect.Dialect) HibernateConfiguration(org.apereo.portal.hibernate.DelegatingHibernateIntegrator.HibernateConfiguration) DataAccessException(org.springframework.dao.DataAccessException)

Example 60 with Dialect

use of org.hibernate.dialect.Dialect in project hibernate-orm by hibernate.

the class JavaConstantNode method getRenderText.

@Override
@SuppressWarnings("unchecked")
public String getRenderText(SessionFactoryImplementor sessionFactory) {
    final Type type = expectedType == null ? heuristicType : Number.class.isAssignableFrom(heuristicType.getReturnedClass()) ? heuristicType : expectedType;
    try {
        if (LiteralType.class.isInstance(type)) {
            final LiteralType literalType = (LiteralType) type;
            final Dialect dialect = factory.getDialect();
            return literalType.objectToSQLString(constantValue, dialect);
        } else if (AttributeConverterTypeAdapter.class.isInstance(type)) {
            final AttributeConverterTypeAdapter converterType = (AttributeConverterTypeAdapter) type;
            if (!converterType.getModelType().isInstance(constantValue)) {
                throw new QueryException(String.format(Locale.ENGLISH, "Recognized query constant expression [%s] was not resolved to type [%s] expected by defined AttributeConverter [%s]", constantExpression, constantValue.getClass().getName(), converterType.getModelType().getName()));
            }
            final Object value = converterType.getAttributeConverter().toRelationalValue(constantValue);
            if (String.class.equals(converterType.getJdbcType())) {
                return "'" + value + "'";
            } else {
                return value.toString();
            }
        } else {
            throw new QueryException(String.format(Locale.ENGLISH, "Unrecognized Hibernate Type for handling query constant (%s); expecting LiteralType implementation or AttributeConverter", constantExpression));
        }
    } catch (QueryException e) {
        throw e;
    } catch (Exception t) {
        throw new QueryException(QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t);
    }
}
Also used : LiteralType(org.hibernate.type.LiteralType) Type(org.hibernate.type.Type) QueryException(org.hibernate.QueryException) Dialect(org.hibernate.dialect.Dialect) LiteralType(org.hibernate.type.LiteralType) AttributeConverterTypeAdapter(org.hibernate.type.descriptor.converter.AttributeConverterTypeAdapter) QueryException(org.hibernate.QueryException)

Aggregations

Dialect (org.hibernate.dialect.Dialect)80 DialectFactory (org.hibernate.engine.jdbc.dialect.spi.DialectFactory)19 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)18 Column (org.hibernate.mapping.Column)14 SQLException (java.sql.SQLException)13 DialectResolutionInfo (org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo)12 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)12 Configuration (org.hibernate.cfg.Configuration)11 ServiceRegistry (org.hibernate.service.ServiceRegistry)11 Properties (java.util.Properties)10 HibernateException (org.hibernate.HibernateException)10 IConfiguration (org.jboss.tools.hibernate.runtime.spi.IConfiguration)10 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)9 DatabaseMetaDataDialectResolutionInfoAdapter (org.hibernate.engine.jdbc.dialect.spi.DatabaseMetaDataDialectResolutionInfoAdapter)9 DialectResolutionInfoSource (org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfoSource)9 HibernateException (org.jboss.tools.hibernate.runtime.spi.HibernateException)9 MetaDataDialect (org.hibernate.cfg.reveng.dialect.MetaDataDialect)8 Test (org.junit.jupiter.api.Test)8 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6