Extracting the year from a timestamp field inside an Esqueleto query

138 Views Asked by At

I am trying to make use of the unsafeSqlExtractSubField from Esqueleto to create one that will extract the year from a date, such as:

data ReportRow = ReportRow Text

userSignupData :: MonadIO m => Key User -> SqlPersistT m [ReportRow]
userSignupData _ = fmap toRow <$> select (from query)
  where
    query s =
      pure $ (extractYear $ s ^. UserCreatedAt)

    toRow yearVal = ReportRow (showText . unValue $ yearVal)

extractYear :: UnsafeSqlFunctionArgument a => a -> SqlExpr (Value Integer)
extractYear =
  unsafeSqlExtractSubField "year"

showText :: Show a => a -> Text
showText = T.pack . show

But I am getting the error:

Could not deduce
  (UnsafeSqlFunctionArgument
    (expr0 (Value UTCTime)))

  arising from a use of ‘query’
from the context: MonadIO m
  bound by the type signature for:
    userSignupData :: forall (m :: * -> *).
                      MonadIO m =>
                      Key User -> SqlPersistT m [ReportRow]

The type variable ‘expr0’ is ambiguous

   |
20 | userSignupData _ = fmap toRow <$> select (from query)
   |                                                ^^^^^

Do I need to define an instance of UnsafeSqlFunctionArgument for UTCTime here or am I trying to fit a square peg into a round hole ?

I'm not after answers that state that I could extract the date at the haskell level, I'd like to get the year inside the query so that I can perform an SQL GROUP BY inside the query.

0

There are 0 best solutions below