]> git.openstreetmap.org Git - rails.git/blob - config/initializers/migrate.rb
Merge remote-tracking branch 'upstream/pull/4319'
[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
46         def create_enumeration(enumeration_name, values)
47           execute "CREATE TYPE #{enumeration_name} AS ENUM ('#{values.join '\',\''}')"
48         end
49
50         def drop_enumeration(enumeration_name)
51           execute "DROP TYPE #{enumeration_name}"
52         end
53
54         def add_enumeration_value(enumeration_name, value)
55           execute "ALTER TYPE #{enumeration_name} ADD VALUE '#{value}'"
56         end
57
58         def rename_enumeration(old_name, new_name)
59           old_name = quote_table_name(old_name)
60           new_name = quote_table_name(new_name)
61
62           execute "ALTER TYPE #{old_name} RENAME TO #{new_name}"
63         end
64       end
65     end
66   end
67
68   ActiveRecord::ConnectionAdapters::PostgreSQL::Quoting.prepend(OpenStreetMap::PostgreSQL::Quoting)
69   ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements.prepend(OpenStreetMap::PostgreSQL::SchemaStatements)
70 end