All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cds.impl.sql.UpsertStatementBuilder Maven / Gradle / Ivy

There is a newer version: 3.4.0
Show newest version
/************************************************************************
 * © 2022-2023 SAP SE or an SAP affiliate company. All rights reserved. *
 ************************************************************************/
package com.sap.cds.impl.sql;

import static com.sap.cds.impl.builder.model.ElementRefImpl.parse;
import static com.sap.cds.impl.sql.SQLHelper.param;
import static com.sap.cds.util.CdsModelUtils.element;

import java.util.ArrayList;
import java.util.List;
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.jdbc.spi.StatementResolver;
import com.sap.cds.ql.cqn.CqnElementRef;
import com.sap.cds.ql.cqn.CqnUpsert;
import com.sap.cds.reflect.CdsElement;
import com.sap.cds.reflect.CdsEntity;
import com.sap.cds.util.CdsModelUtils;

public class UpsertStatementBuilder implements SQLStatementBuilder {

	private final CqnUpsert upsert;
	private final SqlMapping sqlMapping;
	private final CdsEntity entity;
	private final StatementResolver statementResolver;

	public UpsertStatementBuilder(Context context, CqnUpsert upsert) {
		this.upsert = upsert;
		this.entity = context.getCdsModel().getEntity(upsert.ref().firstSegment());
		this.sqlMapping = context.getDbContext().getSqlMapping(entity);
		this.statementResolver = context.getDbContext().getStatementResolver();
	}

	@Override
	public SQLStatement build() {
		List params = new ArrayList<>();

		String tableName = sqlMapping.tableName();
		Stream upsertColumnNames = upsert.elements().map(e -> {
			CqnElementRef ref = parse(e);
			CdsElement element = element(entity, ref);
			params.add(param(e, element));
			return sqlMapping.columnName(ref);
		});
		Stream keyColumnNames = CdsModelUtils.concreteKeyNames(entity).stream().map(sqlMapping::columnName);
		Stream paramMarkers = upsert.elements().map(c -> "?");
		String sql = statementResolver.upsert(tableName, keyColumnNames, upsertColumnNames, paramMarkers);

		return new SQLStatement(sql, params);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy