on 293706d help sign in
rel8/src/Rel8.hs
668 lines 19 kB history raw
1{-# language DuplicateRecordFields #-}
3module Rel8
4 ( -- * Getting Started
5 -- $setup
7 -- ** Writing Queries
8 -- $guideQueries
10 -- ** Joins
11 -- $guideJoins
13 -- ** Aggregation
14 -- $guideAggregation
16 -- * Database types
17 -- ** @DBType@
18 DBType(..)
20 -- *** Deriving-via helpers
21 -- **** @JSONEncoded@
22 , JSONEncoded(..)
23 , JSONBEncoded(..)
25 -- **** @ReadShow@
26 , ReadShow(..)
28 -- *** @TypeInformation@
29 , TypeInformation(..)
30 , mapTypeInformation
31 , parseTypeInformation
33 -- ** The @DBType@ hierarchy
34 , DBSemigroup(..)
35 , DBMonoid(..)
36 , DBNum
37 , DBFractional
39 -- * Tables and higher-kinded tables
40 , Rel8able
41 , Column
42 , Default, Label
43 , HMaybe
44 , HList
45 , HNonEmpty
46 , HThese
48 , Table
49 , AltTable((<|>:))
50 , EqTable, (==:), (/=:)
51 , OrdTable, ascTable, descTable
52 , lit
53 , bool
54 , case_
56 -- ** @MaybeTable@
57 , MaybeTable
58 , maybeTable, nothingTable, justTable
59 , isNothingTable, isJustTable
60 , optional
61 , catMaybeTable
62 , bindMaybeTable
63 , traverseMaybeTable
65 -- ** @EitherTable@
66 , EitherTable
67 , eitherTable, leftTable, rightTable
68 , isLeftTable, isRightTable
69 , keepLeftTable
70 , keepRightTable
71 , bindEitherTable
72 , bitraverseEitherTable
74 -- ** @TheseTable@
75 , TheseTable
76 , theseTable, thisTable, thatTable, thoseTable
77 , isThisTable, isThatTable, isThoseTable
78 , hasHereTable, hasThereTable
79 , justHereTable, justThereTable
80 , alignBy
81 , keepHereTable, loseHereTable
82 , keepThereTable, loseThereTable
83 , keepThisTable, loseThisTable
84 , keepThatTable, loseThatTable
85 , keepThoseTable, loseThoseTable
86 , bindTheseTable
87 , bitraverseTheseTable
89 -- ** @ListTable@
90 , ListTable
91 , many
93 -- ** @NonEmptyTable@
94 , NonEmptyTable
95 , some
97 -- ** Table schemas
98 , TableSchema(..)
99 , Name
100 , namesFromLabels
102 -- * Expressions
103 , Expr
104 , Sql
105 , litExpr
106 , unsafeCastExpr
108 -- ** @null@
109 , nullify
110 , nullable
111 , isNull
112 , isNonNull
113 , mapNullable
114 , liftOpNullable
115 , catNullable
117 -- ** Boolean operations
118 , DBEq
119 , true, false, not_
120 , (&&.), and_
121 , (||.), or_
122 , (==.), (/=.), (==?), (/=?)
123 , in_
124 , boolExpr, caseExpr
126 -- ** Ordering
127 , DBOrd
128 , (<.), (<=.), (>.), (>=.)
129 , (<?), (<=?), (>?), (>=?)
130 , leastExpr, greatestExpr
132 -- ** Functions
133 , Function
134 , function
135 , nullaryFunction
137 -- * Queries
138 , Query
139 , showQuery
141 -- ** Selecting rows
142 , Selects
143 , each
144 , values
146 -- ** Filtering
147 , filter
148 , where_
149 , whereExists
150 , whereNotExists
151 , distinct
152 , distinctOn
153 , distinctOnBy
155 -- ** @LIMIT@/@OFFSET@
156 , limit
157 , offset
159 -- ** @UNION@
160 , union
161 , unionAll
163 -- ** @INTERSECT@
164 , intersect
165 , intersectAll
167 -- ** @EXCEPT@
168 , except
169 , exceptAll
171 -- ** @EXISTS@
172 , exists
173 , with
174 , withBy
175 , without
176 , withoutBy
178 -- ** Aggregation
179 , Aggregate
180 , aggregate
181 , listAgg
182 , nonEmptyAgg
183 , groupBy
184 , DBMax, max
185 , DBMin, min
186 , DBSum, sum
187 , DBString, stringAgg
188 , count
189 , countStar
190 , countDistinct
191 , countWhere
192 , and
193 , or
195 -- ** Ordering
196 , orderBy
197 , Order
198 , asc
199 , desc
200 , nullsFirst
201 , nullsLast
203 -- * IO
204 , Serializable
206 -- * Running statements
207 -- ** @SELECT@
208 , select
210 -- ** @INSERT@
211 , Insert(..)
212 , OnConflict(..)
213 , insert
214 , toInsert
215 , toInsertDefaults
217 -- ** @DELETE@
218 , Delete(..)
219 , delete
221 -- ** @UPDATE@
222 , update
223 , Update(..)
225 -- ** @.. RETURNING@
226 , Returning(..)
228 -- * TODO
229 -- TODO
230 -- These need organizing, but are reachable from Rel8's documentation so we
231 -- do need to export and document them.
232 , Nullabilizes
233 , HTable
234 , Labelable
235 , Context
236 , IsMaybe
237 ) where
239-- base
240import Prelude ()
242-- rel8
243import Rel8.Aggregate
244import Rel8.Expr
245import Rel8.Expr.Aggregate
246import Rel8.Expr.Bool
247import Rel8.Expr.Eq
248import Rel8.Expr.Function
249import Rel8.Expr.Null
250import Rel8.Expr.Ord
251import Rel8.Expr.Order
252import Rel8.Expr.Serialize
253import Rel8.Order
254import Rel8.Query
255import Rel8.Query.Aggregate
256import Rel8.Query.Distinct
257import Rel8.Query.Each
258import Rel8.Query.Either
259import Rel8.Query.Exists
260import Rel8.Query.Filter
261import Rel8.Query.Limit
262import Rel8.Query.List
263import Rel8.Query.Maybe
264import Rel8.Query.Null
265import Rel8.Query.Order
266import Rel8.Query.SQL (showQuery)
267import Rel8.Query.Set
268import Rel8.Query.These
269import Rel8.Query.Values
270import Rel8.Schema.Column
271import Rel8.Schema.Context (Name)
272import Rel8.Schema.Context.Label
273import Rel8.Schema.Generic
274import Rel8.Schema.HTable
275import Rel8.Schema.Nullability
276import Rel8.Schema.Table
277import Rel8.Statement.Delete
278import Rel8.Statement.Insert
279import Rel8.Statement.Returning
280import Rel8.Statement.Select
281import Rel8.Statement.Update
282import Rel8.Table
283import Rel8.Table.Aggregate
284import Rel8.Table.Alternative
285import Rel8.Table.Bool
286import Rel8.Table.Either
287import Rel8.Table.Eq
288import Rel8.Table.Insert
289import Rel8.Table.List
290import Rel8.Table.Maybe
291import Rel8.Table.Name
292import Rel8.Table.NonEmpty
293import Rel8.Table.Ord
294import Rel8.Table.Order
295import Rel8.Table.Recontextualize
296import Rel8.Table.Serialize
297import Rel8.Table.These
298import Rel8.Type
299import Rel8.Type.Eq
300import Rel8.Type.Information
301import Rel8.Type.JSONEncoded
302import Rel8.Type.JSONBEncoded
303import Rel8.Type.Monoid
304import Rel8.Type.Num
305import Rel8.Type.Ord
306import Rel8.Type.ReadShow
307import Rel8.Type.Semigroup
308import Rel8.Type.String
309import Rel8.Type.Sum
310import Rel8.Expr.Opaleye (unsafeCastExpr)
313-- $setup
314--
315-- In this section, we'll take a look at using Rel8 to work with a small
316-- database for Haskell packages. We'll take a look at idiomatic usage of Rel8,
317-- mapping tables to Haskell, and then look at writing some simple queries.
318--
319-- The documentation in this library uses the following language extensions:
320--
321-- >>> :set -XBlockArguments
322-- >>> :set -XDeriveAnyClass
323-- >>> :set -XDeriveGeneric
324-- >>> :set -XDerivingStrategies
325-- >>> :set -XDerivingVia
326-- >>> :set -XDuplicateRecordFields
327-- >>> :set -XGeneralizedNewtypeDeriving
328-- >>> :set -XOverloadedStrings
329-- >>> :set -XStandaloneDeriving
330-- >>> :set -XTypeApplications
331-- >>> :set -XTypeFamilies
332--
333-- Before we start writing any Haskell, let's take a look at the schema we'll
334-- work with.
335--
336-- > author: project:
337-- >
338-- > Column │ Type │ Nullable Column │ Type │ Nullable
339-- > ═══════════╪═════════╪══════════ ═══════════╪═════════╪══════════
340-- > author_id │ integer │ not null author_id │ integer │ not null
341-- > name │ text │ not null name │ text │ not null
342-- > url │ text │
343--
344-- Our schema consists of two tables - @author@ and @project@. A @project@
345-- always has an @author@, but not all @author@s have projects. Each @author@
346-- has a name and (maybe) an associated website, and each project has a name.
347--
348-- Now that we've seen our schema, we can begin writing a mapping in Rel8. The
349-- idiomatic way to map a table is to use a record that is parameterised what
350-- Rel8 calls an /interpretation functor/, and to define each field with
351-- 'Column'. For this type to be usable with Rel8 we need it to be an instance
352-- of 'HigherKindedTable', which can be derived with a combination of
353-- @DeriveAnyClass@ and @DeriveGeneric@.
354--
355-- Following these steps for @author@, we have:
356--
357-- > data Author f = Author
358-- > { authorId :: Column f Int64
359-- > , name :: Column f Text
360-- > , url :: Column f (Maybe Text)
361-- > } deriving (Generic, HigherKindedTable)
362--
363-- This is a perfectly reasonable definition, but cautious readers might notice
364-- a problem - in particular, with the type of the @authorId@ field. While
365-- @Int64@ is correct, it's not the best type. If we had other identifier types
366-- in our project, it would be too easy to accidentally mix them up and create
367-- nonsensical joins. As Haskell programmers, we often solve this problem by
368-- creating @newtype@ wrappers, and we can also use this technique with Rel8:
369--
370-- >>> :{
371-- newtype AuthorId = AuthorId { toInt64 :: Int64 }
372-- deriving newtype (DBEq, DBType, Eq, Show)
373-- :}
374--
375-- Now we can write our final schema mapping. First, the @author@ table:
376--
377-- >>> :{
378-- data Author f = Author
379-- { authorId :: Column f AuthorId
380-- , authorName :: Column f Text
381-- , authorUrl :: Column f (Maybe Text)
382-- }
383-- deriving stock Generic
384-- deriving anyclass HigherKindedTable
385-- :}
386--
387-- And similarly, the @project@ table:
388--
389-- >>> :{
390-- data Project f = Project
391-- { projectAuthorId :: Column f AuthorId
392-- , projectName :: Column f Text
393-- }
394-- deriving stock Generic
395-- deriving anyclass HigherKindedTable
396-- :}
397--
398-- To show query results in this documentation, we'll also need @Show@
399-- instances: Unfortunately these definitions look a bit scary, but they are
400-- essentially just @deriving (Show)@:
401--
402-- >>> deriving stock instance f ~ Identity => Show (Author f)
403-- >>> deriving stock instance f ~ Identity => Show (Project f)
404--
405-- These data types describe the structural mapping of the tables, but we also
406-- need to specify a 'TableSchema' for each table. A @TableSchema@ contains the
407-- name of the table and the name of all columns in the table, which will
408-- ultimately allow us to @SELECT@ and @INSERT@ rows for these tables.
409--
410-- To define a @TableSchema@, we just need to fill construct appropriate
411-- @TableSchema@ values. When it comes to the @tableColumns@ field, we
412-- construct values of our data types above, and set each field to the name of
413-- the column that it maps to:
414--
415-- First, @authorSchema@ describes the column names of the @author@ table when
416-- associated with the @Author@ type:
417--
418-- >>> :{
419-- authorSchema :: TableSchema (Author ColumnSchema)
420-- authorSchema = TableSchema
421-- { tableName = "author"
422-- , tableSchema = Nothing
423-- , tableColumns = Author
424-- { authorId = "author_id"
425-- , authorName = "name"
426-- , authorUrl = "url"
427-- }
428-- }
429-- :}
430--
431-- And likewise for @project@ and @Project@:
432--
433-- >>> :{
434-- projectSchema :: TableSchema (Project ColumnSchema)
435-- projectSchema = TableSchema
436-- { tableName = "project"
437-- , tableSchema = Nothing
438-- , tableColumns = Project
439-- { projectAuthorId = "author_id"
440-- , projectName = "name"
441-- }
442-- }
443-- :}
444--
445-- Aside: you might be wondering why this information isn't in the definitions
446-- of @Author@ and @Project@ above. Rel8 decouples @TableSchema@ from the data
447-- types themselves, as not all tables you define will necessarily have a
448-- schema. For example, Rel8 allows you to define helper types to simplify the
449-- types of queries - these tables only exist at query time, but there is no
450-- corresponding base table. We'll see more on this idea later!
451--
452-- With these table definitions, we can now start writing some queries! To
453-- actually run a query, we'll need a database connection. Rel8 uses the
454-- @hasql@ library, and for this documentation we'll get the connection string
455-- from the @$TEST_DATABASE_URL@ environment variable.
456--
457-- >>> connectionString <- System.Environment.getEnv "TEST_DATABASE_URL"
458-- >>> Right c <- Hasql.Connection.acquire (Data.ByteString.Char8.pack connectionString)
459-- >>> Control.Monad.void $ Hasql.Session.run (Hasql.Session.sql "BEGIN") c
461-- $guideQueries
462--
463-- First, we'll take a look at @SELECT@ statements - usually the bulk of most
464-- database heavy applications.
465--
466-- In Rel8, @SELECT@ statements are built using the 'Query' monad. You can
467-- think of this monad like the ordinary @[]@ (List) monad - but this isn't
468-- required knowledge.
469--
470-- To start, we'll look at one of the simplest queries possible - a basic
471-- @SELECT * FROM@ statement. To select all rows from a table, we use 'each',
472-- and supply a 'TableSchema'. So to select all @project@ rows, we can write:
473--
474-- >>> :t each projectSchema
475-- each projectSchema :: Query (Project Expr)
476--
477-- Notice that @each@ gives us a @Query@ that yields @Project Expr@ rows. To
478-- see what this means, let's have a look at a single field of a
479-- @Project Expr@:
480--
481-- >>> let aProjectExpr = undefined :: Project Expr
482-- >>> :t projectAuthorId aProjectExpr
483-- projectAuthorId aProjectExpr :: Expr AuthorId
484--
485-- Recall we defined @projectAuthorId@ as @Column f AuthorId@. Now we have @f@
486-- is @Expr@, and @Column Expr AuthorId@ reduces to @Expr AuthorId@. We'll see
487-- more about @Expr@ soon, but you can think of @Expr a@ as "SQL expressions of
488-- type @a@".
489--
490-- To execute this @Query@, we pass it to 'select':
491--
492-- >>> :t select c (each projectSchema)
493-- select c (each projectSchema) :: MonadIO m => m [Project Identity]
494--
495-- When we @select@ things containing @Expr@s, Rel8 builds a new response table
496-- with the @Identity@ interpretation. This means you'll get back plain Haskell
497-- values. Studying @projectAuthorId@ again, we have:
498--
499-- >>> let aProjectIdentity = undefined :: Project Identity
500-- >>> :t projectAuthorId aProjectIdentity
501-- projectAuthorId aProjectIdentity :: AuthorId
502--
503-- Here @Column Identity AuthorId@ reduces to just @AuthorId@, with no
504-- wrappping type at all.
505--
506-- Putting this all together, we can run our first query:
507--
508-- >>> select c (each projectSchema) >>= mapM_ print
509-- Project {projectAuthorId = 1, projectName = "rel8"}
510-- Project {projectAuthorId = 2, projectName = "aeson"}
511-- Project {projectAuthorId = 2, projectName = "text"}
512--
513-- Cool!
514--
515-- We now know that 'each' is the equivalent of a @SELECT *@ query, but
516-- sometimes we're only interested in a subset of the columns of a table. To
517-- restrict the returned columns, we can specify a projection by using 'Query's
518-- @Functor@ instance:
519--
520-- >>> select c $ projectName <$> each projectSchema
521-- ["rel8","aeson","text"]
523-- $guideJoins
524--
525-- Another common operation in relational databases is to take the @JOIN@ of
526-- multiple tables. Rel8 doesn't have a specific join operation, but we can
527-- recover the functionality of a join by selecting all rows of two tables, and
528-- then using 'where_' to filter them.
529--
530-- To see how this works, first let's look at taking the product of two tables.
531-- We can do this by simply calling 'each' twice, and then returning a tuple of
532-- their results.
533--
534-- >>> :{
535-- mapM_ print =<< select c do
536-- author <- each authorSchema
537-- project <- each projectSchema
538-- return (projectName project, authorName author)
539-- :}
540-- ("rel8","Ollie")
541-- ("rel8","Bryan O'Sullivan")
542-- ("rel8","Emily Pillmore")
543-- ("aeson","Ollie")
544-- ("aeson","Bryan O'Sullivan")
545-- ("aeson","Emily Pillmore")
546-- ("text","Ollie")
547-- ("text","Bryan O'Sullivan")
548-- ("text","Emily Pillmore")
549--
550-- This isn't quite right, though, as we have ended up pairing up the wrong
551-- projects and authors. To fix this, we can use 'where_' to restrict the
552-- returned rows. We could write:
553--
554-- > select c $ do
555-- > author <- each authorSchema
556-- > project <- each projectSchema
557-- > where_ $ projectAuthorId project ==. authorId author
558-- > return (project, author)
559--
560-- but doing this every time you need a join can obscure the meaning of the
561-- query you're writing. A good practice is to introduce specialised functions
562-- for the particular joins in your database. In our case, this would be:
563--
564-- >>> :{
565-- projectsForAuthor :: Author Expr -> Query (Project Expr)
566-- projectsForAuthor a = each projectSchema >>= filter \p ->
567-- projectAuthorId p ==. authorId a
568-- :}
569--
570-- Our final query is then:
571--
572-- >>> :{
573-- mapM_ print =<< select c do
574-- author <- each authorSchema
575-- project <- projectsForAuthor author
576-- return (projectName project, authorName author)
577-- :}
578-- ("rel8","Ollie")
579-- ("aeson","Bryan O'Sullivan")
580-- ("text","Bryan O'Sullivan")
581--
582-- == @LEFT JOIN@s
583--
584-- Rel8 is also capable of performing @LEFT JOIN@s. To perform @LEFT JOIN@s, we
585-- follow the same approach as before, but use the 'optional' query transformer
586-- to allow for the possibility of the join to fail.
587--
588-- In our test database, we can see that there's another author who we haven't
589-- seen yet:
590--
591-- >>> select c $ authorName <$> each authorSchema
592-- ["Ollie","Bryan O'Sullivan","Emily Pillmore"]
593--
594-- Emily wasn't returned in our earlier query because - in our database - she
595-- doesn't have any registered projects. We can account for this partiality in
596-- our original query by wrapping the @projectsForAuthor@ call with 'optional':
597--
598-- >>> :{
599-- mapM_ print =<< select c do
600-- author <- each authorSchema
601-- mproject <- optional $ projectsForAuthor author
602-- return (authorName author, projectName <$> mproject)
603-- :}
604-- ("Ollie",Just "rel8")
605-- ("Bryan O'Sullivan",Just "aeson")
606-- ("Bryan O'Sullivan",Just "text")
607-- ("Emily Pillmore",Nothing)
609-- $guideAggregation
610--
611-- Aggregations are operations like @sum@ and @count@ - operations that reduce
612-- multiple rows to single values. To perform aggregations in Rel8, we can use
613-- the 'aggregate' function, which takes a 'Query' of aggregated expressions,
614-- runs the aggregation, and returns aggregated rows.
615--
616-- To start, let's look at a simple aggregation that tells us how many projects
617-- exist:
618--
619-- >>> error "TODO"
620--
621-- Rel8 is also capable of aggregating multiple rows into a single row by
622-- concatenating all rows as a list. This aggregation allows us to break free
623-- of the row-orientated nature of SQL and write queries that return tree-like
624-- structures. Earlier we saw an example of returning authors with their
625-- projects, but the query didn't do a great job of describing the one-to-many
626-- relationship between authors and their projects.
627--
628-- Let's look again at a query that returns authors and their projects, and
629-- focus on the /type/ of that query.
630--
631-- >>> :{
632-- projectsForAuthor a = each projectSchema >>= filter \p ->
633-- projectAuthorId p ==. authorId a
634-- :}
635--
636-- >>> :{
637-- let authorsAndProjects = do
638-- author <- each authorSchema
639-- project <- projectsForAuthor author
640-- return (author, project)
641-- where
642-- :}
643--
644-- >>> :t select c authorsAndProjects
645-- select c authorsAndProjects
646-- :: MonadIO m => m [(Author Identity, Project Identity)]
647--
648-- Our query gives us a single list of pairs of authors and projects. However,
649-- with our domain knowledge of the schema, this isn't a great type - what we'd
650-- rather have is a list of pairs of authors and /lists/ of projects. That is,
651-- what we'd like is:
652--
653-- > [(Author Identity, [Project Identity])]
654--
655-- This would be a much better type! Rel8 can produce a query with this type by
656-- simply wrapping the call to @projectsForAuthor@ with either 'some' or
657-- 'many'. Here we'll use 'many', which allows for the possibility of an author
658-- to have no projects:
659--
660-- >>> :{
661-- mapM_ print =<< select c do
662-- author <- each authorSchema
663-- projectNames <- many $ projectName <$> projectsForAuthor author
664-- return (authorName author, projectNames)
665-- :}
666-- ("Ollie",["rel8"])
667-- ("Bryan O'Sullivan",["aeson","text"])
668-- ("Emily Pillmore",[])