Created
November 15, 2019 07:54
-
-
Save mutovkin/ba014557d2e2fb5c0095d76b1262faff to your computer and use it in GitHub Desktop.
Attempt to wrap enum.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class PgEnumScalarType<T extends Enum<T>> extends ScalarTypeBase<T> { | |
final String postgresType; | |
public T enumVal; | |
public PgEnumScalarType(final String postgresType, final T enumVal) { | |
super(enumVal.getDeclaringClass(), false, java.sql.Types.OTHER); | |
this.postgresType = postgresType; | |
this.enumVal = enumVal; | |
} | |
@Override | |
public T read(DataReader reader) throws SQLException { | |
String content = reader.getStringFromStream(); | |
if (content == null) { | |
return null; | |
} | |
// Thanks to this: | |
// https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection | |
return T.valueOf((Class<T>) | |
((ParameterizedType)getClass().getGenericSuperclass()) | |
.getActualTypeArguments()[0], content); | |
} | |
@Override | |
public void bind(DataBind bind, Enum value) throws SQLException { | |
bind.setObject(PostgresHelper.asObject(postgresType, value.name())); | |
} | |
@Override | |
public Object toJdbcType(Object value) { | |
return null; | |
} | |
@Override | |
public T toBeanType(Object value) { | |
return null; | |
} | |
@Override | |
public String formatValue(T value) { | |
return value.name(); | |
} | |
@Override | |
public T parse(String value) { | |
return T.valueOf((Class<T>) | |
((ParameterizedType)getClass().getGenericSuperclass()) | |
.getActualTypeArguments()[0], value); | |
} | |
@Override | |
public DocPropertyType getDocType() { | |
return DocPropertyType.OBJECT; | |
} | |
@Override | |
public boolean isDateTimeCapable() { | |
return false; | |
} | |
@Override | |
public T convertFromMillis(long dateTime) { | |
throw new IllegalStateException("Not supported"); | |
} | |
@Override | |
public T readData(DataInput dataInput) throws IOException { | |
if (!dataInput.readBoolean()) { | |
return null; | |
} else { | |
return parse(dataInput.readUTF()); | |
} | |
} | |
@Override | |
public void writeData(DataOutput dataOutput, T value) throws IOException { | |
if (value == null) { | |
dataOutput.writeBoolean(false); | |
} else { | |
ScalarHelp.writeUTF(dataOutput, format(value)); | |
} | |
} | |
@Override | |
public T jsonRead(JsonParser parser) throws IOException { | |
throw new RuntimeException("Should never be called"); | |
} | |
@Override | |
public void jsonWrite(JsonGenerator writer, T value) throws IOException { | |
throw new RuntimeException("Should never be called"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment