kysely-org / kysely

A type-safe typescript SQL query builder
https://kysely.dev
MIT License
9.81k stars 249 forks source link

orderBy gives an error when a space separated string of sortBy and sortOrder is passed in eg- orderBy('sortBy sortOrder') #1023

Closed kavitakothari closed 1 month ago

kavitakothari commented 1 month ago

Kysely documentation allows a space separated string for sortBy and sortOrder to be passed in to orderBy - https://kysely-org.github.io/kysely-apidoc/interfaces/SelectQueryBuilder.html#orderBy

However when this syntax is tested on the Kysely playground it gives an error "argument of type "age desc" is not assignable to parameter of type 'OrderByExpression<From<Database, "person">, "person", AllSelection<From<Databased, "person">, "person">>'

This does not work in VsCode either when trying to pass in an array of strings for multiple sort. It gives an error

  Overload 1 of 3, '(orderBy: UndirectedOrderByExpression<Database, "tableName", { description: string; ... 4 more ... }>, direction?: OrderByDirectionExpression | undefined): SelectQueryBuilder<...>', gave the following error.
    Argument of type 'string[]' is not assignable to parameter of type 'UndirectedOrderByExpression<Database, "tableName", { description: string; ... 4 more ... }>'.
  Overload 2 of 3, '(ref: DirectedOrderByStringReference<Database, "tableName", { description: string; ... 4 more ... }>): SelectQueryBuilder<...>', gave the following error. Argument of type 'string[]' is not assignable to parameter of type 'DirectedOrderByStringReference<Database, "tableName", { description: string; ... 4 more ... }>'.
  Overload 3 of 3, '(refs: readonly OrderByExpression<Database, "tableName", { description: string; ... 4 more ... }>[]): SelectQueryBuilder<...>', gave the following error.
    Argument of type 'string[]' is not assignable to parameter of type 'readonly OrderByExpression<Database, "tableName", { description: string; ... 4 more ... }>[]'. Type 'string' is not assignable to type 'OrderByExpression<Database, "tableName", { description: string; 4 more ... }>'.ts(2769) 
igalklebanov commented 1 month ago

Hey 👋

Can you provide a kyse.link that reproduces this?

koskimas commented 1 month ago

Seems to work for me https://kyse.link/FLt0L

You can't do this

const orders = ["first_name asc", "last_name desc"]

...

.orderBy(orders)

since orders is just an array of strings.

However, you can do this:

const orders = ["first_name asc", "last_name desc"] as const

...

.orderBy(orders)

as const makes the type ('first_name asc' | 'last_name desc')[].

If the orders array is user input, you need to validate it and then cast it.