Объединение таблиц Haskell Esqueleto 3

Это мои попытки сделать ВЫБОР из трех таблиц. Но они не компилируются, и я не понимаю ошибки (я не знаю, почему он ожидает кортеж (Entity Issue, b0) вместо триплета, который, как мне кажется, пытается получить код).

Попытка 1:

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}

module Handler.Support where

import           Import hiding ((==.))
import qualified Database.Esqueleto as E
import           Database.Esqueleto      ((^.), (==.), (&&.))
import           Data.Traversable

getSupportR :: CustomerId -> Handler Html
getSupportR customerId = do
  customer_issues_followUps_list <- runDB $
    E.select $
    E.from $ \(i, f, c) -> do
    E.where_ (i ^. IssueCustomerId ==. E.val customerId &&. i ^. IssueId ==. f ^. FollowUpIssueId &&. i ^. IssueCustomerId ==. c ^. CustomerId)
    return (i, f, c)
  let issues = map listToMaybe . group . sort . fst . unzip $ customer_issues_followUps_list
  defaultLayout $ do
    setTitle "Your Licenses"
    $(widgetFile "support-display")

ошибка 1:

/home/hhefesto/dev/laurus-nobilis/src/Handler/Support.hs:41:5: error:
    • Couldn't match type ‘(ra, rb, rc)’ with ‘(Entity Issue, b0)’
        arising from a functional dependency between:
          constraint ‘Database.Esqueleto.Internal.Sql.SqlSelect
                        (E.SqlExpr (Entity Issue), E.SqlExpr (Entity FollowUp),
                         E.SqlExpr (Entity Customer))
                        (Entity Issue, b0)’
            arising from a use of ‘E.select’
          instance ‘Database.Esqueleto.Internal.Sql.SqlSelect
                      (a3, b3, c) (ra3, rb3, rc3)’
            at <no location info>
    • In the second argument of ‘($)’, namely
        ‘E.select
           $ E.from
               $ \ (i, f, c)
                   -> do E.where_
                           (i ^. IssueCustomerId ==. E.val customerId
                              &&.
                                i ^. IssueId ==. f ^. FollowUpIssueId
                                  &&. i ^. IssueCustomerId ==. c ^. CustomerId)
                         return (i, f, c)’
      In a stmt of a 'do' block:
        customer_issues_followUps_list <- runDB
                                            $ E.select
                                                $ E.from
                                                    $ \ (i, f, c)
                                                        -> do E.where_
                                                                (i ^. IssueCustomerId
                                                                   ==. E.val customerId
                                                                   &&.
                                                                     i ^. IssueId
                                                                       ==. f ^. FollowUpIssueId
                                                                       &&.
                                                                         i ^. IssueCustomerId
                                                                           ==. c ^. CustomerId)
                                                              return (i, f, c)
      In the expression:
        do customer_issues_followUps_list <- runDB
                                               $ E.select $ E.from $ \ (i, f, c) -> do ...
           let issues
                 = map listToMaybe . group . sort . fst . unzip
                     $ customer_issues_followUps_list
           defaultLayout
             $ do setTitle "Your Licenses"
                  (do ...)
   |
41 |     E.select $
   |     ^^^^^^^^^^...

Попытка 2:

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}

module Handler.Support where

import           Import hiding ((==.))
import qualified Database.Esqueleto as E
import           Database.Esqueleto      ((^.), (==.), (&&.))
import           Data.Traversable

getSupportR :: CustomerId -> Handler Html
getSupportR customerId = do
  customer_issues_followUps_list <- runDB $
    E.select $
    E.from $ \(i `E.InnerJoin` f `E.InnerJoin` c) -> do
    E.on (c ^. CustomerId ==. i ^. IssueCustomerId)
    E.on (i ^. IssueId ==. f ^. FollowUpIssueId)
    E.where_ (i ^. IssueCustomerId ==. E.val customerId)
    return (i, f, c)
  let issues = map listToMaybe . group . sort . fst . unzip $ customer_issues_followUps_list
  defaultLayout $ do
    setTitle "Your Licenses"
    $(widgetFile "support-display")

ошибка 2:

