Class: Motel::Sources::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/motel/sources/database.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Database

Returns a new instance of Database.



10
11
12
13
# File 'lib/motel/sources/database.rb', line 10

def initialize(config = {})
  @source_spec = config[:source_spec]
  @table_name  = config[:table_name]
end

Instance Attribute Details

#source_specObject

Returns the value of attribute source_spec.



8
9
10
# File 'lib/motel/sources/database.rb', line 8

def source_spec
  @source_spec
end

#table_nameObject

Returns the value of attribute table_name.



8
9
10
# File 'lib/motel/sources/database.rb', line 8

def table_name
  @table_name
end

Instance Method Details

#add_tenant(name, spec) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/motel/sources/database.rb', line 38

def add_tenant(name, spec)
  raise ExistingTenantError if tenant?(name)

  spec = spec.merge(:name => name.to_s)
  spec.delete_if{ |c,v| v.nil? }

  sql = <<-SQL
    INSERT INTO #{table_name} (#{spec.keys.map{|c| "\`#{c}\`"}.join(',')})
    VALUES (#{spec.values.map(&:inspect).join(',')})
  SQL

  connection_pool.with_connection { |conn| conn.execute(sql) }
end

#connectionObject



77
78
79
# File 'lib/motel/sources/database.rb', line 77

def connection
  connection_pool.connection
end

#delete_tenant(name) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/motel/sources/database.rb', line 67

def delete_tenant(name)
  if tenant?(name)
    sql = <<-SQL
      DELETE FROM #{table_name} WHERE name = "#{name}"
    SQL

    connection_pool.with_connection { |conn| conn.execute(sql) }
  end
end

#tenant(name) ⇒ Object



30
31
32
# File 'lib/motel/sources/database.rb', line 30

def tenant(name)
  tenants[name]
end

#tenant?(name) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/motel/sources/database.rb', line 34

def tenant?(name)
  tenants.key?(name)
end

#tenantsObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/motel/sources/database.rb', line 15

def tenants
  query_result.inject({}) do |hash, tenant|
    name = tenant.delete('name')

    tenant.each do |field, value|
      if table[field].respond_to? :column
        tenant[field] = table[field].column.type_cast(value)
      end
    end

    hash[name] = tenant
    hash
  end
end

#update_tenant(name, spec) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/motel/sources/database.rb', line 52

def update_tenant(name, spec)
  raise NonexistentTenantError unless tenant?(name)

  spec = spec.merge(:name => name.to_s)
  spec.delete_if{ |c,v| v.nil? }

  sql = <<-SQL
    UPDATE #{table_name}
    SET #{spec.map{|c, v| "\`#{c}\` = \"#{v}\""}.join(',')}
    WHERE name = "#{name}"
  SQL

  connection_pool.with_connection { |conn| conn.execute(sql) }
end