Class: ActiveRecord::Migration

Inherits:
Object
  • Object
show all
Defined in:
lib/jun/active_record/migration.rb

Instance Method Summary collapse

Instance Method Details

#add_column(table_name, column_name, column_type, options = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/jun/active_record/migration.rb', line 13

def add_column(table_name, column_name, column_type, options = {})
  sql = ["ALTER TABLE #{table_name} ADD COLUMN #{column_name}"]

  sql << column_type.to_s.upcase
  sql << "NOT NULL" if options[:null] == false
  sql << "DEFAULT #{options[:default]}" if options[:default]
  sql << "UNIQUE" if options[:unique] == true

  execute(sql.join(" "))
end

#create_table(table_name, options = {}) ⇒ Object



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
# File 'lib/jun/active_record/migration.rb', line 28

def create_table(table_name, options = {})
  sql = "CREATE TABLE IF NOT EXISTS #{table_name}"
  column_options = []

  if options[:id] || !options.key?(:id)
    column_options << {
      name: :id,
      type: :integer,
      primary_key: true,
      null: false
    }
  end

  column_options += options.fetch(:columns, [])

  columns_sql = column_options.map do |column|
    next(column) if column.is_a?(String)

    column_sql = []

    column_sql << column[:name]
    column_sql << column[:type]&.to_s&.upcase
    column_sql << "PRIMARY KEY" if column[:primary_key] == true
    column_sql << "NOT NULL" if column[:null] == false
    column_sql << "DEFAULT #{column[:default]}" if column[:default]
    column_sql << "UNIQUE" if column[:unique] == true

    column_sql.compact.join(" ")
  end

  sql += " (#{columns_sql.join(", ")})"
  sql += ";"

  execute(sql)
end

#downObject

Raises:

  • (NoMethodError)


9
10
11
# File 'lib/jun/active_record/migration.rb', line 9

def down
  raise NoMethodError, "Subclass must implement method."
end

#drop_table(table_name) ⇒ Object



64
65
66
# File 'lib/jun/active_record/migration.rb', line 64

def drop_table(table_name)
  execute("DROP TABLE IF EXISTS #{table_name};")
end

#execute(*args) ⇒ Object



72
73
74
# File 'lib/jun/active_record/migration.rb', line 72

def execute(*args)
  ActiveRecord::Base.connection.execute(*args)
end

#remove_column(table_name, column_name) ⇒ Object



24
25
26
# File 'lib/jun/active_record/migration.rb', line 24

def remove_column(table_name, column_name)
  execute("ALTER TABLE #{table_name} DROP COLUMN #{column_name};")
end

#rename_table(old_table_name, new_table_name) ⇒ Object



68
69
70
# File 'lib/jun/active_record/migration.rb', line 68

def rename_table(old_table_name, new_table_name)
  execute("ALTER TABLE #{old_table_name} RENAME TO #{new_table_name};")
end

#upObject

Raises:

  • (NoMethodError)


5
6
7
# File 'lib/jun/active_record/migration.rb', line 5

def up
  raise NoMethodError, "Subclass must implement method."
end