Class: Perpetuity::Postgres::Table::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/perpetuity/postgres/table/attribute.rb

Constant Summary collapse

NoDefaultValue =
Module.new
UUID =
Module.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



12
13
14
15
16
17
18
# File 'lib/perpetuity/postgres/table/attribute.rb', line 12

def initialize name, type, options={}
  @name = name
  @type = type
  @max_length = options[:max_length]
  @primary_key = options.fetch(:primary_key) { false }
  @default = options.fetch(:default) { NoDefaultValue }
end

Instance Attribute Details

#max_lengthObject (readonly)

Returns the value of attribute max_length.



7
8
9
# File 'lib/perpetuity/postgres/table/attribute.rb', line 7

def max_length
  @max_length
end

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/perpetuity/postgres/table/attribute.rb', line 7

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



7
8
9
# File 'lib/perpetuity/postgres/table/attribute.rb', line 7

def type
  @type
end

Instance Method Details

#defaultObject



60
61
62
# File 'lib/perpetuity/postgres/table/attribute.rb', line 60

def default
  @default
end

#primary_key?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/perpetuity/postgres/table/attribute.rb', line 56

def primary_key?
  !!@primary_key
end

#sql_declarationObject



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/perpetuity/postgres/table/attribute.rb', line 42

def sql_declaration
  if self.default.is_a? String
    default = "'#{self.default}'"
  else
    default = self.default
  end

  sql = "#{name} #{sql_type}"
  sql << ' PRIMARY KEY' if primary_key?
  sql << " DEFAULT #{default}" unless self.default == NoDefaultValue

  sql
end

#sql_typeObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/perpetuity/postgres/table/attribute.rb', line 20

def sql_type
  if type == String
    if max_length
      "VARCHAR(#{max_length})"
    else
      'TEXT'
    end
  elsif type == Integer or type == Fixnum
    'BIGINT'
  elsif type == Bignum or type == BigDecimal
    'NUMERIC'
  elsif type == Float
    'FLOAT'
  elsif type == UUID
    'UUID'
  elsif type == Time
    'TIMESTAMPTZ'
  else
    'JSON'
  end
end