class Apartment::Adapters::PostgresqlSchemaFromSqlAdapter

Another Adapter for Postgresql when using schemas and SQL

def check_input_against_regexps(input, regexps)


Checks if any of regexps matches against input
def check_input_against_regexps(input, regexps)
  regexps.select {|c| input.match c}
end

def clone_pg_schema


Clone default schema into new schema named after current tenant
def clone_pg_schema
  pg_schema_sql = patch_search_path(pg_dump_schema)
  Apartment.connection.execute(pg_schema_sql)
end

def collect_table_names(models)


Collect table names from AR Models
def collect_table_names(models)
  models.map do |m|
    m.constantize.table_name
  end
end

def copy_schema_migrations


Copy data from schema_migrations into new schema
def copy_schema_migrations
  pg_migrations_data = patch_search_path(pg_dump_schema_migrations_data)
  Apartment.connection.execute(pg_migrations_data)
end

def dbname


Convenience method for current database name
def dbname
  ActiveRecord::Base.connection_config[:database]
end

def default_schema


Convenience method for the default schema
def default_schema
  Apartment.default_schema
end

def import_database_schema

def import_database_schema
  clone_pg_schema
  copy_schema_migrations
end

def patch_search_path(sql)

Returns:
  • (String) - patched raw SQL dump
def patch_search_path(sql)
  search_path = "SET search_path = \"#{current}\", #{default_schema};"
  sql
    .split("\n")
    .select {|line| check_input_against_regexps(line, PSQL_DUMP_BLACKLISTED_STATEMENTS).empty?}
    .prepend(search_path)
    .join("\n")
end

def pg_dump_schema

Returns:
  • (String) - raw SQL contaning only postgres schema dump
def pg_dump_schema
  # Skip excluded tables? :/
  # excluded_tables =
  #   collect_table_names(Apartment.excluded_models)
  #   .map! {|t| "-T #{t}"}
  #   .join(' ')
  # `pg_dump -s -x -O -n #{default_schema} #{excluded_tables} #{dbname}`
  `pg_dump -s -x -O -n #{default_schema} #{dbname}`
end

def pg_dump_schema_migrations_data

Returns:
  • (String) - raw SQL contaning inserts with data from schema_migrations
def pg_dump_schema_migrations_data
  `pg_dump -a --inserts -t schema_migrations -n #{default_schema} #{dbname}`
end