使用persistent将值列表插入数据库

时间:2012-12-25 03:53:53

标签: haskell persistent yesod

假设我有这段代码(简化自"Synopsis"

{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Resource (runResourceT)

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
Person
  name String
|]

main :: IO ()
main = runResourceT $ withSqliteConn ":memory:" $ runSqlConn $ do
  runMigration migrateAll

  johnID <- insert $ Person "John Doe"
  janeID <- insert $ Person "Jane Doe"

  liftIO $ print johnID
  liftIO $ print janeID

  return ()

input = [Person "John Doe", Person "Jane Doe"]

如何插入列表input并依次接收ID列表?

1 个答案:

答案 0 :(得分:4)

您可以将forM功能用于runSqlConn块。例如:

main :: IO ()
main = runResourceT $ withSqliteConn ":memory:" $ runSqlConn $ do
    runMigration migrateAll

    ids <- forM input insert
    liftIO $ print ids

  where
    input = [Person "John Doe", Person "Jane Doe"]