Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add inet FromField and ToField instances #133

Open
JonathanLorimer opened this issue Dec 16, 2023 · 1 comment
Open

Add inet FromField and ToField instances #133

JonathanLorimer opened this issue Dec 16, 2023 · 1 comment

Comments

@JonathanLorimer
Copy link

The inet type exists already here

postgresql-binary has examples of encoding and decoding

@JonathanLorimer JonathanLorimer changed the title Add inet type with FromField and ToField instances Add inet FromField and ToField instances Dec 16, 2023
@JonathanLorimer
Copy link
Author

JonathanLorimer commented Dec 16, 2023

Here is a candidate version that uses postgresql-binary

import Network.IP.Addr
import Database.PostgreSQL.Simple.ToField (ToField (..))
import Database.PostgreSQL.Simple.FromField (FromField (..), Field (..), returnError, ResultError (..))
import PostgreSQL.Binary.Encoding qualified as ENC
import PostgreSQL.Binary.Decoding qualified as DEC
import Database.PostgreSQL.Simple.TypeInfo.Static qualified as TI
import qualified Data.Text as T

instance ToField (NetAddr IP) where
    toField = toField . ENC.encodingBytes . ENC.inet
    {-# INLINE toField #-}

instance FromField (NetAddr IP) where
    fromField f mbs =
      if typeOid f /= TI.uuidOid
      then returnError Incompatible f ""
      else case mbs of
             Nothing -> returnError UnexpectedNull f ""
             Just bs ->
                 case DEC.valueParser DEC.inet bs of
                   Left t -> returnError ConversionFailed f $ "Invalid inet: " <>  T.unpack t
                   Right inet -> pure uuid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant