Browse Source
Reuse existing EvaluationContextProvider infrastructure and static parser/parser context instances. Parse expressions early. Update Javadoc to reflect SpEL support. Reformat code to use tabs instead of spaces. Rename types for consistency. Rename SpelExpressionResultSanitizer to SqlIdentifierSanitizer to express its intended usage. Eagerly initialize entities where applicable. Simplify code. See #1325 Original pull request: #1461pull/1526/head
13 changed files with 416 additions and 300 deletions
@ -0,0 +1,159 @@
@@ -0,0 +1,159 @@
|
||||
/* |
||||
* 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 Lazy<SqlIdentifier> tableName; |
||||
private final @Nullable Expression tableNameExpression; |
||||
|
||||
private final Lazy<Optional<SqlIdentifier>> schemaName; |
||||
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.expressionEvaluator = expressionEvaluator; |
||||
|
||||
Lazy<Optional<SqlIdentifier>> defaultSchema = Lazy.of(() -> StringUtils.hasText(namingStrategy.getSchema()) |
||||
? Optional.of(createDerivedSqlIdentifier(namingStrategy.getSchema())) |
||||
: Optional.empty()); |
||||
|
||||
if (isAnnotationPresent(Table.class)) { |
||||
|
||||
Table table = getRequiredAnnotation(Table.class); |
||||
|
||||
this.tableName = Lazy.of(() -> StringUtils.hasText(table.value()) ? createSqlIdentifier(table.value()) |
||||
: createDerivedSqlIdentifier(namingStrategy.getTableName(getType()))); |
||||
this.tableNameExpression = detectExpression(table.value()); |
||||
|
||||
this.schemaName = StringUtils.hasText(table.schema()) |
||||
? Lazy.of(() -> Optional.of(createSqlIdentifier(table.schema()))) |
||||
: defaultSchema; |
||||
|
||||
} else { |
||||
|
||||
this.tableName = Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getTableName(getType()))); |
||||
this.tableNameExpression = null; |
||||
this.schemaName = defaultSchema; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 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; |
||||
if (schemaNameExpression != null) { |
||||
schema = createSqlIdentifier(expressionEvaluator.evaluate(schemaNameExpression)); |
||||
} else { |
||||
schema = schemaName.get().orElse(null); |
||||
} |
||||
|
||||
if (schema == null) { |
||||
return getTableName(); |
||||
} |
||||
|
||||
return SqlIdentifier.from(schema, getTableName()); |
||||
} |
||||
|
||||
@Override |
||||
public SqlIdentifier getIdColumn() { |
||||
return getRequiredIdProperty().getColumnName(); |
||||
} |
||||
|
||||
@Override |
||||
public String toString() { |
||||
return String.format("BasicRelationalPersistentEntity<%s>", getType()); |
||||
} |
||||
} |
||||
@ -0,0 +1,47 @@
@@ -0,0 +1,47 @@
|
||||
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 #setSanitizer(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; |
||||
} |
||||
} |
||||
@ -1,139 +0,0 @@
@@ -1,139 +0,0 @@
|
||||
/* |
||||
* 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.lang.Nullable; |
||||
import org.springframework.util.StringUtils; |
||||
|
||||
/** |
||||
* Meta data a repository might need for implementing persistence operations for instances of type {@code T} |
||||
* |
||||
* @author Jens Schauder |
||||
* @author Greg Turnquist |
||||
* @author Bastian Wilhelm |
||||
* @author Mikhail Polivakha |
||||
* @author Kurt Niemi |
||||
*/ |
||||
class RelationalPersistentEntityImpl<T> extends BasicPersistentEntity<T, RelationalPersistentProperty> |
||||
implements RelationalPersistentEntity<T> { |
||||
|
||||
private final NamingStrategy namingStrategy; |
||||
private final Lazy<Optional<SqlIdentifier>> tableName; |
||||
private final Lazy<Optional<SqlIdentifier>> schemaName; |
||||
private boolean forceQuote = true; |
||||
private SpelExpressionProcessor spelExpressionProcessor = new SpelExpressionProcessor(); |
||||
|
||||
/** |
||||
* Creates a new {@link RelationalPersistentEntityImpl} for the given {@link TypeInformation}. |
||||
* |
||||
* @param information must not be {@literal null}. |
||||
*/ |
||||
RelationalPersistentEntityImpl(TypeInformation<T> information, NamingStrategy namingStrategy) { |
||||
|
||||
super(information); |
||||
|
||||
this.namingStrategy = namingStrategy; |
||||
|
||||
this.tableName = Lazy.of(() -> Optional.ofNullable(findAnnotation(Table.class)) //
|
||||
.map(Table::value) //
|
||||
.map(spelExpressionProcessor::applySpelExpression) //
|
||||
.filter(StringUtils::hasText) //
|
||||
.map(this::createSqlIdentifier)); |
||||
|
||||
this.schemaName = Lazy.of(() -> Optional.ofNullable(findAnnotation(Table.class)) //
|
||||
.map(Table::schema) //
|
||||
.filter(StringUtils::hasText) //
|
||||
.map(this::createSqlIdentifier)); |
||||
} |
||||
|
||||
public SpelExpressionProcessor getSpelExpressionProcessor() { |
||||
return spelExpressionProcessor; |
||||
} |
||||
|
||||
public void setSpelExpressionProcessor(SpelExpressionProcessor spelExpressionProcessor) { |
||||
this.spelExpressionProcessor = spelExpressionProcessor; |
||||
} |
||||
|
||||
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() { |
||||
|
||||
Optional<SqlIdentifier> explicitlySpecifiedTableName = tableName.get(); |
||||
SqlIdentifier schemalessTableIdentifier = createDerivedSqlIdentifier(namingStrategy.getTableName(getType())); |
||||
|
||||
return explicitlySpecifiedTableName.orElse(schemalessTableIdentifier); |
||||
} |
||||
|
||||
@Override |
||||
public SqlIdentifier getQualifiedTableName() { |
||||
|
||||
SqlIdentifier schema = determineCurrentEntitySchema(); |
||||
Optional<SqlIdentifier> explicitlySpecifiedTableName = tableName.get(); |
||||
|
||||
SqlIdentifier schemalessTableIdentifier = createDerivedSqlIdentifier(namingStrategy.getTableName(getType())); |
||||
|
||||
if (schema == null) { |
||||
return explicitlySpecifiedTableName.orElse(schemalessTableIdentifier); |
||||
} |
||||
|
||||
return explicitlySpecifiedTableName.map(sqlIdentifier -> SqlIdentifier.from(schema, sqlIdentifier)) |
||||
.orElse(SqlIdentifier.from(schema, schemalessTableIdentifier)); |
||||
} |
||||
|
||||
/** |
||||
* @return {@link SqlIdentifier} representing the current entity schema. If the schema is not specified, neither |
||||
* explicitly, nor via {@link NamingStrategy}, then return {@link null} |
||||
*/ |
||||
@Nullable |
||||
private SqlIdentifier determineCurrentEntitySchema() { |
||||
|
||||
Optional<SqlIdentifier> explicitlySpecifiedSchema = schemaName.get(); |
||||
return explicitlySpecifiedSchema.orElseGet( |
||||
() -> StringUtils.hasText(namingStrategy.getSchema()) ? createDerivedSqlIdentifier(namingStrategy.getSchema()) |
||||
: null); |
||||
} |
||||
|
||||
@Override |
||||
public SqlIdentifier getIdColumn() { |
||||
return getRequiredIdProperty().getColumnName(); |
||||
} |
||||
|
||||
@Override |
||||
public String toString() { |
||||
return String.format("RelationalPersistentEntityImpl<%s>", getType()); |
||||
} |
||||
} |
||||
@ -1,87 +0,0 @@
@@ -1,87 +0,0 @@
|
||||
package org.springframework.data.relational.core.mapping; |
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.expression.EvaluationException; |
||||
import org.springframework.expression.Expression; |
||||
import org.springframework.expression.common.TemplateParserContext; |
||||
import org.springframework.expression.spel.standard.SpelExpressionParser; |
||||
import org.springframework.expression.spel.support.StandardEvaluationContext; |
||||
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 SpelExpressionResultSanitizer} interface and then invoking the |
||||
* {@link #setSpelExpressionResultSanitizer(SpelExpressionResultSanitizer)} method. |
||||
* |
||||
* @author Kurt Niemi |
||||
* @see SpelExpressionResultSanitizer |
||||
* @since 3.1 |
||||
*/ |
||||
public class SpelExpressionProcessor { |
||||
private SpelExpressionResultSanitizer spelExpressionResultSanitizer; |
||||
private StandardEvaluationContext evalContext = new StandardEvaluationContext(); |
||||
private SpelExpressionParser parser = new SpelExpressionParser(); |
||||
private TemplateParserContext templateParserContext = new TemplateParserContext(); |
||||
|
||||
public String applySpelExpression(String expression) throws EvaluationException { |
||||
|
||||
Assert.notNull(expression, "Expression must not be null."); |
||||
|
||||
// Only apply logic if we have the prefixes/suffixes required for a SpEL expression as firstly
|
||||
// there is nothing to evaluate (i.e. whatever literal passed in is returned as-is) and more
|
||||
// importantly we do not want to perform any sanitization logic.
|
||||
if (!isSpellExpression(expression)) { |
||||
return expression; |
||||
} |
||||
|
||||
Expression expr = parser.parseExpression(expression, templateParserContext); |
||||
String result = expr.getValue(evalContext, String.class); |
||||
|
||||
// Normally an exception is thrown by the Spel parser on invalid syntax/errors but this will provide
|
||||
// a consistent experience for any issues with Spel parsing.
|
||||
if (result == null) { |
||||
throw new EvaluationException("Spel Parsing of expression \"" + expression + "\" failed."); |
||||
} |
||||
|
||||
String sanitizedResult = getSpelExpressionResultSanitizer().sanitize(result); |
||||
|
||||
return sanitizedResult; |
||||
} |
||||
|
||||
protected boolean isSpellExpression(String expression) { |
||||
|
||||
String trimmedExpression = expression.trim(); |
||||
if (trimmedExpression.startsWith(templateParserContext.getExpressionPrefix()) && |
||||
trimmedExpression.endsWith(templateParserContext.getExpressionSuffix())) { |
||||
return true; |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
public SpelExpressionResultSanitizer getSpelExpressionResultSanitizer() { |
||||
|
||||
if (this.spelExpressionResultSanitizer == null) { |
||||
this.spelExpressionResultSanitizer = new SpelExpressionResultSanitizer() { |
||||
@Override |
||||
public String sanitize(String result) { |
||||
|
||||
String cleansedResult = result.replaceAll("[^\\w]", ""); |
||||
return cleansedResult; |
||||
} |
||||
}; |
||||
} |
||||
return this.spelExpressionResultSanitizer; |
||||
} |
||||
|
||||
public void setSpelExpressionResultSanitizer(SpelExpressionResultSanitizer spelExpressionResultSanitizer) { |
||||
this.spelExpressionResultSanitizer = spelExpressionResultSanitizer; |
||||
} |
||||
|
||||
} |
||||
@ -1,10 +0,0 @@
@@ -1,10 +0,0 @@
|
||||
package org.springframework.data.relational.core.mapping; |
||||
|
||||
/** |
||||
* Interface for sanitizing Spel Expression results |
||||
* |
||||
* @author Kurt Niemi |
||||
*/ |
||||
public interface SpelExpressionResultSanitizer { |
||||
public String sanitize(String result); |
||||
} |
||||
@ -0,0 +1,42 @@
@@ -0,0 +1,42 @@
|
||||
package org.springframework.data.relational.core.mapping; |
||||
|
||||
import java.util.regex.Pattern; |
||||
|
||||
import org.springframework.util.Assert; |
||||
|
||||
/** |
||||
* Functional interface to sanitize SQL identifiers for SQL usage. Useful to guard SpEL expression results. |
||||
* |
||||
* @author Kurt Niemi |
||||
* @author Mark Paluch |
||||
* @since 3.1 |
||||
* @see RelationalMappingContext#setSqlIdentifierSanitizer(SqlIdentifierSanitizer) |
||||
*/ |
||||
@FunctionalInterface |
||||
public interface SqlIdentifierSanitizer { |
||||
|
||||
/** |
||||
* A sanitizer to allow words only. Non-words are removed silently. |
||||
* |
||||
* @return |
||||
*/ |
||||
static SqlIdentifierSanitizer words() { |
||||
|
||||
Pattern pattern = Pattern.compile("[^\\w_]"); |
||||
|
||||
return name -> { |
||||
|
||||
Assert.notNull(name, "Input to sanitize must not be null"); |
||||
|
||||
return pattern.matcher(name).replaceAll(""); |
||||
}; |
||||
} |
||||
|
||||
/** |
||||
* Sanitize a SQL identifier to either remove unwanted character sequences or to throw an exception. |
||||
* |
||||
* @param sqlIdentifier the identifier name. |
||||
* @return sanitized SQL identifier. |
||||
*/ |
||||
String sanitize(String sqlIdentifier); |
||||
} |
||||
Loading…
Reference in new issue