Skip to content

Add SpEL support for @Table, @Column and @MappedCollection #1461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ protected RelationalPersistentProperty createPersistentProperty(Property propert
RelationalPersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {
BasicJdbcPersistentProperty persistentProperty = new BasicJdbcPersistentProperty(property, owner, simpleTypeHolder,
this.getNamingStrategy());
persistentProperty.setForceQuote(isForceQuote());
applyDefaults(persistentProperty);
return persistentProperty;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.core.mapping;

import java.util.Optional;

import org.springframework.data.mapping.model.BasicPersistentEntity;
import org.springframework.data.relational.core.sql.SqlIdentifier;
import org.springframework.data.util.Lazy;
import org.springframework.data.util.TypeInformation;
import org.springframework.expression.Expression;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

/**
* SQL-specific {@link RelationalPersistentEntity} implementation that adds SQL-specific meta-data such as the table and
* schema name.
*
* @author Jens Schauder
* @author Greg Turnquist
* @author Bastian Wilhelm
* @author Mikhail Polivakha
* @author Kurt Niemi
*/
class BasicRelationalPersistentEntity<T> extends BasicPersistentEntity<T, RelationalPersistentProperty>
implements RelationalPersistentEntity<T> {

private static final SpelExpressionParser PARSER = new SpelExpressionParser();

private final NamingStrategy namingStrategy;

private final Lazy<SqlIdentifier> tableName;
private final @Nullable Expression tableNameExpression;

private final Lazy<Optional<SqlIdentifier>> schemaName;
private final @Nullable Expression schemaNameExpression;
private final ExpressionEvaluator expressionEvaluator;
private boolean forceQuote = true;

/**
* Creates a new {@link BasicRelationalPersistentEntity} for the given {@link TypeInformation}.
*
* @param information must not be {@literal null}.
*/
BasicRelationalPersistentEntity(TypeInformation<T> information, NamingStrategy namingStrategy,
ExpressionEvaluator expressionEvaluator) {

super(information);

this.namingStrategy = namingStrategy;
this.expressionEvaluator = expressionEvaluator;

Lazy<Optional<SqlIdentifier>> defaultSchema = Lazy.of(() -> {
if (StringUtils.hasText(namingStrategy.getSchema())) {
return Optional.of(createDerivedSqlIdentifier(namingStrategy.getSchema()));
}
return Optional.empty();
});

if (isAnnotationPresent(Table.class)) {

Table table = getRequiredAnnotation(Table.class);

// TODO: support expressions for schema
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mp911de can we please not sprinkle TODOs in our code. Those should be either review comments or issue tickets.

@kurtn718 For this one I'd leave it to you, create a ticket from it, or implement the change as part of this ticket.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm in favor of supporting SpEL for schema within the scope of this ticket.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will see what the scope of changes is - and if small add to this ticket.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just pushed up an update. Adding this was pretty straight-forward.

this.tableName = StringUtils.hasText(table.value()) ? Lazy.of(() -> createSqlIdentifier(table.value()))
: Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getTableName(getType())));
this.tableNameExpression = detectExpression(table.value());

this.schemaName = StringUtils.hasText(table.schema())
? Lazy.of(() -> Optional.of(createSqlIdentifier(table.schema())))
: defaultSchema;
this.schemaNameExpression = detectExpression(table.schema());

} else {

this.tableName = Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getTableName(getType())));
this.tableNameExpression = null;
this.schemaName = defaultSchema;
this.schemaNameExpression = null;
}
}

/**
* Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a
* {@link LiteralExpression} (indicating that no subsequent evaluation is necessary).
*
* @param potentialExpression can be {@literal null}
* @return can be {@literal null}.
*/
@Nullable
private static Expression detectExpression(@Nullable String potentialExpression) {

if (!StringUtils.hasText(potentialExpression)) {
return null;
}

Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION);
return expression instanceof LiteralExpression ? null : expression;
}

private SqlIdentifier createSqlIdentifier(String name) {
return isForceQuote() ? SqlIdentifier.quoted(name) : SqlIdentifier.unquoted(name);
}

private SqlIdentifier createDerivedSqlIdentifier(String name) {
return new DerivedSqlIdentifier(name, isForceQuote());
}

public boolean isForceQuote() {
return forceQuote;
}

public void setForceQuote(boolean forceQuote) {
this.forceQuote = forceQuote;
}

@Override
public SqlIdentifier getTableName() {

if (tableNameExpression == null) {
return tableName.get();
}

return createSqlIdentifier(expressionEvaluator.evaluate(tableNameExpression));
}

@Override
public SqlIdentifier getQualifiedTableName() {

SqlIdentifier schema = schemaName.get().orElse(null);

if (schema == null) {
return getTableName();
}

if (schemaNameExpression != null) {
schema = createSqlIdentifier(expressionEvaluator.evaluate(schemaNameExpression));
}

return SqlIdentifier.from(schema, getTableName());
}

@Override
public SqlIdentifier getIdColumn() {
return getRequiredIdProperty().getColumnName();
}

