Class: Perpetuity::Postgres::Table

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

Defined Under Namespace

Classes: Attribute

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, attributes) ⇒ Table

Returns a new instance of Table.



9
10
11
12
13
14
# File 'lib/perpetuity/postgres/table.rb', line 9

def initialize name, attributes
  @name = TableName.new(name)
  @attributes = attributes.to_a

  generate_id_attribute unless has_id_attribute?
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



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

def attributes
  @attributes
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

Instance Method Details

#create_table_sqlObject



16
17
18
19
20
# File 'lib/perpetuity/postgres/table.rb', line 16

def create_table_sql
  sql = "CREATE TABLE IF NOT EXISTS #{name} ("
  sql << attributes.map(&:sql_declaration).join(', ')
  sql << ')'
end

#generate_id_attributeObject



26
27
28
29
# File 'lib/perpetuity/postgres/table.rb', line 26

def generate_id_attribute
  id = Attribute.new('id', Attribute::UUID, primary_key: true, default: Expression.new('uuid_generate_v4()'))
  attributes.unshift id
end

#has_id_attribute?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/perpetuity/postgres/table.rb', line 22

def has_id_attribute?
  attributes.any? { |attr| attr.name.to_s == 'id' }
end

#to_sObject



31
32
33
# File 'lib/perpetuity/postgres/table.rb', line 31

def to_s
  name.to_s
end