Skip to content

Instantly share code, notes, and snippets.

@cdparks

cdparks/sqlQQ.md

Created Jan 17, 2019
Embed
What would you like to do?
What is sqlQQ really doing

Here's a simple query with variable interpolation:

getBadge
  :: MonadIO m
  => BadgeId
  -> SqlPersistT m [Entity BadgeEvent]
getBadge badgeId =
  [sqlQQ|
    SELECT
      ??
    FROM
      ^{BadgeEvent}
    WHERE
      @{BadgeEventId} = #{badgeId}
  |]

The actual splices look sort of like this:

getBadge badgeId =
    uncurry rawSql
       =<<
         (fmap $ Control.Arrow.first (Data.Text.pack " SELECT ?? FROM " <>))
           (getTableName (error "record" :: BadgeEvent)
              >>=
                (\ table_aHOf
                   -> (fmap $ Control.Arrow.first (table_aHOf <>))
                        ((fmap $ Control.Arrow.first (Data.Text.pack " WHERE " <>))
                           (getFieldName BadgeEventId
                              >>=
                                (\ field_aHOg
                                   -> (fmap $ Control.Arrow.first (field_aHOg <>))
                                        ((fmap $ Control.Arrow.first (Data.Text.pack " = " <>))
                                           ((fmap
                                               $ (Control.Arrow.first ("?" <>)
                                                    GHC.Base..
                                                      Control.Arrow.second
                                                        (toPersistValue badgeId :)))
                                              ((fmap $ Control.Arrow.first (Data.Text.pack " " <>))
                                                 (return (mempty, mempty))))))))))

Which is really doing:

getBadge badgeId = do
  q1 <- first (pack " SELECT ?? FROM " <>) <$> getTableName (error "record" :: BadgeEvent)
  q2 <- first ((q1 <> pack " WHERE ") <>) <$> getFieldName BadgeEventId
  q3 <- first ((q2 <> pack " = " <> "? ") <>) . second (toPersistValue badgeId :) <$> pure (mempty, mempty)
  uncurry rawSql q3

That is, updating both elements of a pair, where the first element is the textual query, and the second element is list of the parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.