Class: MultitenancyTools::ExtensionsDumper

Inherits:
Object
  • Object
show all
Defined in:
lib/multitenancy_tools/extensions_dumper.rb

Overview

ExtensionsDumper can be used to generate a SQL dump of all extensions that are enabled on a PostgreSQL database.

Examples:

dumper = MultitenancyTools::ExtensionsDumper.new
dumper.dump_to('path/to/file.sql')

Constant Summary collapse

EXTENSION_SQL =
<<-'SQL'.freeze
  SELECT extname, nspname FROM pg_catalog.pg_extension
  JOIN pg_catalog.pg_namespace n ON (extnamespace = n.oid)
SQL
CREATE_EXTENSION_SQL =
'CREATE EXTENSION IF NOT EXISTS "%s" WITH SCHEMA %s;'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(connection = ActiveRecord::Base.connection) ⇒ ExtensionsDumper

Returns a new instance of ExtensionsDumper.

Parameters:

  • connection (ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) (defaults to: ActiveRecord::Base.connection)

    connection adapter



17
18
19
# File 'lib/multitenancy_tools/extensions_dumper.rb', line 17

def initialize(connection = ActiveRecord::Base.connection)
  @connection = connection
end

Instance Method Details

#dump_to(file, mode: 'w') ⇒ Object

Generates a dump and writes it into a file. Please see IO.new for open modes.

Parameters:

  • file (String)

    file path

  • mode (String) (defaults to: 'w')

    IO open mode

See Also:



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/multitenancy_tools/extensions_dumper.rb', line 28

def dump_to(file, mode: 'w')
  results = @connection.execute(EXTENSION_SQL)

  File.open(file, mode) do |f|
    results.each do |result|
      name = result.fetch('extname')
      schema = result.fetch('nspname')

      f.puts(format(CREATE_EXTENSION_SQL, name, schema))
    end
  end
end