Sha256: a2af400e19747e67d7fae9ec7f8fcd124b626371abcf3f8c00c8838f560db33d

Contents?: true

Size: 876 Bytes

Versions: 8

Compression:

Stored size: 876 Bytes

Contents

class Simple::SQL::Connection::Scope
  EXACT_COUNT_THRESHOLD = 10_000

  # Returns the exact count of matching records
  def count
    sql = order_by(nil).to_sql(pagination: false)

    @connection.ask("SELECT COUNT(*) FROM (#{sql}) _total_count", *args)
  end

  # Returns the fast count of matching records
  #
  # For counts larger than EXACT_COUNT_THRESHOLD this returns an estimate
  def fast_count
    estimate = estimated_count
    return estimate if estimate > EXACT_COUNT_THRESHOLD

    sql = order_by(nil).to_sql(pagination: false)
    @connection.ask("SELECT COUNT(*) FROM (#{sql}) _total_count", *args)
  end

  private

  def estimated_count
    sql = order_by(nil).to_sql(pagination: false)
    lines = @connection.all("EXPLAIN #{sql}", *args)
    lines.each do |line|
      next unless line =~ /\brows=(\d+)/

      return Integer($1)
    end

    -1
  end
end

Version data entries

8 entries across 4 versions & 1 rubygems

Version Path
simple-sql-0.5.8 lib/simple/sql/connection/scope/count.rb
simple-sql-0.5.8 lib/simple/sql/scope/count.rb
simple-sql-0.5.7 lib/simple/sql/connection/scope/count.rb
simple-sql-0.5.7 lib/simple/sql/scope/count.rb
simple-sql-0.5.6 lib/simple/sql/connection/scope/count.rb
simple-sql-0.5.6 lib/simple/sql/scope/count.rb
simple-sql-0.5.5 lib/simple/sql/connection/scope/count.rb
simple-sql-0.5.5 lib/simple/sql/scope/count.rb