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

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

There is a newer version: 3.4.0
Show newest version
/************************************************************************
 * © 2019-2022 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 static java.util.stream.Collectors.joining;

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.ql.cqn.CqnElementRef;
import com.sap.cds.ql.cqn.CqnInsert;
import com.sap.cds.ql.cqn.CqnStructuredTypeRef;
import com.sap.cds.reflect.CdsElement;
import com.sap.cds.reflect.CdsEntity;

public class InsertStatementBuilder implements SQLStatementBuilder {

	private final CqnInsert insert;
	private final SqlMapping sqlMapping;
	private final CdsEntity entity;

	public InsertStatementBuilder(Context context, CqnInsert insert) {
		this.insert = insert;
		CqnStructuredTypeRef ref = insert.ref();
		entity = context.getCdsModel().getEntity(ref.firstSegment());
		sqlMapping = context.getDbContext().getSqlMapping(entity);
	}

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

		String tableName = sqlMapping.tableName();
		String columnsString = SQLHelper.commaSeparated(insert.elements().map(e -> {
			CqnElementRef ref = parse(e);
			CdsElement element = element(entity, ref);
			params.add(param(e, element));
			return sqlMapping.columnName(ref);
		}));
		String ps = SQLHelper.commaSeparated(insert.elements().map(c -> "?"));
		String sql = Stream.of("INSERT INTO", tableName, columnsString, "VALUES", ps).collect(joining(" "));

		return new SQLStatement(sql, params);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy