Class: Sequel::Schema::AlterTableOperations

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/schema/alter_table_operations.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ AlterTableOperations

Returns a new instance of AlterTableOperations.



4
5
6
# File 'lib/sequel/schema/alter_table_operations.rb', line 4

def initialize(options={})
  @immutable_columns = options[:immutable_columns]
end

Class Method Details

.build(db_table, new_table, options = {}) ⇒ Object

Returns an array of operations to change the current database table to be like the defined table.



11
12
13
# File 'lib/sequel/schema/alter_table_operations.rb', line 11

def self.build(db_table, new_table, options={})
  new(options).build(db_table, new_table)
end

Instance Method Details

#build(db_table, new_table) ⇒ Object



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
# File 'lib/sequel/schema/alter_table_operations.rb', line 15

def build(db_table, new_table)
  db_columns = db_table[:columns].inject({}) {|hsh, column| hsh[column.name] = column; hsh }
  new_column_names = new_table[:columns].map {|c| c.name }
  dropped_columns = db_columns.keys - new_column_names

  operations = new_table[:columns].map do |column|
    if db_columns[column.name]
      build_column_operations db_columns[column.name], column
    else
      column.add_statement
    end
  end.flatten

  operations += dropped_columns.map do |name| 
    db_columns[name].drop_statement
  end

  db_indexes = Schema::DbIndex.build_from_hash(db_table[:indexes] || {})
  new_indexes = Schema::DbIndex.build_from_hash(new_table[:indexes] || {})
  
  operations += (db_indexes - new_indexes).map do |index|
    index.drop_statement unless index.columns.all? {|c| dropped_columns.include?(c) }
  end
  
  operations += (new_indexes - db_indexes).map do |index|
    index.add_statement          
  end
  
  operations        
end

#build_column_operations(db_column, new_column) ⇒ Object

Returns an array of operations to change the current database column to be like the defined column.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sequel/schema/alter_table_operations.rb', line 49

def build_column_operations(db_column, new_column)
  result = []
  
  diffs = db_column.diff(new_column)

  if @immutable_columns && !diffs.empty?
    result << :drop_statement
    result << :add_statement
  else
    result << :change_type_statement    if [:elements, :column_type, :size, :unsigned].any? {|sym| diffs.include?(sym) }
    # only need to explicitly set the default if we're not changing the column type.
    result << :change_default_statement if diffs.include?(:default) && result.empty?
    result << :change_null_statement    if diffs.include?(:null)
  end
  
  result.map {|statement| new_column.__send__(statement) }
end