Repository navigation
fix: implement ROW_COUNT() affected-row semantics - #25750
Conversation
ROW_COUNT() was an unimplemented stub that always returned 0. Track the previous statement's affected rows on the session and process (mirroring last_insert_id) and have the ROW_COUNT() builtin read it, following MySQL semantics: affected rows for DML, -1 after a result-set statement, and 0 after DDL. Add unit tests at the process/function/frontend layers and a BVT case. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review on the initial ROW_COUNT() fix: - Record the affected-rows value once per statement at the execution point (executeStmtWithResponse), updating both the process and the session, instead of in per-responder code. This fixes ROW_COUNT() inside a multi-statement COM_QUERY (all statements reuse one proc) and keeps the binary-protocol execute path correct. - Drop the now-redundant per-responder writebacks. - BVT: replace the existing-key REPLACE case (MO returns 1, MySQL 2) with a new-key REPLACE so the golden no longer encodes non-MySQL semantics. - Add TestRecordLastAffectedRows. ROW_COUNT() inside stored procedures / after CALL (background NullResp path) is tracked separately in matrixorigin#24783. Co-Authored-By: Claude Opus 4.8 <[email protected]>
recordLastAffectedRows only runs after a statement succeeds, so when the previous statement failed (parse / compile / execution error) ROW_COUNT() kept returning the last successful statement's value. MySQL returns -1 after a failed statement. Set the ROW_COUNT() state to -1 on every error path of the main COM_QUERY / COM_STMT_EXECUTE flow via a deferred handler in doComQuery, covering parse, compile and execution errors. Extend the BVT with a failed-DML case. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two follow-up fixes from review: 1. Mark the row_count() overload as volatile + realTimeRelated, mirroring last_insert_id. Without these flags constant folding froze the value into the prepared plan at PREPARE time, so `prepare s from 'select row_count()'` returned the affected rows captured at prepare time instead of the live session state at EXECUTE time. 2. When parseStmtExecute fails (malformed execute packet, missing prepared statement, binary param decode error) the request returns before reaching doComQuery, so its error defer never ran and the next ROW_COUNT() leaked the previous successful DML value. Reset the ROW_COUNT() state to -1 on that path too. Extracted the shared reset into markRowCountFailed. Tests: frontend unit test for markRowCountFailed; BVT prepared-statement case verifying EXECUTE-time evaluation. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…r paths Follow-up fixes from review: 1. ProcessInfo did not carry AffectedRows, so when an expression that reads ROW_COUNT() (e.g. `select row_count() from <table>` whose projection is pushed down to a TableScan) is shipped to a remote CN, the codec-built proc started at the default 0 instead of the previous statement's affected rows. Added affected_rows to the ProcessInfo proto message and carry/restore it in BuildProcessInfo / Decode. 2. COM_STMT_CLOSE / COM_STMT_RESET returned an error response for a missing prepared statement before reaching doComQuery, so the next ROW_COUNT() leaked the previous value. Reset it to -1 on those paths too, matching the COM_STMT_EXECUTE parse-failure fix. Tests: pipeline.ProcessInfo Marshal/Unmarshal round-trip for AffectedRows (including the -1 sentinel). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ard short packets Follow-up fixes from review: 1. The main remote-run path does not go through process_codec.Decode(); it rebuilds the proc via generateProcessHelper / newCompile in remoterunServer.go, which did not carry AffectedRows. So row_count() pushed down to a remote TableScan/Projection still read the default 0. Carry affected_rows through processHelper and call proc.SetAffectedRows on the rebuilt remote proc. 2. The affected_rows field was hand-added to pipeline.pb.go last round but the embedded FileDescriptor was stale, so Descriptor()/reflection saw the old schema. Regenerated pipeline.pb.go (gogofast) so the descriptor matches. 3. COM_STMT_CLOSE / COM_STMT_RESET read the statement id without a length check, panicking on a short packet (recovered later, but ROW_COUNT() kept its old value). Guard the packet length and reset ROW_COUNT() to -1 on a malformed packet instead. Co-Authored-By: Claude Opus 4.8 <[email protected]>
recordLastAffectedRows() only preserved AffectRows for the Insert/Update/Delete/ Replace/Load AST whitelist and stored 0 for everything else. That discarded the real affected-row count of successful status statements outside the whitelist, e.g. `CREATE TABLE ... AS SELECT` and status-returning `SELECT ... INTO ...`, which run through status_stmt.go with a real runResult.AffectRows. The following `SELECT ROW_COUNT()` then wrongly reported 0. Key the recorded value off the statement's output type instead: - OUTPUT_RESULT_ROW -> -1 - OUTPUT_STATUS -> runResult.AffectRows (DDL/no-op status carry 0) - otherwise -> 0 Removed the now-unused isRowCountDML helper. Added a status-select unit case and a `create table ... as select` BVT case (reports 6, previously 0). Co-Authored-By: Claude Opus 4.8 <[email protected]>
ParseExecuteData() validated the declared length byte of TIME/DATE/DATETIME/ TIMESTAMP binary parameters but not that the payload was actually present. The readTime/readDate/readDateTime/readTimestamp helpers then index the buffer at fixed offsets, so a truncated packet panicked during parsing (recovered later) and skipped the parse-failure path that sets ROW_COUNT() to -1. Guard each temporal case with `pos+int(length) > len(data)` so a truncated payload returns a malformed-packet error, which flows through the normal COM_STMT_EXECUTE failure handling (markRowCountFailed -> -1). Co-Authored-By: Claude Opus 4.8 <[email protected]>
COM_FIELD_LIST is routed through doComQuery as InternalCmdFieldList, whose StmtKind() is OUTPUT_STATUS. Since recordLastAffectedRows runs after every successful statement, an OUTPUT_STATUS statement with no runResult recorded 0, so `INSERT ...; <COM_FIELD_LIST>; SELECT ROW_COUNT()` wrongly returned 0 instead of the insert's affected-row count. InternalCmdFieldList is a protocol-only metadata helper, not a user SQL statement, so skip it in recordLastAffectedRows and leave the preceding statement's ROW_COUNT() state untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two issues found in multi-statement / protocol handling: 1. SELECT ... INTO ... (export) discarded the RunResult from runner.Run(0) in status_stmt.go, and the multi-statement COM_QUERY loop never cleared execCtx.runResult between statements (it is only reset on Close()). So in `UPDATE ...; SELECT ... INTO OUTFILE ...; SELECT ROW_COUNT();` the export statement inherited the UPDATE's affected rows for both ROW_COUNT() and its OK packet. The export branch now keeps its own runResult, and the loop clears execCtx.runResult before each statement so a statement that does not set it no longer inherits a stale value. 2. COM_STMT_CLOSE / COM_STMT_RESET are rewritten to DEALLOCATE/RESET PREPARE and run through doComQuery, so a successful close/reset recorded 0 and clobbered the preceding statement's ROW_COUNT(). These are protocol-only side effects; save and restore the ROW_COUNT() state around the rewritten query on success (a genuine failure still leaves the -1 marking in place). Tests: TestRestoreRowCount; verified the multi-statement export case with go-sql-driver multiStatements=true (returns the export's own count, not the previous UPDATE's). ROW_COUNT() after CALL/stored procedures remains tracked in matrixorigin#24783. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add BVT coverage for two more affected-rows paths the implementation touches: - INSERT ... ON DUPLICATE KEY UPDATE that inserts a new row -> 1 - LOAD DATA INFILE -> number of imported rows (4) Note: REPLACE-over-existing and ON DUPLICATE KEY UPDATE's update/no-op cases are intentionally not added. MatrixOne's executor counts net rows written to the target table once (REPLACE-conflict=1, ODKU update=1, ODKU no-op=1) rather than MySQL's client-protocol convention (2/2/0); see build_dml_util.go addAffectedRows. That is an executor-level affected-rows semantic, independent of ROW_COUNT(), so the golden does not encode the non-MySQL values. Co-Authored-By: Claude Opus 4.8 <[email protected]>
# Conflicts: # pkg/pb/pipeline/pipeline.pb.go
Pin ROW_COUNT() for the high-value duplicate-key paths a reviewer asked about: REPLACE that collides with an existing key, and INSERT ... ON DUPLICATE KEY UPDATE that hits an existing row (real change and no-op). These lock MatrixOne's current values (all 1): MatrixOne counts the net rows written to the target table once, whereas MySQL reports 2 for REPLACE-over- existing and ODKU update, and 0 for an ODKU no-op. That affected-rows divergence is an executor-level semantic (not ROW_COUNT() plumbing) and is tracked separately in matrixorigin#24907; the case comments call this out. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-reviewed current head 005872a8a with a full protocol/state/remote/migration unhappy-path audit. The four previous blockers are resolved: FIELD_LIST and unsupported commands set -1, every COM_STMT_CLOSE path preserves the prior value, and fresh sessions initialize session/process state to -1. SEND_LONG_DATA and truncated binary temporal packets also have explicit failure handling.
The state propagation is closed end-to-end (Session -> Process -> remote ProcessInfo -> receiver, and source CN -> proxy -> target Session), including signed -1 round trips. Q1-Q3 audit found no new resource, wait-termination, or unbounded-accumulation risk.
Local verification passed: go test for frontend/process/function/pipeline/compile/proxy, targeted go test -race, go vet for all affected Go packages, and git diff --check. CI still has jobs in progress but no failures at review time.
Merge Queue Status
This pull request spent 1 hour 29 minutes 45 seconds in the queue, including 58 minutes 43 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #24767
What this PR does / why we need it:
ROW_COUNT()was an unimplemented stub that always returned0. This PR tracks the previous statement affected-row state across the frontend session, process, prepared-statement paths, and remote CN execution, then evaluatesROW_COUNT()at execution time.It follows the expected semantics:
-1after result-set or failed statements;0after statements that affect no rows.It also preserves the state across protocol-only commands and rejects truncated temporal binary parameters without panicking.
Tests cover the function, session/process state, protobuf round trips, frontend protocol paths, prepared statements, multi-statements, REPLACE, ODKU, and LOAD DATA.
Validation:
makego test ./pkg/sql/plan/function ./pkg/vm/process ./pkg/frontend ./pkg/pb/pipelinego test -racefor the new session/process state tests