@Override
public String toString() {
return String.format("BasicRelationalPersistentEntity<%s>", getType());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,29 +25,40 @@
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.relational.core.mapping.Embedded.OnEmpty;
import org.springframework.data.relational.core.sql.SqlIdentifier;
import org.springframework.data.spel.EvaluationContextProvider;
import org.springframework.data.util.Lazy;
import org.springframework.data.util.Optionals;
import org.springframework.expression.Expression;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
* Meta data about a property to be used by repository implementations.
* SQL-specific {@link org.springframework.data.mapping.PersistentProperty} implementation.
*
* @author Jens Schauder
* @author Greg Turnquist
* @author Florian Lüdiger
* @author Bastian Wilhelm
* @author Kurt Niemi
*/
public class BasicRelationalPersistentProperty extends AnnotationBasedPersistentProperty<RelationalPersistentProperty>
implements RelationalPersistentProperty {

private static final SpelExpressionParser PARSER = new SpelExpressionParser();

private final Lazy<SqlIdentifier> columnName;
private final @Nullable Expression columnNameExpression;
private final Lazy<Optional<SqlIdentifier>> collectionIdColumnName;
private final Lazy<SqlIdentifier> collectionKeyColumnName;
private final Lazy<Boolean> isEmbedded;
private final Lazy<String> embeddedPrefix;
private final NamingStrategy namingStrategy;
private boolean forceQuote = true;
private ExpressionEvaluator spelExpressionProcessor = new ExpressionEvaluator(EvaluationContextProvider.DEFAULT);

/**
* Creates a new {@link BasicRelationalPersistentProperty}.
Expand Down Expand Up @@ -88,12 +99,20 @@ public BasicRelationalPersistentProperty(Property property, PersistentEntity<?,
.map(Embedded::prefix) //
.orElse(""));

this.columnName = Lazy.of(() -> Optional.ofNullable(findAnnotation(Column.class)) //
.map(Column::value) //
.filter(StringUtils::hasText) //
.map(this::createSqlIdentifier) //
.orElseGet(() -> createDerivedSqlIdentifier(namingStrategy.getColumnName(this))));
if (isAnnotationPresent(Column.class)) {

Column column = getRequiredAnnotation(Column.class);

columnName = StringUtils.hasText(column.value()) ? Lazy.of(() -> createSqlIdentifier(column.value()))
: Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getColumnName(this)));
columnNameExpression = detectExpression(column.value());

} else {
columnName = Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getColumnName(this)));
columnNameExpression = null;
}

// TODO: support expressions for MappedCollection
this.collectionIdColumnName = Lazy.of(() -> Optionals
.toStream(Optional.ofNullable(findAnnotation(MappedCollection.class)) //
.map(MappedCollection::idColumn), //
Expand All @@ -110,6 +129,29 @@ public BasicRelationalPersistentProperty(Property property, PersistentEntity<?,
.orElseGet(() -> createDerivedSqlIdentifier(namingStrategy.getKeyColumn(this))));
}

void setSpelExpressionProcessor(ExpressionEvaluator spelExpressionProcessor) {
this.spelExpressionProcessor = spelExpressionProcessor;
}

/**
* Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a
* {@link LiteralExpression} (indicating that no subsequent evaluation is necessary).
*
* @param potentialExpression can be {@literal null}
* @return can be {@literal null}.
*/
@Nullable
private static Expression detectExpression(@Nullable String potentialExpression) {

if (!StringUtils.hasText(potentialExpression)) {
return null;
}

Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION);
return expression instanceof LiteralExpression ? null : expression;
}


private SqlIdentifier createSqlIdentifier(String name) {
return isForceQuote() ? SqlIdentifier.quoted(name) : SqlIdentifier.unquoted(name);
}
Expand Down Expand Up @@ -138,7 +180,12 @@ public boolean isEntity() {

@Override
public SqlIdentifier getColumnName() {
return columnName.get();

if (columnNameExpression == null) {
return columnName.get();
}

return createSqlIdentifier(spelExpressionProcessor.evaluate(columnNameExpression));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
public @interface Column {

/**
* The mapping column name.
* The column name. The attribute supports SpEL expressions to dynamically calculate the column name on a
* per-operation basis.
*/
String value() default "";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package org.springframework.data.relational.core.mapping;

import org.springframework.data.spel.EvaluationContextProvider;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.util.Assert;

/**
* Provide support for processing SpEL expressions in @Table and @Column annotations, or anywhere we want to use SpEL
* expressions and sanitize the result of the evaluated SpEL expression. The default sanitization allows for digits,
* alphabetic characters and _ characters and strips out any other characters. Custom sanitization (if desired) can be
* achieved by creating a class that implements the {@link SqlIdentifierSanitizer} interface and then invoking the
* {@link #setSpelExpressionResultSanitizer(SqlIdentifierSanitizer)} method.
*
* @author Kurt Niemi
* @see SqlIdentifierSanitizer
* @since 3.1
*/
class ExpressionEvaluator {

private EvaluationContextProvider provider;

private SqlIdentifierSanitizer sanitizer = SqlIdentifierSanitizer.words();

public ExpressionEvaluator(EvaluationContextProvider provider) {
this.provider = provider;
}

public String evaluate(Expression expression) throws EvaluationException {

Assert.notNull(expression, "Expression must not be null.");

String result = expression.getValue(provider.getEvaluationContext(null), String.class);

return sanitizer.sanitize(result);
}

public void setSanitizer(SqlIdentifierSanitizer sanitizer) {

Assert.notNull(sanitizer, "SqlIdentifierSanitizer must not be null");

this.sanitizer = sanitizer;
}

public void setProvider(EvaluationContextProvider provider) {
this.provider = provider;
}
}
Loading