@@ -12,13 +12,15 @@ import (
1212 "os"
1313 "path/filepath"
1414 "reflect"
15+ "runtime"
1516 "slices"
1617 "sort"
1718 "strconv"
1819 "strings"
1920 "time"
2021 "unicode"
2122
23+ "github.com/lib/pq/internal/pgservice"
2224 "github.com/lib/pq/internal/pqutil"
2325 "github.com/lib/pq/internal/proto"
2426)
@@ -412,6 +414,23 @@ type Config struct {
412414 // Maximum PostgreSQL protocol version to request from the server. Defaults to "3.0".
413415 MaxProtocolVersion ProtocolVersion `postgres:"max_protocol_version" env:"PGMAXPROTOCOLVERSION"`
414416
417+ // Load connection parameters from the service file at ~/.pg_service.conf
418+ // (which can be configured with PGSERVICEFILE).
419+ //
420+ // The service file is a INI-like file to configure connection parameters:
421+ //
422+ // [servicename]
423+ // # Comment
424+ // dbname=foo
425+ //
426+ // Unlike libpq, this does not look at the system-wide service file, as the
427+ // location of this is a compile-time value that is not easy for pq to
428+ // retrieve.
429+ Service string `postgres:"service" env:"PGSERVICE"`
430+
431+ // Path to connection service file. Defaults to ~/.pg_service.conf.
432+ ServiceFile string `postgres:"-" env:"PGSERVICEFILE"`
433+
415434 // Runtime parameters: any unrecognized parameter in the DSN will be added
416435 // to this and sent to PostgreSQL during startup.
417436 Runtime map [string ]string `postgres:"-" env:"-"`
@@ -440,7 +459,10 @@ type ConfigMultihost struct {
440459 Port uint16
441460}
442461
443- // NewConfig creates a new [Config] from the defaults, environment, and DSN.
462+ // NewConfig creates a new [Config] from the defaults, environment, service
463+ // file, and DSN, in that order. That is: a service overrides any value from the
464+ // environment, which in turn gets overridden by the same parameter in the
465+ // connection string.
444466//
445467// Most connection parameters supported by PostgreSQL are supported; see the
446468// [Config] struct for supported parameters. pq also lets you specify any
@@ -534,6 +556,9 @@ func newConfig(dsn string, env []string) (Config, error) {
534556 if err := cfg .fromDSN (dsn ); err != nil {
535557 return Config {}, err
536558 }
559+ if err := cfg .fromService (); err != nil {
560+ return Config {}, err
561+ }
537562
538563 // Need to have exactly the same number of host and hostaddr, or only specify one.
539564 if cfg .isset ("host" ) && cfg .Host != "" && cfg .Hostaddr != (netip.Addr {}) && len (cfg .multiHost ) != len (cfg .multiHostaddr ) {
@@ -650,7 +675,7 @@ func (cfg *Config) fromEnv(env []string) error {
650675 switch k {
651676 case "PGREQUIRESSL" , "PGSSLCOMPRESSION" , // Deprecated.
652677 "PGREALM" , "PGGSSENCMODE" , "PGGSSDELEGATION" , "PGGSSLIB" , // krb stuff
653- "PGREQUIREAUTH" , "PGCHANNELBINDING" , "PGSERVICE" , "PGSERVICEFILE" ,
678+ "PGREQUIREAUTH" , "PGCHANNELBINDING" ,
654679 "PGSSLCERTMODE" , "PGSSLCRL" , "PGSSLCRLDIR" , "PGREQUIREPEER" :
655680 return fmt .Errorf ("pq: environment variable $%s is not supported" , k )
656681 case "PGKRBSRVNAME" :
@@ -660,7 +685,7 @@ func (cfg *Config) fromEnv(env []string) error {
660685 }
661686 e [k ] = v
662687 }
663- return cfg .setFromTag (e , "env" )
688+ return cfg .setFromTag (e , "env" , false )
664689}
665690
666691// parseOpts parses the options from name and adds them to the values.
@@ -766,10 +791,31 @@ func (cfg *Config) fromDSN(dsn string) error {
766791 opt [string (keyRunes )] = string (valRunes )
767792 }
768793
769- return cfg .setFromTag (opt , "postgres" )
794+ return cfg .setFromTag (opt , "postgres" , false )
795+ }
796+
797+ func (cfg * Config ) fromService () error {
798+ if cfg .Service == "" {
799+ return nil
800+ }
801+
802+ if ! cfg .isset ("PGSERVICEFILE" ) {
803+ if home := pqutil .Home (); home != "" {
804+ if runtime .GOOS != "windows" {
805+ home = filepath .Dir (home ) // Unlike other files this uses ~/ and not ~/.postgresql
806+ }
807+ cfg .ServiceFile = filepath .Join (home , ".pg_service.conf" )
808+ }
809+ }
810+
811+ opts , err := pgservice .FindService (cfg .ServiceFile , cfg .Service )
812+ if err != nil {
813+ return fmt .Errorf ("pq: %w" , err )
814+ }
815+ return cfg .setFromTag (opts , "postgres" , true )
770816}
771817
772- func (cfg * Config ) setFromTag (o map [string ]string , tag string ) error {
818+ func (cfg * Config ) setFromTag (o map [string ]string , tag string , service bool ) error {
773819 f := "pq: wrong value for %q: "
774820 if tag == "env" {
775821 f = "pq: wrong value for $%s: "
@@ -803,7 +849,11 @@ func (cfg *Config) setFromTag(o map[string]string, tag string) error {
803849 v , ok := o [k ]
804850 delete (o , k )
805851 if ok {
806- if t , ok := rt .Tag .Lookup ("postgres" ); ok && t != "" && t != "-" {
852+ t , ok := rt .Tag .Lookup ("postgres" )
853+ if ! ok || t == "" || t == "-" { // For PGSERVICEFILE, which can only be from env
854+ t , ok = rt .Tag .Lookup ("env" )
855+ }
856+ if ok && t != "" && t != "-" {
807857 cfg .set = append (cfg .set , t )
808858 }
809859 switch rt .Type .Kind () {
@@ -903,8 +953,18 @@ func (cfg *Config) setFromTag(o map[string]string, tag string) error {
903953 }
904954 }
905955
956+ if service && len (o ) > 0 {
957+ // TODO(go1.23): use maps.Keys once we require Go 1.23.
958+ var key string
959+ for k := range o {
960+ key = k
961+ break
962+ }
963+ return fmt .Errorf ("pq: unknown setting %q in service file for service %q" , key , cfg .Service )
964+ }
965+
906966 // Set run-time; we delete map keys as they're set in the struct.
907- if tag == "postgres" {
967+ if ! service && tag == "postgres" {
908968 // Make sure database= sets dbname=, as that previously worked (kind of
909969 // by accident).
910970 // TODO(v2): remove
0 commit comments