Skip to content

Instantly share code, notes, and snippets.

@mpellegrini
Created August 28, 2024 21:27
Show Gist options
  • Save mpellegrini/5f195e5e4f8ad0698b685e180a474eea to your computer and use it in GitHub Desktop.
Save mpellegrini/5f195e5e4f8ad0698b685e180a474eea to your computer and use it in GitHub Desktop.
Drizzle Utility Functions
import { type AnyColumn, type SQL, sql } from 'drizzle-orm'
/**
* The Coalesce function evaluates the arguments in the specified order
* and always returns the first non-null value from the argument list.
*
* @template T - The type of the value being coalesced.
* @param args - The value to be coalesced.
* @returns - The SQL expression representing the coalesced value.
*/
export const coalesce = <T>(
...args: (AnyColumn | SQL.Aliased<T> | SQL<T> | T)[]
): SQL<T | null> => {
const sqlArgs = args.map((arg) => sql`${arg}`)
return sql`coalesce(${sql.join(sqlArgs, sql.raw(','))})`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment