Project

General

Profile

RE: Ticket grouping plugin » 20100313132032_add_issues_nested_sets_columns.rb

Vitaly Klimov, 2010-06-17 10:47

 
1
class AddIssuesNestedSetsColumns < ActiveRecord::Migration
2
  def self.up
3
    #add_column :issues, :parent_id, :integer, :default => nil
4
    add_column :issues, :root_id, :integer, :default => nil
5
    #add_column :issues, :lft, :integer, :default => nil
6
    #add_column :issues, :rgt, :integer, :default => nil
7

    
8
    issues=Issue.find(:all)
9
    args_to_save=Array.new
10

    
11
    say("Issues found: #{issues.size.to_s}")
12

    
13
    issues.each do |issue|
14
	    if issue.parent_id == nil
15
		    args=Hash.new
16
		    args[:parent_id]=0
17
		    args[:id]=issue.id
18
		    args[:root_id]=issue.id
19
		    r=issue.rgt
20
		    l=issue.lft
21
		    if (r-l) > 1
22
			    children=issues.select do |i|
23
				    true if i.id != issue.id && i.lft > l && i.rgt < r
24
			    end
25
			    children.each do |c|
26
				    c_args=Hash.new
27
				    c_args[:id]=c.id
28
				    c_args[:root_id]=issue.id
29
				    c_args[:lft]=c.lft-(l-1)
30
				    c_args[:rgt]=c.rgt-(l-1)
31
				    c_args[:parent_id]=c.parent_id
32
				    args_to_save << c_args
33
			    end
34
			    args[:rgt]=issue.rgt-(l-1)
35
			    args[:lft]=1
36
		    else
37
			    args[:rgt]=2
38
			    args[:lft]=1
39
		    end
40
		    args_to_save << args
41
	    end
42
    end
43

    
44
    issues.clear()
45

    
46
    say("Total of #{args_to_save.size.to_s} issues will be affected")
47

    
48
    say_with_time "Migrating issues from IssuesGroup plugin" do
49
			args_to_save.each_with_index do |a,idx|
50
				say("Issues processed so far: #{idx.to_s}") if (idx > 0 && idx%1000 == 0)
51
				update_str="parent_id = #{( a[:parent_id] == 0 ? "NULL" : a[:parent_id].to_s)}, root_id = #{a[:root_id].to_s}, lft = #{a[:lft].to_s}, rgt = #{a[:rgt].to_s}"
52
				Issue.update_all(update_str,"id = #{a[:id].to_s}")
53
			end
54
    end
55
	  
56
    #Issue.update_all("parent_id = NULL, root_id = id, lft = 1, rgt = 2")
57
    #Issue.update_all("root_id = id")
58
  end
59

    
60
  def self.down
61
	  raise ActiveRecord::IrreversibleMigration, "Can't roll back parent information"
62
    #remove_column :issues, :parent_id
63
    #remove_column :issues, :root_id
64
    #remove_column :issues, :lft
65
    #remove_column :issues, :rgt
66
  end
67
end
(1-1/2)