Sha256: 4cebbad8946f7786ad81d8011680b7be39a9bc94a337b28d19fdbb9fa5402c30

Contents?: true

Size: 1.52 KB

Versions: 4

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

require 'apartment/adapters/abstract_adapter'

module Apartment
  module Tenant
    def self.mysql2_adapter(config)
      if Apartment.use_schemas
        Adapters::Mysql2SchemaAdapter.new(config)
      else
        Adapters::Mysql2Adapter.new(config)
      end
    end
  end

  module Adapters
    class Mysql2Adapter < AbstractAdapter
      def initialize(config)
        super

        @default_tenant = config[:database]
      end

      protected

      def rescue_from
        Mysql2::Error
      end
    end

    class Mysql2SchemaAdapter < AbstractAdapter
      def initialize(config)
        super

        @default_tenant = config[:database]
        reset
      end

      #   Reset current tenant to the default_tenant
      #
      def reset
        Apartment.connection.execute "use `#{default_tenant}`"
      end

      protected

      #   Connect to new tenant
      #
      def connect_to_new(tenant)
        return reset if tenant.nil?

        Apartment.connection.execute "use `#{environmentify(tenant)}`"
      rescue ActiveRecord::StatementInvalid => e
        Apartment::Tenant.reset
        raise_connect_error!(tenant, e)
      end

      def process_excluded_model(model)
        model.constantize.tap do |klass|
          # Ensure that if a schema *was* set, we override
          table_name = klass.table_name.split('.', 2).last

          klass.table_name = "#{default_tenant}.#{table_name}"
        end
      end

      def reset_on_connection_exception?
        true
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ros-apartment-2.6.1 lib/apartment/adapters/mysql2_adapter.rb
ros-apartment-2.6.0 lib/apartment/adapters/mysql2_adapter.rb
ros-apartment-2.5.0 lib/apartment/adapters/mysql2_adapter.rb
ros-apartment-2.4.0 lib/apartment/adapters/mysql2_adapter.rb