Skip to content

Commit 958aaf4

Browse files
authored
[fix](protocol) Prevent Connector/J cursor fetch from hanging on empty results (apache#67520)
### What problem does this PR solve? Issue Number: None Related PR: apache#61050, apache#61062 After `CLIENT_DEPRECATE_EOF` is negotiated, affected Connector/J clients using `useCursorFetch=true` and a positive fetch size can hang when a server-prepared statement returns an empty result. The driver consumes the first terminator after column definitions while checking whether a server cursor was created. With no rows, this consumes the only result-end marker, so the driver waits for a packet that Doris will never send. The reported Connector/J 8.2.0 case is covered by real-driver tests. This PR preserves the final result marker for affected clients and avoids inserting the compatibility marker for identified Connector/J 9.5+ and MariaDB clients. It also preserves this behavior through FE forwarding and fixes related packet/capability regressions. ### What is changed? 1. **Cursor result boundaries.** Read `CURSOR_TYPE_READ_ONLY` from each `COM_STMT_EXECUTE`, retain it in the request context, and classify driver behavior using connection attributes. For affected cursor clients with deprecated EOF enabled, insert a compatibility ResultSet OK after metadata so the real final marker remains available. Identified modern clients and ordinary non-cursor requests keep the standard sequence. 2. **FE forwarding.** Forward cursor intent and negotiated capabilities through optional Thrift fields. The master restores them before serializing results. A new follower adapts buffered results from an older master that has not confirmed protocol adaptation: insert/remove/convert metadata boundaries as appropriate and convert the final legacy EOF when needed. Row payloads are retained; confirmed results are not adapted twice. 3. **Complete OK information.** Preserve the original forwarded DML/DDL OK and ERR packets rather than rebuilding a partial successful OK. Retain affected rows, warnings, info, load labels and transaction IDs. Preserve warnings and server status when producing/converting result-set terminators. SQL is not re-executed by this adaptation. 4. **Legacy protocol compatibility.** Configure the serializer using the intersection of client/server capabilities, rather than server defaults. Limit the empty OK-info compatibility byte to the applicable negotiated format, preserving legacy OK behavior. 5. **Arrow follower compatibility.** Access MySQL-channel capabilities only for MySQL connections, so the shared forwarding path does not call the unsupported MySQL-channel getter on an Arrow Flight SQL context. 6. **Clients without connection attributes.** Remove the new fail-fast rejection of anonymous cursor clients. When client behavior is unknown, prioritize the older Connector/J compatibility sequence. This retains the older-client target but cannot simultaneously guarantee compatibility with anonymous clients requiring the standard sequence. 7. **File-load compatibility.** In both LOAD handlers, require `CLIENT_LOCAL_FILES` only for client-side `LOCAL INFILE` uploads. FE-side file reads do not require a client-upload capability and remain usable when that bit is absent. Full PR diff against the merged master, at `32d01e5df19`: | Category | Files | Added lines | Removed lines | Net added lines | |---|---:|---:|---:|---:| | Production code, including Thrift IDL | 12 | 218 | 40 | 178 | | Tests and expected output | 12 | 787 | 13 | 774 | The test total includes 11 automatically generated expected-output lines. Environment configuration and review documents are excluded. ### Compatibility boundaries - This preserves streamed results; it does not implement MySQL server-side cursors or `COM_STMT_FETCH` batching. - **New follower → old master** is covered by the mixed-version client matrix. **Old follower → new master** may have already lost cursor intent; the master cannot reconstruct it. The historical cursor hang on that route remains until the client-facing follower is upgraded. Existing ordinary prepared-statement behavior is retained. - Identified Connector/J 9.5+ and MariaDB clients use the standard path. Anonymous clients requiring that sequence remain outside the older-client fallback guarantee. - The OIDC provider and authentication routing implementation are not changed by this PR. ### Release note Fix affected Connector/J cursor queries hanging on empty prepared results. Preserve negotiated MySQL packet formats, forwarded DML/DDL OK information, Arrow Flight SQL forwarding and FE-side file loading. Upgrade the client-facing follower to preserve cursor intent during an FE rolling upgrade. ### Check List (For Author) - Test: - [x] Unit Test: **113 targeted FE tests passed, 0 failures/errors**, before the final master/JUnit 5 merge. Coverage includes driver classification, cursor boundaries, forwarding, capabilities, packet serialization, authentication routing and both LOAD handlers. - [x] Regression test: `prepared_stmt_p0/cursor_fetch_empty_result`, `prepared_stmt_p0/prepared_show`, and `arrow_flight_sql_p0/test_ddl` through a real follower passed. Cursor expected output was generated by the regression runner. - [x] Manual test: **120 successful real-JDBC driver/endpoint/transport runs** across baseline/candidate direct endpoints, a same-version follower and a new follower targeting an old master, with plaintext/TLS modes. Each driver JAR runs in its own JVM to avoid classpath version collisions. - MySQL Connector/J: **5.1.49, 8.0.28, 8.0.33, 8.2.0, 8.4.0, 9.0.0, 9.4.0, 9.5.0, 9.6.0**. MariaDB Connector/J: **3.5.6**. - Each run exercises 12 requested combinations of cursor/server-prepare switches and fetch sizes **0/1/10000**, repeated Statement/PreparedStatement empty→nonempty→empty results on reused connections, and wrong-password rejection. Drivers may couple cursor and server-prepare settings internally. Connection/read timeouts bound failures; a timeout is not counted as success. - Additional checks passed: explicit TLS 1.2/1.3 (16 groups), MySQL Shell 8/9 ordinary authentication (16), legacy EOF via PyMySQL (8), SQL-error connection reuse (8), and suppressed connection attributes with older drivers (12). - Actual baseline/candidate FE-file and client-file imports passed; forwarded INSERT retained label/status/txnId. Real LDAP/local-password routing, rejected credentials and connection reuse passed 20 baseline/candidate checks across plaintext/TLS. - Independent FE-only raw-protocol tests passed 12 configurations covering multi-result status, cursor transitions, RESET/CLOSE and reuse after errors. These are packet tests, not additional real JDBC runs or proof of mixed-version multi-statement forwarding. - FE build passed before the final master merge. After the merge, standalone `mvn checkstyle:check -pl fe-core -Dcheckstyle.skip=false` passed with **0 violations**. Compilation and unit tests were not rerun after the JUnit 5 migration. - The multi-version JDBC matrix was executed locally with retained scripts/logs; it is not an automatic all-version CI matrix. - Review and validation limits: - The latest independent review of the complete final diff found **0 Blocker / 0 Major production findings**. It noted two deterministic SQL-result assertions that still use `assertEquals` rather than regression `qt` output, and missing dedicated tests for errors occurring after partial metadata or rows have been buffered. Those error paths were inspected in source, not fault-injected; the OK/ERR preservation unit test does not cover buffered intermediate errors. - Connector/J 6.0.6 failed handshakes on both baseline and candidate in six runs; it is not counted as passing or newly supported. - Four broader prepared suites failed identically on baseline/candidate with the available older BE because it cannot execute the plan. Authentication-integration metadata regression also remains incomplete with that BE. Four independent SELECT configurations without a BE were blocked and not counted as passing. - Full product OIDC-provider login/new TLS-extension E2E and the customer's exact SmartBI environment were not validated. Ordinary password/TLS and authentication unit tests do not replace these checks. - Behavior changed: - [x] Yes. Correct cursor packet boundaries, preserve complete forwarded OK information and use negotiated capabilities, with the compatibility boundaries above. - Does this need documentation? - [x] No. ### Check List (For Reviewer who merge this PR) - [ ] Confirm the release note - [ ] Confirm test cases - [ ] Confirm document - [ ] Add branch pick label
1 parent 0d36c66 commit 958aaf4

26 files changed

Lines changed: 1120 additions & 55 deletions
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.apache.doris.mysql;
19+
20+
import com.google.common.collect.ImmutableSet;
21+
22+
import java.util.Map;
23+
import java.util.Set;
24+
import java.util.regex.Pattern;
25+
26+
/** Resolves the incompatible cursor result-set behavior used by Connector/J releases. */
27+
public final class MysqlCursorFetchCompatibility {
28+
private static final Set<String> MYSQL_CONNECTOR_J_CLIENT_NAMES = ImmutableSet.of(
29+
"MySQL Connector/J", "MySQL Connector Java");
30+
private static final Pattern CONSUMES_METADATA_TERMINATOR =
31+
Pattern.compile("^(?:(?:5|6|8)\\.|9\\.[0-4](?:\\.|$))");
32+
private static final Pattern VERSION = Pattern.compile("^\\d+(?:\\.\\d+)+(?:[-+].*)?$");
33+
34+
public enum Behavior {
35+
CONSUMES_METADATA_TERMINATOR,
36+
STANDARD,
37+
UNKNOWN
38+
}
39+
40+
private MysqlCursorFetchCompatibility() {
41+
}
42+
43+
public static Behavior resolve(Map<String, String> connectAttributes) {
44+
String clientName = connectAttributes.get("_client_name");
45+
if (clientName == null) {
46+
return Behavior.UNKNOWN;
47+
}
48+
if (!MYSQL_CONNECTOR_J_CLIENT_NAMES.contains(clientName)) {
49+
return Behavior.STANDARD;
50+
}
51+
52+
String clientVersion = connectAttributes.get("_client_version");
53+
if (clientVersion == null || !VERSION.matcher(clientVersion).matches()) {
54+
return Behavior.UNKNOWN;
55+
}
56+
if (CONSUMES_METADATA_TERMINATOR.matcher(clientVersion).find()) {
57+
return Behavior.CONSUMES_METADATA_TERMINATOR;
58+
}
59+
return Behavior.STANDARD;
60+
}
61+
}

‎fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlOkPacket.java‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,11 @@ public void writeTo(MysqlSerializer serializer) {
5858
// TODO(zhaochun): STATUS_FLAGS
5959
// if ((STATUS_FLAGS & MysqlStatusFlag.SERVER_SESSION_STATE_CHANGED) != 0) {
6060
// }
61-
} else {
62-
// Always write the info field as a length-encoded string.
63-
// When CLIENT_DEPRECATE_EOF is negotiated, the driver's OkPacket.parse()
64-
// unconditionally reads STRING_LENENC for info, so an empty string must
65-
// still be written (as a single 0x00 byte representing length 0).
66-
if (Strings.isNullOrEmpty(infoMessage)) {
67-
serializer.writeVInt(0);
68-
} else {
69-
serializer.writeLenEncodedString(infoMessage);
70-
}
61+
} else if (!Strings.isNullOrEmpty(infoMessage)) {
62+
serializer.writeLenEncodedString(infoMessage);
63+
} else if (capability.isDeprecatedEOF()) {
64+
// Connector/J parses the info field for CLIENT_DEPRECATE_EOF even when it is empty.
65+
serializer.writeVInt(0);
7166
}
7267
}
7368
}

