From 4d0e18c294e834692f11dcfb229e351a29ef2b61 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Wed, 1 Oct 2025 15:42:54 +0200 Subject: [PATCH] Update `affected_rows` after calling `mysql_next_result` Fix: https://github.com/brianmario/mysql2/issues/1411 Followup: https://github.com/brianmario/mysql2/pull/1383 When using multi statement, we need to update the affected rows after each call to `mysql_next_result`. --- ext/mysql2/client.c | 1 + spec/mysql2/client_spec.rb | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/ext/mysql2/client.c b/ext/mysql2/client.c index 2ad71bd9..693def4f 100644 --- a/ext/mysql2/client.c +++ b/ext/mysql2/client.c @@ -1282,6 +1282,7 @@ static VALUE rb_mysql_client_next_result(VALUE self) int ret; GET_CLIENT(self); ret = mysql_next_result(wrapper->client); + wrapper->affected_rows = mysql_affected_rows(wrapper->client); if (ret > 0) { rb_raise_mysql2_error(wrapper); return Qfalse; diff --git a/spec/mysql2/client_spec.rb b/spec/mysql2/client_spec.rb index 460fd132..34a8f116 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -1064,12 +1064,23 @@ def run_gc end it "#affected_rows should return a Fixnum, from the last INSERT/UPDATE" do - @client.query "INSERT INTO lastIdTest (blah) VALUES (1234)" - expect(@client.affected_rows).to eql(1) + @client.query "INSERT INTO lastIdTest (blah) VALUES (1234), (5678)" + expect(@client.affected_rows).to eql(2) @client.query "UPDATE lastIdTest SET blah=4321 WHERE id=1" expect(@client.affected_rows).to eql(1) end + it "#affected_rows with multi statements returns the last result's affected_rows" do + @client.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_ON) + + @client.query("INSERT INTO lastIdTest (blah) VALUES (1234), (5678); UPDATE lastIdTest SET blah=4321 WHERE id=1") + expect(@client.affected_rows).to eq(2) + expect(@client.next_result).to eq(true) + expect(@client.affected_rows).to eq(1) + ensure + @client.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_OFF) + end + it "#affected_rows isn't cleared by Statement#close" do stmt = @client.prepare("INSERT INTO lastIdTest (blah) VALUES (1234)")