kysely icon indicating copy to clipboard operation
kysely copied to clipboard

Feature request: third argument in `orderBy` for null sorting in relevant dialects

Open jericirenej opened this issue 1 year ago • 3 comments

In PostgreSQL and SQLite the ORDER BY clause accepts a sorting configuration to override default behaviour. Currently, only two arguments can be passed - the value on which to order by and the direction. Alternatively, a raw query can also be provided. However, this might introduce some vulnerabilities when dealing with dynamic inputs.

A potential workaround currently is to use raw sql for the direction property: .orderBy(columnName, sql.raw(`${verifiedDirection} NULLS LAST`).

It would be useful to have an optional third argument by which to influence the default null sorting behaviour, perhaps something similar to:

orderBy(
UndirectedOrderByExpression<DB, TB, O>, 
direction?: OrderByDirectionExpression,
nulls?: "first"|"last"
)

jericirenej avatar Sep 23 '23 10:09 jericirenej

Hey 👋

I don't think the proposed API is the cleanest.

Since we're about to tackle this area anyway, because of mssql (orderby-offset-fetch coupling), we'll probably come up with an order by builder factory variant that'll have a nulls('first'|'last) method and maybe modifyEnd.

igalklebanov avatar Sep 28 '23 13:09 igalklebanov

That sounds great and I'm looking forward to it! 👍 Does this mean that the current orderBy will no longer operate as it does now (with two parameters)? Or is this going to be an additional option or variant to add to the orderBy method?

jericirenej avatar Sep 28 '23 15:09 jericirenej

+1 for this feature, Our workaround is as follows:

  export const orderNullsLast = (direction: OrderByDirection) => sql`${sql.raw(direction)} nulls last`;


db.selectFrom('table')
    .orderBy(order, orderNullsLast(direction))

jacsamell avatar Dec 14 '23 10:12 jacsamell