Skip to content

Commit

Permalink
Fixed connection leasing for Active Record 7.2+
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Oct 7, 2024
1 parent c340612 commit cdf1095
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 0.5.0 (unreleased)

- Fixed connection leasing for Active Record 7.2+
- Dropped support for Ruby < 3.1 and Active Record < 7

## 0.4.1 (2023-09-20)
Expand Down
12 changes: 8 additions & 4 deletions lib/active_median/model.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
module ActiveMedian
module Model
def median(column)
calculate_percentile(column, 0.5, "median")
connection_pool.with_connection do |connection|
calculate_percentile(column, 0.5, "median", connection)
end
end

def percentile(column, percentile)
calculate_percentile(column, percentile, "percentile")
connection_pool.with_connection do |connection|
calculate_percentile(column, percentile, "percentile", connection)
end
end

private

def calculate_percentile(column, percentile, operation)
def calculate_percentile(column, percentile, operation, connection)
percentile = Float(percentile, exception: false)
raise ArgumentError, "invalid percentile" if percentile.nil?
raise ArgumentError, "percentile is not between 0 and 1" if percentile < 0 || percentile > 1
Expand Down Expand Up @@ -39,7 +43,7 @@ def calculate_percentile(column, percentile, operation)
# column resolution
node = relation.send(:arel_columns, [column]).first
node = Arel::Nodes::SqlLiteral.new(node) if node.is_a?(String)
column = relation.connection.visitor.accept(node, Arel::Collectors::SQLString.new).value
column = connection.visitor.accept(node, Arel::Collectors::SQLString.new).value

# prevent SQL injection
percentile = connection.quote(percentile)
Expand Down
11 changes: 11 additions & 0 deletions test/median_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,15 @@ def test_hash
def test_hash_block
assert_equal 2.5, {a: 1, b: 1, c: 2, d: 3, e: 4, f: 100}.median { |k, v| v }
end

def test_connection_leasing
skip if mongoid?

ActiveRecord::Base.connection_handler.clear_active_connections!
assert_nil ActiveRecord::Base.connection_pool.active_connection?
ActiveRecord::Base.connection_pool.with_connection do
User.median(:visits_count)
end
assert_nil ActiveRecord::Base.connection_pool.active_connection?
end
end

0 comments on commit cdf1095

Please sign in to comment.