on 00a36f5 help sign in
rel8/src/Rel8/Table/Order.hs
54 lines 1.9 kB history raw
1{-# language NamedFieldPuns #-}
2{-# language ScopedTypeVariables #-}
3{-# language TypeApplications #-}
4{-# language TypeFamilies #-}
6module Rel8.Table.Order
7 ( ascTable
8 , descTable
9 )
10where
12-- base
13import Data.Functor.Const ( Const( Const ), getConst )
14import Data.Functor.Contravariant ( (>$<), contramap )
15import Prelude
17-- rel8
18import Rel8.Expr.Order ( asc, desc, nullsFirst, nullsLast )
19import Rel8.Order ( Order )
20import Rel8.Schema.Context ( unDB )
21import Rel8.Schema.Dict ( Dict( Dict ) )
22import Rel8.Schema.HTable (htabulateA, hfield, hdicts, hspecs)
23import Rel8.Schema.Nullability ( Nullability( Nullable, NonNullable ) )
24import Rel8.Schema.Spec ( SSpec(..) )
25import Rel8.Schema.Spec.ConstrainDBType ( ConstrainDBType )
26import Rel8.Table
27import Rel8.Table.Ord
28import Rel8.Type.Ord
31-- | Construct an 'Order' for a 'Table' by sorting all columns into ascending
32-- orders (any nullable columns will be sorted with @NULLS FIRST@).
33ascTable :: forall a. OrdTable a => Order a
34ascTable = contramap toColumns $ getConst $
35 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
36 SSpec {nullability} -> case hfield ords field of
37 Dict -> Const $ unDB . (`hfield` field) >$< case nullability of
38 Nullable -> nullsFirst asc
39 NonNullable -> asc
40 where
41 ords = hdicts @(Columns a) @(ConstrainDBType DBOrd)
44-- | Construct an 'Order' for a 'Table' by sorting all columns into descending
45-- orders (any nullable columns will be sorted with @NULLS LAST@).
46descTable :: forall a. OrdTable a => Order a
47descTable = contramap toColumns $ getConst $
48 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
49 SSpec {nullability} -> case hfield ords field of
50 Dict -> Const $ unDB . (`hfield` field) >$< case nullability of
51 Nullable -> nullsLast desc
52 NonNullable -> desc
53 where
54 ords = hdicts @(Columns a) @(ConstrainDBType DBOrd)