Force parameter to be of certain type

I use the new Temporal proposal (one of the polyfills). Ideally I would like to set up a mapper so every query parameter would correctly map Temporal.PlainDateTime to timestamp (the one without a timezone). Not as a column type, but as a query Parameter type. I believe one can do it for the underlying postgres.js using their .types option to create a custom driver type mapping. But I could not find anything on the drizzle client. Right now it seems like zoneless timestamp parameters passed as strings get their time zones guessed depending on a system time zone and I get different results on my local machine vs a cloud server. Any ideas how to force the parameter type in drizzle?
1 Reply
Davepar
Davepar6mo ago
This is how I defined a custom type that converts Postgres timestamp to Temporal.PlainDateTime:
const temporalTimestamp = customType<{
data: Temporal.PlainDateTime;
driverData: string;
config?: { precision: number };
}>({
dataType(config) {
return `timestamp(${config?.precision ?? 0})`;
},
fromDriver(value: string): Temporal.PlainDateTime {
// This hack is for Drizzle Studio, which seems to always convert timestamps to Dates.
if ((value as unknown as Date).toISOString) {
value = (value as unknown as Date).toISOString().slice(0, -1);
}
return Temporal.PlainDateTime.from(value);
},
toDriver(value: Temporal.PlainDateTime): string {
return value.toString() + 'Z';
},
});
const temporalTimestamp = customType<{
data: Temporal.PlainDateTime;
driverData: string;
config?: { precision: number };
}>({
dataType(config) {
return `timestamp(${config?.precision ?? 0})`;
},
fromDriver(value: string): Temporal.PlainDateTime {
// This hack is for Drizzle Studio, which seems to always convert timestamps to Dates.
if ((value as unknown as Date).toISOString) {
value = (value as unknown as Date).toISOString().slice(0, -1);
}
return Temporal.PlainDateTime.from(value);
},
toDriver(value: Temporal.PlainDateTime): string {
return value.toString() + 'Z';
},
});
All timestamps in my db are UTC, so I don't store timezone. It's working great so far, but notice the hack to get around a bug in Drizzle Studio. It seems to always convert db timestamps to js Date type.
Want results from more Discord servers?
Add your server