com.sap.cds.jdbc.postgresql.PostgreSqlSessionVariableSetter Maven / Gradle / Ivy
package com.sap.cds.jdbc.postgresql;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.stream.Collectors;
import com.sap.cds.impl.sql.SQLHelper;
import com.sap.cds.jdbc.spi.SessionVariableSetter;
public class PostgreSqlSessionVariableSetter implements SessionVariableSetter {
@Override
public void set(Connection conn, String key, String value) throws SQLException {
String sql = sql(key, value);
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(sql);
}
}
@Override
public void set(Connection conn, Map contextVariables) throws SQLException {
String sql = contextVariables.entrySet().stream().map(e -> sql(e.getKey(), e.getValue()))
.collect(Collectors.joining(";\n "));
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(sql);
}
}
private static String sql(String key, String value) {
StringBuilder builder = new StringBuilder("SET SESSION CAP.");
String name = key.replace("-", "_");
builder.append(name);
if (value == null) {
builder.append(" TO DEFAULT");
} else {
builder.append(" = ");
builder.append(SQLHelper.literal(value));
}
return builder.toString();
}
}