]> git.openstreetmap.org Git - rails.git/blob - config/initializers/migrate.rb
Use an HTML5 parser for tests
[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 rename_enumeration(old_name, new_name)
55           old_name = quote_table_name(old_name)
56           new_name = quote_table_name(new_name)
57
58           execute "ALTER TYPE #{old_name} RENAME TO #{new_name}"
59         end
60       end
61     end
62   end
63
64   ActiveRecord::ConnectionAdapters::PostgreSQL::Quoting.prepend(OpenStreetMap::PostgreSQL::Quoting)
65   ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements.prepend(OpenStreetMap::PostgreSQL::SchemaStatements)
66 end