<commit_before># Require whichever elevator you're using below here...
#
# require 'apartment/elevators/generic'
# require 'apartment/elevators/domain'
require 'apartment/elevators/subdomain'
require 'apartment/adapters/postgresql_adapter'
#
# Apartment Configuration
#
Apartment.configure do |config|
  # These models will not be multi-tenanted,
  # but remain in the global (public) namespace
  #
  # An example might be a Customer or Tenant model that stores each tenant information
  # ex:
  #
  # config.excluded_models = %w{Tenant}
  #
  config.excluded_models = %w[]

  # use postgres schemas?
  config.use_schemas = true

  # use raw SQL dumps for creating postgres schemas? (only applies with use_schemas set to true)
  config.use_sql = true

  # Postgis default Schema must be "postgis"
  config.persistent_schemas = %w[postgis]

  # add the Rails environment to database names?
  # config.prepend_environment = false
  # config.append_environment = false
  # supply list of database names for migrations to run on

  multi_database = ENV['MULTI_DATABASE'].to_i
  if multi_database > 0
    # puts "MultiDB mode...".yellow
    config.with_multi_server_setup = true
    config.tenant_names = -> {
      configuration = Rails.configuration.database_configuration[Rails.env]
      index = {}
      conf = Ekylibre::Tenant.list.sort.each_with_object({}) do |tenant, hash|
        database = Ekylibre::Tenant.database_for(tenant)
        index[tenant] = database
        hash[tenant] = configuration.merge('database' => database)
        hash
      end
      File.write(Rails.root.join('config', 'tenant_databases.yml'), index.to_yaml)
      conf
    }
  else
    config.tenant_names = -> { Ekylibre::Tenant.list }
  end
end

module Apartment
  module Elevators
    # Special elevator which permit to switch on header "X-Tenant"
    class Header < Apartment::Elevators::Generic
      def parse_tenant_name(request)
        return nil unless request.env['HTTP_X_TENANT']
        request.env.each do |k, v|
          # puts "#{k.to_s.rjust(30).yellow}: #{v.to_s.red}"
        end
        # puts request.env.keys.inspect.red
        request.env['HTTP_X_TENANT']
      end
    end

    class SecuredSubdomain < Apartment::Elevators::Subdomain
      def call(env)
        super
      rescue ::Apartment::TenantNotFound
        request = Rack::Request.new(env)
        Rails.logger.error "Apartment Tenant not found: #{subdomain(request.host)}"
        return [404, { 'Content-Type' => 'text/html' }, [File.read(Rails.root.join('public', '404.html'))]]
      end
    end
  end

  module Adapters
    class PostgresqlSchemaAdapter < Apartment::Adapters::AbstractAdapter
      protected

      def connect_to_new(tenant = nil)
        return reset if tenant.nil?

        # no switching unless we are in another DATABASE
        # unless Ekylibre::Tenant.database_for(tenant.to_s) == Ekylibre::Tenant.database_for(@current)
        if Ekylibre::Tenant.multi_database > 0
          Apartment.establish_connection multi_tenantify(tenant, false) # Allows us to use the multi-database setup
        end

        raise ActiveRecord::StatementInvalid, "Could not establish connection to database for schema #{tenant}" unless Apartment.connection.active?
        # end

        unless Apartment.connection.schema_exists? tenant
          raise TenantNotFound, "Could not find schema #{tenant}. Search path: [#{full_search_path}]"
        end

        @current = tenant.to_s
        Apartment.connection.schema_search_path = full_search_path

        # rescue *rescuable_exceptions
        #   raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}"
      end
    end
  end
end

if ENV['TENANT']
  Rails.application.config.middleware.use 'Apartment::Elevators::Generic', proc { |_request| ENV['TENANT'] }
elsif Rails.env.test?
  Rails.application.config.middleware.use 'Apartment::Elevators::Generic', proc { |_request| 'test' }
elsif ENV['ELEVATOR'] == 'header'
  Rails.application.config.middleware.use 'Apartment::Elevators::Header'
else
  Rails.application.config.middleware.use 'Apartment::Elevators::SecuredSubdomain'
