Last active
September 25, 2015 07:47
-
-
Save virtualstaticvoid/887168 to your computer and use it in GitHub Desktop.
Multi-schema support for migrations in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # http://www.developerit.com/2010/05/07/creating-a-multi-tenant-application-using-postgresqls-schemas-and-rails | |
| # | |
| module SchemaUtils | |
| def self.add_schema_to_path(schema) | |
| conn = ActiveRecord::Base.connection | |
| conn.execute "SET search_path TO #{schema}, #{conn.schema_search_path}" | |
| end | |
| def self.reset_search_path | |
| conn = ActiveRecord::Base.connection | |
| conn.execute "SET search_path TO #{conn.schema_search_path}" | |
| end | |
| def self.create_and_migrate_schema(schema_name) | |
| conn = ActiveRecord::Base.connection | |
| schemas = conn.select_values("select * from pg_namespace where nspname != 'information_schema' AND nspname NOT LIKE 'pg%'") | |
| if schemas.include?(schema_name) | |
| tables = conn.tables | |
| Rails.logger.info "#{schema_name} exists already with these tables #{tables.inspect}" | |
| else | |
| Rails.logger.info "About to create #{schema_name}" | |
| conn.execute "create schema #{schema_name}" | |
| end | |
| # Save the old search path so we can set it back at the end of this method | |
| old_search_path = conn.schema_search_path | |
| # Tried to set the search path like in the methods above (from Guy Naor) | |
| # conn.execute "SET search_path TO #{schema_name}" | |
| # But the connection itself seems to remember the old search path. | |
| # If set this way, it works. | |
| conn.schema_search_path = schema_name | |
| # Directly from databases.rake. | |
| # In Rails 2.3.5 databases.rake can be found in railties/lib/tasks/databases.rake | |
| file = "#{Rails.root}/db/schema.rb" | |
| if File.exists?(file) | |
| Rails.logger.info "About to load the schema #{file}" | |
| load(file) | |
| else | |
| abort %{#{file} doesn't exist yet. It's possible that you just ran a migration!} | |
| end | |
| Rails.logger.info "About to set search path back to #{old_search_path}." | |
| conn.schema_search_path = old_search_path | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment