Module: Mover::ClassMethods

Defined in:
lib/mover.rb

Instance Method Summary collapse

Instance Method Details

#after_move(*to_class, &block) ⇒ Object



17
18
19
20
# File 'lib/mover.rb', line 17

def after_move(*to_class, &block)
  @after_move ||= []
  @after_move << [ to_class, block ]
end

#before_move(*to_class, &block) ⇒ Object



22
23
24
25
# File 'lib/mover.rb', line 22

def before_move(*to_class, &block)
  @before_move ||= []
  @before_move << [ to_class, block ]
end

#move_to(to_class, options = {}) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/mover.rb', line 27

def move_to(to_class, options={})
  from_class = self
  
  # Conditions
  conditions = options[:conditions] || '1'
  conditions = self.sanitize_sql(conditions)
  where = "WHERE #{conditions}"
  
  # Columns
  magic = options[:magic] || 'moved_at'
  from = {
    :columns => from_class.column_names,
    :table => from_class.table_name
  }
  to = {
    :columns => to_class.column_names,
    :table => to_class.table_name
  }
  
  # insert[column] = value
  insert = (from[:columns] & to[:columns]).inject({}) do |hash, column|
    if column == magic && !options[:migrate]
      hash[column] = Time.now.utc
    else
      hash[column] = column
    end
    hash
  end
  
  # Magic column not in "from" table
  if to[:columns].include?(magic) && !from[:columns].include?(magic)
    insert[magic] = Time.now.utc
  end
  
  # Quote everything
  insert = insert.inject({}) do |hash, (column, value)|
    if value.is_a?(::Time)
      hash[connection.quote_column_name(column)] = connection.quote(value)
    else
      hash[connection.quote_column_name(column)] = connection.quote_column_name(value)
    end
    hash
  end
  
  # Callbacks
  collector = lambda do |(classes, block)|
    classes.collect! { |c| eval(c.to_s) }
    block if classes.include?(to_class) || classes.empty?
  end
  before = (@before_move || []).collect(&collector).compact
  after = (@after_move || []).collect(&collector).compact
  
  # Instances
  instances =
    if options[:instance]
      [ options[:instance] ]
    elsif before.empty? && after.empty?
      []
    else
      self.find(:all, :conditions => conditions)
    end
  options.delete(:instance)
  
  # Callback executor
  exec_callbacks = lambda do |callbacks|
    callbacks.each do |block|
      instances.each do |instance|
        instance.move_options = options
        instance.instance_eval(&block)
        instance.move_options = nil
      end
    end
  end
  
  # Execute
  transaction do
    exec_callbacks.call before
    
    if options[:quick]
      connection.execute(<<-SQL)
        INSERT INTO #{to[:table]} (#{insert.keys.join(', ')})
        SELECT #{insert.values.join(', ')}
        FROM #{from[:table]}
        #{where}
      SQL
    elsif !options[:generic] && connection.class.to_s.include?('Mysql')
      update = insert.collect do |column, value|
        if value.include?("'")
          "#{to[:table]}.#{column} = #{value}"
        else
          "#{to[:table]}.#{column} = #{from[:table]}.#{value}"
        end
      end
      
      connection.execute(<<-SQL)
        INSERT INTO #{to[:table]} (#{insert.keys.join(', ')})
        SELECT #{insert.values.join(', ')}
        FROM #{from[:table]}
        #{where}
        ON DUPLICATE KEY
        UPDATE #{update.join(', ')};
      SQL
    else
      conditions.gsub!(to[:table], 't')
      conditions.gsub!(from[:table], 'f')
      conditions.gsub!(/\"id\"/,'f.id') if connection.class.to_s.include?('PostgreSQL')
      
      select = insert.values.collect { |i| i.include?("'") ? i : "f.#{i}" }
      set = insert.collect do |column, value|
        prefix = 't.' unless connection.class.to_s.include?('PostgreSQL')
        if value.include?("'")
          "#{prefix}#{column} = #{value}"
        else
          "#{prefix}#{column} = f.#{value}"
        end
      end
      
      if connection.class.to_s.include?('PostgreSQL')
        connection.execute(<<-SQL)
          UPDATE #{to[:table]}
            AS t
          SET #{set.join(', ')}
          FROM #{from[:table]}
            AS f
          WHERE f.id = t.id
            AND #{conditions}
        SQL
      else
        connection.execute(<<-SQL)
          UPDATE #{to[:table]}
            AS t
          INNER JOIN #{from[:table]}
            AS f
          ON f.id = t.id
            AND #{conditions}
          SET #{set.join(', ')}
        SQL
      end
  
      connection.execute(<<-SQL)
        INSERT INTO #{to[:table]} (#{insert.keys.join(', ')})
        SELECT #{select.join(', ')}
        FROM #{from[:table]}
          AS f
        LEFT OUTER JOIN #{to[:table]}
          AS t
        ON f.id = t.id
        WHERE (
          t.id IS NULL
          AND #{conditions}
        )
      SQL
    end
    
    unless options[:copy]
      connection.execute("DELETE FROM #{from[:table]} #{where}")
    end
    
    exec_callbacks.call after
  end
end

#reserve_idObject



189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/mover.rb', line 189

def reserve_id
  id = nil
  transaction do
    if connection.class.to_s.include?('PostgreSQL')
      id = connection.insert("INSERT INTO #{self.table_name} (id) VALUES (nextval('#{self.table_name}_id_seq'::regclass))").to_i
    else
      id = connection.insert("INSERT INTO #{self.table_name} () VALUES ()")
    end
    connection.execute("DELETE FROM #{self.table_name} WHERE id = #{id}") if id
  end
  id
end