on da76712 help sign in
rel8/src/Rel8/Table/Order.hs
50 lines 1.7 kB history raw
1{-# language DataKinds #-}
2{-# language NamedFieldPuns #-}
3{-# language ScopedTypeVariables #-}
4{-# language TypeApplications #-}
5{-# language TypeFamilies #-}
7module Rel8.Table.Order
8 ( ascTable
9 , descTable
10 )
11where
13-- base
14import Data.Functor.Const ( Const( Const ), getConst )
15import Data.Functor.Contravariant ( (>$<), contramap )
16import Prelude
18-- rel8
19import Rel8.Expr.Order ( asc, desc, nullsFirst, nullsLast )
20import Rel8.Order ( Order )
21import Rel8.Schema.Dict ( Dict( Dict ) )
22import Rel8.Schema.HTable (htabulateA, hfield, hspecs)
23import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
24import Rel8.Schema.Spec ( Spec( Spec, nullity ) )
25import Rel8.Table ( Columns, toColumns )
26import Rel8.Table.Ord ( OrdTable, ordTable )
29-- | Construct an 'Order' for a 'Table' by sorting all columns into ascending
30-- orders (any nullable columns will be sorted with @NULLS FIRST@).
31ascTable :: forall a. OrdTable a => Order a
32ascTable = contramap toColumns $ getConst $
33 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
34 Spec {nullity} -> case hfield (ordTable @a) field of
35 Dict -> Const $ (`hfield` field) >$<
36 case nullity of
37 Null -> nullsFirst asc
38 NotNull -> asc
41-- | Construct an 'Order' for a 'Table' by sorting all columns into descending
42-- orders (any nullable columns will be sorted with @NULLS LAST@).
43descTable :: forall a. OrdTable a => Order a
44descTable = contramap toColumns $ getConst $
45 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
46 Spec {nullity} -> case hfield (ordTable @a) field of
47 Dict -> Const $ (`hfield` field) >$<
48 case nullity of
49 Null -> nullsLast desc
50 NotNull -> desc