com.sap.cds.impl.sql.DeleteStatementBuilder Maven / Gradle / Ivy
/************************************************************************
* © 2019-2023 SAP SE or an SAP affiliate company. All rights reserved. *
************************************************************************/
package com.sap.cds.impl.sql;
import static com.sap.cds.impl.sql.SQLStatementBuilder.aliasResolver;
import static com.sap.cds.impl.sql.SpaceSeparatedCollector.joining;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import com.sap.cds.impl.Context;
import com.sap.cds.impl.PreparedCqnStmt.Parameter;
import com.sap.cds.jdbc.spi.SqlMapping;
import com.sap.cds.ql.cqn.CqnDelete;
import com.sap.cds.ql.cqn.CqnElementRef;
import com.sap.cds.reflect.CdsEntity;
public class DeleteStatementBuilder implements SQLStatementBuilder {
private final CqnDelete delete;
private final TokenToSQLTransformer toSQL;
private final SqlMapping sqlMapping;
private final String tableName;
private final CdsEntity entity;
private final List params = new ArrayList<>();
public DeleteStatementBuilder(Context context, CqnDelete delete) {
this.delete = delete;
entity = context.getCdsModel().getEntity(delete.ref().firstSegment());
sqlMapping = context.getDbContext().getSqlMapping(entity);
tableName = sqlMapping.tableName();
Function aliasResolver = aliasResolver(context, entity);
toSQL = TokenToSQLTransformer.notCollating(context, aliasResolver, entity, tableName, params);
}
@Override
public SQLStatement build() {
Stream.Builder builder = Stream.builder();
builder.add("DELETE FROM");
builder.add(tableName);
delete.where().map(w -> toSQL.toSQL(entity, w)).ifPresent(s -> {
builder.add("WHERE");
builder.add(s);
});
String sql = builder.build().collect(joining());
return new SQLStatement(sql, params);
}
}