Method: PG::Connection.new

Defined in:
lib/pg/connection.rb

.new(*args) ⇒ Object Also known as: async_connect, connect, open, setdb, setdblogin

call-seq:

PG::Connection.new -> conn
PG::Connection.new(connection_hash) -> conn
PG::Connection.new(connection_string) -> conn
PG::Connection.new(host, port, options, tty, dbname, user, password) ->  conn

Create a connection to the specified server.

connection_hash must be a ruby Hash with connection parameters. See the list of valid parameters in the PostgreSQL documentation.

There are two accepted formats for connection_string: plain keyword = value strings and URIs. See the documentation of connection strings.

The positional parameter form has the same functionality except that the missing parameters will always take on default values. The parameters are:

host

server hostname

port

server port number

options

backend options

tty

(ignored in all versions of PostgreSQL)

dbname

connecting database name

user

login user name

password

login password

If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the connection will have its client_encoding set accordingly.

Raises a PG::Error if the connection fails.

Examples:

# Connect using all defaults
PG::Connection.new

# As a Hash
PG::Connection.new( dbname: 'test', port: 5432 )

# As a String
PG::Connection.new( "dbname=test port=5432" )

# As an Array
PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil )

# As an URI
PG::Connection.new( "postgresql://user:[email protected]:5432/testdb?sslmode=require" )

Specifying Multiple Hosts

It is possible to specify multiple hosts to connect to, so that they are tried in the given order or optionally in random order. In the Keyword/Value format, the host, hostaddr, and port options accept comma-separated lists of values. The details to libpq describe how it works, but there are two small differences how ruby-pg handles multiple hosts:

  • All hosts are resolved before the first connection is tried. This means that when load_balance_hosts is set to random, then all resolved addresses are tried randomly in one level. When a host resolves to more than one address, it is therefore tried more often than a host that has only one address.

  • When a timeout occurs due to the value of connect_timeout, then the given host, hostaddr and port combination is not tried a second time, even if it’s specified several times. It’s still possible to do load balancing with load_balance_hosts set to random and to increase the number of connections a node gets, when the hostname is provided multiple times in the host string. This is because in non-timeout cases the host is tried multiple times.



870
871
872
873
874
875
876
877
878
879
880
881
# File 'lib/pg/connection.rb', line 870

def new(*args)
	conn = connect_to_hosts(*args)

	if block_given?
		begin
			return yield conn
		ensure
			conn.finish
		end
	end
	conn
end