Secoe
Secoe

Reputation: 624

Insert list of values into database with persistent

Assuming I have this code (simplified from "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"]

How would I insert the list input and in turn receive a list of IDs?

Upvotes: 4

Views: 857

Answers (1)

Fedor Gogolev
Fedor Gogolev

Reputation: 10541

You can use forM function into runSqlConn block. For example:

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"]

Upvotes: 4

Related Questions