Class: ClickhouseNative::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



3
4
5
# File 'lib/clickhouse_native/client.rb', line 3

def database
  @database
end

#hostObject (readonly)

Returns the value of attribute host.



3
4
5
# File 'lib/clickhouse_native/client.rb', line 3

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



3
4
5
# File 'lib/clickhouse_native/client.rb', line 3

def port
  @port
end

Instance Method Details

#describe_table(table, db_name: nil) ⇒ Object



5
6
7
8
# File 'lib/clickhouse_native/client.rb', line 5

def describe_table(table, db_name: nil)
  fq = db_name ? "#{db_name}.#{table}" : table
  query("DESCRIBE TABLE #{fq}")
end

#insert(table, rows, columns: nil, db_name: nil, types: nil) ⇒ Object

insert(table, rows, columns: nil, db_name: nil, types: nil)

rows may be Array<Hash=> Object> or Array<Array>. columns defaults to the first hash’s keys (for Array<Hash>) or all table columns in DDL order (for Array<Array>). types may be supplied to skip the DESCRIBE lookup.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/clickhouse_native/client.rb', line 16

def insert(table, rows, columns: nil, db_name: nil, types: nil)
  return 0 if rows.empty?
  fq = db_name ? "#{db_name}.#{table}" : table

  if types && columns
    raise ArgumentError, "types and columns must have the same length" if columns.size != types.size
    col_pairs = columns.zip(types).map { |n, t| [n.to_s, t] }
  else
    schema = describe_table(table, db_name: db_name)
    type_by_name = schema.to_h { |c| [c[:name], c[:type]] }
    columns ||= rows.first.is_a?(Hash) ? rows.first.keys.map(&:to_s) : schema.map { |c| c[:name] }
    col_pairs = columns.map do |name|
      name_s = name.to_s
      t = type_by_name[name_s] or raise ArgumentError, "unknown column #{name_s.inspect} in #{fq}"
      [name_s, t]
    end
  end

  row_arrays =
    if rows.first.is_a?(Hash)
      col_pairs.map { |n, _| [n.to_sym, n] }.then do |lookup|
        rows.map { |h| lookup.map { |sym, str| h.fetch(sym) { h[str] } } }
      end
    else
      rows
    end

  insert_block(fq, col_pairs, row_arrays)
end

#inspectObject



46
47
48
# File 'lib/clickhouse_native/client.rb', line 46

def inspect
  "#<#{self.class} #{host}:#{port}/#{database}>"
end