Class: HQ::Structure

Inherits:
Object
  • Object
show all
Defined in:
lib/hq/structure.rb,
lib/hq/structure/inserts.rb

Defined Under Namespace

Classes: Error, Inserts

Constant Summary collapse

ON_ERROR_STOP_1 =
"ON_ERROR_STOP=1"
SQL_COMMENT_BEGIN =
"--"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_pool:) ⇒ Structure

Returns a new instance of Structure.



35
36
37
# File 'lib/hq/structure.rb', line 35

def initialize(connection_pool:)
  @connection_pool = connection_pool
end

Instance Attribute Details

#connection_poolObject (readonly)

Instance Methods ####



33
34
35
# File 'lib/hq/structure.rb', line 33

def connection_pool
  @connection_pool
end

Class Method Details

.dump(filename, connection_pool:, **options) ⇒ Object



21
22
23
24
# File 'lib/hq/structure.rb', line 21

def self.dump(filename, connection_pool:, **options)
  structure = new(connection_pool: connection_pool)
  structure.dump(filename, **options)
end

.path(filename) ⇒ Object

Class Methods ####



17
18
19
# File 'lib/hq/structure.rb', line 17

def self.path(filename)
  Rails.root.join("db", filename).to_s
end

.restore(filename, connection_pool:, **options) ⇒ Object



26
27
28
29
# File 'lib/hq/structure.rb', line 26

def self.restore(filename, connection_pool:, **options)
  structure = new(connection_pool: connection_pool)
  structure.restore(filename, **options)
end

Instance Method Details

#dump(filename, args: nil, table_inserts: []) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/hq/structure.rb', line 39

def dump(filename, args: nil, table_inserts: [])
  validate_filename!(filename)
  file_path = self.class.path(filename)

  dump_args = ["-s", "-x", "-O", "--no-subscriptions", "-f", file_path, *Array(args), configuration.configuration_hash[:database]]
  run_psql_cmd("pg_dump", dump_args)
  remove_sql_header_comments(file_path)
  inserts = [*default_inserts, *table_inserts]
  inserts_sql = ::HQ::Structure::Inserts.new(connection_pool: connection_pool, tables: inserts).build
  schema_search_path = connection_pool.with_connection(&:schema_search_path)
  File.open(file_path, "a") do |f|
    f << "SET search_path TO #{schema_search_path};\n\n"

    inserts_sql.each do |sql|
      f.puts sql, "\n"
    end
  end
end

#restore(filename, args: nil) ⇒ Object



58
59
60
61
62
63
# File 'lib/hq/structure.rb', line 58

def restore(filename, args: nil)
  validate_filename!(filename)
  file_path = self.class.path(filename)
  restore_args = ["-v", ON_ERROR_STOP_1, "-q", "-X", "-f", file_path, *Array(args), configuration.configuration_hash[:database]]
  run_psql_cmd("psql", restore_args)
end