Does the JDBC Postgres Driver has a way to set the "client_encoding" to connect to the database?

Viewed 3278

Does the JDBC Postgres Driver has a way to set the client_encoding to connect to the database?

I am using Spring (with JPA) and the connection information is in the application.properties file:

spring.datasource.url=jdbc:postgresql://mypgserver.com:5432/mydb?user=myuser&password=mypass&characterEncoding=UTF-8

But reading the JDBC docs at https://jdbc.postgresql.org/documentation/head/connect.html, I didn't find a parameter named characterEncoding.

In fact, there is no parameter for this purpose in the docs.

How can I set the encoding to be used when inputting data to the PG server?

1 Answers

Since Java uses a UNICODE encoding (UTF-16) internally, it would be unnatural to use a client_encoding different from UTF8 in the PostgreSQL JDBC driver.

Consequently, it forces client_encoding to that values, see org.postgresql.core.v3.ConnectionFactoryImpl.getParametersForStartup:

private List<String[]> getParametersForStartup(String user, String database, Properties info) {
  List<String[]> paramList = new ArrayList<String[]>();
  paramList.add(new String[]{"user", user});
  paramList.add(new String[]{"database", database});
  paramList.add(new String[]{"client_encoding", "UTF8"});
  paramList.add(new String[]{"DateStyle", "ISO"});
  [...]

In fact, if the client encoding is changed to anything else, the JDBC driver expresses its unhappiness in no uncertain terms:

public void receiveParameterStatus() throws IOException, SQLException {
  // ParameterStatus
  pgStream.receiveInteger4(); // MESSAGE SIZE
  String name = pgStream.receiveString();
  String value = pgStream.receiveString();

  [...]

  if (name.equals("client_encoding")) {
    if (allowEncodingChanges) {
      if (!value.equalsIgnoreCase("UTF8") && !value.equalsIgnoreCase("UTF-8")) {
        LOGGER.log(Level.FINE,
            "pgjdbc expects client_encoding to be UTF8 for proper operation. Actual encoding is {0}",
            value);
      }
      pgStream.setEncoding(Encoding.getDatabaseEncoding(value));
    } else if (!value.equalsIgnoreCase("UTF8") && !value.equalsIgnoreCase("UTF-8")) {
      close(); // we're screwed now; we can't trust any subsequent string.
      throw new PSQLException(GT.tr(
          "The server''s client_encoding parameter was changed to {0}. The JDBC driver requires client_encoding to be UTF8 for correct operation.",
          value), PSQLState.CONNECTION_FAILURE);

    }
  }

You probably have an encoding conversion problem when you read the data into your Java program; try and fix the problem there.

Related