Search code examples
rubypg

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


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?


Solution

  • 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.