Skip to content

Commit

Permalink
Merge pull request yesodweb#10 from psibi/mockmigrate-example
Browse files Browse the repository at this point in the history
Mockmigrate example
  • Loading branch information
psibi authored Sep 10, 2016
2 parents 5c7b5bf + ca42d5d commit a0d9282
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
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")
```

0 comments on commit a0d9282

Please sign in to comment.