Skip to content

Commit 5c27795

Browse files
committed
2 parents 98b8480 + 9c6363a commit 5c27795

4 files changed

Lines changed: 417 additions & 9 deletions

File tree

‎postgresw/src/main/java/com/arcadedb/postgres/PostgresNetworkExecutor.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,11 @@ else if (record instanceof Edge)
10121012
}
10131013

10141014
private void bindCommand() {
1015+
// Track read progress so a mid-message exception can drain the remaining Bind bytes
1016+
// and keep the channel aligned for the next message.
1017+
int totalParamValues = 0;
1018+
int paramsConsumed = 0;
1019+
boolean resultFormatSectionRead = false;
10151020
try {
10161021
// BIND
10171022
final String portalName = readString();
@@ -1047,6 +1052,7 @@ private void bindCommand() {
10471052
}
10481053

10491054
final int paramValuesCount = channel.readShort();
1055+
totalParamValues = paramValuesCount;
10501056
if (DEBUG)
10511057
LogManager.instance().log(this, Level.INFO, "PSQL: bind paramValuesCount=%d (thread=%s)",
10521058
paramValuesCount, Thread.currentThread().threadId());
@@ -1085,6 +1091,7 @@ private void bindCommand() {
10851091
LogManager.instance().log(this, Level.INFO, "PSQL: bind deserializing param %d typeCode=%d formatCode=%d (thread=%s)",
10861092
i, typeCode, formatCode, Thread.currentThread().threadId());
10871093
portal.parameterValues.add(PostgresType.deserialize(typeCode, formatCode, paramValue));
1094+
paramsConsumed = i + 1;
10881095
if (DEBUG)
10891096
LogManager.instance().log(this, Level.INFO, "PSQL: bind param %d deserialized (thread=%s)", i, Thread.currentThread().threadId());
10901097
}
@@ -1103,6 +1110,7 @@ private void bindCommand() {
11031110
LogManager.instance().log(this, Level.INFO, "PSQL: bind resultFormats=%s (0=text, 1=binary) (thread=%s)",
11041111
portal.resultFormats, Thread.currentThread().threadId());
11051112
}
1113+
resultFormatSectionRead = true;
11061114

11071115
if (errorInTransaction)
11081116
return;
@@ -1120,6 +1128,23 @@ private void bindCommand() {
11201128
writeMessage("bind complete", null, '2', 4);
11211129

11221130
} catch (final Exception e) {
1131+
// Best-effort drain of the remaining Bind message so the channel stays aligned
1132+
// for the next message in the pipelined client request (Describe, Execute, Sync).
1133+
try {
1134+
for (int i = paramsConsumed; i < totalParamValues; i++) {
1135+
final long sz = channel.readUnsignedInt();
1136+
if (sz > 0)
1137+
channel.readBytes(new byte[(int) sz]);
1138+
}
1139+
if (!resultFormatSectionRead) {
1140+
final int resultFormatCount = channel.readShort();
1141+
for (int i = 0; i < resultFormatCount; i++)
1142+
channel.readUnsignedShort();
1143+
}
1144+
} catch (final Exception ignored) {
1145+
// If even the drain fails the channel is unrecoverable; the error response below
1146+
// still goes out and the client will see the failure.
1147+
}
11231148
setErrorInTx();
11241149
writeError(ERROR_SEVERITY.ERROR, "Error on parsing bind message: " + e.getMessage(), "XX000");
11251150
}

‎postgresw/src/main/java/com/arcadedb/postgres/PostgresType.java‎

Lines changed: 66 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ public enum PostgresType {
7474
// PostgreSQL-compatible datetime format (ISO 8601 without 'T' separator)
7575
private static final String POSTGRES_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSSSS";
7676
private static final DateTimeFormatter POSTGRES_DATETIME_FORMATTER = DateTimeFormatter.ofPattern(POSTGRES_TIMESTAMP_FORMAT);
77+
// PostgreSQL caps array dimensions at 6 (MAXDIM in pg_config_manual.h).
78+
private static final int MAX_ARRAY_DIMENSIONS = 6;
7779

7880
public final int code;
7981
public final Class<?> cls;
@@ -509,15 +511,73 @@ private static Object deserializeBinary(final long code, final byte[] valueAsByt
509511
buffer.get(bytes);
510512
yield new JSONObject(new String(bytes));
511513
}
512-
case ARRAY_INT, ARRAY_LONG, ARRAY_DOUBLE, ARRAY_REAL, ARRAY_TEXT, ARRAY_BOOLEAN, ARRAY_CHAR, ARRAY_JSON -> {
513-
// For binary format, would need to implement proper array binary deserialization
514-
// This is a simplified placeholder - proper implementation would need to handle
515-
// array dimensions and element deserialization according to PostgreSQL protocol
516-
throw new PostgresProtocolException("Binary deserialization for arrays not yet implemented");
517-
}
514+
case ARRAY_INT, ARRAY_LONG, ARRAY_DOUBLE, ARRAY_REAL, ARRAY_TEXT, ARRAY_BOOLEAN, ARRAY_CHAR, ARRAY_JSON ->
515+
deserializeBinaryArray(buffer);
518516
};
519517
}
520518

519+
private static List<Object> deserializeBinaryArray(ByteBuffer buffer) {
520+
final int ndim = buffer.getInt(); // number of dimensions
521+
buffer.getInt(); // hasnull flag (unused)
522+
final int elemOid = buffer.getInt(); // element type OID
523+
524+
if (ndim == 0)
525+
return new ArrayList<>();
526+
527+
if (ndim < 0 || ndim > MAX_ARRAY_DIMENSIONS)
528+
throw new PostgresProtocolException("Invalid array dimension count: " + ndim);
529+
530+
long totalElements = 1L;
531+
for (int d = 0; d < ndim; d++) {
532+
final int dimSize = buffer.getInt();
533+
buffer.getInt(); // lower bound (unused)
534+
if (dimSize < 0)
535+
throw new PostgresProtocolException("Negative array dimension size: " + dimSize);
536+
totalElements *= dimSize;
537+
if (totalElements > Integer.MAX_VALUE)
538+
throw new PostgresProtocolException("Array element count exceeds Integer.MAX_VALUE");
539+
}
540+
541+
// Each element occupies at least 4 bytes (the length prefix), so an element count
542+
// exceeding remaining/4 cannot fit and signals a malformed or malicious payload.
543+
if (totalElements > buffer.remaining() / 4L)
544+
throw new PostgresProtocolException("Array element count exceeds remaining buffer bytes");
545+
546+
final int count = (int) totalElements;
547+
final ArrayList<Object> result = new ArrayList<>(count);
548+
for (int i = 0; i < count; i++) {
549+
final int elemLen = buffer.getInt();
550+
if (elemLen == -1) {
551+
result.add(null);
552+
} else {
553+
final byte[] elemBytes = new byte[elemLen];
554+
buffer.get(elemBytes);
555+
result.add(deserializeBinaryElement(elemOid, elemBytes));
556+
}
557+
}
558+
return result;
559+
}
560+
561+
private static Object deserializeBinaryElement(final int elemOid, final byte[] bytes) {
562+
final ByteBuffer buf = ByteBuffer.wrap(bytes);
563+
if (elemOid == BOOLEAN.code)
564+
return buf.get() != 0;
565+
if (elemOid == LONG.code)
566+
return buf.getLong();
567+
// int2[] (OID 1005) is not in the ARRAY_* enum, but int2 elements can appear inside
568+
// any array (e.g. composite types), so we still decode them as Short here.
569+
if (elemOid == SMALLINT.code)
570+
return buf.getShort();
571+
if (elemOid == INTEGER.code)
572+
return buf.getInt();
573+
if (elemOid == REAL.code)
574+
return buf.getFloat();
575+
if (elemOid == DOUBLE.code)
576+
return buf.getDouble();
577+
// text/varchar/bpchar/json/unknown - raw bytes are already the UTF-8 string content.
578+
return new String(bytes, DatabaseFactory.getDefaultCharset());
579+
}
580+
521581
/**
522582
* Checks if this type is an array type.
523583
*/

‎postgresw/src/test/java/com/arcadedb/postgres/PostgresProtocolIT.java‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,4 +1056,68 @@ void selectWhere1Eq0OnEmptyTypeReturnsSchemaColumns() throws Exception {
10561056
}
10571057
}
10581058

