lib/apartment/adapters/postgresql_adapter.rb in ros-apartment-2.6.0 vs lib/apartment/adapters/postgresql_adapter.rb in ros-apartment-2.6.1

- old
+ new

@@ -35,12 +35,18 @@ # @return {String} default schema search path # def reset @current = default_tenant Apartment.connection.schema_search_path = full_search_path + reset_sequence_names end + def init + super + Apartment.connection.schema_search_path = full_search_path + end + def current @current || default_tenant end protected @@ -71,10 +77,11 @@ # When the PostgreSQL version is < 9.3, # there is a issue for prepared statement with changing search_path. # https://www.postgresql.org/docs/9.3/static/sql-prepare.html Apartment.connection.clear_cache! if postgresql_version < 90_300 + reset_sequence_names rescue *rescuable_exceptions raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}" end private @@ -101,9 +108,22 @@ def postgresql_version # ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#postgresql_version is # public from Rails 5.0. Apartment.connection.send(:postgresql_version) + end + + def reset_sequence_names + # sequence_name contains the schema, so it must be reset after switch + # There is `reset_sequence_name`, but that method actually goes to the database + # to find out the new name. Therefore, we do this hack to only unset the name, + # and it will be dynamically found the next time it is needed + ActiveRecord::Base.descendants + .select { |c| c.instance_variable_defined?(:@sequence_name) } + .reject { |c| c.instance_variable_defined?(:@explicit_sequence_name) && c.instance_variable_get(:@explicit_sequence_name) } + .each do |c| + c.remove_instance_variable :@sequence_name + end end end # Another Adapter for Postgresql when using schemas and SQL class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter