Class: Volt::Sql::IndexUpdater

Inherits:
Object
  • Object
show all
Includes:
SqlLogger
Defined in:
app/sql/lib/index_updater.rb

Instance Method Summary collapse

Methods included from SqlLogger

#log

Constructor Details

#initialize(db, model_class, table_name) ⇒ IndexUpdater

Returns a new instance of IndexUpdater.



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
# File 'app/sql/lib/index_updater.rb', line 14

def initialize(db, model_class, table_name)
  @db = db
  @table_name = table_name

  model_indexes = model_class.indexes
  db_indexes = Helper.normalized_indexes_from_table(@db, table_name)

  model_indexes.each_pair do |name, options|
    # See if we have a matching columns/options
    if db_indexes[name] == options
      # Matches, ignore it
      db_indexes.delete(name)
    else
      # Something changed, if a db_index for the name exists,
      # delete it, because the options changed
      if (db_opts = db_indexes[name])
        # Drop the index, drop it from the liast of db_indexes
        drop_index(name, db_opts)
        db_indexes.delete(name)
      end

      # Create the new index
      add_index(name, options)
    end
  end

  # drop any remaining db_indexes, because they are no longer defined in
  # the model
  db_indexes.each do |name, options|
    drop_index(name, options)
  end

  @db.indexes(table_name)
end

Instance Method Details

#add_index(name, options) ⇒ Object



59
60
61
62
63
64
65
# File 'app/sql/lib/index_updater.rb', line 59

def add_index(name, options)
  columns, options = columns_and_options(name, options)
  log("add index on #{columns.inspect}, #{options.inspect}")
  @db.alter_table(@table_name) do
    add_index(columns, options)
  end
end

#drop_index(name, options) ⇒ Object



50
51
52
53
54
55
56
57
# File 'app/sql/lib/index_updater.rb', line 50

def drop_index(name, options)
  columns, options = columns_and_options(name, options)
  log("drop index on #{columns.inspect}, #{options.inspect}")

  @db.alter_table(@table_name) do
    drop_index(columns, options.select {|k,v| k == :name })
  end
end