Currently I'm trying to use more of the composability of beam . Unfortunately I cannot figure out if what I am trying to do is even possible. What I am trying to do is write a function, that takes a Q query, and selects from the query twice, once unmodified and once wrapped into a "count(*)"-aggregate.

So far I got this function:

runPaginatedQuery :: ( QExprToIdentity res ~ a , FromBackendRow Sqlite (QExprToIdentity res) , ProjectibleWithPredicate ValueContext SqliteExpressionSyntax res , ProjectibleWithPredicate AnyType SqliteExpressionSyntax res ) => Connection -> Int -> Int -> (forall s. Q SqliteSelectSyntax db s res) -> IO ([a], Int) runPaginatedQuery conn limit offset q = do (Just count) <- runBeamSqlite conn $ runSelectReturningOne $ select $ aggregate_ (const $ countAll_) q l <- runBeamSqlite conn $ runSelectReturningList $ select q return (l,count)

The function type checks, but if I try to use it, e.g.

main = do conn <- open "test.db" (ss :: [Student], n) <- runPaginatedQuery conn 20 0 (all_ (_students schoolDb)) print n

I get the following type error:

src/Main.hs:57:56: error: • Couldn't match type ‘res0’ with ‘StudentT (QExpr SqliteExpressionSyntax s)’ because type variable ‘s’ would escape its scope This (rigid, skolem) type variable is bound by a type expected by the context: forall s. Q SqliteSelectSyntax SchoolDb s res0 at src/Main.hs:57:27-81 Expected type: Q SqliteSelectSyntax SchoolDb s res0 Actual type: Q SqliteSelectSyntax SchoolDb s (StudentT (QExpr (Database.Beam.Backend.SQL.SQL92.Sql92SelectTableExpressionSyntax (Database.Beam.Backend.SQL.SQL92.Sql92SelectSelectTableSyntax SqliteSelectSyntax)) s)) • In the fourth argument of ‘runPaginatedQuery’, namely ‘(all_ (_students schoolDb))’ In a stmt of a 'do' block: (ss :: [Student], n) <- runPaginatedQuery conn 20 0 (all_ (_students schoolDb)) In the expression: do conn <- open "test.db" (ss :: [Student], n) <- runPaginatedQuery conn 20 0 (all_ (_students schoolDb)) print "hi" | 57 | (ss :: [Student], n) <- runPaginatedQuery conn 20 0 (all_ (_students schoolDb)) | ^^^^^^^^^^^^^^^^^^^^^^^^^

I'm having trouble understanding the error message.

Edit: It seems that what I am trying to achieve is currently not possible, hence I accepted @chi's answer as it has a good explanation why it is not possible.