Module: DynamicMigrations::Postgres::Server::Database::Connection

Included in:
DynamicMigrations::Postgres::Server::Database
Defined in:
lib/dynamic_migrations/postgres/server/database/connection.rb

Defined Under Namespace

Classes: AlreadyConnectedError, MissingDatabaseNameError, NotConnectedError

Instance Method Summary collapse

Instance Method Details

#connectObject



17
18
19
20
21
# File 'lib/dynamic_migrations/postgres/server/database/connection.rb', line 17

def connect
  raise MissingDatabaseNameError unless name
  raise AlreadyConnectedError if @connection
  @connection = Postgres::Connections.create_connection server.host, server.port, server.username, server.password, name
end

#connected?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/dynamic_migrations/postgres/server/database/connection.rb', line 36

def connected?
  !@connection.nil?
end

#connectionObject



23
24
25
# File 'lib/dynamic_migrations/postgres/server/database/connection.rb', line 23

def connection
  @connection || raise(NotConnectedError)
end

#disconnectObject



27
28
29
30
31
32
33
34
# File 'lib/dynamic_migrations/postgres/server/database/connection.rb', line 27

def disconnect
  if (conn = @connection)
    Postgres::Connections.disconnect conn
    @connection = nil
  else
    raise NotConnectedError
  end
end

#with_connection(&block) ⇒ Object

Opens a connection to the database server, and yields the provided block before automatically closing the connection again. This is useful for executing one time queries against the database server.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/dynamic_migrations/postgres/server/database/connection.rb', line 43

def with_connection &block
  # create a temporary connection to the server (unless we are already connected)
  already_connected = connected?
  unless already_connected
    connect
  end

  # perform work with the connection
  # todo: `yield connection` would have been preferred, but rbs/steep doesnt understand that syntax
  if block.is_a? Proc
    result = block.call connection
  end

  # close the connection (unless we were already connected)
  if already_connected
    disconnect
  end

  # return whever was returned from within the block
  result
end