Module: Cell::CloneSchema

Defined in:
lib/cell/clone_schema.rb

Class Method Summary collapse

Class Method Details

.clone_schema(src, dst) ⇒ Object



48
49
50
51
52
53
54
# 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

.configurationObject



11
12
13
# File 'lib/cell/clone_schema.rb', line 11

def self.configuration
  Rails.configuration.database_configuration[Rails.env]
end

.connectionObject



7
8
9
# File 'lib/cell/clone_schema.rb', line 7

def self.connection
  ::ActiveRecord::Base.connection
end

.copy_schema_migrations_to(dst) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# 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) ⇒ Object



43
44
45
46
# 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) ⇒ Object



37
38
39
40
41
# 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) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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_cmdObject



32
33
34
35
# 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