com.sap.cds.jdbc.postgresql.PostgreSqlSessionVariableSetter Maven / Gradle / Ivy
package com.sap.cds.jdbc.postgresql;
import static com.sap.cds.jdbc.postgresql.PostgreSqlDbContext.TIMESTAMP_PRECISION;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
import java.util.Map;
import java.util.stream.Collectors;
import com.sap.cds.impl.sql.SQLHelper;
import com.sap.cds.jdbc.spi.SessionVariableSetter;
import com.sap.cds.util.CdsTypeUtils;
public class PostgreSqlSessionVariableSetter implements SessionVariableSetter {
@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("; "));
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(sql);
}
}
private static String sql(String key, Object value) {
StringBuilder builder = new StringBuilder("SET SESSION ");
String name = switch (key) {
case VALID_FROM -> "valid_from";
case VALID_TO -> "valid_to";
case APPLICATIONUSER -> "applicationuser";
case LOCALE -> "locale";
case TENANT -> "tenant";
default -> key;
};
builder.append("CAP.");
builder.append(name);
if (value == null) {
builder.append(" TO DEFAULT");
} else {
String val = switch (key) {
case VALID_FROM, VALID_TO -> sqlTimestamp(value);
default -> value.toString();
};
builder.append(" = ");
builder.append(SQLHelper.literal(val));
}
return builder.toString();
}
private static String sqlTimestamp(Object value) {
return CdsTypeUtils.timestamp((Instant) value, TIMESTAMP_PRECISION).toString();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy