Skip to content

Instantly share code, notes, and snippets.

@valderman
Last active April 7, 2020 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valderman/d61d245dc47017e1addfb603d830f6cb to your computer and use it in GitHub Desktop.
Save valderman/d61d245dc47017e1addfb603d830f6cb to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedLabels, OverloadedStrings, DeriveGeneric #-}
import Database.Selda
import Database.Selda.SQLite
data Post = Post
{ postId :: ID Post
, topic :: Text
-- ...
} deriving Generic
instance SqlRow Post
data Comment = Comment
{ commentId :: ID Comment
, commentPostId :: ID Post
, comment :: Text
-- ...
} deriving Generic
instance SqlRow Comment
posts :: Table Post
posts = table "posts" [ #postId :- autoPrimary ]
comments :: Table Comment
comments = table "comments"
[ #commentId :- autoPrimary
, #commentPostId :- foreignKey posts #postId
]
commentPosts :: ID Post -> Query s (Row s Comment)
commentPosts pid = do
c <- select comments
restrict (c ! #commentPostId .== literal pid)
return c
-- Alternate version
commentPosts2 :: ID Post -> Query s (Row s Comment)
commentPosts2 pid = select comments `suchThat` (#commentPostId `is` pid)
getCommentPosts :: ID Post -> IO [Comment]
getCommentPosts pid = withSQLite "database.sqlite" $ do
query (commentPosts pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment