/
project_state.cr
68 lines (56 loc) · 2.18 KB
/
project_state.cr
1
2
3
4
5
6
7
8
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
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
module Marten
module DB
module Management
# Represents the state of the whole DB schema of the project at a specific step in a migration plan.
class ProjectState
@tables : Hash(String, TableState)
getter tables
# Initialize a project state from all the current tables of the project applications.
def self.from_apps(apps : Array(Apps::Config))
tables = [] of TableState
apps.each do |app|
app.models.each do |model|
tables << TableState.from_model(model)
end
end
new(tables)
end
def initialize(tables = [] of TableState)
@tables = {} of String => TableState
tables.each { |t| @tables[t.as(TableState).id] = t }
@tables.values.each { |t| t.contribute_to_project(self) }
end
# Returns a clone of the current project state.
def clone
ProjectState.new(@tables.values.map(&.clone))
end
# Adds a table state to the current project state.
def add_table(table : TableState) : Nil
@tables[table.id] = table
table.contribute_to_project(self)
end
# Deletes a table state from the current project state.
def delete_table(app_label : String, name : String) : Nil
@tables.delete(table_id(app_label, name))
end
# Returns the table state corresponding to the passed app label and table name.
def get_table(app_label : String, name : String) : TableState
@tables[table_id(app_label, name)]
end
# Returns the table state corresponding to the passed table ID.
def get_table(id : String) : TableState
@tables[id]
end
# Renames a specific a table state.
def rename_table(app_label : String, old_name : String, new_name : String) : Nil
table = @tables.delete(table_id(app_label, old_name))
table.not_nil!.name = new_name
@tables[table_id(app_label, new_name)] = table.not_nil!
end
private def table_id(app_label, table_name)
TableState.gen_id(app_label, table_name)
end
end
end
end
end