RobinBlomberg / kysely-codegen

Generate Kysely type definitions from your database.
MIT License
819 stars 73 forks source link

Are we able to use string instead of new Date() ? #123

Closed tombohub closed 1 month ago

tombohub commented 11 months ago

postgres generated code for table is:

export interface OvernightDailyOvernightPerformance {
  ...
  date: Timestamp;
  ...
}

I want to filter by date:

const rows = await db
    .selectFrom("overnight.daily_overnight_performance")
    .where("date", "=", "2023-06-02")
    .execute()

but it's an error: image

and cannot run the script.

If I change Timestamp type from:

export type Timestamp = ColumnType<Date, Date | string, Date | string>;

to:

export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;

it still shows the error: image

but at least I can run the script.

Can you make it so it generates code where date string is acceptable for selection?

Upvote & Fund

Fund with Polar

SangJunBak commented 11 months ago

I too have this problem! Especially since Postgres accepts microsecond precision which JavasScript Date objects do not support.

nick-cheatwood7 commented 9 months ago

This is not a perfect fix, but you can sort of trick Typescript into allowing a Date value, at least for timestamp columns in MySQL:

const isoDateString = new Date().toISOString()
// 👇 where "date_column" is a `timestamp` column
await db.insertInto("foo").values({ date_column: isoDateString as unknown as Date  }).execute()

I had a project where I needed to insert a timestamp value as a string and this worked.

RobinBlomberg commented 8 months ago

This sounds like a duplicate of #121. Someone posted a solution there:

import { Selectable } from 'kysely'

const results: Selectable<Thing> = await db.selectFrom('thing').selectAll().execute()

Please check if that solves the issue. If so, I will add the solution to the README.

koskimas commented 8 months ago

@RobinBlomberg This is a different issue. The issue is that where uses the Selectable type, which is Date in Timestamp.

@tombohub

it still shows the error:

No it doesn't. Restart vscode or reboot its typescript server. If you're able to compile that typescript, then surely the typescript running inside vscode also accepts the code.

There's probably nothing kysely-codegen should do here. If you change the selectable type, then the result type is also Date | string. What you (the user) can do is create a helper function like this:

function toDate(date: string) {
  return sql<Date>`${date}`
}

const rows = await db
    .selectFrom("overnight.daily_overnight_performance")
    .where("date", "=", toDate("2023-06-02"))
    .execute()

I'd say this is cleaner than a cast.

RobinBlomberg commented 1 month ago

Should be fixed now in kysely-codegen@0.17.0! Use the new --date-parser option.