Sha256: c0b9d11652e62d1442a40d35042011e41d6b9159fe11f886fb6cafe401a815ad

Contents?: true

Size: 880 Bytes

Versions: 29

Compression:

Stored size: 880 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 count_estimate
    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

29 entries across 29 versions & 1 rubygems

Version Path
simple-sql-0.5.37 lib/simple/sql/scope/count.rb
simple-sql-0.5.36 lib/simple/sql/scope/count.rb
simple-sql-0.5.35 lib/simple/sql/scope/count.rb
simple-sql-0.5.34 lib/simple/sql/scope/count.rb
simple-sql-0.5.33 lib/simple/sql/scope/count.rb
simple-sql-0.5.32 lib/simple/sql/scope/count.rb
simple-sql-0.5.31 lib/simple/sql/scope/count.rb
simple-sql-0.5.30 lib/simple/sql/scope/count.rb
simple-sql-0.5.29 lib/simple/sql/scope/count.rb
simple-sql-0.5.28 lib/simple/sql/scope/count.rb
simple-sql-0.5.27 lib/simple/sql/scope/count.rb
simple-sql-0.5.26 lib/simple/sql/scope/count.rb
simple-sql-0.5.25 lib/simple/sql/scope/count.rb
simple-sql-0.5.24 lib/simple/sql/scope/count.rb
simple-sql-0.5.23 lib/simple/sql/scope/count.rb
simple-sql-0.5.22 lib/simple/sql/scope/count.rb
simple-sql-0.5.21 lib/simple/sql/scope/count.rb
simple-sql-0.5.20 lib/simple/sql/scope/count.rb
simple-sql-0.5.19 lib/simple/sql/scope/count.rb
simple-sql-0.5.18 lib/simple/sql/scope/count.rb