drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[FEATURE]: Coalesce helper

Open acontreras89 opened this issue 11 months ago • 9 comments

Feature hasn't been suggested before.

  • [X] I have verified this feature I'm about to request hasn't been suggested before.

Describe the enhancement you want to request

It would be handy to have a coalesce helper, same as we have for count, distinct or min.

This is what I'm using right now:

function coalesce<C extends Column>(
  column: C,
  defaultValue: C['_']['data'] | AnyColumn<{ data: C['_']['data'] }>
): SQL<C['_']['data']> {
  return sql`coalesce(${column}, ${defaultValue})`.mapWith(column)
}

This covers most basic cases where we want to provide a default value for a column or use a fallback column. However, it would need some extra tweaking to properly handle nullability of the second column when provided.

The function could be overloaded like this:

function coalesce<
  C1 extends Column,
  C2 extends AnyColumn<{ data: C1['_']['data'] }>
>(
  column: C1,
  defaultValue: C2
): SQL<
  C2 extends AnyColumn<{ notNull: true }>
    ? C1['_']['data']
    : C1['_']['data'] | null
>

But this wouldn't account for columns coming out of left/right joins, which could be null even if not nullable.

Also, more complex scenarios like coalescing an arbitrary number of columns are challenging, since we cannot easily pass arbitrary values to sql. We would need something like this:

// NOTE types removed for simplicity
function coalesce(...expressions: any[]) {
  const templateStringsArray = [
    'coalesce(',
    ...new Array(expressions.length - 1).fill(', '),
    ')',
  ] as unknown as TemplateStringsArray

  return sql(templateStringsArray, ...expressions)
}

acontreras89 avatar Dec 07 '24 00:12 acontreras89

Yes!

Would be cool in the cases of updating a field only if the field is null/empty

Using something like this but as you can see it loses the type safety.

name: req.name
            ? sql`COALESCE(NULLIF(users.name, ''), ${req.name})`
            : undefined,

hls-app avatar Jan 05 '25 03:01 hls-app

COALESCE is important basic functionality of Postgres. I hope it gets integrated soon!

Very useful e.g. for fallback translations "get text for locale DE if not null, otherise get fallback DE".

@acontreras89 You can type sql, should work with the generic: sql<T>

MickL avatar Feb 11 '25 15:02 MickL

can't believe this isn't supported ?

waml avatar Mar 30 '25 17:03 waml

can't believe this isn't supported ?

This is supported. The PR adds a helper for convenience, but you can use the sql helper for this and pretty much any other case. Or you can copy the code in the description if you prefer.

acontreras89 avatar Mar 31 '25 14:03 acontreras89

Using sql to me feels like it is not supported

MickL avatar Mar 31 '25 14:03 MickL

This is supported.

@acontreras89 Would you mind to provide a link to the documentation where this is explained?

Image

alexey-sh avatar Apr 14 '25 20:04 alexey-sh

I recommend https://github.com/emmnull/drizzle-orm-helpers if you'd like this helper.

candidia avatar Apr 15 '25 21:04 candidia

can be done with sql as well,

Earlier select block


    .select({
      userId: quizParticipants.userId,
      totalPrizeAmount: sum(quizParticipants.prizeAmount).as('total_prize_amount'),
      totalPoints: sum(quizParticipants.pointsEarned).as('total_points'),
      totalQuestionsCorrect: sum(quizParticipants.questionsCorrect).as('total_questions_correct'),
      totalQuestionsIncorrect: sum(quizParticipants.questionsIncorrect).as('total_questions_incorrect'),
      quizzesParticipated: count().as('quizzes_participated'),
      name: profile.name,
      image: profile.image,
    })

with Coalesce

    .select({
      userId: quizParticipants.userId,
      totalPrizeAmount: sql`coalesce(sum(${quizParticipants.prizeAmount}), 0)  as total_prize_amount`,
      totalPoints: sql`coalesce(sum(${quizParticipants.pointsEarned}), 0) as total_points`,
      totalQuestionsCorrect: sql`coalesce(sum(${quizParticipants.questionsCorrect}), 0) as total_questions_correct`,
      totalQuestionsIncorrect: sql`coalesce(sum(${quizParticipants.questionsIncorrect}), 0) as total_questions_incorrect`,
      quizzesParticipated: count().as('quizzes_participated'),
      name: profile.name,
      image: profile.image,
    })

abhishekhugetech avatar Apr 23 '25 03:04 abhishekhugetech

Isnt the whole purpose of an orm NOT to write sql?

MickL avatar Apr 23 '25 09:04 MickL

