Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change from json_agg to array() #2267

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions grafast/dataplan-pg/src/steps/pgSelect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ export interface PgSelectOptions<
joinAsLateral?: boolean;
}

function withIndexes(frag: SQL, idx: number) {
return sql`${frag} as ${sql.identifier(String(idx))}`;
}

/**
* This represents selecting from a class-like entity (table, view, etc); i.e.
* it represents `SELECT <attributes>, <cursor?> FROM <table>`. You can also add
Expand Down Expand Up @@ -1430,27 +1434,30 @@ and ${sql.indent(sql.parens(condition(i + 1)))}`}
private buildSelect(
options: {
extraSelects?: readonly SQL[];
asJsonAgg?: boolean;
} = Object.create(null),
) {
const { extraSelects = EMPTY_ARRAY } = options;
const selects = [...this.selects, ...extraSelects];
const l = this.selects.length;
const extraSelectIndexes = extraSelects.map((_, i) => i + l);

const fragmentsWithAliases = selects.map(
(frag, idx) => sql`${frag} as ${sql.identifier(String(idx))}`,
);

const sqlAliases: SQL[] = [];
for (const [a, b] of this._symbolSubstitutes.entries()) {
sqlAliases.push(sql.symbolAlias(a, b));
}
const aliases = sql.join(sqlAliases, "");

const selection =
fragmentsWithAliases.length > 0
? sql`\n${sql.indent(sql.join(fragmentsWithAliases, ",\n"))}`
: sql` /* NOTHING?! */`;
const selection = options.asJsonAgg
? selects.length === 0
? // Postgres "cannot accumulate empty arrays"
sql`\n${sql.indent`array[null::text]`}`
: sql`\n${sql.indent`array[${sql.indent(
sql.join(selects, ",\n"),
)}]::text[]`}`
: selects.length > 0
? sql`\n${sql.indent(sql.join(selects.map(withIndexes), ",\n"))}`
: sql` /* NOTHING?! */`;

return { sql: sql`${aliases}select${selection}`, extraSelectIndexes };
}
Expand Down Expand Up @@ -1837,7 +1844,7 @@ and ${sql.indent(sql.parens(condition(i + 1)))}`}
const baseQuery = sql`${select}${from}${join}${where}${groupBy}${having}${orderBy}${limitAndOffset}`;
const query = options.asJsonAgg
? // 's' for 'subquery'
sql`select json_agg(s) from (${sql.indent(baseQuery)}) s`
sql`array(${sql.indent(baseQuery)})::text`
: baseQuery;

return { sql: query, extraSelectIndexes };
Expand Down
Loading