Skip to content

Commit

Permalink
Refactor StringCodec
Browse files Browse the repository at this point in the history
Introduce constructor accepting the default and array type for character codecs.

[#488]

Signed-off-by: Mark Paluch <mpaluch@vmware.com>
  • Loading branch information
mp911de committed Mar 16, 2022
1 parent 70df7c7 commit 3948f06
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/main/java/io/r2dbc/postgresql/codec/StringCodec.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.EnumSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static io.r2dbc.postgresql.codec.PostgresqlObjectId.BPCHAR;
import static io.r2dbc.postgresql.codec.PostgresqlObjectId.CHAR;
Expand All @@ -48,22 +49,32 @@ final class StringCodec extends AbstractCodec<String> implements ArrayCodecDeleg

private final ByteBufAllocator byteBufAllocator;

private final PostgresTypeIdentifier defaultType;

private final PostgresTypeIdentifier arrayType;

StringCodec(ByteBufAllocator byteBufAllocator) {
this(byteBufAllocator, VARCHAR, VARCHAR_ARRAY);
}

StringCodec(ByteBufAllocator byteBufAllocator, PostgresTypeIdentifier defaultType, PostgresTypeIdentifier arrayType) {
super(String.class);
this.byteBufAllocator = Assert.requireNonNull(byteBufAllocator, "byteBufAllocator must not be null");
this.defaultType = Assert.requireNonNull(defaultType, "defaultType must not be null");
this.arrayType = Assert.requireNonNull(arrayType, "arrayType must not be null");
}

@Override
public EncodedParameter encodeNull() {
return createNull(FORMAT_TEXT, VARCHAR);
return createNull(FORMAT_TEXT, this.defaultType);
}

@Override
boolean doCanDecode(PostgresqlObjectId type, Format format) {
Assert.requireNonNull(format, "format must not be null");
Assert.requireNonNull(type, "type must not be null");

return SUPPORTED_TYPES.contains(type);
return this.defaultType == type || SUPPORTED_TYPES.contains(type);
}

@Override
Expand All @@ -75,7 +86,7 @@ String doDecode(ByteBuf buffer, PostgresTypeIdentifier dataType, @Nullable Forma

@Override
EncodedParameter doEncode(String value) {
return doEncode(value, VARCHAR);
return doEncode(value, this.defaultType);
}

@Override
Expand All @@ -94,12 +105,12 @@ public String encodeToText(String value) {

@Override
public PostgresTypeIdentifier getArrayDataType() {
return VARCHAR_ARRAY;
return this.arrayType;
}

@Override
public Iterable<PostgresTypeIdentifier> getDataTypes() {
return SUPPORTED_TYPES.stream().map(PostgresTypeIdentifier.class::cast).collect(Collectors.toList());
return Stream.concat(Stream.of(this.defaultType), SUPPORTED_TYPES.stream()).map(PostgresTypeIdentifier.class::cast).collect(Collectors.toSet());
}

private static class StringDecoder implements Codec<String>, Decoder<String> {
Expand Down

0 comments on commit 3948f06

Please sign in to comment.