]> git.openstreetmap.org Git - rails.git/blob - config/initializers/migrate.rb
Merge remote-tracking branch 'upstream/pull/5296'
[rails.git] / config / initializers / migrate.rb
1 if defined?(ActiveRecord::ConnectionAdapters::AbstractAdapter)
2   module OpenStreetMap
3     module PostgreSQL
4       module Quoting
5         def quote_column_name(name)
6           Array(name).map { |n| super(n) }.join(", ")
7         end
8       end
9
10       module SchemaStatements
11         def add_primary_key(table_name, column_name, options = {})
12           constraint_name = "#{table_name}_pkey"
13
14           options = options.merge(:name => constraint_name, :unique => true)
15
16           add_index(table_name, column_name, **options)
17           set_primary_key table_name, constraint_name
18         end
19
20         def remove_primary_key(table_name)
21           constraint_name = quote_table_name("#{table_name}_pkey")
22           table_name = quote_table_name(table_name)
23
24           execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint_name}"
25         end
26
27         def alter_primary_key(table_name, column_name, options = {})
28           constraint_name = "#{table_name}_pkey"
29           tmp_constraint_name = "#{table_name}_pkey_tmp"
30
31           options = options.merge(:name => tmp_constraint_name, :unique => true)
32
33           add_index(table_name, column_name, **options)
34           remove_primary_key table_name
35           set_primary_key table_name, tmp_constraint_name
36           rename_index table_name, tmp_constraint_name, constraint_name
37         end
38
39         def set_primary_key(table_name, constraint_name)
40           constraint_name = quote_table_name(constraint_name)
41           table_name = quote_table_name(table_name)
42
43           execute "ALTER TABLE #{table_name} ADD PRIMARY KEY USING INDEX #{constraint_name}"
44         end
45       end
46     end
47   end
48
49   ActiveRecord::ConnectionAdapters::PostgreSQL::Quoting.prepend(OpenStreetMap::PostgreSQL::Quoting)
50   ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements.prepend(OpenStreetMap::PostgreSQL::SchemaStatements)
51 end