This is what I came up with:

  • Enforce same column data types or sql types
  • Infer resulting sql datatype

Example usage:

db.select({
   something: coalesce(table1.name1, table1.name2, sql<string>`unknown`),
   something: coalesce(table1.age1, table1.age2, 99),
})
import type { PgColumn } from "drizzle-orm/pg-core";
import type { ColumnBaseConfig, ColumnDataType, SQL } from "drizzle-orm";

type ColumnDataTypeToTSType<T extends ColumnDataType> = T extends "string"
	? string
	: T extends "number"
		? number
		: T extends "boolean"
			? boolean
			: never;

export function coalesce<TDataType extends ColumnDataType>(
	...columns: (
		| PgColumn<ColumnBaseConfig<TDataType, string>>
		| SQL<ColumnDataTypeToTSType<TDataType>>
                | ColumnDataTypeToTSType<TDataType>
	)[]
): SQL<ColumnDataTypeToTSType<TDataType> | null> {
	const sqlArgs = sql.join(
		columns.map((a) => sql`${a}`),
		sql.raw(","),
	);
	return sql`coalesce(${sqlArgs})`;
}

For now I only support string, number and booleans in ColumnDataTypeToTSType. But can be extended...

lasseklovstad avatar Jul 04 '25 06:07 lasseklovstad

This is what I came up with:

  • Enforce same column data types or sql types
  • Infer resulting sql datatype

Example usage:

db.select({ something: coalesce(table1.name1, table1.name2, sqlunknown), something: coalesce(table1.age1, table1.age2, 99), }) import type { PgColumn } from "drizzle-orm/pg-core"; import type { ColumnBaseConfig, ColumnDataType, SQL } from "drizzle-orm";

type ColumnDataTypeToTSType<T extends ColumnDataType> = T extends "string" ? string : T extends "number" ? number : T extends "boolean" ? boolean : never;

export function coalesce<TDataType extends ColumnDataType>( ...columns: ( | PgColumn<ColumnBaseConfig<TDataType, string>> | SQL<ColumnDataTypeToTSType<TDataType>> | ColumnDataTypeToTSType<TDataType> )[] ): SQL<ColumnDataTypeToTSType<TDataType> | null> { const sqlArgs = sql.join( columns.map((a) => sql${a}), sql.raw(","), ); return sqlcoalesce(${sqlArgs}); } For now I only support string, number and booleans in ColumnDataTypeToTSType. But can be extended...

thanks for sharing this

Cavdy avatar Aug 15 '25 16:08 Cavdy

Any plans for this?

princeeze avatar Aug 20 '25 11:08 princeeze

Hey everyone!

I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.

I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!

We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.


First branch is drizzle-kit rewrite

All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439

As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.

What's left here:

  • We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the srid issue here as well).
  • We are finishing commutative migrations for all dialects.
  • We are finishing up the command, so the migration flow will be as simple as drizzle-kit up for you.

Where it brings us:

  • We are getting drizzle-kit into a new good shape where we can call it [email protected]!

Timeline:

  • We need ~2 weeks to finish all of the above and send this branch to beta for testing.

Second big branch is a complex one with several HUGE updates

  • Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)

TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k

You can read more about it here.

What's left here:

Where it brings us:

  • We are getting drizzle-orm into a new good shape where we can call it [email protected]!

Breaking changes:

  • We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.

Third branch is adding support for CockroachDB and MSSQL dialects

Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.

Summary

All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.

We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).

We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.

Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!

Timelines

We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!

AndriiSherman avatar Aug 30 '25 18:08 AndriiSherman

here is a simpler implementation, supporting any column type and properly removing null where necessary.

import { sql, type SQL, type Column, type GetColumnData } from "drizzle-orm";

type AnySql = SQL | Column;
type Coalesce<Array extends AnySql[]> = Array extends [...infer Optionals, infer Last]
  ? Exclude<ExtractSqlType<Optionals[number]>, null | undefined> | ExtractSqlType<Last>
  : never;
type ExtractSqlType<S> = S extends SQL<infer T> ? T : S extends Column ? GetColumnData<S, "query"> : never;

export function coalesce<Args extends [AnySql, AnySql, ...AnySql[]]>(...args: Args) {
  return sql<Coalesce<Args>>`coalesce(${sql.join(args.map((a) => sql`${a}`), sql.raw(","))})`;
}

the type [T, T, ...T[]] forces at least two arguments, and captures all of them into the generic Args. then, Coalesce unpacks the last element off for its special handling, using ExtractSqlType to pull out the underlying type.

paperclover avatar Sep 11 '25 21:09 paperclover