module Rel8.Query.Indexed
  ( indexed
  )
where

-- base
import Control.Applicative ( liftA2 )
import Data.Int ( Int64 )
import Prelude

-- rel8
import Rel8.Expr ( Expr )
import Rel8.Expr.Window ( rowNumber )
import Rel8.Query ( Query )
import Rel8.Query.Window ( window )
import Rel8.Table.Window ( currentRow )


-- | Pair each row of a query with its index within the query.
indexed :: Query a -> Query (Expr Int64, a)
indexed :: forall a. Query a -> Query (Expr Int64, a)
indexed = Window a (Expr Int64, a) -> Query a -> Query (Expr Int64, a)
forall a b. Window a b -> Query a -> Query b
window ((Expr Int64 -> a -> (Expr Int64, a))
-> Window a (Expr Int64) -> Window a a -> Window a (Expr Int64, a)
forall a b c.
(a -> b -> c) -> Window a a -> Window a b -> Window a c
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 (,) (Expr Int64 -> Expr Int64 -> Expr Int64
forall a. Num a => a -> a -> a
subtract Expr Int64
1 (Expr Int64 -> Expr Int64)
-> Window a (Expr Int64) -> Window a (Expr Int64)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Window a (Expr Int64)
forall i. Window i (Expr Int64)
rowNumber) Window a a
forall a. Window a a
currentRow)