Class: BetterRecord::TableSize

Inherits:
Base
  • Object
show all
Defined in:
app/models/better_record/table_size.rb

Constant Summary collapse

UPDATE_TABLE_SIZES_SQL =

Constants ============================================================

<<-SQL
  BEGIN WORK;
    LOCK TABLE #{BetterRecord.db_audit_schema}.table_sizes;
    TRUNCATE TABLE #{BetterRecord.db_audit_schema}.table_sizes;
    INSERT INTO #{BetterRecord.db_audit_schema}.table_sizes (
      SELECT
        *,
        pg_size_pretty(total_bytes) AS total,
        pg_size_pretty(idx_bytes) AS idx,
        pg_size_pretty(toast_bytes) AS toast,
        pg_size_pretty(tbl_bytes) AS tbl
      FROM (
        SELECT
          *,
          total_bytes - idx_bytes - COALESCE(toast_bytes,0) AS tbl_bytes
        FROM (
          SELECT c.oid,nspname AS schema, relname AS name
          , c.reltuples AS row_estimate
          , pg_total_relation_size(c.oid) AS total_bytes
          , pg_indexes_size(c.oid) AS idx_bytes
          , pg_total_relation_size(reltoastrelid) AS toast_bytes
          FROM pg_class c
          LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
          WHERE relkind = 'r'
        ) table_sizes
      ) table_sizes
    );
  COMMIT WORK;
SQL

Class Method Summary collapse

Methods inherited from Base

#dup, full_table_name, gender_enum, #get_hashed_string, get_hashed_string, #indifferent_attributes, reset_all_schemas, reset_qualified_schema, saved_qualified_schema, schema_qualified, set_audit_methods!, table_name_only

Class Method Details

.allObject



63
64
65
66
# File 'app/models/better_record/table_size.rb', line 63

def self.all
  reload_data if self.last_updated.blank? || (self.last_updated < 1.hour.ago)
  super
end

.find_by(*args) ⇒ Object



58
59
60
61
# File 'app/models/better_record/table_size.rb', line 58

def self.find_by(*args)
  reload_data
  super *args
end

.last_updatedObject



73
74
75
# File 'app/models/better_record/table_size.rb', line 73

def self.last_updated
  @@last_updated ||= super_all.first&.updated_at
end

.reload_dataObject



68
69
70
71
# File 'app/models/better_record/table_size.rb', line 68

def self.reload_data
  connection.execute UPDATE_TABLE_SIZES_SQL
  self.last_updated = Time.now
end

.super_allObject



55
# File 'app/models/better_record/table_size.rb', line 55

alias :super_all :all