Last active
March 13, 2024 15:56
-
-
Save Gardego5/b5e1bccdba5217f8507283b567b5605a to your computer and use it in GitHub Desktop.
DrizzleORM SQLite JsonAgg inference with function overload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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