3
5[](https://circleci.com/gh/echatav/squeal)
7[Github](https://github.com/morphismtech/squeal)
9[Hackage](https://hackage.haskell.org/package/squeal-postgresql)
11[Stackage](https://www.stackage.org/package/squeal-postgresql)
15`stack install squeal-postgresql`
19Squeal is a deep embedding of PostgreSQL in Haskell. Let's see an example!
21First, we need some language extensions because Squeal uses modern GHC features.
34Here comes the Main module and imports.
37module Main (main) where
39import Control.Monad.Base (liftBase)
40import Data.Int (Int32)
41import Data.Text (Text)
43import Squeal.PostgreSQL
46We'll use generics to easily convert between Haskell and PostgreSQL values.
49import qualified Generics.SOP as SOP
50import qualified GHC.Generics as GHC
53The 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.
58 '[ "id" ::: 'Optional ('NotNull 'PGint4)
59 , "name" ::: 'Required ('NotNull 'PGtext)
62 '[ "id" ::: 'Optional ('NotNull 'PGint4)
63 , "user_id" ::: 'Required ('NotNull 'PGint4)
64 , "email" ::: 'Required ('Null 'PGtext)
69Next, 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.
72setup :: Definition '[] Schema
76 (text & notNull) `As` #name :* Nil )
77 [ primaryKey (Column #id :* Nil) ]
81 (int & notNull) `As` #user_id :*
82 text `As` #email :* Nil )
83 [ primaryKey (Column #id :* Nil)
84 , foreignKey (Column #user_id :* Nil) #users (Column #id :* Nil)
85 OnDeleteCascade OnUpdateCascade ]
88Notice 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.
91teardown :: Definition Schema '[]
92teardown = dropTable #emails >>> dropTable #users
95Next, 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.
98insertUser :: Manipulation Schema
99 '[ 'Required ('NotNull 'PGtext)]
100 '[ "fromOnly" ::: 'Required ('NotNull 'PGint4) ]
101insertUser = insertInto #users
102 ( Values (def `As` #id :* param @1 `As` #name :* Nil) [] )
103 OnConflictDoNothing (Returning (#id `As` #fromOnly :* Nil))
105insertEmail :: Manipulation Schema
106 '[ 'Required ('NotNull 'PGint4), 'Required ('Null 'PGtext)] '[]
107insertEmail = insertInto #emails ( Values
109 param @1 `As` #user_id :*
110 param @2 `As` #email :* Nil) [] )
111 OnConflictDoNothing (Returning Nil)
114Next 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.
117getUsers :: Query Schema '[]
118 '[ "userName" ::: 'Required ('NotNull 'PGtext)
119 , "userEmail" ::: 'Required ('Null 'PGtext) ]
121 (#u ! #name `As` #userName :* #e ! #email `As` #userEmail :* Nil)
122 ( from (Table (#users `As` #u)
123 & InnerJoin (Table (#emails `As` #e))
124 (#u ! #id .== #e ! #user_id)) )
127Now 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`.
130data User = User { userName :: Text, userEmail :: Maybe Text }
131 deriving (Show, GHC.Generic)
132instance SOP.Generic User
133instance SOP.HasDatatypeInfo User
136Let's also create some users to add to the database.
141 [ User "Alice" (Just "alice@gmail.com")
143 , User "Carole" (Just "carole@hotmail.com")
147Now 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.
152 withConnection "host=localhost port=5432 dbname=exampledb" . runPQ $
155 & thenDefine teardown
158 idResults <- traversePrepared insertUser (Only . userName <$> users)
159 ids <- traverse (fmap fromOnly . getRow (RowNumber 0)) idResults
160 traversePrepared_ insertEmail (zip (ids :: [Int32]) (userEmail <$> users))
161 usersResult <- runQuery getUsers
162 usersRows <- getRows usersResult
163 liftBase $ print (usersRows :: [User])
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list