Search in sources :

Example 16 with Dialect

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

the class AbstractSharedSessionContract method remapSqlTypeDescriptor.

@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (!sqlTypeDescriptor.canBeRemapped()) {
        return sqlTypeDescriptor;
    }
    final Dialect dialect = getJdbcServices().getJdbcEnvironment().getDialect();
    final SqlTypeDescriptor remapped = dialect.remapSqlTypeDescriptor(sqlTypeDescriptor);
    return remapped == null ? sqlTypeDescriptor : remapped;
}
Also used : SqlTypeDescriptor(org.hibernate.type.descriptor.sql.SqlTypeDescriptor) Dialect(org.hibernate.dialect.Dialect)

Example 17 with Dialect

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

the class Loader method prepareQueryStatement.

/**
	 * Obtain a <tt>PreparedStatement</tt> with all parameters pre-bound.
	 * Bind JDBC-style <tt>?</tt> parameters, named parameters, and
	 * limit parameters.
	 */
protected final PreparedStatement prepareQueryStatement(String sql, final QueryParameters queryParameters, final LimitHandler limitHandler, final boolean scroll, final SharedSessionContractImplementor session) throws SQLException, HibernateException {
    final Dialect dialect = getFactory().getDialect();
    final RowSelection selection = queryParameters.getRowSelection();
    final boolean useLimit = LimitHelper.useLimit(limitHandler, selection);
    final boolean hasFirstRow = LimitHelper.hasFirstRow(selection);
    final boolean useLimitOffset = hasFirstRow && useLimit && limitHandler.supportsLimitOffset();
    final boolean callable = queryParameters.isCallable();
    final ScrollMode scrollMode = getScrollMode(scroll, hasFirstRow, useLimitOffset, queryParameters);
    PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareQueryStatement(sql, callable, scrollMode);
    try {
        int col = 1;
        //TODO: can we limit stored procedures ?!
        col += limitHandler.bindLimitParametersAtStartOfQuery(selection, st, col);
        if (callable) {
            col = dialect.registerResultSetOutParameter((CallableStatement) st, col);
        }
        col += bindParameterValues(st, queryParameters, col, session);
        col += limitHandler.bindLimitParametersAtEndOfQuery(selection, st, col);
        limitHandler.setMaxRows(selection, st);
        if (selection != null) {
            if (selection.getTimeout() != null) {
                st.setQueryTimeout(selection.getTimeout());
            }
            if (selection.getFetchSize() != null) {
                st.setFetchSize(selection.getFetchSize());
            }
        }
        // handle lock timeout...
        LockOptions lockOptions = queryParameters.getLockOptions();
        if (lockOptions != null) {
            if (lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER) {
                if (!dialect.supportsLockTimeouts()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debugf("Lock timeout [%s] requested but dialect reported to not support lock timeouts", lockOptions.getTimeOut());
                    }
                } else if (dialect.isLockTimeoutParameterized()) {
                    st.setInt(col++, lockOptions.getTimeOut());
                }
            }
        }
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Bound [{0}] parameters total", col);
        }
    } catch (SQLException | HibernateException e) {
        session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(st);
        session.getJdbcCoordinator().afterStatementExecution();
        throw e;
    }
    return st;
}
Also used : ScrollMode(org.hibernate.ScrollMode) LockOptions(org.hibernate.LockOptions) SQLException(java.sql.SQLException) HibernateException(org.hibernate.HibernateException) CallableStatement(java.sql.CallableStatement) Dialect(org.hibernate.dialect.Dialect) PreparedStatement(java.sql.PreparedStatement) RowSelection(org.hibernate.engine.spi.RowSelection)

Example 18 with Dialect

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

the class UnionSubclassEntityPersister method generateSubquery.

protected String generateSubquery(PersistentClass model, Mapping mapping) {
    Dialect dialect = getFactory().getDialect();
    Settings settings = getFactory().getSettings();
    if (!model.hasSubclasses()) {
        return model.getTable().getQualifiedName(dialect, settings.getDefaultCatalogName(), settings.getDefaultSchemaName());
    }
    HashSet columns = new LinkedHashSet();
    Iterator titer = model.getSubclassTableClosureIterator();
    while (titer.hasNext()) {
        Table table = (Table) titer.next();
        if (!table.isAbstractUnionTable()) {
            Iterator citer = table.getColumnIterator();
            while (citer.hasNext()) {
                columns.add(citer.next());
            }
        }
    }
    StringBuilder buf = new StringBuilder().append("( ");
    Iterator siter = new JoinedIterator(new SingletonIterator(model), model.getSubclassIterator());
    while (siter.hasNext()) {
        PersistentClass clazz = (PersistentClass) siter.next();
        Table table = clazz.getTable();
        if (!table.isAbstractUnionTable()) {
            //TODO: move to .sql package!!
            buf.append("select ");
            Iterator citer = columns.iterator();
            while (citer.hasNext()) {
                Column col = (Column) citer.next();
                if (!table.containsColumn(col)) {
                    int sqlType = col.getSqlTypeCode(mapping);
                    buf.append(dialect.getSelectClauseNullString(sqlType)).append(" as ");
                }
                buf.append(col.getQuotedName(dialect));
                buf.append(", ");
            }
            buf.append(clazz.getSubclassId()).append(" as clazz_");
            buf.append(" from ").append(table.getQualifiedName(dialect, settings.getDefaultCatalogName(), settings.getDefaultSchemaName()));
            buf.append(" union ");
            if (dialect.supportsUnionAll()) {
                buf.append("all ");
            }
        }
    }
    if (buf.length() > 2) {
        //chop the last union (all)
        buf.setLength(buf.length() - (dialect.supportsUnionAll() ? 11 : 7));
    }
    return buf.append(" )").toString();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Table(org.hibernate.mapping.Table) Column(org.hibernate.mapping.Column) SingletonIterator(org.hibernate.internal.util.collections.SingletonIterator) Dialect(org.hibernate.dialect.Dialect) JoinedIterator(org.hibernate.internal.util.collections.JoinedIterator) Iterator(java.util.Iterator) SingletonIterator(org.hibernate.internal.util.collections.SingletonIterator) Settings(org.hibernate.cfg.Settings) JoinedIterator(org.hibernate.internal.util.collections.JoinedIterator) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 19 with Dialect

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

the class QueryParameterBindingsImpl method expandListValuedParameters.

/**
	 * @deprecated (since 5.2) expected changes to "collection-valued parameter binding" in 6.0
	 */
@Deprecated
@SuppressWarnings("unchecked")
public String expandListValuedParameters(String queryString, SharedSessionContractImplementor session) {
    if (queryString == null) {
        return null;
    }
    // more-or-less... for each entry in parameterListBindingMap we will create an
    //		entry in parameterBindingMap for each of the values in the bound value list.  afterwards
    //		we will clear the parameterListBindingMap.
    //
    // NOTE that this is essentially the legacy logical prior to modeling QueryParameterBinding/QueryParameterListBinding.
    // 		Fully expect the details of how this is handled in 6.0
    // HHH-1123
    // Some DBs limit number of IN expressions.  For now, warn...
    final Dialect dialect = session.getFactory().getServiceRegistry().getService(JdbcServices.class).getJdbcEnvironment().getDialect();
    final int inExprLimit = dialect.getInExpressionCountLimit();
    for (Map.Entry<QueryParameter, QueryParameterListBinding> entry : parameterListBindingMap.entrySet()) {
        final NamedParameterDescriptor sourceParam = (NamedParameterDescriptor) entry.getKey();
        final Collection bindValues = entry.getValue().getBindValues();
        if (inExprLimit > 0 && bindValues.size() > inExprLimit) {
            log.tooManyInExpressions(dialect.getClass().getName(), inExprLimit, sourceParam.getName(), bindValues.size());
        }
        final boolean isJpaPositionalParam = sourceParam.isJpaPositionalParameter();
        final String paramPrefix = isJpaPositionalParam ? "?" : ParserHelper.HQL_VARIABLE_PREFIX;
        final String placeholder = paramPrefix + sourceParam.getName();
        final int loc = queryString.indexOf(placeholder);
        if (loc < 0) {
            continue;
        }
        final String beforePlaceholder = queryString.substring(0, loc);
        final String afterPlaceholder = queryString.substring(loc + placeholder.length());
        // check if placeholder is already immediately enclosed in parentheses
        // (ignoring whitespace)
        boolean isEnclosedInParens = StringHelper.getLastNonWhitespaceCharacter(beforePlaceholder) == '(' && StringHelper.getFirstNonWhitespaceCharacter(afterPlaceholder) == ')';
        if (bindValues.size() == 1 && isEnclosedInParens) {
            // short-circuit for performance when only 1 value and the
            // placeholder is already enclosed in parentheses...
            final QueryParameterBinding syntheticBinding = makeBinding(entry.getValue().getBindType());
            syntheticBinding.setBindValue(bindValues.iterator().next());
            parameterBindingMap.put(sourceParam, syntheticBinding);
            continue;
        }
        StringBuilder expansionList = new StringBuilder();
        int i = 0;
        for (Object bindValue : entry.getValue().getBindValues()) {
            // for each value in the bound list-of-values we:
            //		1) create a synthetic named parameter
            //		2) expand the queryString to include each synthetic named param in place of the original
            //		3) create a new synthetic binding for just that single value under the synthetic name
            final String syntheticName = (isJpaPositionalParam ? 'x' : "") + sourceParam.getName() + '_' + i;
            if (i > 0) {
                expansionList.append(", ");
            }
            expansionList.append(ParserHelper.HQL_VARIABLE_PREFIX).append(syntheticName);
            final QueryParameter syntheticParam = new QueryParameterNamedImpl<>(syntheticName, sourceParam.getSourceLocations(), sourceParam.isJpaPositionalParameter(), sourceParam.getType());
            final QueryParameterBinding syntheticBinding = makeBinding(entry.getValue().getBindType());
            syntheticBinding.setBindValue(bindValue);
            parameterBindingMap.put(syntheticParam, syntheticBinding);
            i++;
        }
        queryString = StringHelper.replace(beforePlaceholder, afterPlaceholder, placeholder, expansionList.toString(), true, true);
    }
    return queryString;
}
Also used : QueryParameter(org.hibernate.query.QueryParameter) QueryParameterBinding(org.hibernate.query.spi.QueryParameterBinding) QueryParameterListBinding(org.hibernate.query.spi.QueryParameterListBinding) Dialect(org.hibernate.dialect.Dialect) Collection(java.util.Collection) NamedParameterDescriptor(org.hibernate.engine.query.spi.NamedParameterDescriptor) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 20 with Dialect

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

the class SchemaCreatorImpl method generateCreationCommands.

/**
	 * For testing...
	 *
	 * @param metadata The metadata for which to generate the creation commands.
	 *
	 * @return The generation commands
	 */
public List<String> generateCreationCommands(Metadata metadata, final boolean manageNamespaces) {
    final JournalingGenerationTarget target = new JournalingGenerationTarget();
    final ServiceRegistry serviceRegistry = ((MetadataImplementor) metadata).getMetadataBuildingOptions().getServiceRegistry();
    final Dialect dialect = serviceRegistry.getService(JdbcEnvironment.class).getDialect();
    final ExecutionOptions options = new ExecutionOptions() {

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

        @Override
        public Map getConfigurationValues() {
            return Collections.emptyMap();
        }

        @Override
        public ExceptionHandler getExceptionHandler() {
            return ExceptionHandlerHaltImpl.INSTANCE;
        }
    };
    createFromMetadata(metadata, options, dialect, FormatStyle.NONE.getFormatter(), target);
    return target.commands;
}
Also used : ExecutionOptions(org.hibernate.tool.schema.spi.ExecutionOptions) Dialect(org.hibernate.dialect.Dialect) ServiceRegistry(org.hibernate.service.ServiceRegistry) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)

Aggregations

Dialect (org.hibernate.dialect.Dialect)45 HibernateException (org.hibernate.HibernateException)9 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)7 PostgreSQL81Dialect (org.hibernate.dialect.PostgreSQL81Dialect)4 RowSelection (org.hibernate.engine.spi.RowSelection)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)4 Connection (java.sql.Connection)3 SQLException (java.sql.SQLException)3 Iterator (java.util.Iterator)3 Map (java.util.Map)3 H2Dialect (org.hibernate.dialect.H2Dialect)3 DialectResolutionInfo (org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo)3 Column (org.hibernate.mapping.Column)3 SpatialDialect (org.hibernate.spatial.SpatialDialect)3 AuditEventRecord (com.evolveum.midpoint.audit.api.AuditEventRecord)2 AuditEventStage (com.evolveum.midpoint.audit.api.AuditEventStage)2 AuditEventType (com.evolveum.midpoint.audit.api.AuditEventType)2 AuditResultHandler (com.evolveum.midpoint.audit.api.AuditResultHandler)2 AuditService (com.evolveum.midpoint.audit.api.AuditService)2 PrismObject (com.evolveum.midpoint.prism.PrismObject)2