Skip to content

DatabaseStatements#affected_rows returning nil raising exception in ActiveRecord when comparing with 0 #1304

Closed
@taylorthurlow

Description

@taylorthurlow

I upgraded to Rails 8.0 and activerecord-sqlserver-adapter 8.0.2 (w/ tiny_tds 3.2.0), and started getting a test failure:

NoMethodError:
       undefined method `>' for nil

The test fails at a point where I am deleting a single record from the database.

The exception is being raised from within ActiveRecord: https://github.com/rails/rails/blob/800976975253be2912d09a80757ee70a2bb1e984/activerecord/lib/active_record/counter_cache.rb#L236-L238

The return value of super which when you tug on the method call chain long enough you find is the return value of ActiveRecord::ConnectionAdapters::SQLServer::DatabaseStatements#affected_rows:

def affected_rows(raw_result)
raw_result.first['AffectedRows']
end

Dropping a debugger in here and inspecting raw_result:

irb:rdbg(#<ActiveRecord::ConnectionAda...):006> raw_result
#<ActiveRecord::Result:0x0000000157dd2c70
 @column_indexes={"affectedrows"=>0},
 @column_types={},
 @columns=["affectedrows"],
 @hash_rows=[{"affectedrows"=>1}],
 @rows=[[1]]>

The issue is the capitalization (or lack thereof) the AffectedRows key. Because the query result key is lower case, and this gem is looking under the key AffectedRows, the return value is nil and then that bubbles up into ActiveRecord internally where it chokes.

There are recent changes in #1268 but it does look like it wasn't necessarily unexpected for this method to return nil before, though after this change it does seem that the intent is to allow nil. I haven't speculated any further on what the cause of the issue is. (@aidanharan hope you don't mind the ping here, you are the author on that PR and would probably be the person to ask about this specific issue).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions