Skip to content

Instantly share code, notes, and snippets.

@kidqueb
Last active October 10, 2024 09:16
Show Gist options
  • Save kidqueb/59d84b2280ff4e26d72206631e284e3e to your computer and use it in GitHub Desktop.
Save kidqueb/59d84b2280ff4e26d72206631e284e3e to your computer and use it in GitHub Desktop.
json agg for drizzle
export function jsonAgg<T extends Record<string, AnyColumn>>(select: T) {
const chunks: SQL[] = [];
Object.entries(select).forEach(([key, column], index) => {
if (index > 0) chunks.push(sql`,`);
chunks.push(sql.raw(`'${key}',`), sql`${column}`);
});
return sql<InferColumnsDataTypes<T>[]>`
coalesce(
json_agg(json_build_object(${sql.fromList(chunks)})),
'[]'
)
`;
}
@Gardego5
Copy link

Thanks! I found this helpful!

Here's similar (but for sqlite) that infers with a Record<string, AnyColumn> or a Table
https://gist.github.com/Gardego5/b5e1bccdba5217f8507283b567b5605a

@iyxan23
Copy link

iyxan23 commented Oct 10, 2024

Hi, I noticed that sql.fromList is deprecated in newer drizzle versions, so we need to replace it with sql.join instead, as described by the docs:

-      json_agg(json_build_object(${sql.fromList(chunks)})),
+      json_agg(json_build_object(${sql.join(chunks)})),

Thank you for making this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment