use of org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl in project hibernate-orm by hibernate.
the class AbstractCollectionPersister method selectFragment.
/**
* Generate a list of collection index, key and element columns
*/
@Override
public String selectFragment(String alias, String columnSuffix) {
final PluralAttributeMapping attributeMapping = getAttributeMapping();
final QuerySpec rootQuerySpec = new QuerySpec(true);
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), LockOptions.NONE, (fetchParent, querySpec, creationState) -> new ArrayList<>(), true, getFactory());
final NavigablePath entityPath = new NavigablePath(attributeMapping.getRootPathName());
final TableGroup rootTableGroup = attributeMapping.createRootTableGroup(true, entityPath, null, () -> p -> {
}, new SqlAliasBaseConstant(alias), sqlAstCreationState.getSqlExpressionResolver(), sqlAstCreationState.getFromClauseAccess(), getFactory());
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
attributeMapping.createDomainResult(entityPath, rootTableGroup, null, sqlAstCreationState);
// Wrap expressions with aliases
final SelectClause selectClause = rootQuerySpec.getSelectClause();
final java.util.List<SqlSelection> sqlSelections = selectClause.getSqlSelections();
int i = 0;
for (String keyAlias : keyColumnAliases) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), keyAlias + columnSuffix)));
i++;
}
if (hasIndex) {
for (String indexAlias : indexColumnAliases) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), indexAlias + columnSuffix)));
i++;
}
}
if (hasIdentifier) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), identifierColumnAlias + columnSuffix)));
i++;
}
for (int columnIndex = 0; i < sqlSelections.size(); i++, columnIndex++) {
final SqlSelection sqlSelection = sqlSelections.get(i);
sqlSelections.set(i, new SqlSelectionImpl(sqlSelection.getValuesArrayPosition(), sqlSelection.getJdbcResultSetIndex(), new AliasedExpression(sqlSelection.getExpression(), elementColumnAliases[columnIndex] + columnSuffix)));
}
final String sql = getFactory().getJdbcServices().getDialect().getSqlAstTranslatorFactory().buildSelectTranslator(getFactory(), new SelectStatement(rootQuerySpec)).translate(null, QueryOptions.NONE).getSql();
final int fromIndex = sql.lastIndexOf(" from");
final String expression;
if (fromIndex != -1) {
expression = sql.substring("select ".length(), fromIndex);
} else {
expression = sql.substring("select ".length());
}
return expression;
}
use of org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl in project hibernate-orm by hibernate.
the class LoaderSelectBuilder method generateSelect.
private SelectStatement generateSelect() {
if (loadable instanceof PluralAttributeMapping) {
final PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) loadable;
if (pluralAttributeMapping.getMappedType().getCollectionSemantics() instanceof BagSemantics) {
currentBagRole = pluralAttributeMapping.getNavigableRole().getNavigableName();
}
}
final NavigablePath rootNavigablePath = new NavigablePath(loadable.getRootPathName());
final QuerySpec rootQuerySpec = new QuerySpec(true);
final List<DomainResult<?>> domainResults;
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), lockOptions, this::visitFetches, forceIdentifierSelection, creationContext);
final TableGroup rootTableGroup = loadable.createRootTableGroup(true, rootNavigablePath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, creationContext);
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(rootNavigablePath, rootTableGroup);
registerPluralTableGroupParts(sqlAstCreationState.getFromClauseAccess(), rootTableGroup);
if (partsToSelect != null && !partsToSelect.isEmpty()) {
domainResults = new ArrayList<>(partsToSelect.size());
for (ModelPart part : partsToSelect) {
final NavigablePath navigablePath = rootNavigablePath.append(part.getPartName());
final TableGroup tableGroup;
if (part instanceof TableGroupJoinProducer) {
final TableGroupJoinProducer tableGroupJoinProducer = (TableGroupJoinProducer) part;
final TableGroupJoin tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin(navigablePath, rootTableGroup, null, SqlAstJoinType.LEFT, true, false, sqlAstCreationState);
rootTableGroup.addTableGroupJoin(tableGroupJoin);
tableGroup = tableGroupJoin.getJoinedGroup();
sqlAstCreationState.getFromClauseAccess().registerTableGroup(navigablePath, tableGroup);
registerPluralTableGroupParts(sqlAstCreationState.getFromClauseAccess(), tableGroup);
} else {
tableGroup = rootTableGroup;
}
domainResults.add(part.createDomainResult(navigablePath, tableGroup, null, sqlAstCreationState));
}
} else {
// use the one passed to the constructor or create one (maybe always create and pass?)
// allows re-use as they can be re-used to save on memory - they
// do not share state between
// noinspection rawtypes
final DomainResult domainResult;
if (this.cachedDomainResult != null) {
// used the one passed to the constructor
domainResult = this.cachedDomainResult;
} else {
// create one
domainResult = loadable.createDomainResult(rootNavigablePath, rootTableGroup, null, sqlAstCreationState);
}
// noinspection unchecked
domainResults = Collections.singletonList(domainResult);
}
for (ModelPart restrictedPart : restrictedParts) {
final int numberOfRestrictionColumns = restrictedPart.getJdbcTypeCount();
applyRestriction(rootQuerySpec, rootNavigablePath, rootTableGroup, restrictedPart, numberOfRestrictionColumns, jdbcParameterConsumer, sqlAstCreationState);
}
if (loadable instanceof PluralAttributeMapping) {
final PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) loadable;
applyFiltering(rootQuerySpec, rootTableGroup, pluralAttributeMapping, sqlAstCreationState);
applyOrdering(rootTableGroup, pluralAttributeMapping);
} else {
applyFiltering(rootQuerySpec, rootTableGroup, (Restrictable) loadable, sqlAstCreationState);
}
if (orderByFragments != null) {
orderByFragments.forEach(entry -> entry.getKey().apply(rootQuerySpec, entry.getValue(), sqlAstCreationState));
}
return new SelectStatement(rootQuerySpec, domainResults);
}
use of org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl in project hibernate-orm by hibernate.
the class AbstractEntityPersister method selectFragment.
@Override
public String selectFragment(String alias, String suffix) {
final QuerySpec rootQuerySpec = new QuerySpec(true);
final String rootTableName = getRootTableName();
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), LockOptions.NONE, (fetchParent, querySpec, creationState) -> {
final List<Fetch> fetches = new ArrayList<>();
fetchParent.getReferencedMappingContainer().visitFetchables(fetchable -> {
// Ignore plural attributes
if (fetchable instanceof PluralAttributeMapping) {
return;
}
FetchTiming fetchTiming = fetchable.getMappedFetchOptions().getTiming();
final boolean selectable;
if (fetchable instanceof StateArrayContributorMapping) {
final int propertyNumber = ((StateArrayContributorMapping) fetchable).getStateArrayPosition();
final int tableNumber = getSubclassPropertyTableNumber(propertyNumber);
selectable = !isSubclassTableSequentialSelect(tableNumber) && propertySelectable[propertyNumber];
} else {
selectable = true;
}
if (fetchable instanceof BasicValuedModelPart) {
// Ignore lazy basic columns
if (fetchTiming == FetchTiming.DELAYED) {
return;
}
} else if (fetchable instanceof Association) {
final Association association = (Association) fetchable;
// Ignore the fetchable if the FK is on the other side
if (association.getSideNature() == ForeignKeyDescriptor.Nature.TARGET) {
return;
}
// Ensure the FK comes from the root table
if (!rootTableName.equals(association.getForeignKeyDescriptor().getKeyTable())) {
return;
}
fetchTiming = FetchTiming.DELAYED;
}
if (selectable) {
final NavigablePath navigablePath = fetchParent.resolveNavigablePath(fetchable);
final Fetch fetch = fetchParent.generateFetchableFetch(fetchable, navigablePath, fetchTiming, true, null, creationState);
fetches.add(fetch);
}
}, null);
return fetches;
}, true, getFactory());
final NavigablePath entityPath = new NavigablePath(getRootPathName());
final TableGroup rootTableGroup = createRootTableGroup(true, entityPath, null, () -> p -> {
}, new SqlAliasBaseConstant(alias), sqlAstCreationState.getSqlExpressionResolver(), sqlAstCreationState.getFromClauseAccess(), getFactory());
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
createDomainResult(entityPath, rootTableGroup, null, sqlAstCreationState);
// Wrap expressions with aliases
final SelectClause selectClause = rootQuerySpec.getSelectClause();
final List<SqlSelection> sqlSelections = selectClause.getSqlSelections();
int i = 0;
for (String identifierAlias : identifierAliases) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), identifierAlias + suffix)));
i++;
}
if (entityMetamodel.hasSubclasses()) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), getDiscriminatorAlias() + suffix)));
i++;
}
if (hasRowId()) {
sqlSelections.set(i, new SqlSelectionImpl(i, i + 1, new AliasedExpression(sqlSelections.get(i).getExpression(), ROWID_ALIAS + suffix)));
i++;
}
final String[] columnAliases = getSubclassColumnAliasClosure();
final String[] formulaAliases = getSubclassFormulaAliasClosure();
int columnIndex = 0;
int formulaIndex = 0;
for (; i < sqlSelections.size(); i++) {
final SqlSelection sqlSelection = sqlSelections.get(i);
final ColumnReference columnReference = (ColumnReference) sqlSelection.getExpression();
final String selectAlias;
if (!columnReference.isColumnExpressionFormula()) {
// Skip over columns that are not selectable like in the fetch generation
while (!subclassColumnSelectableClosure[columnIndex]) {
columnIndex++;
}
selectAlias = columnAliases[columnIndex++] + suffix;
} else {
selectAlias = formulaAliases[formulaIndex++] + suffix;
}
sqlSelections.set(i, new SqlSelectionImpl(sqlSelection.getValuesArrayPosition(), sqlSelection.getJdbcResultSetIndex(), new AliasedExpression(sqlSelection.getExpression(), selectAlias)));
}
final String sql = getFactory().getJdbcServices().getDialect().getSqlAstTranslatorFactory().buildSelectTranslator(getFactory(), new SelectStatement(rootQuerySpec)).translate(null, QueryOptions.NONE).getSql();
final int fromIndex = sql.lastIndexOf(" from");
final String expression;
if (fromIndex != -1) {
expression = sql.substring("select ".length(), fromIndex);
} else {
expression = sql.substring("select ".length());
}
return expression;
}
use of org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl in project hibernate-orm by hibernate.
the class LoaderSelectBuilder method generateSelect.
private SelectStatement generateSelect(SubselectFetch subselect) {
assert loadable instanceof PluralAttributeMapping;
final PluralAttributeMapping attributeMapping = (PluralAttributeMapping) loadable;
final QuerySpec rootQuerySpec = new QuerySpec(true);
final NavigablePath rootNavigablePath = new NavigablePath(loadable.getRootPathName());
// We need to initialize the acronymMap based on subselect.getLoadingSqlAst() to avoid alias collisions
final Map<String, TableReference> tableReferences = AliasCollector.getTableReferences(subselect.getLoadingSqlAst());
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(tableReferences.keySet()), new SimpleFromClauseAccessImpl(), lockOptions, this::visitFetches, numberOfKeysToLoad > 1, creationContext);
final TableGroup rootTableGroup = loadable.createRootTableGroup(true, rootNavigablePath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, creationContext);
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(rootNavigablePath, rootTableGroup);
registerPluralTableGroupParts(sqlAstCreationState.getFromClauseAccess(), rootTableGroup);
// generate and apply the restriction
applySubSelectRestriction(rootQuerySpec, rootNavigablePath, rootTableGroup, subselect, sqlAstCreationState);
// NOTE : no need to check - we are explicitly processing a plural-attribute
applyFiltering(rootQuerySpec, rootTableGroup, attributeMapping, sqlAstCreationState);
applyOrdering(rootTableGroup, attributeMapping);
return new SelectStatement(rootQuerySpec, List.of(new CollectionDomainResult(rootNavigablePath, attributeMapping, null, rootTableGroup, sqlAstCreationState)));
}
use of org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl in project hibernate-orm by hibernate.
the class AbstractNaturalIdLoader method selectByNaturalId.
/**
* Perform a select, restricted by natural-id, based on `domainResultProducer` and `fetchProcessor`
*/
protected <L> L selectByNaturalId(Object bindValue, NaturalIdLoadOptions options, BiFunction<TableGroup, LoaderSqlAstCreationState, DomainResult<?>> domainResultProducer, LoaderSqlAstCreationState.FetchProcessor fetchProcessor, Function<Boolean, Long> statementStartHandler, BiConsumer<Object, Long> statementCompletionHandler, SharedSessionContractImplementor session) {
final SessionFactoryImplementor sessionFactory = session.getFactory();
final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
final LockOptions lockOptions;
if (options.getLockOptions() != null) {
lockOptions = options.getLockOptions();
} else {
lockOptions = LockOptions.NONE;
}
final NavigablePath entityPath = new NavigablePath(entityDescriptor.getRootPathName());
final QuerySpec rootQuerySpec = new QuerySpec(true);
final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), lockOptions, fetchProcessor, true, sessionFactory);
final TableGroup rootTableGroup = entityDescriptor.createRootTableGroup(true, entityPath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, sessionFactory);
rootQuerySpec.getFromClause().addRoot(rootTableGroup);
sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
final DomainResult<?> domainResult = domainResultProducer.apply(rootTableGroup, sqlAstCreationState);
final SelectStatement sqlSelect = new SelectStatement(rootQuerySpec, Collections.singletonList(domainResult));
final List<JdbcParameter> jdbcParameters = new ArrayList<>(naturalIdMapping.getJdbcTypeCount());
final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
applyNaturalIdRestriction(bindValue, rootTableGroup, rootQuerySpec::applyPredicate, (jdbcParameter, jdbcParameterBinding) -> {
jdbcParameters.add(jdbcParameter);
jdbcParamBindings.addBinding(jdbcParameter, jdbcParameterBinding);
}, sqlAstCreationState, session);
final QueryOptions queryOptions = new SimpleQueryOptions(lockOptions, false);
final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlSelect).translate(jdbcParamBindings, queryOptions);
final StatisticsImplementor statistics = sessionFactory.getStatistics();
final Long startToken = statementStartHandler.apply(statistics.isStatisticsEnabled());
// noinspection unchecked
final List<L> results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParamBindings, new ExecutionContext() {
private final Callback callback = new CallbackImpl();
@Override
public SharedSessionContractImplementor getSession() {
return session;
}
@Override
public QueryOptions getQueryOptions() {
return queryOptions;
}
@Override
public String getQueryIdentifier(String sql) {
return sql;
}
@Override
public QueryParameterBindings getQueryParameterBindings() {
return QueryParameterBindings.NO_PARAM_BINDINGS;
}
@Override
public Callback getCallback() {
return callback;
}
}, row -> (L) row[0], ListResultsConsumer.UniqueSemantic.FILTER);
if (results.size() > 1) {
throw new HibernateException(String.format("Loading by natural-id returned more that one row : %s", entityDescriptor.getEntityName()));
}
final L result;
if (results.isEmpty()) {
result = null;
} else {
result = results.get(0);
}
statementCompletionHandler.accept(result, startToken);
return result;
}
Aggregations