use of io.micronaut.data.model.naming.NamingStrategy in project micronaut-data by micronaut-projects.
the class MappedEntityVisitor method visitClass.
@Override
public void visitClass(ClassElement element, VisitorContext context) {
NamingStrategy namingStrategy = resolveNamingStrategy(element);
Optional<String> targetName = element.stringValue(MappedEntity.class);
SourcePersistentEntity entity = entityResolver.apply(element);
if (isMappedEntity() && !targetName.isPresent()) {
element.annotate(MappedEntity.class, builder -> {
String mappedName = namingStrategy.mappedName(entity);
builder.value(mappedName);
});
}
Map<String, DataType> dataTypes = getConfiguredDataTypes(element);
Map<String, String> dataConverters = getConfiguredDataConverters(element);
List<SourcePersistentProperty> properties = entity.getPersistentProperties();
final List<AnnotationValue<Index>> indexes = properties.stream().filter(x -> ((PersistentProperty) x).findAnnotation(Indexes.class).isPresent()).map(prop -> prop.findAnnotation(Index.class)).flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
if (!indexes.isEmpty()) {
element.annotate(Indexes.class, builder -> builder.values(indexes.toArray(new AnnotationValue[] {})));
}
for (PersistentProperty property : properties) {
computeMappingDefaults(namingStrategy, property, dataTypes, dataConverters, context);
}
SourcePersistentProperty identity = entity.getIdentity();
if (identity != null) {
computeMappingDefaults(namingStrategy, identity, dataTypes, dataConverters, context);
}
SourcePersistentProperty[] compositeIdentities = entity.getCompositeIdentity();
if (compositeIdentities != null) {
for (SourcePersistentProperty compositeIdentity : compositeIdentities) {
computeMappingDefaults(namingStrategy, compositeIdentity, dataTypes, dataConverters, context);
}
}
SourcePersistentProperty version = entity.getVersion();
if (version != null) {
computeMappingDefaults(namingStrategy, version, dataTypes, dataConverters, context);
}
}
use of io.micronaut.data.model.naming.NamingStrategy in project micronaut-data by micronaut-projects.
the class SqlQueryBuilder method buildJoinTableInsert.
/**
* Builds a join table insert statement for a given entity and association.
*
* @param entity The entity
* @param association The association
* @return The join table insert statement
*/
@NonNull
public String buildJoinTableInsert(@NonNull PersistentEntity entity, @NonNull Association association) {
if (!isForeignKeyWithJoinTable(association)) {
throw new IllegalArgumentException("Join table inserts can only be built for foreign key associations that are mapped with a join table.");
} else {
Optional<Association> inverseSide = association.getInverseSide().map(Function.identity());
Association owningAssociation = inverseSide.orElse(association);
AnnotationMetadata annotationMetadata = owningAssociation.getAnnotationMetadata();
NamingStrategy namingStrategy = entity.getNamingStrategy();
String joinTableName = annotationMetadata.stringValue(ANN_JOIN_TABLE, "name").orElseGet(() -> namingStrategy.mappedName(association));
List<String> leftJoinColumns = resolveJoinTableJoinColumns(annotationMetadata, true, entity, namingStrategy);
List<String> rightJoinColumns = resolveJoinTableJoinColumns(annotationMetadata, false, association.getAssociatedEntity(), namingStrategy);
boolean escape = shouldEscape(entity);
String columns = Stream.concat(leftJoinColumns.stream(), rightJoinColumns.stream()).map(columnName -> escape ? quote(columnName) : columnName).collect(Collectors.joining(","));
String placeholders = IntStream.range(0, leftJoinColumns.size() + rightJoinColumns.size()).mapToObj(i -> "?").collect(Collectors.joining(","));
return INSERT_INTO + quote(joinTableName) + " (" + columns + ") VALUES (" + placeholders + ")";
}
}
use of io.micronaut.data.model.naming.NamingStrategy in project micronaut-data by micronaut-projects.
the class SqlQueryBuilder method buildDropTableStatements.
/**
* Builds the drop table statement. Designed for testing and not production usage. For production a
* SQL migration tool such as Flyway or Liquibase is recommended.
*
* @param entity The entity
* @return The tables for the give entity
*/
@Experimental
@NonNull
public String[] buildDropTableStatements(@NonNull PersistentEntity entity) {
String tableName = getTableName(entity);
boolean escape = shouldEscape(entity);
String sql = "DROP TABLE " + tableName;
Collection<Association> foreignKeyAssociations = getJoinTableAssociations(entity);
List<String> dropStatements = new ArrayList<>();
for (Association association : foreignKeyAssociations) {
AnnotationMetadata associationMetadata = association.getAnnotationMetadata();
NamingStrategy namingStrategy = entity.getNamingStrategy();
String joinTableName = associationMetadata.stringValue(ANN_JOIN_TABLE, "name").orElseGet(() -> namingStrategy.mappedName(association));
dropStatements.add("DROP TABLE " + (escape ? quote(joinTableName) : joinTableName) + ";");
}
dropStatements.add(sql);
return dropStatements.toArray(new String[0]);
}
use of io.micronaut.data.model.naming.NamingStrategy in project micronaut-data by micronaut-projects.
the class AbstractSqlLikeQueryBuilder method appendCriteriaForOperator.
private void appendCriteriaForOperator(StringBuilder whereClause, PropertyParameterCreator propertyParameterCreator, PersistentPropertyPath parameterPropertyPath, QueryPropertyPath propertyPath, Object value, String operator) {
if (value instanceof BindingParameter) {
BindingParameter bindingParameter = (BindingParameter) value;
boolean computePropertyPaths = computePropertyPaths();
if (!computePropertyPaths) {
appendPropertyRef(whereClause, propertyPath);
whereClause.append(operator);
propertyParameterCreator.pushParameter(bindingParameter, newBindingContext(parameterPropertyPath, propertyPath.propertyPath));
return;
}
String currentAlias = propertyPath.getTableAlias();
NamingStrategy namingStrategy = propertyPath.getNamingStrategy();
boolean shouldEscape = propertyPath.shouldEscape();
int length = whereClause.length();
traversePersistentProperties(propertyPath.getAssociations(), propertyPath.getProperty(), (associations, property) -> {
String readTransformer = getDataTransformerReadValue(currentAlias, property).orElse(null);
if (readTransformer != null) {
whereClause.append(readTransformer);
} else {
if (currentAlias != null) {
whereClause.append(currentAlias).append(DOT);
}
String columnName = namingStrategy.mappedName(associations, property);
if (shouldEscape) {
columnName = quote(columnName);
}
whereClause.append(columnName);
}
whereClause.append(operator);
propertyParameterCreator.pushParameter(bindingParameter, newBindingContext(parameterPropertyPath, PersistentPropertyPath.of(associations, property)));
whereClause.append(LOGICAL_AND);
});
int newLength = whereClause.length();
if (newLength != length) {
whereClause.setLength(newLength - LOGICAL_AND.length());
}
} else {
appendPropertyRef(whereClause, propertyPath);
whereClause.append(operator).append(asLiteral(value));
}
}
use of io.micronaut.data.model.naming.NamingStrategy in project micronaut-data by micronaut-projects.
the class AbstractSqlLikeQueryBuilder method buildUpdateStatement.
private void buildUpdateStatement(QueryState queryState, Map<String, Object> propertiesToUpdate) {
StringBuilder queryString = queryState.getQuery();
queryString.append(SPACE).append("SET").append(SPACE);
// keys need to be sorted before query is built
List<Map.Entry<QueryPropertyPath, Object>> update = propertiesToUpdate.entrySet().stream().map(e -> {
QueryPropertyPath propertyPath = findProperty(queryState, e.getKey(), null);
if (propertyPath.getProperty() instanceof Association && ((Association) propertyPath.getProperty()).isForeignKey()) {
throw new IllegalArgumentException("Foreign key associations cannot be updated as part of a batch update statement");
}
return new AbstractMap.SimpleEntry<>(propertyPath, e.getValue());
}).filter(e -> !(e.getValue() instanceof QueryParameter) || !e.getKey().getProperty().isGenerated()).collect(Collectors.toList());
int length = queryString.length();
if (!computePropertyPaths()) {
for (Map.Entry<QueryPropertyPath, Object> entry : update) {
QueryPropertyPath propertyPath = entry.getKey();
PersistentProperty prop = propertyPath.getProperty();
String tableAlias = propertyPath.getTableAlias();
if (tableAlias != null) {
queryString.append(tableAlias).append(DOT);
}
queryString.append(propertyPath.getPath()).append('=');
if (entry.getValue() instanceof BindingParameter) {
appendUpdateSetParameter(queryString, tableAlias, prop, () -> {
queryState.pushParameter((BindingParameter) entry.getValue(), newBindingContext(propertyPath.propertyPath));
});
} else {
queryString.append(asLiteral(entry.getValue()));
}
queryString.append(COMMA);
}
} else {
NamingStrategy namingStrategy = queryState.getEntity().getNamingStrategy();
for (Map.Entry<QueryPropertyPath, Object> entry : update) {
QueryPropertyPath propertyPath = entry.getKey();
if (entry.getValue() instanceof BindingParameter) {
traversePersistentProperties(propertyPath.getAssociations(), propertyPath.getProperty(), (associations, property) -> {
String tableAlias = propertyPath.getTableAlias();
if (tableAlias != null) {
queryString.append(tableAlias).append(DOT);
}
String columnName = namingStrategy.mappedName(associations, property);
if (queryState.escape) {
columnName = quote(columnName);
}
queryString.append(columnName).append('=');
appendUpdateSetParameter(queryString, tableAlias, property, () -> {
queryState.pushParameter((BindingParameter) entry.getValue(), newBindingContext(propertyPath.propertyPath, PersistentPropertyPath.of(associations, property, asPath(associations, property))));
});
queryString.append(COMMA);
});
} else {
String tableAlias = propertyPath.getTableAlias();
if (tableAlias != null) {
queryString.append(tableAlias).append(DOT);
}
queryString.append(propertyPath.getPath()).append('=');
queryString.append(asLiteral(entry.getValue()));
queryString.append(COMMA);
}
}
}
int newLength = queryString.length();
if (length != newLength) {
queryString.setLength(newLength - 1);
}
}
Aggregations