Class: ActiveRecord::ModelSpaces::TableManager

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/active_record/model_spaces/table_manager.rb

Overview

manages the creation and destruction of tables, and the bulk handling of data in those tables

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

all_model_superclasses, class_for_classname, class_from_classname, is_active_record_model?, model_from_name, name_from_model, require_for_classname

Constructor Details

#initialize(model) ⇒ TableManager

Returns a new instance of TableManager.



14
15
16
17
# File 'lib/active_record/model_spaces/table_manager.rb', line 14

def initialize(model)
  @model = model_from_name(model)
  @connection = @model.connection
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



12
13
14
# File 'lib/active_record/model_spaces/table_manager.rb', line 12

def connection
  @connection
end

#modelObject (readonly)

Returns the value of attribute model.



11
12
13
# File 'lib/active_record/model_spaces/table_manager.rb', line 11

def model
  @model
end

Instance Method Details

#copy_table(from, to) ⇒ Object

copy all data from one table to another



45
46
47
# File 'lib/active_record/model_spaces/table_manager.rb', line 45

def copy_table(from, to)
  connection.execute("insert into #{to} select * from #{from}") if from != to
end

#create_table(base_table_name, table_name) ⇒ Object

create a new table with the same schema as the base_table, but a different name



20
21
22
23
24
# File 'lib/active_record/model_spaces/table_manager.rb', line 20

def create_table(base_table_name, table_name)
  if table_name != base_table_name && !connection.table_exists?(table_name)
    get_table_schema_copier(connection).copy_table_schema(connection, base_table_name, table_name)
  end
end

#drop_table(table_name) ⇒ Object

drop a table



27
28
29
# File 'lib/active_record/model_spaces/table_manager.rb', line 27

def drop_table(table_name)
  connection.execute("drop table #{table_name}") if connection.table_exists?(table_name)
end

#recreate_table(base_table_name, table_name) ⇒ Object

drop and recreate a table



32
33
34
35
36
37
# File 'lib/active_record/model_spaces/table_manager.rb', line 32

def recreate_table(base_table_name, table_name)
  if table_name != base_table_name
    drop_table(table_name)
    create_table(base_table_name, table_name)
 end
end

#truncate_table(table_name) ⇒ Object

truncate a table



40
41
42
# File 'lib/active_record/model_spaces/table_manager.rb', line 40

def truncate_table(table_name)
  connection.execute("truncate table #{table_name}")
end