DT
Drizzle Team•15mo ago
volks

Raw sql nullable types, sql<Type | undefined>

const result = await db.select({
customField: sql<Type | null>`...`
const result = await db.select({
customField: sql<Type | null>`...`
This gets inferred to SQL<any> Is there a way to have a nullable type when using raw sql?
6 Replies
bloberenober
bloberenober•15mo ago
yes, it should use the exact type passed as the generic could you post your whole query and the definition of Type?
volks
volks•15mo ago
Sorry, mistook the issue a bit, it seems that without the .mapWith() its inferred properly, but if its mapped then it is always non-nullable. Probably a niche situation but still a bit unusual, here's my whole thing
destination: sql<Point | null>`CASE WHEN driver_shifts.ride_id IS NOT NULL THEN active_rides.destination END`.mapWith(driverShifts.location),
destination: sql<Point | null>`CASE WHEN driver_shifts.ride_id IS NOT NULL THEN active_rides.destination END`.mapWith(driverShifts.location),
Type (property) destination: SQL<Point> But if I remove the mapWith It correctly is inferred to (property) destination: SQL<Point | null>
export const driverShifts = pgTable('driver_shifts', {
id: uuid('id').primaryKey().defaultRandom(),
createdAt: timestamp('created_at').defaultNow().notNull(),
location: pointDB("location").notNull(),
});
export const driverShifts = pgTable('driver_shifts', {
id: uuid('id').primaryKey().defaultRandom(),
createdAt: timestamp('created_at').defaultNow().notNull(),
location: pointDB("location").notNull(),
});
The pointDB is a custom PGColumn. But I don't think I can pass it to mapWith but rather I have to use a column from the table, this is a seperate question, don't think its related to the above problem
bloberenober
bloberenober•15mo ago
OK I see - this is an edge case I didn't think about We automatically assign the result type when you call .mapWith based on the mapper return type So the fastest fix on your side would be to make a custom mapper function that returns a nullable result, and pass it into mapWith something like
function mapper(value: any): Point | null {
return driverShifts.location.mapFromDriverValue(value);
}

.mapWith(mapper)
function mapper(value: any): Point | null {
return driverShifts.location.mapFromDriverValue(value);
}

.mapWith(mapper)
volks
volks•15mo ago
Yeah quite a niche situation, glad I caught it. Thanks @Dan Kochetov Will you create an issue on GH if this warrants one? I would like to follow it
bloberenober
bloberenober•15mo ago
You can create it yourself if you'd like 🙂
volks
volks•15mo ago
GitHub
[FEATURE]: Nullable type inference with .mapWith() · Issue #571 · d...
Describe want to want Description When using .mapWith(), nullable type inference is not being properly handled. Without the .mapWith(), the type is inferred correctly, but when it's mapped, the...