How do I store Either (Key a) (Key b)?

时间:2018-03-25 19:46:37

标签: haskell haskell-persistent

I have the following model:

User
  ...
Group
  ...
Sharing
  objectId (Either UserId GroupId)

In Sharing entity I want to store either UserId or GroupId and differentiate between them. Simply using Either doesn't work:

  • Not in scope: type constructor or class `UserId'
  • Not in scope: type constructor or class `GroupId'

Adding a new sum-type also doesn't work:

data SharingIdType = SharingUserId UserId | SharingGroupId GroupId
  • Not in scope: type constructor or class `SharingIdType'

Moving SharingIdType into another module isn't possible, because it uses UserId and GroupId types. The only way I see is to create an entity for each sharing type, like UserSharing/GroupSharing.

Other than that, how to approach this problem?

1 个答案:

答案 0 :(得分:0)

在搜索了一段时间并思考之后,我得出结论,有两种可能的解决方案:

1

如果SharingIdType的数量是静态的或很少更改(意味着可以重新编译源以更改它或更改数据库模式),处理问题的正确方法是必须使用实体每种分享类型:

User
  ...
Group
  ...
UserSharing
  userId UserId
GroupSharing
  groupId GroupId

这里" sumness"问题被转移到数据库查询。每当我需要找出共享的内容时,我会生成两个selectList并查询两个表而不是一个。

2

如果需要动态更改SharingIdTypes的数量,则需要SharingType实体:

User
  ...
Group
  ...
SharingType
  description String
Sharing
  objectId SharingTypeId

此表填充了与SharingIdType s构造函数对应的值:

do
  insert $ SharingType "user"
  insert $ SharingType "group"

现在每当我们分享某些内容时,我们都会引用SharingTypeId