end<commit_msg>Monkey-patching BLACKLISTED_STATEMENTS in the Apartment::Postgres adapter so we don't carry over some 'CREATE SCHEMA' instructions, since Apartment runs the `create_schema_command` beforehand anyway.<commit_after># Require whichever elevator you're using below here...
#
# require 'apartment/elevators/generic'
# require 'apartment/elevators/domain'
require 'apartment/elevators/subdomain'
require 'apartment/adapters/postgresql_adapter'
#
# Apartment Configuration
#
Apartment.configure do |config|
  # These models will not be multi-tenanted,
  # but remain in the global (public) namespace
  #
  # An example might be a Customer or Tenant model that stores each tenant information
  # ex:
  #
  # config.excluded_models = %w{Tenant}
  #
  config.excluded_models = %w[]

  # use postgres schemas?
  config.use_schemas = true

  # use raw SQL dumps for creating postgres schemas? (only applies with use_schemas set to true)
  config.use_sql = true

  # Postgis default Schema must be "postgis"
  config.persistent_schemas = %w[postgis]

  # add the Rails environment to database names?
  # config.prepend_environment = false
  # config.append_environment = false
  # supply list of database names for migrations to run on

  multi_database = ENV['MULTI_DATABASE'].to_i
  if multi_database > 0
    # puts "MultiDB mode...".yellow
    config.with_multi_server_setup = true
    config.tenant_names = -> {
      configuration = Rails.configuration.database_configuration[Rails.env]
      index = {}
      conf = Ekylibre::Tenant.list.sort.each_with_object({}) do |tenant, hash|
        database = Ekylibre::Tenant.database_for(tenant)
        index[tenant] = database
        hash[tenant] = configuration.merge('database' => database)
        hash
      end
      File.write(Rails.root.join('config', 'tenant_databases.yml'), index.to_yaml)
      conf
    }
  else
    config.tenant_names = -> { Ekylibre::Tenant.list }
  end
end

module Apartment
  module Elevators
    # Special elevator which permit to switch on header "X-Tenant"
    class Header < Apartment::Elevators::Generic
      def parse_tenant_name(request)
        return nil unless request.env['HTTP_X_TENANT']
        request.env.each do |k, v|
          # puts "#{k.to_s.rjust(30).yellow}: #{v.to_s.red}"
        end
        # puts request.env.keys.inspect.red
        request.env['HTTP_X_TENANT']
      end
    end

    class SecuredSubdomain < Apartment::Elevators::Subdomain
      def call(env)
        super
      rescue ::Apartment::TenantNotFound
        request = Rack::Request.new(env)
        Rails.logger.error "Apartment Tenant not found: #{subdomain(request.host)}"
        return [404, { 'Content-Type' => 'text/html' }, [File.read(Rails.root.join('public', '404.html'))]]
      end
    end
  end

  module Adapters
    class PostgresqlSchemaAdapter < Apartment::Adapters::AbstractAdapter
      protected

      def connect_to_new(tenant = nil)
        return reset if tenant.nil?

        # no switching unless we are in another DATABASE
        # unless Ekylibre::Tenant.database_for(tenant.to_s) == Ekylibre::Tenant.database_for(@current)
        if Ekylibre::Tenant.multi_database > 0
          Apartment.establish_connection multi_tenantify(tenant, false) # Allows us to use the multi-database setup
        end

        raise ActiveRecord::StatementInvalid, "Could not establish connection to database for schema #{tenant}" unless Apartment.connection.active?
        # end

        unless Apartment.connection.schema_exists? tenant
          raise TenantNotFound, "Could not find schema #{tenant}. Search path: [#{full_search_path}]"
        end

        @current = tenant.to_s
        Apartment.connection.schema_search_path = full_search_path

        # rescue *rescuable_exceptions
        #   raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}"
      end
    end

    class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter
      PSQL_DUMP_BLACKLISTED_STATEMENTS= [
        /SET search_path/i,                           # overridden later
        /SET lock_timeout/i,                          # new in postgresql 9.3
        /SET row_security/i,                          # new in postgresql 9.5
        /SET idle_in_transaction_session_timeout/i,   # new in postgresql 9.6
        /CREATE SCHEMA/i,
      ]
    end
  end
end

if ENV['TENANT']
  Rails.application.config.middleware.use 'Apartment::Elevators::Generic', proc { |_request| ENV['TENANT'] }
elsif Rails.env.test?
  Rails.application.config.middleware.use 'Apartment::Elevators::Generic', proc { |_request| 'test' }
elsif ENV['ELEVATOR'] == 'header'
  Rails.application.config.middleware.use 'Apartment::Elevators::Header'
else
  Rails.application.config.middleware.use 'Apartment::Elevators::SecuredSubdomain'
end
{'fraction_non_alphanumeric': 0.10078985426632552, 'fraction_numerical': 0.0028924240738680608, 'mean_word_length': 3.3138195777351247, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4129569', 'n_tokens_mistral': 2799, 'n_tokens_neox': 2735, 'n_words': 671}