Skip to content

Document connection strings for unix sockets with postgres #258

@lf-

Description

@lf-

I am using tmp-postgres for Haskell which creates a Unix socket with a connection string like host=/tmp/tmp-postgres-socket-33d7937af9c67679 dbname=postgres port=49905.

I want to use refinery-cli to apply my migrations to such a database.

According to the postgres docs, the connection string can be in several formats, which do support Unix sockets: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING

However, it seems that Refinery parses them itself:

Ok(Self {
main: Main {
db_type,
db_path: Some(
url.as_str()[url.scheme().len()..]
.trim_start_matches(':')
.trim_start_matches("//")
.to_string()
.into(),
),
db_host: url.host_str().map(|r| r.to_string()),
db_port: url.port().map(|r| r.to_string()),
db_user: Some(url.username().to_string()),
db_pass: url.password().map(|r| r.to_string()),
db_name: Some(url.path().trim_start_matches('/').to_string()),
#[cfg(feature = "tiberius-config")]
trust_cert,
},
})

It seems like I need to generate a connection string like so, but this was obtained largely by guessing:

{- | Serializes a 'PG.Options' into the right format for Refinery CLI, which is

 > postgres://user:pass@(urlencoded host)/db

 See <https://github.com/rust-db/refinery/blob/36e2c219de236c95853a0aa6cd606a2d52d255f8/refinery_core/src/config.rs#L225-L243>
-}
optionsToUri :: PG.Options -> Maybe (URIRef Absolute)
optionsToUri PG.Options {host, user, password, dbname, port} = do
  host' <- getLastBS host
  dbname' <- getLastBS dbname
  port' <- getLast port
  -- Postgres will be grumpy if you don't give it a user, so there's not any
  -- reasonable default here
  user' <- getLastBS user
  pure $
    URI
      { uriScheme = Scheme "postgres"
      , uriAuthority =
          Just $
            Authority
              { authorityUserInfo =
                  Just $ UserInfo user' (fromMaybe "" $ getLastBS password)
              , authorityHost = Host (cs . toLazyByteString $ urlEncode [] host')
              , authorityPort = Just $ Port port'
              }
      , uriPath = "/" <> cs dbname'
      , uriQuery = Query []
      , uriFragment = Nothing
      }
  where
    getLastBS :: Last String -> Maybe ByteString
    getLastBS s = cs <$> getLast s

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions