Method: Sequel::Postgres::Database#connect

Defined in:
lib/sequel/adapters/postgres.rb

#connect(server) ⇒ Object

Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection, :connect_timeout is a connection timeout in seconds, :sslmode sets whether postgres’s sslmode, and :notice_receiver handles server notices in a proc. :connect_timeout, :driver_options, :sslmode, and :notice_receiver are only supported if the pg driver is used.



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/sequel/adapters/postgres.rb', line 215

def connect(server)
  opts = server_opts(server)
  if USES_PG
    connection_params = {
      :host => opts[:host],
      :port => opts[:port],
      :dbname => opts[:database],
      :user => opts[:user],
      :password => opts[:password],
      :connect_timeout => opts[:connect_timeout] || 20,
      :sslmode => opts[:sslmode],
      :sslrootcert => opts[:sslrootcert]
    }.delete_if { |key, value| blank_object?(value) }
    # :nocov:
    connection_params.merge!(opts[:driver_options]) if opts[:driver_options]
    # :nocov:
    conn = Adapter.connect(opts[:conn_str] || connection_params)

    conn.instance_variable_set(:@prepared_statements, {})

    if receiver = opts[:notice_receiver]
      conn.set_notice_receiver(&receiver)
    end

    # :nocov:
    if conn.respond_to?(:type_map_for_queries=) && defined?(PG_QUERY_TYPE_MAP)
    # :nocov:
      conn.type_map_for_queries = PG_QUERY_TYPE_MAP
    end
  # :nocov:
  else
    unless typecast_value_boolean(@opts.fetch(:force_standard_strings, true))
      raise Error, "Cannot create connection using postgres-pr unless force_standard_strings is set"
    end

    conn = Adapter.connect(
      (opts[:host] unless blank_object?(opts[:host])),
      opts[:port] || 5432,
      nil, '',
      opts[:database],
      opts[:user],
      opts[:password]
    )
  end
  # :nocov:

  conn.instance_variable_set(:@db, self)

  # :nocov:
  if encoding = opts[:encoding] || opts[:charset]
    if conn.respond_to?(:set_client_encoding)
      conn.set_client_encoding(encoding)
    else
      conn.async_exec("set client_encoding to '#{encoding}'")
    end
  end
  # :nocov:

  connection_configuration_sqls(opts).each{|sql| conn.execute(sql)}
  conn
end