Skip to content

Commit

Permalink
Merge pull request #492 from cbandy/port-integer
Browse files Browse the repository at this point in the history
Return the libpq default port when blank in conninfo
  • Loading branch information
larskanis committed Nov 17, 2022
2 parents b4a371d + e0a0796 commit 574ecad
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
3 changes: 3 additions & 0 deletions ext/pg.c
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,9 @@ Init_pg_ext(void)
rb_define_const(rb_mPGconstants, "INVALID_OID", INT2FIX(InvalidOid));
rb_define_const(rb_mPGconstants, "InvalidOid", INT2FIX(InvalidOid));

/* PostgreSQL compiled in default port */
rb_define_const(rb_mPGconstants, "DEF_PGPORT", INT2FIX(DEF_PGPORT));

/* Add the constants to the toplevel namespace */
rb_include_module( rb_mPG, rb_mPGconstants );

Expand Down
5 changes: 4 additions & 1 deletion ext/pg_connection.c
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,10 @@ static VALUE
pgconn_port(VALUE self)
{
char* port = PQport(pg_get_pgconn(self));
return INT2NUM(atoi(port));
if (!port || port[0] == '\0')
return INT2NUM(DEF_PGPORT);
else
return INT2NUM(atoi(port));
}

/*
Expand Down
1 change: 1 addition & 0 deletions lib/pg/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,7 @@ def new(*args)
# This requires PostgreSQL-10+, so no DNS resolving is done on earlier versions.
ihosts = iopts[:host].split(",", -1)
iports = iopts[:port].split(",", -1)
iports = [nil] if iports.size == 0
iports = iports * ihosts.size if iports.size == 1
raise PG::ConnectionBad, "could not match #{iports.size} port numbers to #{ihosts.size} hosts" if iports.size != ihosts.size

Expand Down
25 changes: 25 additions & 0 deletions spec/pg/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,31 @@
expect( @conn.options ).to eq( "" )
end

it "connects without port and then retrieves the default port" do
gate = Helpers::TcpGateSwitcher.new(
external_host: 'localhost',
external_port: ENV['PGPORT'].to_i,
internal_host: "127.0.0.1",
internal_port: PG::DEF_PGPORT,
debug: ENV['PG_DEBUG']=='1')

PG.connect(host: "localhost",
port: "",
dbname: "test") do |conn|
expect( conn.port ).to eq( PG::DEF_PGPORT )
end

PG.connect(hostaddr: "127.0.0.1",
port: nil,
dbname: "test") do |conn|
expect( conn.port ).to eq( PG::DEF_PGPORT )
end

gate.finish
rescue Errno::EADDRINUSE => err
skip err.to_s
end

it "can retrieve hostaddr for the established connection", :postgresql_12 do
expect( @conn.hostaddr ).to match( /^127\.0\.0\.1$|^::1$/ )
end
Expand Down

0 comments on commit 574ecad

Please sign in to comment.