1059+
// ==================== PreparedStatement.setArray Tests ====================
1060+
1061+
@Test
1062+
void preparedStatementSetArrayTextDoesNotHang() throws Exception {
1063+
// PreparedStatement.setArray with text[] sends a binary-format parameter in the Bind message.
1064+
// Previously this threw "Binary deserialization for arrays not yet implemented" and left the
1065+
// channel in an inconsistent state, causing both client and server to block on socket reads.
1066+
try (var conn = getConnection()) {
1067+
try (var st = conn.createStatement()) {
1068+
st.execute("CREATE DOCUMENT TYPE SetArrayTextTest IF NOT EXISTS");
1069+
st.execute("INSERT INTO SetArrayTextTest SET name = 'alpha', tag = 'a'");
1070+
st.execute("INSERT INTO SetArrayTextTest SET name = 'beta', tag = 'b'");
1071+
st.execute("INSERT INTO SetArrayTextTest SET name = 'gamma', tag = 'c'");
1072+
}
1073+
1074+
try (var pst = conn.prepareStatement("SELECT FROM SetArrayTextTest WHERE tag IN ?")) {
1075+
Array arr = conn.createArrayOf("text", new Object[]{"a", "c"});
1076+
pst.setArray(1, arr);
1077+
try (ResultSet rs = pst.executeQuery()) {
1078+
// Iterating must complete without blocking. We do not assert row count because the
1079+
// engine's handling of an array-typed IN parameter is orthogonal to the protocol fix.
1080+
while (rs.next()) {
1081+
// drain
1082+
}
1083+
}
1084+
}
1085+
1086+
// Connection state must remain intact: a subsequent statement on the same connection
1087+
// succeeds, proving the wire protocol is still aligned after the binary-array bind.
1088+
try (var st = conn.createStatement(); var rs = st.executeQuery("SELECT count(*) AS c FROM SetArrayTextTest")) {
1089+
assertThat(rs.next()).isTrue();
1090+
assertThat(rs.getInt("c")).isEqualTo(3);
1091+
}
1092+
}
1093+
}
1094+
1095+
@Test
1096+
void preparedStatementSetArrayLongDoesNotHang() throws Exception {
1097+
// int8[] (ARRAY_LONG) binary deserialization must also not hang.
1098+
try (var conn = getConnection()) {
1099+
try (var st = conn.createStatement()) {
1100+
st.execute("CREATE DOCUMENT TYPE SetArrayLongTest IF NOT EXISTS");
1101+
st.execute("INSERT INTO SetArrayLongTest SET id = 1, name = 'one'");
1102+
st.execute("INSERT INTO SetArrayLongTest SET id = 2, name = 'two'");
1103+
}
1104+
1105+
try (var pst = conn.prepareStatement("SELECT FROM SetArrayLongTest WHERE id IN ?")) {
1106+
Array arr = conn.createArrayOf("int8", new Object[]{1L, 2L});
1107+
pst.setArray(1, arr);
1108+
try (ResultSet rs = pst.executeQuery()) {
1109+
while (rs.next()) {
1110+
// drain
1111+
}
1112+
}
1113+
}
1114+
1115+
// Subsequent query on the same connection proves channel alignment is intact.
1116+
try (var st = conn.createStatement(); var rs = st.executeQuery("SELECT count(*) AS c FROM SetArrayLongTest")) {
1117+
assertThat(rs.next()).isTrue();
1118+
assertThat(rs.getInt("c")).isEqualTo(2);
1119+
}
1120+
}
1121+
}
1122+
10591123
}

0 commit comments

Comments
 (0)