Module: Sequel::Postgres::LooseCount

Defined in:
lib/sequel/extensions/pg_loose_count.rb

Instance Method Summary collapse

Instance Method Details

#loose_count(table) ⇒ Object

Look at the table statistics for the given table to get an approximate count of the number of rows.



35
36
37
# File 'lib/sequel/extensions/pg_loose_count.rb', line 35

def loose_count(table)
  from(:pg_class).where(:oid=>regclass_oid(table)).get(Sequel.cast(:reltuples, Integer))
end

#loose_counts(schema) ⇒ Object

Look at the table statistics for the given schema and return a hash with table name keys and approximate counts. Results include normal tables, materialized views, and partitioned tables.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/sequel/extensions/pg_loose_count.rb', line 42

def loose_counts(schema)
  case schema
  when Symbol
    schema = schema.to_s
  when String
    nil
  when SQL::Identifier
    schema = schema.value.to_s
  else
    raise Error, "unsupported argument type, should be symbol, string, or Sequel::SQL::Identifier, given #{schema.inspect}"
  end

  namespace_oid = if server_version >= 90500
    Sequel.function(:to_regnamespace, schema).cast(:oid)
  else
    from(:pg_namespace).where(nspname: schema).select(:oid)
  end

  hash = {}
  from(:pg_class).
    where(relnamespace: namespace_oid, relkind: %w"r m p").
    order(:relname).
    select_map([:relname, Sequel.cast(:reltuples, Integer).as(:v)]).
    each do |k, v|
      hash[k.to_sym] = v
    end
  hash
end