module Cell::CloneSchema

Public Class Methods

clone_schema(src, dst) click to toggle source
# File lib/cell/clone_schema.rb, line 48
def self.clone_schema(src, dst)
  clone_cmd = "#{pg_dump_cmd(src)} | #{filter_cmd(src, dst)} | #{psql_cmd}"
  result = %x(#{clone_cmd})
  unless $?.success?
    fail ActiveRecord::StatementInvalid, result
  end
end
configuration() click to toggle source
# File lib/cell/clone_schema.rb, line 11
def self.configuration
  Rails.configuration.database_configuration[Rails.env]
end
connection() click to toggle source
# File lib/cell/clone_schema.rb, line 7
def self.connection
  ::ActiveRecord::Base.connection
end
copy_schema_migrations_to(dst) click to toggle source
# File lib/cell/clone_schema.rb, line 56
    def self.copy_schema_migrations_to(dst)
      Cell::Meta.with_schema(dst, exclusive: true) do
        ::ActiveRecord::SchemaMigration.create_table
      end

      connection.execute <<~SQL
        INSERT INTO #{connection.quote_schema_name(dst)}.schema_migrations
          SELECT * from schema_migrations
      SQL
    end
filter_cmd(src, dst) click to toggle source
# File lib/cell/clone_schema.rb, line 43
def self.filter_cmd(src, dst)
  # This is slightly dumb, but better than trying to do it in DDL
  "sed -e 's/#{src}/#{dst}/g'"
end
pg_dump_cmd(schema_name) click to toggle source
# File lib/cell/clone_schema.rb, line 37
def self.pg_dump_cmd(schema_name)
  cmd = ["pg_dump"] + postgres_cli_args(:pg_dump).map{|s| Shellwords.escape(s)}
  cmd << "--schema" << Shellwords.escape(schema_name)
  cmd.join(" ")
end
postgres_cli_args(cmd) click to toggle source
# File lib/cell/clone_schema.rb, line 15
def self.postgres_cli_args(cmd)
  fail ArgumentError unless [:psql, :pg_dump].include?(cmd)

  conf = configuration

  r = []
  r << '--host'     << conf['host'] if conf['host']
  r << '--port'     << conf['port'] if conf['port']
  r << '--dbname'   << conf['database'] if conf['database']
  r << '--username' << conf['username'] if conf['username']
  r << '--password' << conf['password'] if conf['password']
  # psql doesn't accept --encoding
  r << '--encoding' << conf['encoding'] if conf['encoding'] unless cmd == :psql

  r
end
psql_cmd() click to toggle source
# File lib/cell/clone_schema.rb, line 32
def self.psql_cmd
  cmd = ["psql"] + postgres_cli_args(:psql).map{|s| Shellwords.escape(s)}
  cmd.join(" ")
end