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

How would you handle outer joins elegantly? #25

Open
JonathanLorimer opened this issue Jul 28, 2024 · 0 comments
Open

How would you handle outer joins elegantly? #25

JonathanLorimer opened this issue Jul 28, 2024 · 0 comments

Comments

@JonathanLorimer
Copy link
Contributor

JonathanLorimer commented Jul 28, 2024

right now I have some code that looks like this:

getUserSessionByGoogleOIDCSubject 
  :: GoogleOIDCSubject 
  -> Statement () (Maybe (User, Maybe ServerSession))
getUserSessionByGoogleOIDCSubject googleOIDCSub = fromRows <$$>
  interp
    False
    [sql|
    SELECT 
      u.id, u.email,
      ss.id, ss.user_id, ss.ip_range, ss.user_agent, ss.expires_at
    FROM users u
    JOIN user_authentication_sources uas ON uas.user_id = u.id
    LEFT JOIN server_sessions ss ON ss.user_id = u.id AND NOW() < ss.expires_at 
    WHERE uas.google_oidc_sub = #{googleOIDCSub} 
  |]
   where
    fromRows
      :: ( UserId
         , Email
         , Maybe SessionId
         , Maybe UserId
         , Maybe IPRange
         , Maybe Text
         , Maybe UTCTime
         )
      -> (User, Maybe ServerSession)
    fromRows
      ( userId
        , email
        , mSessionId
        , mSessionUserId
        , ipAddress
        , userAgent
        , mExpiresAt
        ) =
        ( User{..}
        , do 
          sessionId <- mSessionId
          sessionUserId <- mSessionUserId
          expiresAt <- mExpiresAt
          pure ServerSession
            { userId = sessionUserId
            , ..
            }
        )

This is slightly unsatisfactory for a few reason:

  1. Instead of having a Maybe ServerSessionRow, I need to have a Maybe on every column, which suggests that some columns may be present and some may be missing, while this is not the case if the left join does not hit.
  2. There are columns (ip_range and user_agent) that are nullable in their own right, and this fact is masked by them potentially being null due to a left join miss. I just have to know their nullability and not check for it in my Maybe do block at the bottom.

Is there guidance on a better way to handle this case?

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