Class: ClickHouse::Client::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/click_house/client/formatter.rb

Constant Summary collapse

DEFAULT =
->(value) { value }
TYPE_CASTERS =
{
  # UInt8/16/32/64, Int8/16/32/64
  /\AU?Int\d+\z/ => ->(value) { Integer(value) },
  # Float8/16/32/64
  /\AFloat\d+\z/ => ->(value) { Float(value) },
  # Date, Date32
  /\ADate\d*\z/ => ->(value) { Date.parse(value) },
  # DateTime64(0/3/6/9, 'UTC')
  /\ADateTime64\(\d+, 'UTC'\)\z/ => ->(value) { ActiveSupport::TimeZone['UTC'].parse(value) },
  "DateTime('UTC')" => ->(value) { ActiveSupport::TimeZone['UTC'].parse(value) },
  "IntervalSecond" => ->(value) { ActiveSupport::Duration.build(value.to_i) },
  "IntervalMillisecond" => ->(value) { ActiveSupport::Duration.build(value.to_i / 1000.0) }
}.freeze

Class Method Summary collapse

Class Method Details

.format(result) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/click_house/client/formatter.rb', line 22

def self.format(result)
  column_typecasters = result['meta'].each_with_object({}) do |column, hash|
    hash[column['name']] = get_typecaster(column['type']) || DEFAULT
  end

  result['data'].map do |row|
    row.each_with_object({}) do |(column, value), casted_row|
      casted_row[column] = value.nil? ? value : column_typecasters[column].call(value)
    end
  end
end

.get_typecaster(column_type) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/click_house/client/formatter.rb', line 34

def self.get_typecaster(column_type)
  return unless column_type

  inner_type = column_type
    .sub(/\ANullable\((.+)\)\z/, '\1') # e.g Nullable(String)
    .sub(/\ALowCardinality\((.+)\)\z/, '\1') # e.g. LowCardinality(String)
    .sub(/\ASimpleAggregateFunction\(.+,\s*(.+)\)\z/, '\1') # e.g. SimpleAggregateFunction(sum, UInt64)

  TYPE_CASTERS.each do |key, caster|
    return caster if key.is_a?(String) ? key == inner_type : key.match?(inner_type)
  end

  nil
end