@@ -11,3 +11,152 @@ Main repository for the squeal database library.
1111The easiest way to install `squeal-postgresql` is to use the haskell [stack](https://docs.haskellstack.org/en/stable/README/) tool.
1212
1313Use `resolver: nightly-2017-08-25`. We're stuck with nightlies until an lts supports GHC-8.2. Do a `stack upgrade && stack update` to make sure you get GHC-8.2 and the nightly. Then add `squeal-postgresql-0.1.1.2` as an extra dependency in your `stack.yaml` and you should be good to go.
14+
15+## usage
16+
17+Squeal is a deep embedding of PostgreSQL in Haskell. Let's see an example!
18+
19+First, we need some language extensions because Squeal uses modern GHC features.
20+
21+```haskell
22+{-# LANGUAGE
23+ DataKinds
24+ , DeriveGeneric
25+ , OverloadedLabels
26+ , OverloadedStrings
27+ , TypeApplications
28+ , TypeOperators
29+#-}
30+```
31+
32+Here comes the Main module and imports.
33+
34+```haskell
35+module Main (main) where
36+
37+import Control.Monad.Base (liftBase)
38+import Data.Int (Int32)
39+import Data.Text (Text)
40+
41+import Squeal.PostgreSQL
42+```
43+
44+We'll use generics to easily convert between Haskell and PostgreSQL values.
45+
46+```haskell
47+import qualified Generics.SOP as SOP
48+import qualified GHC.Generics as GHC
49+```
50+
51+The first step is to define the schema of our database. This is where we use DataKinds and TypeOperators. The schema consists of a type-level list of tables, a `:::` pairing of a type level string or `Symbol` and a list a columns, itself a `:::` pairing of a `Symbol` and a `ColumnType`. The `ColumnType` describes the PostgreSQL type of the column as well as whether or not it may contain `NULL` and whether or not inserts and updates can use a `DEFAULT`. For our schema, we'll define two tables, a users table and an emails table.
52+
53+```haskell
54+type Schema =
55+ '[ "users" :::
56+ '[ "id" ::: 'Optional ('NotNull 'PGint4)
57+ , "name" ::: 'Required ('NotNull 'PGtext)
58+ ]
59+ , "emails" :::
60+ '[ "id" ::: 'Optional ('NotNull 'PGint4)
61+ , "user_id" ::: 'Required ('NotNull 'PGint4)
62+ , "email" ::: 'Required ('Null 'PGtext)
63+ ]
64+ ]
65+```
66+
67+Next, we'll write Definitions to set up and tear down the schema. In Squeal, a Definition is a `createTable`, `alterTable` or `dropTable` command and has two type parameters, corresponding to the schema before being run and the schema after. We can compose definitions using `>>>`. Here and in the rest of our commands we make use of overloaded labels to refer to named tables and columns in our schema.
68+
69+```haskell
70+setup :: Definition '[] Schema
71+setup =
72+ createTable #users
73+ ( serial `As` #id :*
74+ (text & notNull) `As` #name :* Nil )
75+ [ primaryKey (Column #id :* Nil) ]
76+ >>>
77+ createTable #emails
78+ ( serial `As` #id :*
79+ (int & notNull) `As` #user_id :*
80+ text `As` #email :* Nil )
81+ [ primaryKey (Column #id :* Nil)
82+ , foreignKey (Column #user_id :* Nil) #users (Column #id :* Nil)
83+ OnDeleteCascade OnUpdateCascade ]
84+```
85+
86+Notice that setup starts with an empty schema `'[]` and produces `Schema`. In our `createTable` commands we included `TableConstraint`s to define primary and foreign keys, making them somewhat complex. Our tear down `Definition` is simpler.
87+
88+```haskell
89+teardown :: Definition Schema '[]
90+teardown = dropTable #emails >>> dropTable #users
91+```
92+
93+Next, we'll write `Manipulation`s to insert data into our two tables. A `Manipulation` is an `insertInto`, `update` or `deleteFrom` command and has three type parameters, the schema it refers to, a list of parameters it can take as input, and a list of columns it produces as output. When we insert into the users table, we will need a parameter for the name field but not for the id field. Since it's optional, we can use a default value. However, since the emails table refers to the users table, we will need to retrieve the user id that the insert generates and insert it into the emails table. Take a careful look at the type and definition of both of our inserts.
94+
95+```haskell
96+insertUser :: Manipulation Schema
97+ '[ 'Required ('NotNull 'PGtext)]
98+ '[ "fromOnly" ::: 'Required ('NotNull 'PGint4) ]
99+insertUser = insertInto #users
100+ ( Values (def `As` #id :* param @1 `As` #name :* Nil) [] )
101+ OnConflictDoNothing (Returning (#id `As` #fromOnly :* Nil))
102+
103+insertEmail :: Manipulation Schema
104+ '[ 'Required ('NotNull 'PGint4), 'Required ('Null 'PGtext)] '[]
105+insertEmail = insertInto #emails ( Values
106+ ( def `As` #id :*
107+ param @1 `As` #user_id :*
108+ param @2 `As` #email :* Nil) [] )
109+ OnConflictDoNothing (Returning Nil)
110+```
111+
112+Next we write a `Query` to retrieve users from the database. We're not interested in the ids here, just the usernames and email addresses. We need to use an inner join to get the right result. A `Query` is like a `Manipulation` with the same kind of type parameters.
113+
114+```haskell
115+getUsers :: Query Schema '[]
116+ '[ "userName" ::: 'Required ('NotNull 'PGtext)
117+ , "userEmail" ::: 'Required ('Null 'PGtext) ]
118+getUsers = select
119+ (#u ! #name `As` #userName :* #e ! #email `As` #userEmail :* Nil)
120+ ( from (Table (#users `As` #u)
121+ & InnerJoin (Table (#emails `As` #e))
122+ (#u ! #id .== #e ! #user_id)) )
123+```
124+
125+Now that we've defined the SQL side of things, we'll need a Haskell type for users. We give the type `Generic` and `HasDatatypeInfo` instances so that we can decode the rows we receive when we run getUsers. Notice that the record fields of the `User` type match the column names of getUsers.
126+
127+```haskell
128+data User = User { userName :: Text, userEmail :: Maybe Text }
129+ deriving (Show, GHC.Generic)
130+instance SOP.Generic User
131+instance SOP.HasDatatypeInfo User
132+```
133+
134+Let's also create some users to add to the database.
135+
136+```haskell
137+users :: [User]
138+users =
139+ [ User "Alice" (Just "alice@gmail.com")
140+ , User "Bob" Nothing
141+ , User "Carole" (Just "carole@hotmail.com")
142+ ]
143+```
144+
145+Now we can put together all the pieces into a program. The program connects to the database, sets up the schema, inserts the user data (using prepared statements as an optimization), queries the user data and prints it out and finally closes the connection. We can thread the changing schema information through by using the indexed `PQ` monad transformer and when the schema doesn't change we can use `Monad` and `MonadPQ` functionality.
146+
147+```haskell
148+main :: IO ()
149+main = void $
150+ withConnection "host=localhost port=5432 dbname=exampledb" . runPQ $
151+ define setup
152+ & pqThen session
153+ & thenDefine teardown
154+ where
155+ session = do
156+ idResults <- traversePrepared insertUser (Only . userName <$> users)
157+ ids <- traverse (fmap fromOnly . getRow (RowNumber 0)) idResults
158+ traversePrepared_ insertEmail (zip (ids :: [Int32]) (userEmail <$> users))
159+ usersResult <- runQuery getUsers
160+ usersRows <- getRows usersResult
161+ liftBase $ print (usersRows :: [User])
162+```