Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `PG.connect` and `PG::Connection.open` in the Ruby 'pg' gem?

Tags:

ruby

pg

From the pg module doc, it seems like the right way to connect to a PG db is to use:

conn = PG::Connection.open(dbname: 'test')

However, I find other examples online which make use of the PG.connect method instead:

conn = PG.connect(dbname: 'testdb', user: 'janbodnar', password: 'pswd37')

Is there a difference between these two ways of connecting to a postgresql database? If yes, what is it? Is one way better than the other? What are the drawbacks / advantages of each method?

like image 733
Thibauld Avatar asked Oct 16 '25 00:10

Thibauld


1 Answers

From the documentation for the PG module itself, you can see that PG.connect is a "convenience alias" for PG::Connection.new:

def self::connect( *args )
  return PG::Connection.new( *args )
end

From the source code of PG::Connection, it's also clear that PG::Connection.open is an alias of PG::Connection.new:

void
init_pg_connection()
{
    …
    SINGLETON_ALIAS(rb_cPGconn, "open", "new");
    …
}

So, all three are actually identical in terms of how they connect to the database. PG.connect adds the cost of one extra method call, since it internally calls PG::Connection.new.

like image 162
user513951 Avatar answered Oct 17 '25 17:10

user513951