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

val may not round trip for an obvious PersistField instance #314

Open
parsonsmatt opened this issue Apr 13, 2022 · 0 comments
Open

val may not round trip for an obvious PersistField instance #314

parsonsmatt opened this issue Apr 13, 2022 · 0 comments

Comments

@parsonsmatt
Copy link
Collaborator

We have this instance at work:

instance PersistField UUID where
  toPersistValue = PersistLiteralEscaped . uuidToBytes
  fromPersistValue (PersistLiteralEscaped bytes)
    | Just uuid <- fromAsciiBytes bytes = Right uuid
  fromPersistValue other =
    Left $ "Failed to make UUID from: " <> tshow other

This fails to round-trip if you do a select $ pure $ val uuid - it fails, because we were given a PersistText instead of a PersistLiteralEscaped.

The logic, as far as I can tell, is something like:

  1. We splice in val uuid, which turns into ( "?", toPersistValue uuid) to ("?", PersistLiteralEscaped uuid)
  2. After parameter substitution, postgres sees a '1234-2345-3456-4567' looking thing, which looks a lot like a text value. So that's the type it infers.
  3. postgresql-simple asks Postgres what the type of the column is, and says text.
  4. So persistent wraps the text in a PersistText constructor
  5. And then esqueleto tries to parse a UUID from it, which fails, since the PersistText constructor isn't specified above.

One potential fix is to provide a type annotation to val. Something like,

val x = 
    ( mconcat ["(? :: ", showType (sqlType (Proxy :: Proxy a)), ")"]
    , toPersistValue x
    ) 

Another fix is on persistent side, where we encourage folks to use helpers instead of the PersistValue constructors directly. Eg, withBytes :: PersistValue -> (ByteString -> Either Text a) -> Either Text a, similar to the withObject etc functions in aeson. These would, behind the scenes, translate a PersistText txt -> f (encodeUtf8 txt).

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