Sha256: 433db5d16f8aa5d8a1fdc7078781e11f4665b3483df1ec892489de372f3d24ce

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

module ActiveTenant
  class PostgresAdapter
    delegate :connection_config, :establish_connection, :connection, to: ::ActiveRecord::Base

    def initialize
      self.global = ActiveTenant.configuration.global if ActiveTenant.configuration.global
    end

    def all
      connection.select_values("SELECT nspname FROM pg_namespace WHERE nspname <> 'information_schema' AND nspname NOT LIKE 'pg%'") - [global]
    end

    def create(name)
      unless all.include? name
        connection.execute "CREATE SCHEMA \"#{name}\""
      end
    end

    def remove(name)
      if all.include? name
        connection.execute "DROP SCHEMA \"#{name}\" CASCADE"
      end
    end

    def with(name)
      return yield if name == search_path

      ex = nil
      current_schema = search_path
      search_path name
      begin
        result = yield
      rescue => e
        ex = e
      ensure
        search_path current_schema
        raise ex unless ex.nil?
        result
      end
    end

    def connection_settings(name)
      connection_config.merge(schema_search_path: name)
    end

    def name
      search_path
    end

    def global
      @global || 'public'
    end

    def global?
      global == name
    end

    private

    def global=(name)
      @global = name
    end

    def search_path(name=nil)
      if name
        establish_connection connection_settings(name)
      else
        connection_config[:schema_search_path]
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_tenant-0.0.4 lib/active_tenant/adapters/postgres_adapter.rb
active_tenant-0.0.3 lib/active_tenant/adapters/postgres_adapter.rb