Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mockmigrate example #10

Merged
merged 2 commits into from
Sep 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cookbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ For non-Yesod code, see also [Snippets](https://github.com/yesodweb/yesod-cookbo
* [Adding Seed data to Scaffolded Site](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Adding-Seed-Data-to-Scaffolded-Site.md)
* [Handling exception in persistence](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Handling-Persistence-Exception.md)
* [Builtin Postgresql types with Persistent](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/CustomPostgresqlTypes.md)
* [Modelling Schema with Persistent](./cookbook/modelling-schema.md)

## State

Expand Down
54 changes: 54 additions & 0 deletions cookbook/modelling-schema.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
You can use persistent to model your DB schema and see the generated
sql query without even the presence of the actual database
server. Example code demonstrating it:

``` haskell
#!/usr/bin/env stack
{- stack
--resolver lts-6.11
--install-ghc
runghc
--package persistent
--package persistent-postgresql
--package persistent-template
-}

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

import Database.Persist
import Database.Persist.Postgresql
import Database.Persist.TH

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
name String
age Int Maybe
address Int
deriving Show
BlogPost
title String
authorId PersonId
deriving Show
|]

main :: IO ()
main = mockMigration migrateAll
```

On execution, this will produce:

``` shellsession
sibi { ~/scripts }-> ./migration.hs
CREATe TABLE "person"("id" SERIAL8 PRIMARY KEY UNIQUE,"name" VARCHAR NOT NULL,"age" INT8 NULL,"address" INT8 NOT NULL)
CREATe TABLE "blog_post"("id" SERIAL8 PRIMARY KEY UNIQUE,"title" VARCHAR NOT NULL,"author_id" INT8 NOT NULL)
ALTER TABLE "blog_post" ADD CONSTRAINT "blog_post_author_id_fkey" FOREIGN KEY("author_id") REFERENCES "person"("id")
```