pgjdbc: Can't insert enum: ERROR: column "enumtest" is of type marital_status but expression is of type character varying

I’m submitting a …

  • bug report
  • feature request

The reason why I think this is a bug report is that all of MySQL, MariaDB and H2 JDBC drivers support this kind of automatic conversion between varchar and enum.

Describe the issue Having table with a column of ENUM type, I’d like to run the following statement via JDBC: INSERT INTO Person(maritalStatus) VALUES (?) and pass in Enum String constant name.

Driver Version? 42.2.5

Java Version? 8

OS Version? Ubuntu x86-64 4.18.0-15

PostgreSQL Version? 10.3

To Reproduce

CREATE TYPE marital_status AS ENUM ('Single', 'Married', 'Widowed', 'Divorced');
CREATE TABLE TypeMappingEntity(id bigserial primary key, maritalStatus marital_status);

Then, run the following prepared statement:

INSERT INTO Person(maritalStatus) VALUES (?)

and pass "Divorced" as the first parameter.

Expected behaviour I expect the insert to succeed and the record is inserted into the database, with the maritalStatus column of value “Divorced”.

What actually happens:

Caused by: org.postgresql.util.PSQLException: ERROR: column "maritalStatus" is of type marital_status but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 50
	at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
	at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
	at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
	at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
	at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
	at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Comments: 15 (6 by maintainers)

Most upvoted comments

I solved same issue with cast

CREATE CAST (character varying AS auth.user_role) WITH INOUT AS ASSIGNMENT;

@mvysny

I presume you are using setString(1,‘Divorced’)

Using setObject(1,‘Divorced’,Types.OTHER)

Should work

@Test public void testOtherAsEnum() throws Exception { PreparedStatement update = con.prepareStatement(“insert into stringtypetest (m) values (?)”); update.setObject(1, “happy”, Types.OTHER); update.executeUpdate(); // all good TestUtil.closeQuietly(update); }

@paullarionov not sure what you are looking for here.

If you attempt to use setString(column,"enumvalue") it will fail. If you use setObject(column, "enumvalue", Types.OTHER) it should work