Skip to content

Commit 574ecad

Browse files
authored
Merge pull request #492 from cbandy/port-integer
Return the libpq default port when blank in conninfo
2 parents b4a371d + e0a0796 commit 574ecad

File tree

4 files changed

+33
-1
lines changed

4 files changed

+33
-1
lines changed

ext/pg.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,9 @@ Init_pg_ext(void)
679679
rb_define_const(rb_mPGconstants, "INVALID_OID", INT2FIX(InvalidOid));
680680
rb_define_const(rb_mPGconstants, "InvalidOid", INT2FIX(InvalidOid));
681681

682+
/* PostgreSQL compiled in default port */
683+
rb_define_const(rb_mPGconstants, "DEF_PGPORT", INT2FIX(DEF_PGPORT));
684+
682685
/* Add the constants to the toplevel namespace */
683686
rb_include_module( rb_mPG, rb_mPGconstants );
684687

ext/pg_connection.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,10 @@ static VALUE
702702
pgconn_port(VALUE self)
703703
{
704704
char* port = PQport(pg_get_pgconn(self));
705-
return INT2NUM(atoi(port));
705+
if (!port || port[0] == '\0')
706+
return INT2NUM(DEF_PGPORT);
707+
else
708+
return INT2NUM(atoi(port));
706709
}
707710

708711
/*

lib/pg/connection.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,7 @@ def new(*args)
723723
# This requires PostgreSQL-10+, so no DNS resolving is done on earlier versions.
724724
ihosts = iopts[:host].split(",", -1)
725725
iports = iopts[:port].split(",", -1)
726+
iports = [nil] if iports.size == 0
726727
iports = iports * ihosts.size if iports.size == 1
727728
raise PG::ConnectionBad, "could not match #{iports.size} port numbers to #{ihosts.size} hosts" if iports.size != ihosts.size
728729

spec/pg/connection_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,31 @@
731731
expect( @conn.options ).to eq( "" )
732732
end
733733

734+
it "connects without port and then retrieves the default port" do
735+
gate = Helpers::TcpGateSwitcher.new(
736+
external_host: 'localhost',
737+
external_port: ENV['PGPORT'].to_i,
738+
internal_host: "127.0.0.1",
739+
internal_port: PG::DEF_PGPORT,
740+
debug: ENV['PG_DEBUG']=='1')
741+
742+
PG.connect(host: "localhost",
743+
port: "",
744+
dbname: "test") do |conn|
745+
expect( conn.port ).to eq( PG::DEF_PGPORT )
746+
end
747+
748+
PG.connect(hostaddr: "127.0.0.1",
749+
port: nil,
750+
dbname: "test") do |conn|
751+
expect( conn.port ).to eq( PG::DEF_PGPORT )
752+
end
753+
754+
gate.finish
755+
rescue Errno::EADDRINUSE => err
756+
skip err.to_s
757+
end
758+
734759
it "can retrieve hostaddr for the established connection", :postgresql_12 do
735760
expect( @conn.hostaddr ).to match( /^127\.0\.0\.1$|^::1$/ )
736761
end

0 commit comments

Comments
 (0)