Skip to content

4.0: fix: implement ROW_COUNT() to return previous statement's affected rows - #24768

Closed
ck89119 wants to merge 14 commits into
matrixorigin:4.0-devfrom
ck89119:row-affected
Closed

ck89119 wants to merge 14 commits into
matrixorigin:4.0-devfrom
ck89119:row-affected

Conversation

@ck89119

@ck89119 ck89119 commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

issue #24767

What this PR does / why we need it:

ROW_COUNT() was an unimplemented stub that always returned 0, so it never
reflected the previous statement's affected rows.

This PR tracks the previous statement's affected rows on the session and
process (mirroring how last_insert_id() is plumbed) and has the
ROW_COUNT() builtin read it, following MySQL semantics:

  • affected rows for DML (INSERT/UPDATE/DELETE/REPLACE/LOAD);
  • -1 after a statement that returns a result set (e.g. SELECT);
  • 0 after a statement that affects no rows (e.g. DDL).

The builtin's return type is changed from uint64 to int64 to allow the
-1 sentinel.

Note: the affected-rows count in the protocol OK packet was already correct
(verified across text protocol, server-side PREPARE/EXECUTE, and binary
protocol); the bug was strictly in the ROW_COUNT() SQL function.

Tests: unit tests at the process/function/frontend layers and a BVT case
(test/distributed/cases/function/row_count.{sql,result}).

…ed rows

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]>
@ck89119
ck89119 requested a review from a user June 2, 2026 04:34
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

… bvt

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]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking correctness issue:

recordLastAffectedRows() is still too narrow. It only preserves execCtx.runResult.AffectRows for Insert/Update/Delete/Replace/Load, and otherwise stores either -1 (result-set statement) or 0.

That loses valid affected-row counts for successful statements outside that small whitelist. In particular, MatrixOne already has status-returning SELECT ... INTO ... paths that execute through status_stmt.go with a real execCtx.runResult.AffectRows, but tree.Select with Ep != nil is a status statement (pkg/sql/parsers/tree/stmt.go), so the new logic falls through to 0 instead of preserving the actual affected-row count.

So the core semantic contract is still wrong for at least that class of statements: the following SELECT ROW_COUNT() will report 0 even though the executor already knows how many rows were processed.

Please base the recorded value on statement/result behavior rather than the current hard-coded DML AST whitelist, and add coverage for a successful status-returning SELECT ... INTO ... (or equivalent non-result-set path with AffectRows).

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]>

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean MySQL-compatible ROW_COUNT() implementation. Previously a stub returning 0.

Session state: lastAffectedRows int64 added to Session, protected by mutex (SetLastAffectedRows/GetLastAffectedRows).

MySQL semantics correct:

  • -1 after result-set statements (SELECT/SHOW)
  • 0 after DDL
  • Actual count after DML
  • -1 after a failed statement (the statement following a failed one returns -1)

Multi-statement COM_QUERY: recordLastAffectedRows called per-statement. Session carries state across statements. Deferred markRowCountFailed sets -1 on any error path in doComQuery.

Binary protocol: COM_STMT_EXECUTE and COM_STMT_CLOSE paths have explicit markRowCountFailed calls for parse/compile failures and malformed packets (also adds a bounds check for <4 byte CLOSE packet — fixing a latent panic).

Pipeline proto: int64 affected_rows added to InstructionInfo, plumbed through process_types.go and process_codec.go for remote execution.

BVT: 71 new result lines covering DML (INSERT/UPDATE/DELETE/REPLACE), SELECT, SHOW, DDL (CREATE/DROP), multi-statement, failed statements, subquery, VALUES, LOAD DATA.

LGTM.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking correctness issue:

The earlier status SELECT / SELECT ... INTO issue looks fixed on the latest head, but the new unconditional ROW_COUNT recording now lets COM_FIELD_LIST clobber the previous SQL statement's ROW_COUNT state.

COM_FIELD_LIST is routed through doComQuery, represented as InternalCmdFieldList, and its StmtKind() reports OUTPUT_STATUS. After every successful statement, executeStmtWithResponse now unconditionally calls recordLastAffectedRows, and for an OUTPUT_STATUS statement with no runResult that stores 0.

So a sequence like:

  1. INSERT ... -- ROW_COUNT should become affected rows
  2. client sends COM_FIELD_LIST
  3. SELECT ROW_COUNT()

will now return 0 instead of the insert's affected-row count, even though COM_FIELD_LIST is just a protocol metadata helper rather than a user-visible SQL statement.

Please exclude internal/protocol-only helper statements such as InternalCmdFieldList from ROW_COUNT state updates.

ck89119 and others added 2 commits June 9, 2026 11:35
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]>
…mmands

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]>

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我这轮没有再挖到新的硬 correctness blocker,但按高标准看,当前 BVT 对 ROW_COUNT() 这个用户可见语义的几个高价值场景还没打到位。

现在已有覆盖已经不错了:普通 INSERT / UPDATE / DELETE / SELECT / prepared statement / failed statement 都测到了。

但我还想继续挡下面几类,因为它们正是用户最常依赖 ROW_COUNT() 的地方:

  1. REPLACE 命中主键冲突
    现在只测了“纯插入”的 REPLACE,没测最关键的 replace-over-existing-row 语义。这个场景应该能直接锁住 ROW_COUNT() = 2。

  2. INSERT ... ON DUPLICATE KEY UPDATE
    这类语义里通常要区分:

    • insert happened → 1
    • update happened → 2
    • duplicate but no-op update → 0
      这是非常典型的应用依赖点,现在还没在 BVT 里看到。
  3. LOAD DATA / load path
    这次实现改了 affected rows 的传递链路,我会希望至少有一条 end-to-end case 证明 ROW_COUNT() 在 load 后能返回导入行数。

