https://github.com/prosumma/haskellpg
A simple wrapper around Database.PostgreSQL.Simple
https://github.com/prosumma/haskellpg
Last synced: 8 months ago
JSON representation
A simple wrapper around Database.PostgreSQL.Simple
- Host: GitHub
- URL: https://github.com/prosumma/haskellpg
- Owner: Prosumma
- License: mit
- Created: 2022-06-12T04:33:08.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2023-07-01T22:14:18.000Z (almost 3 years ago)
- Last Synced: 2025-05-23T04:28:57.707Z (about 1 year ago)
- Language: Haskell
- Size: 49.8 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: ChangeLog.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Piggy
Piggy is a tiny little Haskell library that makes Database.PostgreSQL.Simple just a tiny bit easier to work with. It also facilitates easier unit testing.
It uses the [Operational monad](https://hackage.haskell.org/package/operational-0.2.3.5/docs/Control-Monad-Operational.html) and a simple typeclass:
```haskell
class Monad m => MonadPG m where
interpret :: PGDSL a -> m a
withTransaction :: m a -> m a
withTransaction t = t
```
A default interpreter — `interpg` — that talks to a Postgres database is provided, as is `PG`, a default implementation of `MonadPG` that actually talks to a database using `interpg`.
```haskell
instance MonadPG PG where
interpret = interpg
withTransaction transact = withPostgresTransaction $ flip withPG transact
```
In unit tests, it's relatively straightforward to replace actual database access with stubs.
```haskell
getPatients :: MonadPG m => m [Patient]
getPatients = interpret $ singleton (Query_ "SELECT * FROM patients")
patients :: [Patient]
-- etc.
interstubs :: Monad m => PGDSL a -> m a
interstubs m = case view m of
(Query_ "SELECT * FROM patients") :>>= k -> return patients >>= interstubs . k
-- etc.
newtype PGStub a = PGStub a deriving (Functor, Applicative, Monad)
-- If `getPatients` is called with `PGStub`, it will be interpreted with
-- interstubs and no actual database access will occur. In fact, the
-- function is actually pure because it does not require `MonadIO`.
instance MonadPG PGStub where
interpret = interstubs
```