Module: RailsSync::ActiveRecord

Defined in:
lib/rails_sync/active_record.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_sync(options = {}) ⇒ Object

source source_client dest_table



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rails_sync/active_record.rb', line 9

def acts_as_sync(options = {})
  @syncs ||= []

  options[:dest_table] ||= self.table_name
  _mappings = Array(options.delete(:mapping)).to_h
  if options[:only]
    _filter_columns = self.column_names & Array(options.delete(:only))
  else
    _filter_columns = self.column_names - Array(options.delete(:except))
  end
  options[:primary_key] = Array(options[:primary_key] || self.primary_key).map { |i| i.to_s }
  options[:dest_primary_key] = Array(options[:dest_primary_key] || options[:primary_key]).map { |i| i.to_s }
  options[:dest_conditions] = options[:dest_conditions]
  options[:full_mappings] = _filter_columns.map { |column_name|
    next if options[:primary_key].include?(column_name)
    if _mappings.key?(column_name)
      [column_name, _mappings[column_name]]
    else
      [column_name, column_name]
    end
  }.compact

  options[:server_id] = self.server_id
  options[:analyzer] = RailsSync::Analyzer.new(record: self, **options)

  RailsSync.synchro_types << self.name
  @syncs << options
end

#analyze_diffs(type = 'update') ⇒ Object



52
53
54
55
56
57
# File 'lib/rails_sync/active_record.rb', line 52

def analyze_diffs(type = 'update')
  @syncs.flat_map do |options|
    next if !options[:primary_key].include?(self.primary_key) && type == 'delete'
    options[:analyzer].analyze_diffs(type)
  end
end

#cache_all_diffs(*types) ⇒ Object



66
67
68
69
70
71
# File 'lib/rails_sync/active_record.rb', line 66

def cache_all_diffs(*types)
  types = ['update', 'insert', 'delete'] if types.blank?
  types.each do |type|
    cache_diffs(type)
  end
end

#cache_diffs(type = 'update') ⇒ Object



59
60
61
62
63
64
# File 'lib/rails_sync/active_record.rb', line 59

def cache_diffs(type = 'update')
  @syncs.flat_map do |options|
    next if !options[:primary_key].include?(self.primary_key) && type == 'delete'
    options[:analyzer].cache_diffs(type)
  end
end

#id_insert?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/rails_sync/active_record.rb', line 73

def id_insert?
  @syncs.find { |i| i[:primary_key] == ['id'] }.present?
end

#prepare_syncObject



77
78
79
80
81
# File 'lib/rails_sync/active_record.rb', line 77

def prepare_sync
  @syncs.flat_map do |options|
    options[:analyzer].reset_temp_table unless options[:analyzer].same_server?
  end
end

#server_idObject



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

def server_id
  begin
    result = connection.query('select @@server_uuid')
  rescue
    result = connection.query('select @@server_id')
  end
  _id = result.to_a.flatten.first
  if _id.is_a?(Hash)
    _id.values.first
  else
    _id
  end
end