Class: TableSaw::CreateDumpFile

Inherits:
Object
  • Object
show all
Defined in:
lib/table_saw/create_dump_file.rb

Constant Summary collapse

FORMATS =
{
  'copy' => TableSaw::Formats::Copy,
  'insert' => TableSaw::Formats::Insert
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(records, output:, format:) ⇒ CreateDumpFile

Returns a new instance of CreateDumpFile.



14
15
16
17
18
# File 'lib/table_saw/create_dump_file.rb', line 14

def initialize(records, output:, format:)
  @records = records
  @file = output
  @format = format
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



7
8
9
# File 'lib/table_saw/create_dump_file.rb', line 7

def file
  @file
end

#formatObject (readonly)

Returns the value of attribute format.



7
8
9
# File 'lib/table_saw/create_dump_file.rb', line 7

def format
  @format
end

#recordsObject (readonly)

Returns the value of attribute records.



7
8
9
# File 'lib/table_saw/create_dump_file.rb', line 7

def records
  @records
end

Instance Method Details

#callObject

rubocop:disable Metrics/MethodLength,Metrics/AbcSize



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/table_saw/create_dump_file.rb', line 21

def call
  FileUtils.rm_f(file)
  FileUtils.mkdir_p(File.dirname(file))

  alter_constraints_deferrability

  write_to_file <<~SQL
    BEGIN;

    SET statement_timeout = 0;
    SET lock_timeout = 0;
    SET client_encoding = 'UTF8';
    SET standard_conforming_strings = on;
    SET check_function_bodies = false;
    SET client_min_messages = warning;

    SET search_path = public, pg_catalog;
  SQL

  records.each do |name, table|
    defer_constraints(name)

    write_to_file <<~COMMENT
      --
      -- Data for Name: #{name}; Type: TABLE DATA
      --

    COMMENT

    formatter = FORMATS.fetch(format.fetch('type', 'copy'), TableSaw::Formats::Copy).new(name, options: format)

    Array(formatter.header).each { |line| write_to_file(line) }

    TableSaw.connection_pool.with_connection do |conn|
      conn.raw_connection.copy_data "COPY (#{table.copy_statement}) TO STDOUT", formatter.coder do
        while (row = conn.raw_connection.get_copy_data)
          write_to_file formatter.dump_row(row)
        end
      end
    end

    Array(formatter.footer).each { |line| write_to_file(line) }
  end

  write_to_file 'COMMIT;'
  write_to_file "\n"

  refresh_materialized_views
  restart_sequences

  alter_constraints_deferrability keyword: 'NOT DEFERRABLE'
end