@@ -11,3 +11,152 @@ Main repository for the squeal database library.
11The easiest way to install `squeal-postgresql` is to use the haskell [stack](https://docs.haskellstack.org/en/stable/README/) tool.
11The easiest way to install `squeal-postgresql` is to use the haskell [stack](https://docs.haskellstack.org/en/stable/README/) tool.
13Use `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.
13Use `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.
17+Squeal is a deep embedding of PostgreSQL in Haskell. Let's see an example!
19+First, we need some language extensions because Squeal uses modern GHC features.
32+Here comes the Main module and imports.
35+module Main (main) where
37+import Control.Monad.Base (liftBase)
38+import Data.Int (Int32)
39+import Data.Text (Text)
41+import Squeal.PostgreSQL
44+We'll use generics to easily convert between Haskell and PostgreSQL values.
47+import qualified Generics.SOP as SOP
48+import qualified GHC.Generics as GHC
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.
56+ '[ "id" ::: 'Optional ('NotNull 'PGint4)
57+ , "name" ::: 'Required ('NotNull 'PGtext)
60+ '[ "id" ::: 'Optional ('NotNull 'PGint4)
61+ , "user_id" ::: 'Required ('NotNull 'PGint4)
62+ , "email" ::: 'Required ('Null 'PGtext)
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.
70+setup :: Definition '[] Schema
74+ (text & notNull) `As` #name :* Nil )
75+ [ primaryKey (Column #id :* Nil) ]
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 ]
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.
89+teardown :: Definition Schema '[]
90+teardown = dropTable #emails >>> dropTable #users
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.
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))
103+insertEmail :: Manipulation Schema
104+ '[ 'Required ('NotNull 'PGint4), 'Required ('Null 'PGtext)] '[]
105+insertEmail = insertInto #emails ( Values
107+ param @1 `As` #user_id :*
108+ param @2 `As` #email :* Nil) [] )
109+ OnConflictDoNothing (Returning Nil)
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.
115+getUsers :: Query Schema '[]
116+ '[ "userName" ::: 'Required ('NotNull 'PGtext)
117+ , "userEmail" ::: 'Required ('Null 'PGtext) ]
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)) )
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.
128+data User = User { userName :: Text, userEmail :: Maybe Text }
129+ deriving (Show, GHC.Generic)
130+instance SOP.Generic User
131+instance SOP.HasDatatypeInfo User
134+Let's also create some users to add to the database.
139+ [ User "Alice" (Just "alice@gmail.com")
140+ , User "Bob" Nothing
141+ , User "Carole" (Just "carole@hotmail.com")
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.
150+ withConnection "host=localhost port=5432 dbname=exampledb" . runPQ $
153+ & thenDefine teardown
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])