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 "    ALTER SEQUENCE \#{sequence_name} RESTART WITH \#{start}; -- any_fixture:dump\n  SQL\nend\n"

#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 "    SELECT\n      pp.proname, pn.nspname,\n      pg_get_functiondef(pp.oid) AS definition\n    FROM pg_proc pp\n    JOIN pg_namespace pn\n      ON pn.oid = pp.pronamespace\n    WHERE pp.proname in (\#{quoted_functions})\n    ORDER BY pp.oid;\n  SQL\n\n  uuid_funcs.each do |(func, ns, _)|\n    execute <<~SQL\n      CREATE OR REPLACE FUNCTION \#{ns}.\#{func}()\n        RETURNS UUID\n        LANGUAGE SQL\n        AS $$\n          SELECT md5(random()::TEXT)::UUID;\n        $$; -- any_fixture:dump\n    SQL\n  end\n\n  execute <<~SQL\n    SELECT setseed(\#{rand}); -- any_fixture:dump\n  SQL\nend\n"

#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