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

fix sticky parent tables #168

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
22 changes: 22 additions & 0 deletions src/db/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,28 @@ export class SQLFragment<RunResult = pg.QueryResult['rows'], Constraint = never>

constructor(protected literals: string[], protected expressions: SQL[]) { }

/**
* Performs a shallow copy of this SQLFragment, optionally overriding some of its properties.
* @param override The properties to override
*/
copy(override?: {
literals?: string[];
expressions?: SQL[];
parentTable?: string;
preparedName?: string;
noop?: boolean;
noopResult?: any;
}): SQLFragment<RunResult, Constraint> {
const { literals = this.literals, expressions = this.expressions, ...overrideRest } = override ?? {};
const copy = new SQLFragment<RunResult, Constraint>(literals, expressions);
return Object.assign(copy, {
parentTable: this.parentTable,
preparedName: this.preparedName,
noop: this.noop,
noopResult: this.noopResult
}, overrideRest);
}

/**
* Instruct Postgres to treat this as a prepared statement: see
* https://node-postgres.com/features/queries#prepared-statements
Expand Down
7 changes: 3 additions & 4 deletions src/db/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,12 +542,11 @@ export const select: SelectSignatures = function (
}),
lateralSQL = lateral === undefined ? [] :
lateral instanceof SQLFragment ? (() => {
lateral.parentTable = alias;
return sql` LEFT JOIN LATERAL (${lateral}) AS "lateral_passthru" ON true`;
return sql` LEFT JOIN LATERAL (${lateral.copy({ parentTable: alias })}) AS "lateral_passthru" ON true`;
})() :
Object.keys(lateral).sort().map(k => {
const subQ = lateral[k];
subQ.parentTable = alias; // enables `parent('column')` in subquery's Whereables
/// enables `parent('column')` in subquery's Whereables
const subQ = lateral[k].copy({ parentTable: alias });
return sql` LEFT JOIN LATERAL (${subQ}) AS "lateral_${raw(k)}" ON true`;
});

Expand Down