Class: TestProf::AnyFixture::Dump::PostgreSQL

Inherits:
BaseAdapter
  • Object
show all
Defined in:
lib/test_prof/any_fixture/dump/postgresql.rb

Constant Summary collapse

UUID_FUNCTIONS =
%w[
  gen_random_uuid
  uuid_generate_v4
]

Instance Method Summary collapse

Instance Method Details

#compile_sql(sql, binds) ⇒ Object



25
26
27
# File 'lib/test_prof/any_fixture/dump/postgresql.rb', line 25

def compile_sql(sql, binds)
  sql.gsub(/\$\d+/) { binds.shift.gsub("\n", "' || chr(10) || '") }
end

#import(path) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/test_prof/any_fixture/dump/postgresql.rb', line 29

def import(path)
  # Test if psql is installed
  `psql --version`

  tasks = ActiveRecord::Tasks::PostgreSQLDatabaseTasks.new(config)

  while_disconnected do
    tasks.structure_load(path, "--output=/dev/null")
  end

  true
rescue Errno::ENOENT
  false
end

#reset_sequence!(table_name, start) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/test_prof/any_fixture/dump/postgresql.rb', line 14

def reset_sequence!(table_name, start)
  _pk, sequence = conn.pk_and_sequence_for(table_name)
  return unless sequence

  sequence_name = "#{sequence.schema}.#{sequence.identifier}"

  execute <<~SQL
    ALTER SEQUENCE #{sequence_name} RESTART WITH #{start}; -- any_fixture:dump
  SQL
end

#setup_envObject



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
73
# File 'lib/test_prof/any_fixture/dump/postgresql.rb', line 44

def setup_env
  # Mock UUID generating functions to provide consistent results
  quoted_functions = UUID_FUNCTIONS.map { |func| "'#{func}'" }.join(", ")

  @uuid_funcs = execute <<~SQL
    SELECT
      pp.proname, pn.nspname,
      pg_get_functiondef(pp.oid) AS definition
    FROM pg_proc pp
    JOIN pg_namespace pn
      ON pn.oid = pp.pronamespace
    WHERE pp.proname in (#{quoted_functions})
    ORDER BY pp.oid;
  SQL

  uuid_funcs.each do |(func, ns, _)|
    execute <<~SQL
      CREATE OR REPLACE FUNCTION #{ns}.#{func}()
        RETURNS UUID
        LANGUAGE SQL
        AS $$
          SELECT md5(random()::TEXT)::UUID;
        $$; -- any_fixture:dump
    SQL
  end

  execute <<~SQL
    SELECT setseed(#{rand}); -- any_fixture:dump
  SQL
end

#teardown_envObject



75
76
77
78
79
# File 'lib/test_prof/any_fixture/dump/postgresql.rb', line 75

def teardown_env
  uuid_funcs.each do |(func, ns, definition)|
    execute "#{definition}; -- any_fixture:dump"
  end
end