Class: ClickhouseRuby::Types::Nullable

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

Overview

Type handler for ClickHouse Nullable type

Nullable wraps another type to allow NULL values. Without Nullable, ClickHouse columns cannot contain NULL.

Examples:

type = Nullable.new('Nullable', element_type: Integer.new('Int32'))
type.cast(nil)   # => nil
type.cast(42)    # => 42
type.nullable?   # => true

Instance Attribute Summary collapse

Attributes inherited from Base

#name

Instance Method Summary collapse

Methods inherited from Base

#==, #hash

Constructor Details

#initialize(name, element_type: nil) ⇒ Nullable

Returns a new instance of Nullable.

Parameters:

  • name (String)

    the type name

  • element_type (Base) (defaults to: nil)

    the wrapped type



22
23
24
25
# File 'lib/clickhouse_ruby/types/nullable.rb', line 22

def initialize(name, element_type: nil)
  super(name)
  @element_type = element_type || Base.new('String')
end

Instance Attribute Details

#element_typeBase (readonly)

Returns the wrapped type.

Returns:

  • (Base)

    the wrapped type



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

def element_type
  @element_type
end

Instance Method Details

#cast(value) ⇒ Object?

Converts a Ruby value, allowing nil

Parameters:

  • value (Object)

    the value to convert

Returns:

  • (Object, nil)

    the converted value



31
32
33
34
35
# File 'lib/clickhouse_ruby/types/nullable.rb', line 31

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

  @element_type.cast(value)
end

#deserialize(value) ⇒ Object?

Converts a value from ClickHouse, allowing nil

Parameters:

  • value (Object)

    the value from ClickHouse

Returns:

  • (Object, nil)

    the Ruby value



41
42
43
44
45
46
# File 'lib/clickhouse_ruby/types/nullable.rb', line 41

def deserialize(value)
  return nil if value.nil?
  return nil if value.is_a?(::String) && value == '\\N'

  @element_type.deserialize(value)
end

#nullable?Boolean

Returns true - this type allows NULL

Returns:



61
62
63
# File 'lib/clickhouse_ruby/types/nullable.rb', line 61

def nullable?
  true
end

#serialize(value) ⇒ String

Converts a value to SQL literal, handling NULL

Parameters:

  • value (Object, nil)

    the value to serialize

Returns:

  • (String)

    the SQL literal



52
53
54
55
56
# File 'lib/clickhouse_ruby/types/nullable.rb', line 52

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

  @element_type.serialize(value)
end

#to_sString

Returns the full type string

Returns:

  • (String)

    the type string



68
69
70
# File 'lib/clickhouse_ruby/types/nullable.rb', line 68

def to_s
  "Nullable(#{@element_type})"
end