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