Skip to content

Instantly share code, notes, and snippets.

@Gardego5
Last active March 13, 2024 15:56
Show Gist options
  • Save Gardego5/b5e1bccdba5217f8507283b567b5605a to your computer and use it in GitHub Desktop.
Save Gardego5/b5e1bccdba5217f8507283b567b5605a to your computer and use it in GitHub Desktop.
DrizzleORM SQLite JsonAgg inference with function overload
import { AnyColumn, InferColumnsDataTypes, SQL, Table, sql } from "drizzle-orm";
export function jsonAgg<T extends Record<string, AnyColumn>>(select: T): SQL<InferColumnsDataTypes<T>[]>;
export function jsonAgg<T extends Table>(select: T): SQL<T["$inferSelect"][]>;
export function jsonAgg<T extends Record<string, AnyColumn> | Table>(select: T) {
const chunks: SQL[] = [];
var notNullColumn;
Object.entries(select).forEach(([key, column], index) => {
if (index > 0) {
chunks.push(sql`,`);
} else {
notNullColumn = column;
}
chunks.push(sql.raw(`'${key}',`), sql`${column}`);
});
if (!notNullColumn) throw new Error("No columns in select for jsonAgg");
return sql<string>`COALESCE(JSON_GROUP_ARRAY(JSON_OBJECT(${sql.join(chunks)}))
FILTER (WHERE ${notNullColumn} IS NOT NULL),'[]')`
.mapWith(JSON.parse);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment