1{-# language DuplicateRecordFields #-}
20 -- *** Deriving-via helpers
28 -- *** @TypeInformation@
31 , parseTypeInformation
33 -- ** The @DBType@ hierarchy
39 -- * Tables and higher-kinded tables
50 , EqTable, (==:), (/=:)
51 , OrdTable, ascTable, descTable
58 , maybeTable, ($?), nothingTable, justTable
59 , isNothingTable, isJustTable
67 , eitherTable, leftTable, rightTable
68 , isLeftTable, isRightTable
72 , bitraverseEitherTable
76 , theseTable, thisTable, thatTable, thoseTable
77 , isThisTable, isThatTable, isThoseTable
78 , hasHereTable, hasThereTable
79 , justHereTable, justThereTable
81 , keepHereTable, loseHereTable
82 , keepThereTable, loseThereTable
83 , keepThisTable, loseThisTable
84 , keepThatTable, loseThatTable
85 , keepThoseTable, loseThoseTable
87 , bitraverseTheseTable
101 , namesFromLabelsWith
120 -- ** Boolean operations
125 , (==.), (/=.), (==?), (/=?)
131 , (<.), (<=.), (>.), (>=.)
132 , (<?), (<=?), (>?), (>=?)
133 , leastExpr, greatestExpr
159 -- ** @LIMIT@/@OFFSET@
186 , distributeAggregate
187 , listAgg, listAggExpr
188 , nonEmptyAgg, nonEmptyAggExpr
192 , DBSum, sum, sumWhere
193 , DBString, stringAgg
212 -- * Running statements
236 -- These need organizing, but are reachable from Rel8's documentation so we
237 -- do need to export and document them.
251import Rel8.Expr.Aggregate
254import Rel8.Expr.Function
257import Rel8.Expr.Order
258import Rel8.Expr.Serialize
261import Rel8.Query.Aggregate
262import Rel8.Query.Distinct
263import Rel8.Query.Each
264import Rel8.Query.Either
265import Rel8.Query.Exists
266import Rel8.Query.Filter
267import Rel8.Query.Limit
268import Rel8.Query.List
269import Rel8.Query.Maybe
270import Rel8.Query.Null
271import Rel8.Query.Order
272import Rel8.Query.SQL (showQuery)
274import Rel8.Query.These
275import Rel8.Query.Values
276import Rel8.Schema.Column
277import Rel8.Schema.Context.Label
278import Rel8.Schema.Generic
279import Rel8.Schema.HTable
280import Rel8.Schema.Name
281import Rel8.Schema.Nullability
282import Rel8.Schema.Table
283import Rel8.Statement.Delete
284import Rel8.Statement.Insert
285import Rel8.Statement.Returning
286import Rel8.Statement.Select
287import Rel8.Statement.Update
289import Rel8.Table.Aggregate
290import Rel8.Table.Alternative
291import Rel8.Table.Bool
292import Rel8.Table.Either
294import Rel8.Table.Insert
295import Rel8.Table.List
296import Rel8.Table.Maybe
297import Rel8.Table.Name
298import Rel8.Table.NonEmpty
300import Rel8.Table.Order
301import Rel8.Table.Serialize
302import Rel8.Table.These
305import Rel8.Type.Information
306import Rel8.Type.JSONEncoded
307import Rel8.Type.JSONBEncoded
308import Rel8.Type.Monoid
311import Rel8.Type.ReadShow
312import Rel8.Type.Semigroup
313import Rel8.Type.String
315import Rel8.Expr.Opaleye (unsafeCastExpr)
320-- In this section, we'll take a look at using Rel8 to work with a small
321-- database for Haskell packages. We'll take a look at idiomatic usage of Rel8,
322-- mapping tables to Haskell, and then look at writing some simple queries.
324-- The documentation in this library uses the following language extensions:
326-- >>> :set -XBlockArguments
327-- >>> :set -XDeriveAnyClass
328-- >>> :set -XDeriveGeneric
329-- >>> :set -XDerivingStrategies
330-- >>> :set -XDerivingVia
331-- >>> :set -XDuplicateRecordFields
332-- >>> :set -XGeneralizedNewtypeDeriving
333-- >>> :set -XOverloadedStrings
334-- >>> :set -XStandaloneDeriving
335-- >>> :set -XTypeApplications
336-- >>> :set -XTypeFamilies
338-- Before we start writing any Haskell, let's take a look at the schema we'll
343-- > Column │ Type │ Nullable Column │ Type │ Nullable
344-- > ═══════════╪═════════╪══════════ ═══════════╪═════════╪══════════
345-- > author_id │ integer │ not null author_id │ integer │ not null
346-- > name │ text │ not null name │ text │ not null
349-- Our schema consists of two tables - @author@ and @project@. A @project@
350-- always has an @author@, but not all @author@s have projects. Each @author@
351-- has a name and (maybe) an associated website, and each project has a name.
353-- Now that we've seen our schema, we can begin writing a mapping in Rel8. The
354-- idiomatic way to map a table is to use a record that is parameterised what
355-- Rel8 calls an /interpretation functor/, and to define each field with
356-- 'Column'. For this type to be usable with Rel8 we need it to be an instance
357-- of 'HigherKindedTable', which can be derived with a combination of
358-- @DeriveAnyClass@ and @DeriveGeneric@.
360-- Following these steps for @author@, we have:
362-- > data Author f = Author
363-- > { authorId :: Column f Int64
364-- > , name :: Column f Text
365-- > , url :: Column f (Maybe Text)
366-- > } deriving (Generic, HigherKindedTable)
368-- This is a perfectly reasonable definition, but cautious readers might notice
369-- a problem - in particular, with the type of the @authorId@ field. While
370-- @Int64@ is correct, it's not the best type. If we had other identifier types
371-- in our project, it would be too easy to accidentally mix them up and create
372-- nonsensical joins. As Haskell programmers, we often solve this problem by
373-- creating @newtype@ wrappers, and we can also use this technique with Rel8:
376-- newtype AuthorId = AuthorId { toInt64 :: Int64 }
377-- deriving newtype (DBEq, DBType, Eq, Show)
380-- Now we can write our final schema mapping. First, the @author@ table:
383-- data Author f = Author
384-- { authorId :: Column f AuthorId
385-- , authorName :: Column f Text
386-- , authorUrl :: Column f (Maybe Text)
388-- deriving stock Generic
389-- deriving anyclass HigherKindedTable
392-- And similarly, the @project@ table:
395-- data Project f = Project
396-- { projectAuthorId :: Column f AuthorId
397-- , projectName :: Column f Text
399-- deriving stock Generic
400-- deriving anyclass HigherKindedTable
403-- To show query results in this documentation, we'll also need @Show@
404-- instances: Unfortunately these definitions look a bit scary, but they are
405-- essentially just @deriving (Show)@:
407-- >>> deriving stock instance f ~ Identity => Show (Author f)
408-- >>> deriving stock instance f ~ Identity => Show (Project f)
410-- These data types describe the structural mapping of the tables, but we also
411-- need to specify a 'TableSchema' for each table. A @TableSchema@ contains the
412-- name of the table and the name of all columns in the table, which will
413-- ultimately allow us to @SELECT@ and @INSERT@ rows for these tables.
415-- To define a @TableSchema@, we just need to fill construct appropriate
416-- @TableSchema@ values. When it comes to the @tableColumns@ field, we
417-- construct values of our data types above, and set each field to the name of
418-- the column that it maps to:
420-- First, @authorSchema@ describes the column names of the @author@ table when
421-- associated with the @Author@ type:
424-- authorSchema :: TableSchema (Author ColumnSchema)
425-- authorSchema = TableSchema
426-- { tableName = "author"
427-- , tableSchema = Nothing
428-- , tableColumns = Author
429-- { authorId = "author_id"
430-- , authorName = "name"
431-- , authorUrl = "url"
436-- And likewise for @project@ and @Project@:
439-- projectSchema :: TableSchema (Project ColumnSchema)
440-- projectSchema = TableSchema
441-- { tableName = "project"
442-- , tableSchema = Nothing
443-- , tableColumns = Project
444-- { projectAuthorId = "author_id"
445-- , projectName = "name"
450-- Aside: you might be wondering why this information isn't in the definitions
451-- of @Author@ and @Project@ above. Rel8 decouples @TableSchema@ from the data
452-- types themselves, as not all tables you define will necessarily have a
453-- schema. For example, Rel8 allows you to define helper types to simplify the
454-- types of queries - these tables only exist at query time, but there is no
455-- corresponding base table. We'll see more on this idea later!
457-- With these table definitions, we can now start writing some queries! To
458-- actually run a query, we'll need a database connection. Rel8 uses the
459-- @hasql@ library, and for this documentation we'll get the connection string
460-- from the @$TEST_DATABASE_URL@ environment variable.
462-- >>> connectionString <- System.Environment.getEnv "TEST_DATABASE_URL"
463-- >>> Right c <- Hasql.Connection.acquire (Data.ByteString.Char8.pack connectionString)
464-- >>> Control.Monad.void $ Hasql.Session.run (Hasql.Session.sql "BEGIN") c
468-- First, we'll take a look at @SELECT@ statements - usually the bulk of most
469-- database heavy applications.
471-- In Rel8, @SELECT@ statements are built using the 'Query' monad. You can
472-- think of this monad like the ordinary @[]@ (List) monad - but this isn't
473-- required knowledge.
475-- To start, we'll look at one of the simplest queries possible - a basic
476-- @SELECT * FROM@ statement. To select all rows from a table, we use 'each',
477-- and supply a 'TableSchema'. So to select all @project@ rows, we can write:
479-- >>> :t each projectSchema
480-- each projectSchema :: Query (Project Expr)
482-- Notice that @each@ gives us a @Query@ that yields @Project Expr@ rows. To
483-- see what this means, let's have a look at a single field of a
486-- >>> let aProjectExpr = undefined :: Project Expr
487-- >>> :t projectAuthorId aProjectExpr
488-- projectAuthorId aProjectExpr :: Expr AuthorId
490-- Recall we defined @projectAuthorId@ as @Column f AuthorId@. Now we have @f@
491-- is @Expr@, and @Column Expr AuthorId@ reduces to @Expr AuthorId@. We'll see
492-- more about @Expr@ soon, but you can think of @Expr a@ as "SQL expressions of
495-- To execute this @Query@, we pass it to 'select':
497-- >>> :t select c (each projectSchema)
498-- select c (each projectSchema) :: MonadIO m => m [Project Identity]
500-- When we @select@ things containing @Expr@s, Rel8 builds a new response table
501-- with the @Identity@ interpretation. This means you'll get back plain Haskell
502-- values. Studying @projectAuthorId@ again, we have:
504-- >>> let aProjectIdentity = undefined :: Project Identity
505-- >>> :t projectAuthorId aProjectIdentity
506-- projectAuthorId aProjectIdentity :: AuthorId
508-- Here @Column Identity AuthorId@ reduces to just @AuthorId@, with no
509-- wrappping type at all.
511-- Putting this all together, we can run our first query:
513-- >>> select c (each projectSchema) >>= mapM_ print
514-- Project {projectAuthorId = 1, projectName = "rel8"}
515-- Project {projectAuthorId = 2, projectName = "aeson"}
516-- Project {projectAuthorId = 2, projectName = "text"}
520-- We now know that 'each' is the equivalent of a @SELECT *@ query, but
521-- sometimes we're only interested in a subset of the columns of a table. To
522-- restrict the returned columns, we can specify a projection by using 'Query's
523-- @Functor@ instance:
525-- >>> select c $ projectName <$> each projectSchema
526-- ["rel8","aeson","text"]
530-- Another common operation in relational databases is to take the @JOIN@ of
531-- multiple tables. Rel8 doesn't have a specific join operation, but we can
532-- recover the functionality of a join by selecting all rows of two tables, and
533-- then using 'where_' to filter them.
535-- To see how this works, first let's look at taking the product of two tables.
536-- We can do this by simply calling 'each' twice, and then returning a tuple of
540-- mapM_ print =<< select c do
541-- author <- each authorSchema
542-- project <- each projectSchema
543-- return (projectName project, authorName author)
546-- ("rel8","Bryan O'Sullivan")
547-- ("rel8","Emily Pillmore")
549-- ("aeson","Bryan O'Sullivan")
550-- ("aeson","Emily Pillmore")
552-- ("text","Bryan O'Sullivan")
553-- ("text","Emily Pillmore")
555-- This isn't quite right, though, as we have ended up pairing up the wrong
556-- projects and authors. To fix this, we can use 'where_' to restrict the
557-- returned rows. We could write:
560-- > author <- each authorSchema
561-- > project <- each projectSchema
562-- > where_ $ projectAuthorId project ==. authorId author
563-- > return (project, author)
565-- but doing this every time you need a join can obscure the meaning of the
566-- query you're writing. A good practice is to introduce specialised functions
567-- for the particular joins in your database. In our case, this would be:
570-- projectsForAuthor :: Author Expr -> Query (Project Expr)
571-- projectsForAuthor a = each projectSchema >>= filter \p ->
572-- projectAuthorId p ==. authorId a
575-- Our final query is then:
578-- mapM_ print =<< select c do
579-- author <- each authorSchema
580-- project <- projectsForAuthor author
581-- return (projectName project, authorName author)
584-- ("aeson","Bryan O'Sullivan")
585-- ("text","Bryan O'Sullivan")
589-- Rel8 is also capable of performing @LEFT JOIN@s. To perform @LEFT JOIN@s, we
590-- follow the same approach as before, but use the 'optional' query transformer
591-- to allow for the possibility of the join to fail.
593-- In our test database, we can see that there's another author who we haven't
596-- >>> select c $ authorName <$> each authorSchema
597-- ["Ollie","Bryan O'Sullivan","Emily Pillmore"]
599-- Emily wasn't returned in our earlier query because - in our database - she
600-- doesn't have any registered projects. We can account for this partiality in
601-- our original query by wrapping the @projectsForAuthor@ call with 'optional':
604-- mapM_ print =<< select c do
605-- author <- each authorSchema
606-- mproject <- optional $ projectsForAuthor author
607-- return (authorName author, projectName <$> mproject)
609-- ("Ollie",Just "rel8")
610-- ("Bryan O'Sullivan",Just "aeson")
611-- ("Bryan O'Sullivan",Just "text")
612-- ("Emily Pillmore",Nothing)
616-- Aggregations are operations like @sum@ and @count@ - operations that reduce
617-- multiple rows to single values. To perform aggregations in Rel8, we can use
618-- the 'aggregate' function, which takes a 'Query' of aggregated expressions,
619-- runs the aggregation, and returns aggregated rows.
621-- To start, let's look at a simple aggregation that tells us how many projects
626-- Rel8 is also capable of aggregating multiple rows into a single row by
627-- concatenating all rows as a list. This aggregation allows us to break free
628-- of the row-orientated nature of SQL and write queries that return tree-like
629-- structures. Earlier we saw an example of returning authors with their
630-- projects, but the query didn't do a great job of describing the one-to-many
631-- relationship between authors and their projects.
633-- Let's look again at a query that returns authors and their projects, and
634-- focus on the /type/ of that query.
637-- projectsForAuthor a = each projectSchema >>= filter \p ->
638-- projectAuthorId p ==. authorId a
642-- let authorsAndProjects = do
643-- author <- each authorSchema
644-- project <- projectsForAuthor author
645-- return (author, project)
649-- >>> :t select c authorsAndProjects
650-- select c authorsAndProjects
651-- :: MonadIO m => m [(Author Identity, Project Identity)]
653-- Our query gives us a single list of pairs of authors and projects. However,
654-- with our domain knowledge of the schema, this isn't a great type - what we'd
655-- rather have is a list of pairs of authors and /lists/ of projects. That is,
658-- > [(Author Identity, [Project Identity])]
660-- This would be a much better type! Rel8 can produce a query with this type by
661-- simply wrapping the call to @projectsForAuthor@ with either 'some' or
662-- 'many'. Here we'll use 'many', which allows for the possibility of an author
663-- to have no projects:
666-- mapM_ print =<< select c do
667-- author <- each authorSchema
668-- projectNames <- many $ projectName <$> projectsForAuthor author
669-- return (authorName author, projectNames)
672-- ("Bryan O'Sullivan",["aeson","text"])
673-- ("Emily Pillmore",[])
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