Module: Replicator

Defined in:
lib/replicator.rb

Defined Under Namespace

Classes: Trigger

Instance Method Summary collapse

Instance Method Details

#create_replicated_table(table_name) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/replicator.rb', line 23

def create_replicated_table(table_name)
  table  = nil
  fields = []
  joins  = []

  replicated_table_slices(table_name).each do |slice|
    if table
      joins << "LEFT OUTER JOIN #{slice[:name]} ON #{table}.id = #{slice[:name]}.id"
    else
      table = slice[:name]
      fields << "#{table}.id"
    end
    fields << slice[:fields].collect {|f| "#{slice[:name]}.#{f}"}
  end

  execute %{
    CREATE TABLE #{table_name} AS
      SELECT #{fields.flatten.join(', ')}
        FROM #{table}
        #{joins.join(' ')}
  }
end

#replicate(table, opts) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/replicator.rb', line 2

def replicate(table, opts)
  action = opts.delete(:action) || :create
  trigger = Trigger.new(table, opts)

  case action
  when :create
    execute(trigger.create_sql)
  when :drop
    execute(trigger.drop_sql)
  when :initialize     
    sql_by_slice = trigger.initialize_sql
    sql_by_slice.each do |slice, sql|
      execute("DROP TABLE IF EXISTS #{slice[:name]}")
      execute(sql)
    end
    replicated_table_slices(trigger.to).concat(sql_by_slice.keys)
  else
    raise "invalid action: #{action}"
  end
end

#replicated_table_slices(table_name = nil) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/replicator.rb', line 46

def replicated_table_slices(table_name = nil)
  if table_name
    replicated_table_slices[table_name.to_sym] ||= []
  else
    @replicated_table_slices ||= {}
  end
end