helpers.ts30 lines · main
| 1 | import { ident, joinSqlFragments, literal, safeSql, type SafeSqlFragment } from './pg-format' |
| 2 | |
| 3 | export const coalesceRowsToArray = (source: string, filter: SafeSqlFragment) => { |
| 4 | return safeSql` |
| 5 | COALESCE( |
| 6 | ( |
| 7 | SELECT |
| 8 | array_agg(row_to_json(${ident(source)})) FILTER (WHERE ${filter}) |
| 9 | FROM |
| 10 | ${ident(source)} |
| 11 | ), |
| 12 | '{}' |
| 13 | ) AS ${ident(source)}` |
| 14 | } |
| 15 | |
| 16 | export function filterByList(include?: string[], exclude?: string[], defaultExclude?: string[]) { |
| 17 | if (defaultExclude) { |
| 18 | exclude = defaultExclude.concat(exclude ?? []) |
| 19 | } |
| 20 | if (include?.length) { |
| 21 | return safeSql`IN (${joinSqlFragments(include.map(literal), ',')})` |
| 22 | } else if (exclude?.length) { |
| 23 | return safeSql`NOT IN (${joinSqlFragments(exclude.map(literal), ',')})` |
| 24 | } |
| 25 | return safeSql`` |
| 26 | } |
| 27 | |
| 28 | export function exceptionIdentifierNotFound(entityName: string, whereClause: string) { |
| 29 | return safeSql`raise exception 'Cannot find ${ident(entityName)} with: %', ${literal(whereClause)};` |
| 30 | } |