/home/hhefesto/dev/laurus-nobilis/src/Handler/Support.hs:40:5: error:
    • Couldn't match type ‘(ra, rb, rc)’ with ‘(Entity Issue, b0)’
        arising from a functional dependency between:
          constraint ‘Database.Esqueleto.Internal.Sql.SqlSelect
                        (E.SqlExpr (Entity Issue), E.SqlExpr (Entity FollowUp),
                         E.SqlExpr (Entity Customer))
                        (Entity Issue, b0)’
            arising from a use of ‘E.select’
          instance ‘Database.Esqueleto.Internal.Sql.SqlSelect
                      (a2, b2, c) (ra2, rb2, rc2)’
            at <no location info>
    • In the second argument of ‘($)’, namely
        ‘E.select
           $ E.from
               $ \ (i `E.InnerJoin` f `E.InnerJoin` c)
                   -> do E.on (c ^. CustomerId ==. i ^. IssueCustomerId)
                         E.on (i ^. IssueId ==. f ^. FollowUpIssueId)
                         ....’
      In a stmt of a 'do' block:
        customer_issues_followUps_list <- runDB
                                            $ E.select
                                                $ E.from
                                                    $ \ (i `E.InnerJoin` f `E.InnerJoin` c)
                                                        -> do E.on
                                                                (c ^. CustomerId
                                                                   ==. i ^. IssueCustomerId)
                                                              E.on
                                                                (i ^. IssueId
                                                                   ==. f ^. FollowUpIssueId)
                                                              ....
      In the expression:
        do customer_issues_followUps_list <- runDB
                                               $ E.select
                                                   $ E.from
                                                       $ \ (i `E.InnerJoin` f `E.InnerJoin` c)
                                                           -> do ...
           let issues
                 = map listToMaybe . group . sort . fst . unzip
                     $ customer_issues_followUps_list
           defaultLayout
             $ do setTitle "Your Licenses"
                  (do ...)
   |
40 |     E.select $
   |     ^^^^^^^^^^...

это моя постоянная модель:

Customer
    email Text
    password Text
    firstName Text
    lastName Text
    address1 Text
    address2 Text
    city Text
    state Text
    zipCode Text
    country Text
    phone Text
    organization Text
    UniqueCustomer email
    deriving Typeable
    deriving Show
    deriving Eq
    deriving Ord
License
    licenseAlias Text
    expirationDate UTCTime
    assignedTo CustomerId
    customerId CustomerId
    deriving Show
    deriving Eq
    deriving Ord
Issue
    customerId CustomerId
    issueSummary Text
    issueDetails Text
    issueState Int
    issueDate UTCTime
    deriving Show
    deriving Eq
    deriving Ord
FollowUp
    issueId IssueId
    followUpDate UTCTime
    followUpAuthor CustomerId
    followUpText Text
    deriving Show
    deriving Eq
    deriving Ord


-- Soon to be deleted:
Email
    email Text
    customerId CustomerId Maybe
    verkey Text Maybe
    UniqueEmail email
Comment json -- Adding "json" causes ToJSON and FromJSON instances to be derived.
    message Text
    customerId CustomerId Maybe
    deriving Eq
    deriving Show

Как видите, ошибка в обеих попытках одна и та же: ожидался кортеж вместо триплета.

Любая помощь будет принята с благодарностью :)

Ваш запрос выглядит нормально, но затем вы передаете результат через unzip, который ожидает список из двух кортежей. Вместо этого попробуйте unzip3?

DarthFennec 25.10.2018 20:10

Да! точно. Спасибо

hhefesto 25.10.2018 20:16
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
2
218
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Виновные были в заявлении let:

let issues = map listToMaybe . group . sort . fst . unzip $ customer_issues_followUps_list

fst и unzip работают с кортежами, поэтому компилятор подразумевает, что customer_issues_followUps_list был кортежем.

Чтобы решить эту проблему, просто добавьте «-extra» к вашим зависимостям package.yml (или файлу cabal) и замените fst и unzip на fst3 и unzip3 в операторе let следующим образом:

let issues = map listToMaybe . group . sort . fst3 . unzip3 $ customer_issues_followUps_list

Другие вопросы по теме