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