Jakub Arnold
Jakub Arnold

Reputation: 87210

How can I query using persistent-mysql using withMySQLConn?

I'm using persistent-mysql and trying to find a way to execute a simple command from the SqlPersistM () monad. However I'm running into type errors.

First there is withMySQLConn defaultConnectInfo, which has the following type

(MonadLogger m, MonadBaseControl IO m, MonadIO m) =>
 (Connection -> m a) -> m a

The problem here is that if I try to run this in the IO monad, I'll get an error saying there's no MonadLogger instance for IO.

λ> :t withMySQLConn defaultConnectInfo $
        \c -> runSqlPersistM (runMigration migrateAll) c

<interactive>:1:1-13:
    No instance for (MonadLogger IO)
      arising from a use of ‘withMySQLConn’
    In the expression: withMySQLConn defaultConnectInfo
    In the expression:
      withMySQLConn defaultConnectInfo
      $ \ c -> runSqlPersistM (runMigration migrateAll) c

It seems there was one in an older version of monad-logger, but not anymore. I'm not sure if I'm using this wrong, or if there's an underlying problem. I only have a small cabal project with persistent 2.1.1.4 setup, and trying to run the migrations from cabal repl.

If it's of any relevance, here is my whole database setup code

{-# LANGUAGE EmptyDataDecls             #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}
module Model where

import Control.Monad.Trans.Control
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Control.Monad.Logger

import Data.Text (Text)
import Data.Time (UTCTime)
import Database.Persist
import Database.Persist.TH
import Database.Persist.MySQL
import Database.Persist.Sqlite

share [mkPersist sqlSettings, mkMigrate "migrateAll"]
    [persistLowerCase|
     Receipt
         name Text
         createdAt UTCTime
            |]

I've tried using persistent-sqlite and everything seems to work fine (based on the book tutorial), but I can't seem to get things working in MySQL.

What I'm looking for is a simple snippet showing how to execute a SqlPersistM a query (or equivalent) using persistent-mysql.

This question is a followup from a GitHub issue discussion.

Upvotes: 2

Views: 375

Answers (1)

Michael Snoyman
Michael Snoyman

Reputation: 31315

You're almost there. You just need to use one of the functions from monad-logger to provide a MonadLogger context. You may want to try runStdoutLoggingT.

Upvotes: 4

Related Questions