Class: QuickCount::Adapters::Postgresql

Inherits:
Base
  • Object
show all
Defined in:
lib/quick_count/adapters/postgresql.rb

Instance Attribute Summary

Attributes inherited from Base

#connection

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from QuickCount::Adapters::Base

Instance Method Details

#count_estimate(query) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/quick_count/adapters/postgresql.rb', line 25

def count_estimate(query)
  # Use EXPLAIN to get row estimate directly
  result = execute_sql("EXPLAIN #{query}")

  # Parse the rows from EXPLAIN output
  if result.respond_to?(:each)
    result.each do |row|
      if row['QUERY PLAN'] && row['QUERY PLAN'].match(/rows=(\d+)/)
        return $1.to_i
      end
    end
  end

  # Fallback: return 0 if we can't parse
  0
end

#quick_count(table_name, threshold: nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/quick_count/adapters/postgresql.rb', line 10

def quick_count(table_name, threshold: nil)
  threshold ||= 500_000

  # Use direct SQL estimation without needing functions
  estimated_count = get_table_estimate(table_name)

  if estimated_count < threshold
    # Use exact count for small tables
    result = execute_sql("SELECT COUNT(*) as count FROM #{quote_identifier(table_name)}")
    result[0]['count'].to_i
  else
    estimated_count
  end
end

#supported?Boolean

Returns:



6
7
8
# File 'lib/quick_count/adapters/postgresql.rb', line 6

def supported?
  connection.adapter_name.downcase.match?(/postg/)
end