‎fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlProto.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -183,10 +183,6 @@ public static boolean negotiate(ConnectContext context) throws IOException {
183183
if (handshakeResponse == null) {
184184
return failHandshake(context, CLIENT_CLOSED_CONNECTION_DURING_HANDSHAKE);
185185
}
186-
if (capability.isDeprecatedEOF()) {
187-
context.getMysqlChannel().setClientDeprecatedEOF();
188-
}
189-
190186
// we do not save client capability to context, so here we save CLIENT_MULTI_STATEMENTS to MysqlChannel
191187
if (capability.isClientMultiStatements()) {
192188
context.getMysqlChannel().setClientMultiStatements();
@@ -208,7 +204,11 @@ public static boolean negotiate(ConnectContext context) throws IOException {
208204
}
209205

210206
// change the capability of serializer
211-
context.setCapability(context.getServerCapability());
207+
context.setCapability(new MysqlCapability(context.getServerCapability().getFlags()
208+
& authPacket.getCapability().getFlags()));
209+
if (context.getCapability().isDeprecatedEOF()) {
210+
channel.setClientDeprecatedEOF();
211+
}
212212
serializer.setCapability(context.getCapability());
213213

214214
String qualifiedUser = parseUser(context, authPacket.getAuthResponse(), authPacket.getUser());

‎fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlResultSetEndPacket.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public class MysqlResultSetEndPacket extends MysqlPacket {
4040

4141
public MysqlResultSetEndPacket(QueryState state) {
4242
this.serverStatus = state.serverStatus;
43+
this.warningCount = state.getWarningRows();
4344
}
4445

4546
@Override

‎fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/LoadCommand.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ public void handleLoadCommand(ConnectContext ctx, StmtExecutor executor) {
496496
}
497497
LoadManager loadManager = ctx.getEnv().getLoadManager();
498498
if (etlJobType == EtlJobType.LOCAL_FILE) {
499-
if (!ctx.getCapability().supportClientLocalFile()) {
499+
if (getDataDescriptions().get(0).isClientLocal() && !ctx.getCapability().supportClientLocalFile()) {
500500
ctx.getState().setError(ErrorCode.ERR_NOT_ALLOWED_COMMAND, "This client is not support"
501501
+ " to load client local file.");
502502
return;

‎fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/load/MysqlLoadCommand.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ public void validate(ConnectContext ctx) throws UserException, IOException {
219219
private void handleMysqlLoadCommand(ConnectContext ctx) {
220220
try {
221221
LoadManager loadManager = ctx.getEnv().getLoadManager();
222-
if (!ctx.getCapability().supportClientLocalFile()) {
222+
if (mysqlDataDescription.isClientLocal() && !ctx.getCapability().supportClientLocalFile()) {
223223
ctx.getState().setError(ErrorCode.ERR_NOT_ALLOWED_COMMAND, "This client is not support"
224224
+ " to load client local file.");
225225
return;

‎fe/fe-core/src/main/java/org/apache/doris/qe/ConnectContext.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,9 @@ public enum ConnectType {
287287
@Setter
288288
private ByteBuffer prepareExecuteBuffer;
289289

290+
// Whether the current COM_STMT_EXECUTE requested a server-side read-only cursor.
291+
private boolean cursorFetchRequested;
292+
290293
private MysqlHandshakePacket mysqlHandshakePacket;
291294

292295
public void setUserQueryTimeout(int queryTimeout) {
@@ -513,6 +516,14 @@ public void setConnectAttributes(Map<String, String> connectAttributes) {
513516
this.connectAttributes = new HashMap<>(connectAttributes);
514517
}
515518

519+
public boolean isCursorFetchRequested() {
520+
return cursorFetchRequested;
521+
}
522+
523+
public void setCursorFetchRequested(boolean cursorFetchRequested) {
524+
this.cursorFetchRequested = cursorFetchRequested;
525+
}
526+
516527
public boolean isTxnModel() {
517528
return txnEntry != null && txnEntry.isTxnModel();
518529
}
@@ -1008,6 +1019,7 @@ public void clear() {
10081019
statementContext = null;
10091020
loadBackendSelectionDecision = null;
10101021
loadBackendSelectionHint = null;
1022+
cursorFetchRequested = false;
10111023
}
10121024

10131025
// Arrow Flight SQL only.

‎fe/fe-core/src/main/java/org/apache/doris/qe/ConnectProcessor.java‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
import org.apache.doris.datasource.DelegatedCredential;
5555
import org.apache.doris.datasource.SessionContext;
5656
import org.apache.doris.metric.MetricRepo;
57+
import org.apache.doris.mysql.MysqlCapability;
5758
import org.apache.doris.mysql.MysqlChannel;
5859
import org.apache.doris.mysql.MysqlCommand;
5960
import org.apache.doris.mysql.MysqlPacket;
@@ -754,15 +755,10 @@ public TMasterOpResult proxyExecute(TMasterOpRequest request) throws TException
754755
// set compute group
755756
ctx.setComputeGroup(Env.getCurrentEnv().getAuth().getComputeGroup(ctx.getQualifiedUser()));
756757

757-
// Propagate the client's CLIENT_DEPRECATE_EOF capability to the proxy channel.
758-
// This ensures the master generates packets matching the original client's protocol.
759-
if (request.isSetClientDeprecatedEOF() && request.isClientDeprecatedEOF()) {
760-
ctx.getMysqlChannel().setClientDeprecatedEOF();
761-
}
762-
763758
ctx.setThreadLocalInfo();
764759
StmtExecutor executor = null;
765760
try {
761+
restoreForwardedMysqlContext(ctx, request);
766762
// 0 for compatibility.
767763
int idx = request.isSetStmtIdx() ? request.getStmtIdx() : 0;
768764
executor = new StmtExecutor(ctx, new OriginStatement(request.getSql(), idx), true);
@@ -848,6 +844,7 @@ public TMasterOpResult proxyExecute(TMasterOpRequest request) throws TException
848844
ctx.getState().serverStatus |= MysqlServerStatusFlag.SERVER_MORE_RESULTS_EXISTS;
849845
}
850846
result.setPacket(getResultPacket());
847+
result.setClientDeprecatedEofApplied(ctx.getMysqlChannel().clientDeprecatedEOF());
851848
result.setStatus(ctx.getState().toString());
852849
if (ctx.getState().getStateType() == MysqlStateType.OK) {
853850
result.setStatusCode(0);
@@ -883,6 +880,24 @@ public TMasterOpResult proxyExecute(TMasterOpRequest request) throws TException
883880
return result;
884881
}
885882

883+
static void restoreForwardedMysqlContext(ConnectContext context, TMasterOpRequest request) {
884+
int flags = request.isSetMysqlCapability() ? request.getMysqlCapability()
885+
: MysqlCapability.DEFAULT_CAPABILITY.getFlags()
886+
& ~MysqlCapability.Flag.CLIENT_DEPRECATE_EOF.getFlagBit();
887+
if (request.isSetClientDeprecatedEOF() && request.isClientDeprecatedEOF()) {
888+
flags |= MysqlCapability.Flag.CLIENT_DEPRECATE_EOF.getFlagBit();
889+
}
890+
MysqlCapability capability = new MysqlCapability(flags);
891+
context.setCapability(capability);
892+
context.getMysqlChannel().getSerializer().setCapability(capability);
893+
if (capability.isDeprecatedEOF()) {
894+
context.getMysqlChannel().setClientDeprecatedEOF();
895+
}
896+
// Old followers do not carry the cursor flag. Keep their existing behavior; they must
897+
// be upgraded to preserve cursor intent. Do not reject their ordinary prepared statements.
898+
context.setCursorFetchRequested(request.isSetCursorFetchRequested() && request.isCursorFetchRequested());
899+
}
900+
886901
static void restoreForwardedSessionContext(ConnectContext context, TMasterOpRequest request) {
887902
if (!request.isSetDelegatedCredentialToken()) {
888903
return;

‎fe/fe-core/src/main/java/org/apache/doris/qe/FEOpExecutor.java‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
import org.apache.doris.common.ErrorCode;
2727
import org.apache.doris.datasource.DelegatedCredential;
2828
import org.apache.doris.mysql.MysqlCommand;
29+
import org.apache.doris.mysql.MysqlCursorFetchCompatibility;
30+
import org.apache.doris.mysql.MysqlProto;
31+
import org.apache.doris.mysql.MysqlResultSetEndPacket;
32+
import org.apache.doris.mysql.MysqlSerializer;
2933
import org.apache.doris.qe.ConnectContext.ConnectType;
3034
import org.apache.doris.thrift.FrontendService;
3135
import org.apache.doris.thrift.TExpr;
@@ -46,6 +50,7 @@
4650
import org.apache.thrift.transport.TTransportException;
4751

4852
import java.nio.ByteBuffer;
53+
import java.util.ArrayList;
4954
import java.util.Collections;
5055
import java.util.List;
5156
import java.util.Map;
@@ -215,6 +220,7 @@ protected TMasterOpRequest buildStmtForwardParams() throws AnalysisException {
215220
if (null != ctx.getPrepareExecuteBuffer()) {
216221
params.setPrepareExecuteBuffer(ctx.getPrepareExecuteBuffer());
217222
}
223+
params.setCursorFetchRequested(ctx.isCursorFetchRequested());
218224
}
219225

220226
ctx.getSessionContext().getDelegatedCredential().ifPresent((DelegatedCredential credential) -> {
@@ -231,6 +237,7 @@ protected TMasterOpRequest buildStmtForwardParams() throws AnalysisException {
231237
// master on its default packet layout.
232238
if (ctx.getConnectType() == ConnectType.MYSQL) {
233239
params.setClientDeprecatedEOF(ctx.getMysqlChannel().clientDeprecatedEOF());
240+
params.setMysqlCapability(ctx.getCapability().getFlags());
234241
}
235242

236243
return params;
@@ -264,6 +271,76 @@ public ByteBuffer getOutputPacket() {
264271
return result.packet;
265272
}
266273

274+
public boolean isClientDeprecatedEofApplied() {
275+
return result != null && result.isSetClientDeprecatedEofApplied()
276+
&& result.isClientDeprecatedEofApplied();
277+
}
278+
279+
public boolean hasQueryResultPackets() {
280+
return result != null && result.isSetQueryResultBufList()
281+
&& !result.getQueryResultBufList().isEmpty();
282+
}
283+
284+
// An old master cannot add the Connector/J cursor terminator. Normalize its buffered
285+
// result at the follower, which still has the original execute flag and client capability.
286+
// DML/DDL OK and ERR packets are retained verbatim, including warnings and load info.
287+
public void prepareQueryResultForClient() {
288+
if (!ctx.getMysqlChannel().clientDeprecatedEOF() || isClientDeprecatedEofApplied()
289+
|| !hasQueryResultPackets()) {
290+
return;
291+
}
292+
List<ByteBuffer> packets = new ArrayList<>(result.getQueryResultBufList());
293+
int metadataEnd = Math.toIntExact(MysqlProto.readVInt(packets.get(0).duplicate())) + 1;
294+
boolean needsCursorTerminator = ctx.isCursorFetchRequested()
295+
&& MysqlCursorFetchCompatibility.resolve(ctx.getConnectAttributes())
296+
!= MysqlCursorFetchCompatibility.Behavior.STANDARD;
297+
// An execution error may occur after only part of the metadata has been buffered.
298+
if (metadataEnd > packets.size()) {
299+
Preconditions.checkState(isErrorPacket(result.packet));
300+
return;
301+
}
302+
boolean hasMetadataTerminator = metadataEnd < packets.size()
303+
&& isEofPacket(packets.get(metadataEnd));
304+
if (hasMetadataTerminator) {
305+
ByteBuffer metadata = packets.remove(metadataEnd);
306+
if (needsCursorTerminator) {
307+
packets.add(metadataEnd, resultSetTerminator(metadata));
308+
}
309+
} else if (needsCursorTerminator) {
310+
MysqlSerializer serializer = MysqlSerializer.newInstance(ctx.getCapability());
311+
new MysqlResultSetEndPacket(new QueryState()).writeTo(serializer);
312+
packets.add(metadataEnd, serializer.toByteBuffer());
313+
}
314+
result.setQueryResultBufList(packets);
315+
if (isEofPacket(result.packet)) {
316+
result.setPacket(resultSetTerminator(result.packet));
317+
}
318+
result.setClientDeprecatedEofApplied(true);
319+
}
320+
321+
private static boolean isErrorPacket(ByteBuffer packet) {
322+
return Byte.toUnsignedInt(packet.get(packet.position())) == 0xFF;
323+
}
324+
325+
private static boolean isEofPacket(ByteBuffer packet) {
326+
return packet.remaining() <= 8 && Byte.toUnsignedInt(packet.get(packet.position())) == 0xFE;
327+
}
328+
329+
private static ByteBuffer resultSetTerminator(ByteBuffer packet) {
330+
if (packet.remaining() != 5) {
331+
return packet;
332+
}
333+
ByteBuffer eof = packet.duplicate();
334+
MysqlProto.readInt1(eof);
335+
int warnings = MysqlProto.readInt2(eof);
336+
QueryState state = new QueryState();
337+
state.setOk(0, warnings, null);
338+
state.serverStatus = MysqlProto.readInt2(eof);
339+
MysqlSerializer serializer = MysqlSerializer.newInstance();
340+
new MysqlResultSetEndPacket(state).writeTo(serializer);
341+
return serializer.toByteBuffer();
342+
}
343+
267344
public TUniqueId getQueryId() {
268345
if (result != null && result.isSetQueryId()) {
269346
return result.getQueryId();

‎fe/fe-core/src/main/java/org/apache/doris/qe/MysqlConnectProcessor.java‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
*/
6464
public class MysqlConnectProcessor extends ConnectProcessor {
6565
private static final Logger LOG = LogManager.getLogger(MysqlConnectProcessor.class);
66+
private static final int CURSOR_TYPE_READ_ONLY = 0x01;
6667

6768
private ByteBuffer packetBuf;
6869

@@ -128,13 +129,14 @@ protected void handleExecute(PrepareCommand prepareCommand, long stmtId, Prepare
128129
String stmtStr = "";
129130
try {
130131
StatementContext statementContext = prepCtx.getStatementContext();
132+
if (!ctx.isProxy()) {
133+
// An empty buffer still identifies a zero-parameter COM_STMT_EXECUTE when forwarding.
134+
ctx.setPrepareExecuteBuffer(packetBuf.duplicate());
135+
}
131136
if (paramCount > 0) {
132137
if (LOG.isDebugEnabled()) {
133138
LOG.debug("execute param buf: {}, array: {}", packetBuf, getHexStr(packetBuf));
134139
}
135-
if (!ctx.isProxy()) {
136-
ctx.setPrepareExecuteBuffer(packetBuf.duplicate());
137-
}
138140
byte[] nullbitmapData = new byte[(paramCount + 7) / 8];
139141
packetBuf.get(nullbitmapData);
140142
// new_params_bind_flag
@@ -208,8 +210,8 @@ private void handleExecute() {
208210
packetBuf = packetBuf.order(ByteOrder.LITTLE_ENDIAN);
209211
// parse stmt_id, flags, params
210212
int stmtId = packetBuf.getInt();
211-
// flag
212-
packetBuf.get();
213+
int flags = Byte.toUnsignedInt(packetBuf.get());
214+
ctx.setCursorFetchRequested((flags & CURSOR_TYPE_READ_ONLY) != 0);
213215
// iteration_count always 1,
214216
packetBuf.getInt();
215217
if (LOG.isDebugEnabled()) {

0 commit comments

Comments
 (0)