Module: SchemaPlus::ActiveRecord::ConnectionAdapters::SchemaStatements

Defined in:
lib/schema_plus/active_record/connection_adapters/schema_statements.rb

Defined Under Namespace

Modules: AddIndex

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_index_exception_handler(connection, table, columns, options, e) ⇒ Object

:nodoc:



48
49
50
51
52
53
54
55
# File 'lib/schema_plus/active_record/connection_adapters/schema_statements.rb', line 48

def self.add_index_exception_handler(connection, table, columns, options, e) #:nodoc:
  raise unless e.message.match(/["']([^"']+)["'].*already exists/)
  name = $1
  existing = connection.indexes(table).find{|i| i.name == name}
  attempted = ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table, columns, options.merge(:name => name)) 
  raise if attempted != existing
  ::ActiveRecord::Base.logger.warn "[schema_plus] Index name #{name.inspect}' on table #{table.inspect} already exists. Skipping."
end

.included(base) ⇒ Object

:nodoc:



4
5
6
7
8
9
# File 'lib/schema_plus/active_record/connection_adapters/schema_statements.rb', line 4

def self.included(base) #:nodoc:
  base.class_eval do
    alias_method_chain :create_table, :schema_plus
    include AddIndex
  end
end

Instance Method Details

#create_table_with_schema_plus(table, options = {}) ⇒ Object

:method: create_table

SchemaPlus extends SchemaStatements::create_table to allow you to specify configuration options per table. Pass them in as a hash keyed by configuration set (see SchemaPlus::Config), for example:

create_table :widgets, :foreign_keys => {:auto_create => true, :on_delete => :cascade} do |t|
   ...
end


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
# File 'lib/schema_plus/active_record/connection_adapters/schema_statements.rb', line 20

def create_table_with_schema_plus(table, options = {})
  options = options.dup
  config_options = {}
  options.keys.each { |key| config_options[key] = options.delete(key) if SchemaPlus.config.class.attributes.include? key }

  # override rails' :force to cascade
  drop_table(table, if_exists: true, cascade: true) if options.delete(:force)

  if ::ActiveRecord::VERSION::MAJOR.to_i < 4
    indexes = []
  end
  create_table_without_schema_plus(table, options) do |table_definition|
    table_definition.schema_plus_config = SchemaPlus.config.merge(config_options)
    if ::ActiveRecord::VERSION::MAJOR.to_i < 4
      table_definition.name = table
    end
    yield table_definition if block_given?
    if ::ActiveRecord::VERSION::MAJOR.to_i < 4
      indexes = table_definition.indexes
    end
  end
  if ::ActiveRecord::VERSION::MAJOR.to_i < 4
    indexes.each do |index|
      add_index(table, index.columns, index.opts)
    end
  end
end