Class: DbVcs::Adapters::Postgres

Inherits:
Object
  • Object
show all
Extended by:
DbVcs::AdapterInterface
Defined in:
lib/db_vcs/adapters/postgres.rb

Defined Under Namespace

Classes: Config

Class Method Summary collapse

Methods included from DbVcs::AdapterInterface

config, connection, copy_database, create_database, db_exists?, drop_by_dbname, list_databases

Class Method Details

.configDbVcs::Adapters::Postgres::Config



23
24
25
# File 'lib/db_vcs/adapters/postgres.rb', line 23

def config
  DbVcs.config.pg_config
end

.connectionPG::Connection

Returns:

  • (PG::Connection)


28
29
30
31
32
33
34
# File 'lib/db_vcs/adapters/postgres.rb', line 28

def connection
  @connection ||=
    begin
      require "pg"
      PG.connect(user: config.username, host: config.host, port: config.port, password: config.password)
    end
end

.copy_database(to_db, from_db) ⇒ Object

Returns void.

Parameters:

  • to_db (String)
  • from_db (String)

Returns:

  • void



45
46
47
# File 'lib/db_vcs/adapters/postgres.rb', line 45

def copy_database(to_db, from_db)
  connection.exec("CREATE DATABASE #{to_db} TEMPLATE #{from_db} OWNER #{config.username}")
end

.create_database(db_name) ⇒ Object

Returns void.

Parameters:

  • db_name (String)

Returns:

  • void



51
52
53
# File 'lib/db_vcs/adapters/postgres.rb', line 51

def create_database(db_name)
  connection.exec("CREATE DATABASE #{db_name} OWNER #{config.username}")
end

.db_exists?(db_name) ⇒ Boolean

Parameters:

  • db_name (String)

Returns:

  • (Boolean)


38
39
40
# File 'lib/db_vcs/adapters/postgres.rb', line 38

def db_exists?(db_name)
  !connection.exec("SELECT 1 AS one FROM pg_database WHERE datname='#{db_name}' LIMIT 1").first.nil?
end

.drop_by_dbname(db_name) ⇒ void

This method returns an undefined value.

Parameters:

  • db_name (String)


62
63
64
# File 'lib/db_vcs/adapters/postgres.rb', line 62

def drop_by_dbname(db_name)
  connection.exec("DROP DATABASE IF EXISTS #{db_name}")
end

.list_databasesArray<String>

Returns:

  • (Array<String>)


56
57
58
# File 'lib/db_vcs/adapters/postgres.rb', line 56

def list_databases
  connection.exec("SELECT datname FROM pg_database WHERE datistemplate = false").to_a.flat_map(&:values)
end