Class: ClickhouseRuby::Types::String

Inherits:
Base
  • Object
show all
Defined in:
lib/clickhouse_ruby/types/string.rb

Overview

Type handler for ClickHouse string types

Handles: String, FixedString(N)

ClickHouse strings are byte sequences, not necessarily valid UTF-8. However, most usage is with UTF-8 text.

Instance Attribute Summary collapse

Attributes inherited from Base

#name

Instance Method Summary collapse

Methods inherited from Base

#==, #hash, #nullable?, #to_s

Constructor Details

#initialize(name, length: nil) ⇒ String

Returns a new instance of String.



17
18
19
20
# File 'lib/clickhouse_ruby/types/string.rb', line 17

def initialize(name, length: nil)
  super(name)
  @length = length
end

Instance Attribute Details

#lengthInteger? (readonly)

The fixed length for FixedString types

Returns:

  • (Integer, nil)

    the fixed length or nil for String type



15
16
17
# File 'lib/clickhouse_ruby/types/string.rb', line 15

def length
  @length
end

Instance Method Details

#cast(value) ⇒ String?

Converts a Ruby value to a string

Parameters:

  • value (Object)

    the value to convert

Returns:

  • (String, nil)

    the string value



26
27
28
29
30
31
32
33
34
35
# File 'lib/clickhouse_ruby/types/string.rb', line 26

def cast(value)
  return nil if value.nil?

  str = value.to_s

  # For FixedString, pad or truncate to length
  str = str.ljust(@length, "\0")[0, @length] if @length

  str
end

#deserialize(value) ⇒ String?

Converts a value from ClickHouse to Ruby String

Parameters:

  • value (Object)

    the value from ClickHouse

Returns:

  • (String, nil)

    the string value



41
42
43
44
45
46
47
48
49
50
# File 'lib/clickhouse_ruby/types/string.rb', line 41

def deserialize(value)
  return nil if value.nil?

  str = value.to_s

  # For FixedString, remove trailing null bytes
  str = str.gsub(/\0+\z/, "") if @length

  str
end

#serialize(value) ⇒ String

Converts a string to SQL literal with proper escaping

Parameters:

  • value (String, nil)

    the value to serialize

Returns:

  • (String)

    the SQL literal



56
57
58
59
60
61
# File 'lib/clickhouse_ruby/types/string.rb', line 56

def serialize(value)
  return "NULL" if value.nil?

  escaped = escape_string(value.to_s)
  "'#{escaped}'"
end