Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lag and lead function support #390

Open
rinn7e opened this issue May 1, 2024 · 1 comment
Open

lag and lead function support #390

rinn7e opened this issue May 1, 2024 · 1 comment

Comments

@rinn7e
Copy link

rinn7e commented May 1, 2024

I want to do a select as the following:

SELECT
	LAG(a.id, 1) OVER (
		ORDER BY a.sent_at DESC
	) previous_a,
	lead(a.id, 1) OVER (
		ORDER BY a.sent_at DESC
	) next_a
FROM
...

Since esqueleto doesn't have lag and lead yet, I want to create it using raw sql, but I believe using unsafeSqlFuntion doesn't work due to having over clause.

Hope someone could point me to the right direction.

@rinn7e
Copy link
Author

rinn7e commented May 1, 2024

Found a work around, inspired from unsafeSqlAggFunction:

unsafeSqlWindowFunction
    :: UnsafeSqlFunctionArgument a
    => TLB.Builder
    -> a
    -> [OrderByClause]
    -> SqlExpr (Value b)
unsafeSqlWindowFunction name args orderByClauses = ERaw noMeta $ \_ info ->
    let (orderTLB, orderVals) = makeOrderByNoNewline info orderByClauses
        (argsTLB, argsVals) =
            uncommas' $ map (\(ERaw _ f) -> f Never info) $ toArgList args

    in ( name <> parens (argsTLB) <> " OVER " <> parens(orderTLB)
       , argsVals <> orderVals
       )

lag :: SqlExpr (Value a) -> SqlExpr (Value Int64) -> [OrderByClause] -> SqlExpr (Value (Maybe a))
lag fieldArg offsetArg clause = unsafeSqlWindowFunction "lag" (fieldArg, offsetArg) clause

lead :: SqlExpr (Value a) -> SqlExpr (Value Int64) -> [OrderByClause] -> SqlExpr (Value (Maybe a))
lead fieldArg offsetArg clause = unsafeSqlWindowFunction "lead" (fieldArg, offsetArg) clause

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant