1
+ {-# language FlexibleContexts #-}
1
2
module Database.PostgreSQL.Driver.Connection where
2
3
3
4
@@ -7,6 +8,7 @@ import Data.ByteString.Lazy (toStrict)
7
8
import Data.ByteString.Builder (Builder , toLazyByteString )
8
9
import Control.Monad
9
10
import Data.Traversable
11
+ import Safe (headMay )
10
12
import Data.Foldable
11
13
import Control.Applicative
12
14
import Data.IORef
@@ -87,7 +89,6 @@ defaultUnixPathDirectory = "/var/run/postgresql"
87
89
unixPathFilename :: B. ByteString
88
90
unixPathFilename = " .s.PGSQL."
89
91
90
-
91
92
createRawConnection :: ConnectionSettings -> IO (Either Error RawConnection )
92
93
createRawConnection settings
93
94
| host == " " = unixConnection defaultUnixPathDirectory
@@ -96,30 +97,26 @@ createRawConnection settings
96
97
where
97
98
unixConnection dirPath = do
98
99
let mAddress = socketAddressUnixPath $ makeUnixPath dirPath
99
- case mAddress of
100
- Nothing -> throwAuthErrorInIO AuthInvalidAddress
101
- Just address -> do
102
- s <- socket :: IO (Socket Unix Stream Unix )
103
- Socket. connect s address
104
- pure . Right $ constructRawConnection s
100
+ createAndConnect mAddress (socket :: IO (Socket Unix Stream Unix ))
105
101
106
102
tcpConnection = do
107
- addressInfo <- getAddressInfo (Just host) Nothing aiV4Mapped
108
- :: IO [AddressInfo Inet Stream TCP ]
109
- case socketAddress <$> addressInfo of
110
- [] -> throwAuthErrorInIO AuthInvalidAddress
111
- (address: _) -> do
112
- s <- socket :: IO (Socket Inet Stream TCP )
113
- Socket. connect s address
114
- { inetPort = fromIntegral $ settingsPort settings }
115
- pure . Right $ constructRawConnection s
116
-
117
- host = settingsHost settings
103
+ mAddress <- fmap socketAddress . headMay <$>
104
+ (getAddressInfo (Just host) (Just portStr) aiV4Mapped
105
+ :: IO [AddressInfo Inet Stream TCP ])
106
+ createAndConnect mAddress (socket :: IO (Socket Inet Stream TCP ))
107
+
108
+ createAndConnect Nothing creating = throwAuthErrorInIO AuthInvalidAddress
109
+ createAndConnect (Just address) creating = do
110
+ s <- creating
111
+ Socket. connect s address
112
+ pure . Right $ constructRawConnection s
113
+
114
+ portStr = BS. pack . show $ settingsPort settings
115
+ host = settingsHost settings
118
116
makeUnixPath dirPath =
119
117
-- 47 - `/`, removing slash on the end of the path
120
118
let dir = B. reverse . B. dropWhile (== 47 ) $ B. reverse dirPath
121
- in dir <> " /" <> unixPathFilename
122
- <> BS. pack (show $ settingsPort settings)
119
+ in dir <> " /" <> unixPathFilename <> portStr
123
120
124
121
constructRawConnection :: Socket f t p -> RawConnection
125
122
constructRawConnection s = RawConnection
0 commit comments