所以我这边的结论是:核心实现基本可以,但产品级回归面还差这几条最值回票价的 SQL 场景。如果把 REPLACE 冲突、ODKU、LOAD DATA` 这三类补上,我会更放心放行。

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]>
@ck89119

ck89119 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. On the BVT coverage:

Added in cb4ba7548:

  • INSERT ... ON DUPLICATE KEY UPDATE that inserts a new row → ROW_COUNT() = 1
  • LOAD DATA INFILE → ROW_COUNT() = <imported rows> (end-to-end through the load path)

On REPLACE-over-existing and ON DUPLICATE KEY UPDATE update/no-op: MatrixOne's executor reports 1 for all of these, not MySQL's 2 / 2 / 0. This is an executor/planner-level affected-rows semantic (affected rows = net rows written to the target main table, counted once; see Scope.affectedRows() summing only operators with AddAffectedRows==true, and the addAffectedRows comment in pkg/sql/plan/build_dml_util.go). It is independent of the ROW_COUNT() plumbing in this PR, which faithfully surfaces whatever the executor counts, and it affects the OK-packet affected-rows seen by every client, not just ROW_COUNT().

So this PR intentionally does not encode those non-MySQL values in the golden (consistent with the earlier removal of the existing-key REPLACE case). I've filed #24907 to track fixing the underlying REPLACE/ODKU affected-rows accounting separately.

ROW_COUNT() inside stored procedures / after CALL remains tracked in #24783.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-checked the latest update. One of the previously missing cases is now covered: the PR now has an end-to-end LOAD DATA case and verifies ROW_COUNT() = 4, which is good.

But the other two high-value user-facing gaps are still missing:

  1. REPLACE on duplicate-key collision
    The BVT still only covers REPLACE as a plain insert. It does not cover the collision path where one row is deleted and one row is inserted, which is the important ROW_COUNT() = 2 case.

  2. INSERT ... ON DUPLICATE KEY UPDATE on duplicate hit
    The new ODKU case only covers the fresh-insert path (ROW_COUNT() = 1). It still does not cover the two more important outcomes:

    • duplicate hit with actual row change (ROW_COUNT() = 2)
    • duplicate hit with no-op update (ROW_COUNT() = 0)

Those are the cases applications most commonly rely on when they use ROW_COUNT(). So my view is still the same: the core implementation looks fine, but the product-level regression surface is not fully pinned down until those cases are added.

…te hit

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]>
@ck89119

ck89119 commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

Added in the latest commit: BVT cases for REPLACE on duplicate-key collision and INSERT ... ON DUPLICATE KEY UPDATE on duplicate hit (both the real-change and the no-op paths).

One thing to flag on the expected values: in MatrixOne these currently report ROW_COUNT() = 1 for all three, not the MySQL 2 / 2 / 0:

Case MatrixOne MySQL
REPLACE over existing key 1 2
ODKU duplicate hit, real change 1 2
ODKU duplicate hit, no-op 1 0

This is because MatrixOne's executor counts the net rows written to the target table once (REPLACE does not separately count the collision delete; ODKU does not distinguish update vs no-op). That value is what flows into the OK packet for every client, and ROW_COUNT() in this PR faithfully surfaces it — so it is an executor-level affected-rows semantic, independent of the ROW_COUNT() plumbing here.

Rather than encode the divergent values silently, the BVT pins MatrixOne's current behavior with comments, and the affected-rows fix to match MySQL (2 / 2 / 0) is tracked separately in #24907. Happy to align them in that issue.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-checked the latest update, and at this point the main problem is no longer just missing coverage — the behavior itself still does not match the expected ROW_COUNT() semantics for some high-value cases.

Two concrete examples from the updated SQL/result files:

  1. REPLACE on duplicate-key collision is still wrong
    The PR now avoids the existing-key REPLACE case in BVT by changing it to a brand-new key (replace into t values (50,500)), because the duplicate-hit case in MO still returns 1 instead of the MySQL-visible 2. That means the test was changed to avoid the bad behavior, not to fix it.

  2. ODKU duplicate-hit paths are still wrong
    The newly added duplicate-hit ODKU cases still assert ROW_COUNT() = 1 both for the changed-row case and the no-op case. Those are exactly the user-visible scenarios that should distinguish 2 (actual update) and 0 (duplicate hit but no effective change).

So my current conclusion is: this PR is still not ready to approve, because the latest version is now explicitly encoding non-MySQL ROW_COUNT() behavior in the BVT instead of correcting it.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the latest state again, and the duplicate-key ROW_COUNT semantics are still not fixed. At this point the issue is no longer just about missing coverage. The PR now explicitly codifies the current MatrixOne behavior for these cases instead of correcting it: REPLACE on an existing key still returns 1 instead of the MySQL-visible 2; INSERT ... ON DUPLICATE KEY UPDATE on a duplicate-hit update still returns 1 instead of 2; and the duplicate-hit no-op case still returns 1 instead of 0. The latest SQL comments and result file make that explicit rather than accidental. So I do not think this PR is ready to approve in its current form: it is still preserving known wrong ROW_COUNT semantics for the highest-value user-facing duplicate-key cases.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants