]> git.openstreetmap.org Git - rails.git/blob - config/initializers/migrate.rb
Merge pull request #3169 from harry-wood/empty-lists
[rails.git] / config / initializers / migrate.rb
1 if defined?(ActiveRecord::ConnectionAdapters::AbstractAdapter)
2   module OpenStreetMap
3     module ActiveRecord
4       module AbstractAdapter
5         def add_index_options(table_name, column_name, options = {})
6           columns = options.delete(:columns)
7           index_name, index_type, index_columns, index_options, algorithm, using = super(table_name, column_name, options)
8           [index_name, index_type, columns || index_columns, index_options, algorithm, using]
9         end
10       end
11
12       module PostgreSQLAdapter
13         def quote_column_name(name)
14           Array(name).map { |n| super(n) }.join(", ")
15         end
16
17         def add_primary_key(table_name, column_name, _options = {})
18           table_name = quote_table_name(table_name)
19           column_name = quote_column_name(column_name)
20
21           execute "ALTER TABLE #{table_name} ADD PRIMARY KEY (#{column_name})"
22         end
23
24         def remove_primary_key(table_name)
25           table_name = quote_table_name(table_name)
26
27           execute "ALTER TABLE #{table_name} DROP PRIMARY KEY"
28         end
29
30         def alter_primary_key(table_name, new_columns)
31           constraint_name = quote_table_name("#{table_name}_pkey")
32           table_name = quote_table_name(table_name)
33           new_columns = quote_column_name(new_columns)
34
35           execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint_name}"
36           execute "ALTER TABLE #{table_name} ADD PRIMARY KEY (#{new_columns})"
37         end
38
39         def create_enumeration(enumeration_name, values)
40           execute "CREATE TYPE #{enumeration_name} AS ENUM ('#{values.join '\',\''}')"
41         end
42
43         def drop_enumeration(enumeration_name)
44           execute "DROP TYPE #{enumeration_name}"
45         end
46
47         def rename_enumeration(old_name, new_name)
48           old_name = quote_table_name(old_name)
49           new_name = quote_table_name(new_name)
50
51           execute "ALTER TYPE #{old_name} RENAME TO #{new_name}"
52         end
53       end
54     end
55   end
56
57   ActiveRecord::ConnectionAdapters::AbstractAdapter.prepend(OpenStreetMap::ActiveRecord::AbstractAdapter)
58   ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(OpenStreetMap::ActiveRecord::PostgreSQLAdapter)
59 end