Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8549705
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T13:46:48+00:00 2026-06-11T13:46:48+00:00

Sweet but simple, how do Persistent joins work? Consider the following model: Person number

  • 0

Sweet but simple, how do Persistent joins work? Consider the following model:

Person
    number Int
    numberOfEyes Int
    firstName FirstnamesId
    lastName LastnamesId
Lastnames
    lastname String
Firstnames
    firstname String

Assuming I only have the number of a Person, how do I retrieve his full name and the number of his eyes?

I tried looking through the haskellers.org source but couldn’t find any examples of joins. I also checked out the chapter on joins in the yesod book but it only made my eyes spin. The level of my Haskell knowledge is very low so be gentle.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T13:46:49+00:00Added an answer on June 11, 2026 at 1:46 pm

    Here are two ways with identical result type:

    1. the new typed sql, based on the "esqueleto" package from Felipe Lessa which is persistent based

    2. and the previous rawSql way

      just add 1 or 2 as argument to the test


    {- file prova.hs-}
    {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
    {-# LANGUAGE GADTs, FlexibleContexts, ConstraintKinds, ScopedTypeVariables #-}
    import Prelude hiding (catch)
    import Control.Exception  
    import Database.Persist
    import Database.Persist.Sqlite
    import Database.Persist.TH
    import Control.Monad.IO.Class (liftIO)
    import Data.Text (Text)
    import Database.Persist.Quasi
    import Database.Esqueleto as Esql
    import Database.Persist.GenericSql (SqlPersist, rawSql)
    import Control.Monad.Logger (MonadLogger)
    import Control.Monad.Trans.Resource (MonadResourceBase)
    import System.Environment (getProgName, getArgs)   
    import System.Exit (exitSuccess, exitWith, ExitCode(..))
    import Text.Printf (printf)
    
    import QQStr(str)  -- heredoc quasiquoter module
    
    share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
    Person
        number Int
        numberOfEyes Int
        firstName FirstnamesId
        lastName LastnamesId
        UniquePersonNumber number 
        deriving Show
    
    Lastnames
        lastname String
        deriving Show
    
    Firstnames
        firstname String
        deriving Show
    |]
    
    -- the esqueleto way
    
    -- with this type annotation it could be run in a yesod handler with ''runDB''
    getPersonInfoByNumber :: (PersistQuery SqlPersist m, MonadLogger m, MonadResourceBase m) => Int -> SqlPersist m (Maybe (Int, String, String))
    getPersonInfoByNumber pNumber = do
        result <- select $ from $ \(fn `InnerJoin` p `InnerJoin` ln) -> do
                on ((p ^. PersonFirstName) Esql.==. (fn ^. FirstnamesId))
                on ((p ^. PersonLastName) Esql.==. (ln ^. LastnamesId))
                where_ ((p ^. PersonNumber) Esql.==. val pNumber)
                return (p , fn, ln)
    
        case result of
            [(Entity _ p, Entity _ fn, Entity _ ln)] -> return $ Just (personNumberOfEyes p, firstnamesFirstname fn, lastnamesLastname ln)
            _ -> return Nothing
    
    -- the rawSql way
    
    stmt = [str|SELECT ??, ??, ??
                              FROM Person, Lastnames, Firstnames
                              ON Person.firstName = Firstnames.id
                              AND Person.lastName = Lastnames.id
                              WHERE Person.number = ?
                             |]
                             
    getPersonInfoByNumberRaw :: (PersistQuery SqlPersist m, MonadLogger m, MonadResourceBase m) => Int -> SqlPersist m (Maybe (Int, String, String))
    getPersonInfoByNumberRaw pNumber = do
        result <- rawSql stmt [toPersistValue pNumber]
    
        case result of
            [(Entity _ p, Entity _ fn, Entity _ ln)] -> return $ Just (personNumberOfEyes p, firstnamesFirstname fn, lastnamesLastname ln)
            _ -> return Nothing
    
            
    main :: IO ()
    main = do
        args <- getArgs
        nomProg <- getProgName
        case args of
            [] -> do
                 printf "%s: just specify 1 for esqueleto or 2 for rawSql.\n" nomProg
                 exitWith (ExitFailure 1)
    
            [arg] -> (withSqliteConn ":memory:" $ runSqlConn $ do
                  runMigration migrateAll
     
                  let myNumber = 5
                  fnId <- insert $ Firstnames "John"
                  lnId <- insert $ Lastnames "Doe"
    
                  -- in case of insert collision, because of UniquePersonNumber constraint
                  --    insertUnique does not throw exceptions, returns success in a Maybe result
                  --    insert would throw an exception 
    
                  maybePersId <- insertUnique $ Person {personNumber = myNumber, personNumberOfEyes=2,
                                                    personFirstName = fnId, personLastName = lnId}
    
                  info <- case arg of
                              "1" -> getPersonInfoByNumber myNumber
                              _ -> getPersonInfoByNumberRaw myNumber
                  liftIO $ putStrLn $ show info
                  )
                  `catch` (\(excep::SomeException) -> 
                                   putStrLn $ "AppSqlError: " ++ show excep)  
    

    extra module for heredoc quasiquoter

    module QQStr(str) where
    
    import Prelude
    import Language.Haskell.TH
    import Language.Haskell.TH.Quote
    
    str = QuasiQuoter { quoteExp = stringE, quotePat = undefined
                      , quoteType = undefined, quoteDec = undefined }
    

    execution:

    gabi64@zotac-ion:~/webs/yesod/prova$ ./cabal-dev/bin/prova 1
    Migrating: CREATE TABLE "Person"("id" INTEGER PRIMARY KEY,"number" INTEGER NOT NULL,"numberOfEyes" INTEGER NOT NULL,"firstName" INTEGER NOT NULL REFERENCES "Firstnames","lastName" INTEGER NOT NULL REFERENCES "Lastnames")
    Migrating: CREATE TABLE "Lastnames"("id" INTEGER PRIMARY KEY,"lastname" VARCHAR NOT NULL)
    Migrating: CREATE TABLE "Firstnames"("id" INTEGER PRIMARY KEY,"firstname" VARCHAR NOT NULL)
    Just (2,"John","Doe")
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Embarrassingly simple question but I can't work it out or find the answer via
I am sure this has to as sweet and plain as butter. But I
I'm looking to implement a simple cache without doing too much work (naturally). It
All, I'm trying to use vlookup in a simple VBA function, but it is
my apologies for asking what must be very simple to solve, but I just
In lotusscript I usually do the following to create a simple email which contains
The VBA I'm trying to write is fairly simple but Ive never written VBA
Probably a pretty simple question, but I can't get my head around it. I
I've got a fairly simple NodeJS app that is nothing but a shell that
This should be really simple, but I've been trawling forums and SO answers for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.