Search code examples
rubypostgresqlpg

PGconn.connect details of the hash needed in ruby pg gem


I would like to better document my code rather than having a statement like the below:

pg_c = PGconn.connect("Main-my_db_lk", 5433, '', '', "report_center", "repozenter", "rp_23_xhg")

How do I know what is what in this statement? Is it possible to point out each parameter to the method like this: port => 5433, host=> xxx

How better write the connection string? what are the empty 3rd and 4th parameters?

Thanks


Solution

  • The arguments to connect in array form are: host, port, options, tty, dbname, user, and password.

    The 3rd argument can contain one or more runtime options, e.g.,

    [1] pry(main)> c = PG.connect( '', '', '-c search_path=public,test', '', 'test' )
    => #<PG::Connection:0x007f9e19c16d30>
    [2] pry(main)> c.exec( 'show search_path' ).values
    => [["public,test"]]
    

    The 4th argument isn't used anymore, but remains for backward-compatibility.

    You can also pass a hash of options when connecting, as you suggested, which is a bit clearer:

    conn = PG.connect( :dbname => 'test', :user => 'postgres' )
    

    The available keys are listed in the API documentation for PG::Connection.new.