Class: PgHistogram::Histogram

Inherits:
Object
  • Object
show all
Defined in:
lib/pg_histogram/histogram.rb

Constant Summary collapse

BUCKET_COL =
'bucket'
FREQUENCY_COL =
'frequency'
ROUND_METHODS_BY_DIRECTION =
{
  nil => :round,
  down:  :floor,
  up:    :ceil
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, column_name, options = {}) ⇒ Histogram

column_name name must be safe for SQL injection



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/pg_histogram/histogram.rb', line 14

def initialize(query, column_name, options = {})
  @query = query
  @column = column_name.to_s
  if options.is_a? Hash
    if options[:buckets]
      @min = options[:min] || 0
      @max = options[:max]
      @buckets = options[:buckets]
      @bucket_size = calculate_bucket_size
    else
      @min = options[:min]
      @max = options[:max]
      @bucket_size = (options[:bucket_size] || 1).to_f
    end
  else
    @bucket_size = options.to_f
  end
end

Instance Attribute Details

#bucket_sizeObject (readonly)

Returns the value of attribute bucket_size.



3
4
5
# File 'lib/pg_histogram/histogram.rb', line 3

def bucket_size
  @bucket_size
end

#columnObject (readonly)

Returns the value of attribute column.



3
4
5
# File 'lib/pg_histogram/histogram.rb', line 3

def column
  @column
end

#queryObject (readonly)

Returns the value of attribute query.



3
4
5
# File 'lib/pg_histogram/histogram.rb', line 3

def query
  @query
end

Instance Method Details

#maxObject



49
50
51
# File 'lib/pg_histogram/histogram.rb', line 49

def max
  @max ||= round_to_increment(source_max, :up)
end

#minObject



45
46
47
# File 'lib/pg_histogram/histogram.rb', line 45

def min
  @min ||= round_to_increment(source_min, :down)
end

#resultsObject

returns histogram as hash bucket minimum as a key frequency as value



36
37
38
39
40
41
42
43
# File 'lib/pg_histogram/histogram.rb', line 36

def results
  # error handling case
  if max == min
    { min => subquery.where("#{pure_column} = ?", min).count }
  else
    labeled_histogram
  end
end