joist-core 2.5.0-next.1 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/queries/find/QueryParser.cjs +7 -18
- package/build/queries/find/QueryParser.cjs.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.cjs +1 -2
- package/build/queries/find/QueryParser.collectionJoins.cjs.map +1 -1
- package/build/queries/find/QueryParser.collectionJoins.js +1 -2
- package/build/queries/find/QueryParser.collectionJoins.js.map +1 -1
- package/build/queries/find/QueryParser.d.cts +0 -21
- package/build/queries/find/QueryParser.d.cts.map +1 -1
- package/build/queries/find/QueryParser.d.mts +0 -21
- package/build/queries/find/QueryParser.d.mts.map +1 -1
- package/build/queries/find/QueryParser.js +7 -18
- package/build/queries/find/QueryParser.js.map +1 -1
- package/build/queries/find/QueryParser.pruning.cjs +1 -50
- package/build/queries/find/QueryParser.pruning.cjs.map +1 -1
- package/build/queries/find/QueryParser.pruning.d.cts +1 -14
- package/build/queries/find/QueryParser.pruning.d.cts.map +1 -1
- package/build/queries/find/QueryParser.pruning.d.mts +1 -14
- package/build/queries/find/QueryParser.pruning.d.mts.map +1 -1
- package/build/queries/find/QueryParser.pruning.js +1 -50
- package/build/queries/find/QueryParser.pruning.js.map +1 -1
- package/package.json +2 -2
|
@@ -3,21 +3,7 @@ const require_queries_parsedConditions = require("../parsedConditions.cjs");
|
|
|
3
3
|
const require_queries_find_QueryParser = require("./QueryParser.cjs");
|
|
4
4
|
const require_utils = require("../../utils.cjs");
|
|
5
5
|
//#region src/queries/find/QueryParser.pruning.ts
|
|
6
|
-
|
|
7
|
-
* Removes unused joins and their optional conditions from the query in place.
|
|
8
|
-
*
|
|
9
|
-
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
10
|
-
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
11
|
-
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
12
|
-
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
13
|
-
*
|
|
14
|
-
* @param parsed The query to mutate.
|
|
15
|
-
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
16
|
-
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
17
|
-
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
18
|
-
*/
|
|
19
|
-
function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ new Set()) {
|
|
20
|
-
pruneIdOnlyJoins(parsed, keepAliases, /* @__PURE__ */ new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]));
|
|
6
|
+
function pruneUnusedJoins(parsed, keepAliases) {
|
|
21
7
|
const dt = new DependencyTracker();
|
|
22
8
|
const todo = [...parsed.tables];
|
|
23
9
|
while (todo.length > 0) {
|
|
@@ -69,41 +55,6 @@ function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ n
|
|
|
69
55
|
});
|
|
70
56
|
if (parsed.condition && parsed.condition.conditions.length === 0) parsed.condition = void 0;
|
|
71
57
|
}
|
|
72
|
-
/**
|
|
73
|
-
* Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.
|
|
74
|
-
*
|
|
75
|
-
* Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS
|
|
76
|
-
* on the join table, with no otherTable join left to optimize. Positive branches can still contain
|
|
77
|
-
* otherTable joins; this pass replaces their id conditions and makes those joins removable.
|
|
78
|
-
*
|
|
79
|
-
* If a collection remains a LEFT JOIN, replace its id conditions the same way: for
|
|
80
|
-
* `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,
|
|
81
|
-
* replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.
|
|
82
|
-
* When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,
|
|
83
|
-
* so the replacement also preserves conditions that accept missing memberships.
|
|
84
|
-
*/
|
|
85
|
-
function pruneIdOnlyJoins(query, keepAliases, visibleCtes) {
|
|
86
|
-
const conditions = require_queries_parsedConditions.deepFindConditions(query.condition, false);
|
|
87
|
-
for (const condition of conditions) if (condition.kind === "exists") pruneUnusedJoins(condition.subquery, [], visibleCtes);
|
|
88
|
-
for (const table of query.tables) if (table.join === "lateral") pruneUnusedJoins(table.query, [], visibleCtes);
|
|
89
|
-
for (const otherTable of query.tables) {
|
|
90
|
-
if (otherTable.join !== "inner" && otherTable.join !== "outer") continue;
|
|
91
|
-
const joinTable = query.tables.find((t) => "idJoin" in t && t.idJoin?.alias === otherTable.alias);
|
|
92
|
-
const idJoin = joinTable && "idJoin" in joinTable ? joinTable.idJoin : void 0;
|
|
93
|
-
if (visibleCtes.has(otherTable.table)) continue;
|
|
94
|
-
if (!joinTable || !idJoin || otherTable.table !== idJoin.table || otherTable.col1 !== idJoin.col1 || otherTable.col2 !== idJoin.col2) continue;
|
|
95
|
-
const alias = otherTable.alias;
|
|
96
|
-
if (keepAliases.includes(alias)) continue;
|
|
97
|
-
if (query.selects.some((s) => typeof s === "string" ? selectReferencesAlias(s, alias) : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias))) continue;
|
|
98
|
-
if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) continue;
|
|
99
|
-
if (query.tables.some((t) => t !== otherTable && (t.join === "lateral" || (t.join === "inner" || t.join === "outer") && joinDependencies(t).includes(alias)))) continue;
|
|
100
|
-
if (conditions.some((c) => c.kind === "column" ? c.alias === alias && c.column !== "id" : c.kind === "raw" ? c.aliases.includes(alias) : c.outerAliases.includes(alias))) continue;
|
|
101
|
-
for (const condition of conditions) if (condition.kind === "column" && condition.alias === alias) {
|
|
102
|
-
condition.alias = joinTable.alias;
|
|
103
|
-
condition.column = idJoin.fkColumn;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
58
|
/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */
|
|
108
59
|
function joinDependencies(t) {
|
|
109
60
|
return [require_queries_find_QueryParser.parseAlias(t.col1), require_queries_find_QueryParser.parseAlias(t.col2)].filter((alias) => alias !== t.alias);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.cjs","names":["deepFindConditions","parseAlias"],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n/**\n * Removes unused joins and their optional conditions from the query in place.\n *\n * First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,\n * including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,\n * allowing the `tags t` join to be removed when nothing else reads it. This uses the final\n * table names, join columns, and alias usages after plugins and collection rewriting.\n *\n * @param parsed The query to mutate.\n * @param keepAliases Aliases to retain even when the query has no explicit reference to them.\n * @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names\n * so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.\n */\nexport function pruneUnusedJoins(\n parsed: ParsedFindQuery,\n keepAliases: string[],\n inheritedCtes: ReadonlySet<string> = new Set(),\n): void {\n const visibleCtes = new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]);\n pruneIdOnlyJoins(parsed, keepAliases, visibleCtes);\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/**\n * Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.\n *\n * Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS\n * on the join table, with no otherTable join left to optimize. Positive branches can still contain\n * otherTable joins; this pass replaces their id conditions and makes those joins removable.\n *\n * If a collection remains a LEFT JOIN, replace its id conditions the same way: for\n * `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,\n * replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.\n * When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,\n * so the replacement also preserves conditions that accept missing memberships.\n */\nfunction pruneIdOnlyJoins(query: ParsedFindQuery, keepAliases: string[], visibleCtes: ReadonlySet<string>): void {\n const conditions = deepFindConditions(query.condition, false);\n // Each subquery needs the full pruning pass: substituting `t.id` with `att.tag_id` alone\n // leaves the unused `tags t` join in its FROM list. The enclosing query's dependency tracker\n // cannot remove joins from a subquery, so recurse through pruneUnusedJoins, not just this helper.\n for (const condition of conditions) {\n if (condition.kind === \"exists\") pruneUnusedJoins(condition.subquery, [], visibleCtes);\n }\n for (const table of query.tables) {\n if (table.join === \"lateral\") pruneUnusedJoins(table.query, [], visibleCtes);\n }\n for (const otherTable of query.tables) {\n // Primary, cross, and lateral tables are not otherTable joins eligible for FK substitution.\n if (otherTable.join !== \"inner\" && otherTable.join !== \"outer\") {\n continue;\n }\n\n // I.e. otherTable is `tags t`; its marker is on the m2m table `authors_to_tags att`.\n const joinTable = query.tables.find((t) => \"idJoin\" in t && t.idJoin?.alias === otherTable.alias);\n const idJoin = joinTable && \"idJoin\" in joinTable ? joinTable.idJoin : undefined;\n\n // A visible `WITH tags AS (...)` changes what `JOIN tags` reads, including inside nested EXISTS.\n // Keep this join to apply the CTE's restrictions; unrelated CTEs do not affect the FK guarantee.\n if (visibleCtes.has(otherTable.table)) {\n continue;\n }\n\n // The parser did not mark this join as eligible, or a plugin changed otherTable/the ON clause.\n // Keep the join because reading its id may now filter rows differently from reading the join-table FK.\n if (\n !joinTable ||\n !idJoin ||\n otherTable.table !== idJoin.table ||\n otherTable.col1 !== idJoin.col1 ||\n otherTable.col2 !== idJoin.col2\n ) {\n continue;\n }\n\n const alias = otherTable.alias;\n // The caller explicitly needs this alias even if no visible expression reads it.\n if (keepAliases.includes(alias)) {\n continue;\n }\n\n // A projection reads the otherTable row; rewriting only its conditions would not remove the lookup.\n if (\n query.selects.some((s) =>\n typeof s === \"string\"\n ? selectReferencesAlias(s, alias)\n : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias),\n )\n ) {\n continue;\n }\n\n // Ordering by otherTable still needs the join. Grouped queries are conservatively excluded because\n // this pass does not establish whether substitution preserves their grouping semantics.\n if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) {\n continue;\n }\n\n // Another join depends on this alias, or a lateral query may reference it in its own scope.\n // Keep otherTable rather than leaving a dangling reference; lateral usages are not analyzed here.\n if (\n query.tables.some(\n (t) =>\n t !== otherTable &&\n (t.join === \"lateral\" || ((t.join === \"inner\" || t.join === \"outer\") && joinDependencies(t).includes(alias))),\n )\n ) {\n continue;\n }\n\n // A condition reads another otherTable column, raw SQL references the alias, or EXISTS correlates\n // through it. Those usages cannot be satisfied by replacing otherTable-id column conditions alone.\n if (\n conditions.some((c) =>\n c.kind === \"column\"\n ? c.alias === alias && c.column !== \"id\"\n : c.kind === \"raw\"\n ? c.aliases.includes(alias)\n : c.outerAliases.includes(alias),\n )\n ) {\n continue;\n }\n\n // Now redirect all conditions on otherTable.id to joinTable's FK, keeping their operators and bindings.\n // I.e. `t.id IN (...)` becomes `att.tag_id IN (...)`. Nothing else reads otherTable after the checks\n // above, so pruneUnusedJoins can remove its now-unused join after this helper returns.\n for (const condition of conditions) {\n if (condition.kind === \"column\" && condition.alias === alias) {\n condition.alias = joinTable.alias;\n condition.column = idJoin.fkColumn;\n }\n }\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBACd,QACA,aACA,gCAAqC,IAAI,IAAI,GACvC;CAEN,iBAAiB,QAAQ,6BAAa,IADd,IAAI,CAAC,GAAG,eAAe,IAAI,OAAO,QAAQ,CAAC,EAAA,CAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,CAC7C,CAAC;CACjD,MAAM,KAAK,IAAI,kBAAkB;CAGjC,MAAM,OAAO,CAAC,GAAG,OAAO,MAAM;CAC9B,OAAO,KAAK,SAAS,GAAG;EACtB,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,EAAE,SAAS,WAAW;GACxB,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC;GAElC,KAAK,KAAK,GAAG,EAAE,MAAM,MAAM;EAC7B,OAAO,IAAI,EAAE,SAAS,SACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,EAAE,SAAS,WACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,OAAO,MAAM,MAAM,QAAQ,IAAI,UAAU,EAAE,KAAK,GAAG;GAC5D,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;GACxC,GAAG,aAAa,EAAE,KAAK;EACzB,OACE,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;CA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B,UAAW,aAAa,QAAO,SAAS,OAEzC,OAAO;EAGT,QAAQ,OAAO,QAAQ,WAAW,QAAQ,UAAU,MAAM;CAC5D;CACA,OAAO;AACT;;AAGA,SAAS,oBAAoB,MAAmC;CAC9D,OAAO,SAAS,KAAA,KAAa,eAAe,KAAK,IAAI;AACvD;;AAGA,IAAM,oBAAN,MAAwB;CACtB,wBAAuC,IAAI,IAAI;CAC/C,2BAAwB,IAAI,IAAI;CAEhC,SAAS,OAAe,eAAyB,CAAC,GAAS;EACzD,KAAK,MAAM,IAAI,OAAO,YAAY;CACpC;CAEA,aAAa,OAAqB;EAChC,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,CAAC,KAAK;EACnB,OAAO,KAAK,SAAS,GAAG;GACtB,MAAM,QAAQ,KAAK,IAAI;GACvB,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG;IACtB,OAAO,IAAI,KAAK;IAChB,KAAK,KAAK,GAAI,KAAK,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;GAC5C;EACF;EACA,KAAK,2BAAW,IAAI,IAAI,CAAC,GAAG,KAAK,UAAU,GAAG,MAAM,CAAC;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.cjs","names":["parseAlias"],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n// Remove any joins that are not used in the select or conditions\nexport function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void {\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;AAKA,SAAgB,iBAAiB,QAAyB,aAA6B;CACrF,MAAM,KAAK,IAAI,kBAAkB;CAGjC,MAAM,OAAO,CAAC,GAAG,OAAO,MAAM;CAC9B,OAAO,KAAK,SAAS,GAAG;EACtB,MAAM,IAAI,KAAK,IAAI;EACnB,IAAI,EAAE,SAAS,WAAW;GACxB,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC;GAElC,KAAK,KAAK,GAAG,EAAE,MAAM,MAAM;EAC7B,OAAO,IAAI,EAAE,SAAS,SACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,EAAE,SAAS,WACpB,GAAG,aAAa,EAAE,KAAK;OAClB,IAAI,OAAO,MAAM,MAAM,QAAQ,IAAI,UAAU,EAAE,KAAK,GAAG;GAC5D,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;GACxC,GAAG,aAAa,EAAE,KAAK;EACzB,OACE,GAAG,SAAS,EAAE,OAAO,iBAAiB,CAAC,CAAC;CAE5C;CAGA,OA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AN,MAAwB;CACtB,wBAAuC,IAAI,IAAI;CAC/C,2BAAwB,IAAI,IAAI;CAEhC,SAAS,OAAe,eAAyB,CAAC,GAAS;EACzD,KAAK,MAAM,IAAI,OAAO,YAAY;CACpC;CAEA,aAAa,OAAqB;EAChC,MAAM,yBAAS,IAAI,IAAY;EAC/B,MAAM,OAAO,CAAC,KAAK;EACnB,OAAO,KAAK,SAAS,GAAG;GACtB,MAAM,QAAQ,KAAK,IAAI;GACvB,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG;IACtB,OAAO,IAAI,KAAK;IAChB,KAAK,KAAK,GAAI,KAAK,MAAM,IAAI,KAAK,KAAK,CAAC,CAAE;GAC5C;EACF;EACA,KAAK,2BAAW,IAAI,IAAI,CAAC,GAAG,KAAK,UAAU,GAAG,MAAM,CAAC;CACvD;AACF"}
|
|
@@ -1,19 +1,6 @@
|
|
|
1
1
|
import { ParsedFindQuery } from "./QueryParser.cjs";
|
|
2
2
|
//#region src/queries/find/QueryParser.pruning.d.ts
|
|
3
|
-
|
|
4
|
-
* Removes unused joins and their optional conditions from the query in place.
|
|
5
|
-
*
|
|
6
|
-
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
7
|
-
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
8
|
-
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
9
|
-
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
10
|
-
*
|
|
11
|
-
* @param parsed The query to mutate.
|
|
12
|
-
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
13
|
-
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
14
|
-
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
15
|
-
*/
|
|
16
|
-
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[], inheritedCtes?: ReadonlySet<string>): void;
|
|
3
|
+
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void;
|
|
17
4
|
/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */
|
|
18
5
|
export declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
19
6
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.d.cts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.d.cts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":";;wBAKgB,iBAAiB,QAAQ,iBAAiB;;wBAkG1C,sBAAsB,gBAAgB"}
|
|
@@ -1,19 +1,6 @@
|
|
|
1
1
|
import { ParsedFindQuery } from "./QueryParser.mjs";
|
|
2
2
|
//#region src/queries/find/QueryParser.pruning.d.ts
|
|
3
|
-
|
|
4
|
-
* Removes unused joins and their optional conditions from the query in place.
|
|
5
|
-
*
|
|
6
|
-
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
7
|
-
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
8
|
-
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
9
|
-
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
10
|
-
*
|
|
11
|
-
* @param parsed The query to mutate.
|
|
12
|
-
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
13
|
-
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
14
|
-
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
15
|
-
*/
|
|
16
|
-
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[], inheritedCtes?: ReadonlySet<string>): void;
|
|
3
|
+
export declare function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void;
|
|
17
4
|
/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */
|
|
18
5
|
export declare function selectReferencesAlias(select: string, alias: string): boolean;
|
|
19
6
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.d.mts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.d.mts","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"mappings":";;wBAKgB,iBAAiB,QAAQ,iBAAiB;;wBAkG1C,sBAAsB,gBAAgB"}
|
|
@@ -2,21 +2,7 @@ import { deepFindConditions } from "../parsedConditions.js";
|
|
|
2
2
|
import { parseAlias } from "./QueryParser.js";
|
|
3
3
|
import { assertNever } from "../../utils.js";
|
|
4
4
|
//#region src/queries/find/QueryParser.pruning.ts
|
|
5
|
-
|
|
6
|
-
* Removes unused joins and their optional conditions from the query in place.
|
|
7
|
-
*
|
|
8
|
-
* First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,
|
|
9
|
-
* including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,
|
|
10
|
-
* allowing the `tags t` join to be removed when nothing else reads it. This uses the final
|
|
11
|
-
* table names, join columns, and alias usages after plugins and collection rewriting.
|
|
12
|
-
*
|
|
13
|
-
* @param parsed The query to mutate.
|
|
14
|
-
* @param keepAliases Aliases to retain even when the query has no explicit reference to them.
|
|
15
|
-
* @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names
|
|
16
|
-
* so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.
|
|
17
|
-
*/
|
|
18
|
-
function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ new Set()) {
|
|
19
|
-
pruneIdOnlyJoins(parsed, keepAliases, /* @__PURE__ */ new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]));
|
|
5
|
+
function pruneUnusedJoins(parsed, keepAliases) {
|
|
20
6
|
const dt = new DependencyTracker();
|
|
21
7
|
const todo = [...parsed.tables];
|
|
22
8
|
while (todo.length > 0) {
|
|
@@ -68,41 +54,6 @@ function pruneUnusedJoins(parsed, keepAliases, inheritedCtes = /* @__PURE__ */ n
|
|
|
68
54
|
});
|
|
69
55
|
if (parsed.condition && parsed.condition.conditions.length === 0) parsed.condition = void 0;
|
|
70
56
|
}
|
|
71
|
-
/**
|
|
72
|
-
* Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.
|
|
73
|
-
*
|
|
74
|
-
* Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS
|
|
75
|
-
* on the join table, with no otherTable join left to optimize. Positive branches can still contain
|
|
76
|
-
* otherTable joins; this pass replaces their id conditions and makes those joins removable.
|
|
77
|
-
*
|
|
78
|
-
* If a collection remains a LEFT JOIN, replace its id conditions the same way: for
|
|
79
|
-
* `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,
|
|
80
|
-
* replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.
|
|
81
|
-
* When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,
|
|
82
|
-
* so the replacement also preserves conditions that accept missing memberships.
|
|
83
|
-
*/
|
|
84
|
-
function pruneIdOnlyJoins(query, keepAliases, visibleCtes) {
|
|
85
|
-
const conditions = deepFindConditions(query.condition, false);
|
|
86
|
-
for (const condition of conditions) if (condition.kind === "exists") pruneUnusedJoins(condition.subquery, [], visibleCtes);
|
|
87
|
-
for (const table of query.tables) if (table.join === "lateral") pruneUnusedJoins(table.query, [], visibleCtes);
|
|
88
|
-
for (const otherTable of query.tables) {
|
|
89
|
-
if (otherTable.join !== "inner" && otherTable.join !== "outer") continue;
|
|
90
|
-
const joinTable = query.tables.find((t) => "idJoin" in t && t.idJoin?.alias === otherTable.alias);
|
|
91
|
-
const idJoin = joinTable && "idJoin" in joinTable ? joinTable.idJoin : void 0;
|
|
92
|
-
if (visibleCtes.has(otherTable.table)) continue;
|
|
93
|
-
if (!joinTable || !idJoin || otherTable.table !== idJoin.table || otherTable.col1 !== idJoin.col1 || otherTable.col2 !== idJoin.col2) continue;
|
|
94
|
-
const alias = otherTable.alias;
|
|
95
|
-
if (keepAliases.includes(alias)) continue;
|
|
96
|
-
if (query.selects.some((s) => typeof s === "string" ? selectReferencesAlias(s, alias) : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias))) continue;
|
|
97
|
-
if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) continue;
|
|
98
|
-
if (query.tables.some((t) => t !== otherTable && (t.join === "lateral" || (t.join === "inner" || t.join === "outer") && joinDependencies(t).includes(alias)))) continue;
|
|
99
|
-
if (conditions.some((c) => c.kind === "column" ? c.alias === alias && c.column !== "id" : c.kind === "raw" ? c.aliases.includes(alias) : c.outerAliases.includes(alias))) continue;
|
|
100
|
-
for (const condition of conditions) if (condition.kind === "column" && condition.alias === alias) {
|
|
101
|
-
condition.alias = joinTable.alias;
|
|
102
|
-
condition.column = idJoin.fkColumn;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
57
|
/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */
|
|
107
58
|
function joinDependencies(t) {
|
|
108
59
|
return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryParser.pruning.js","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n/**\n * Removes unused joins and their optional conditions from the query in place.\n *\n * First replaces eligible many-to-many otherTable-id conditions with join-table FK conditions,\n * including inside EXISTS and lateral subqueries. I.e. `t.id = 1` becomes `att.tag_id = 1`,\n * allowing the `tags t` join to be removed when nothing else reads it. This uses the final\n * table names, join columns, and alias usages after plugins and collection rewriting.\n *\n * @param parsed The query to mutate.\n * @param keepAliases Aliases to retain even when the query has no explicit reference to them.\n * @param inheritedCtes CTE names visible from enclosing queries. Combined with local CTE names\n * so FK substitution cannot bypass a CTE that shadows otherTable in a nested query.\n */\nexport function pruneUnusedJoins(\n parsed: ParsedFindQuery,\n keepAliases: string[],\n inheritedCtes: ReadonlySet<string> = new Set(),\n): void {\n const visibleCtes = new Set([...inheritedCtes, ...(parsed.ctes ?? []).map((cte) => cte.alias)]);\n pruneIdOnlyJoins(parsed, keepAliases, visibleCtes);\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/**\n * Replaces conditions on a many-to-many otherTable's id with its join-table FK when no other columns are used.\n *\n * Run after collection rewriting: a standalone `otherTable.id IS NULL` branch becomes NOT EXISTS\n * on the join table, with no otherTable join left to optimize. Positive branches can still contain\n * otherTable joins; this pass replaces their id conditions and makes those joins removable.\n *\n * If a collection remains a LEFT JOIN, replace its id conditions the same way: for\n * `authors a LEFT JOIN authors_to_tags att ... LEFT JOIN tags t ON att.tag_id = t.id`,\n * replace `t.id = 1` with `att.tag_id = 1` and let pruning remove `tags t`.\n * When an author has no join-table row, both `t.id` and `att.tag_id` are NULL,\n * so the replacement also preserves conditions that accept missing memberships.\n */\nfunction pruneIdOnlyJoins(query: ParsedFindQuery, keepAliases: string[], visibleCtes: ReadonlySet<string>): void {\n const conditions = deepFindConditions(query.condition, false);\n // Each subquery needs the full pruning pass: substituting `t.id` with `att.tag_id` alone\n // leaves the unused `tags t` join in its FROM list. The enclosing query's dependency tracker\n // cannot remove joins from a subquery, so recurse through pruneUnusedJoins, not just this helper.\n for (const condition of conditions) {\n if (condition.kind === \"exists\") pruneUnusedJoins(condition.subquery, [], visibleCtes);\n }\n for (const table of query.tables) {\n if (table.join === \"lateral\") pruneUnusedJoins(table.query, [], visibleCtes);\n }\n for (const otherTable of query.tables) {\n // Primary, cross, and lateral tables are not otherTable joins eligible for FK substitution.\n if (otherTable.join !== \"inner\" && otherTable.join !== \"outer\") {\n continue;\n }\n\n // I.e. otherTable is `tags t`; its marker is on the m2m table `authors_to_tags att`.\n const joinTable = query.tables.find((t) => \"idJoin\" in t && t.idJoin?.alias === otherTable.alias);\n const idJoin = joinTable && \"idJoin\" in joinTable ? joinTable.idJoin : undefined;\n\n // A visible `WITH tags AS (...)` changes what `JOIN tags` reads, including inside nested EXISTS.\n // Keep this join to apply the CTE's restrictions; unrelated CTEs do not affect the FK guarantee.\n if (visibleCtes.has(otherTable.table)) {\n continue;\n }\n\n // The parser did not mark this join as eligible, or a plugin changed otherTable/the ON clause.\n // Keep the join because reading its id may now filter rows differently from reading the join-table FK.\n if (\n !joinTable ||\n !idJoin ||\n otherTable.table !== idJoin.table ||\n otherTable.col1 !== idJoin.col1 ||\n otherTable.col2 !== idJoin.col2\n ) {\n continue;\n }\n\n const alias = otherTable.alias;\n // The caller explicitly needs this alias even if no visible expression reads it.\n if (keepAliases.includes(alias)) {\n continue;\n }\n\n // A projection reads the otherTable row; rewriting only its conditions would not remove the lookup.\n if (\n query.selects.some((s) =>\n typeof s === \"string\"\n ? selectReferencesAlias(s, alias)\n : s.aliases.includes(alias) || selectReferencesAlias(s.sql, alias),\n )\n ) {\n continue;\n }\n\n // Ordering by otherTable still needs the join. Grouped queries are conservatively excluded because\n // this pass does not establish whether substitution preserves their grouping semantics.\n if (query.orderBys.some((o) => o.alias === alias) || query.groupBys?.length) {\n continue;\n }\n\n // Another join depends on this alias, or a lateral query may reference it in its own scope.\n // Keep otherTable rather than leaving a dangling reference; lateral usages are not analyzed here.\n if (\n query.tables.some(\n (t) =>\n t !== otherTable &&\n (t.join === \"lateral\" || ((t.join === \"inner\" || t.join === \"outer\") && joinDependencies(t).includes(alias))),\n )\n ) {\n continue;\n }\n\n // A condition reads another otherTable column, raw SQL references the alias, or EXISTS correlates\n // through it. Those usages cannot be satisfied by replacing otherTable-id column conditions alone.\n if (\n conditions.some((c) =>\n c.kind === \"column\"\n ? c.alias === alias && c.column !== \"id\"\n : c.kind === \"raw\"\n ? c.aliases.includes(alias)\n : c.outerAliases.includes(alias),\n )\n ) {\n continue;\n }\n\n // Now redirect all conditions on otherTable.id to joinTable's FK, keeping their operators and bindings.\n // I.e. `t.id IN (...)` becomes `att.tag_id IN (...)`. Nothing else reads otherTable after the checks\n // above, so pruneUnusedJoins can remove its now-unused join after this helper returns.\n for (const condition of conditions) {\n if (condition.kind === \"column\" && condition.alias === alias) {\n condition.alias = joinTable.alias;\n condition.column = idJoin.fkColumn;\n }\n }\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBACd,QACA,aACA,gCAAqC,IAAI,IAAI,GACvC;CAEN,iBAAiB,QAAQ,6BAAa,IADd,IAAI,CAAC,GAAG,eAAe,IAAI,OAAO,QAAQ,CAAC,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CAAE;GAC5C;EACF;EACA,KAAK,2BAAW,IAAI,IAAI,CAAC,GAAG,KAAK,UAAU,GAAG,MAAM,CAAC;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"QueryParser.pruning.js","names":[],"sources":["../../../src/queries/find/QueryParser.pruning.ts"],"sourcesContent":["import { type JoinTable, type ParsedFindQuery, parseAlias } from \"src/queries/find/QueryParser.ts\";\nimport { deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\n// Remove any joins that are not used in the select or conditions\nexport function pruneUnusedJoins(parsed: ParsedFindQuery, keepAliases: string[]): void {\n const dt = new DependencyTracker();\n\n // First setup the alias -> alias dependencies...\n const todo = [...parsed.tables];\n while (todo.length > 0) {\n const t = todo.pop()!;\n if (t.join === \"lateral\") {\n dt.addAlias(t.alias, [t.fromAlias]);\n // Recurse into lateral joins...\n todo.push(...t.query.tables);\n } else if (t.join === \"cross\") {\n dt.markRequired(t.alias);\n } else if (t.join === \"primary\") {\n dt.markRequired(t.alias);\n } else if (parsed.ctes?.some((cte) => cte.alias === t.table)) {\n dt.addAlias(t.alias, joinDependencies(t));\n dt.markRequired(t.alias);\n } else {\n dt.addAlias(t.alias, joinDependencies(t));\n }\n }\n\n // Mark all terminal usages\n parsed.selects.forEach((s) => {\n if (typeof s === \"string\") {\n markSelectAliases(dt, parsed, s);\n } else if (\"aliases\" in s) {\n for (const a of s.aliases) dt.markRequired(a);\n markSelectAliases(dt, parsed, s.sql);\n }\n });\n parsed.orderBys.forEach((o) => dt.markRequired(o.alias));\n parsed.groupBys?.forEach((g) => {\n if (\"expression\" in g) {\n markSelectAliases(dt, parsed, g.expression);\n } else {\n dt.markRequired(g.alias);\n }\n });\n keepAliases.forEach((a) => dt.markRequired(a));\n // Look recursively into CTE & lateral join conditions\n const todo2 = [{ query: parsed, filterPruneable: true }];\n while (todo2.length > 0) {\n const { query, filterPruneable } = todo2.pop()!;\n deepFindConditions(query.condition, filterPruneable).forEach((c) => {\n if (c.kind === \"column\") {\n dt.markRequired(c.alias);\n } else if (c.kind === \"raw\") {\n for (const alias of c.aliases) dt.markRequired(alias);\n } else if (c.kind === \"exists\") {\n for (const alias of c.outerAliases) dt.markRequired(alias);\n } else {\n assertNever(c);\n }\n });\n todo2.push(\n ...query.tables.filter((t) => t.join === \"lateral\").map((t) => ({ query: t.query, filterPruneable: false })),\n );\n }\n\n // Now remove any unused joins\n parsed.tables = parsed.tables.filter((t) => dt.required.has(t.alias));\n\n // And then remove any inline soft-delete conditions we don't need anymore\n if (parsed.condition && parsed.condition.op === \"and\") {\n parsed.condition.conditions = parsed.condition.conditions.filter((c) => {\n if (c.kind === \"column\") {\n const prune = c.pruneable && !dt.required.has(c.alias);\n // if (prune) console.log(`DROPPING`, c);\n return !prune;\n } else {\n return c;\n }\n });\n }\n\n // Remove any `{ and: [...] }`s that are empty; we should probably do this deeply?\n if (parsed.condition && parsed.condition.conditions.length === 0) {\n parsed.condition = undefined;\n }\n}\n\n/** Returns the aliases needed to evaluate a join's ON clause, excluding the joined alias itself. */\nfunction joinDependencies(t: JoinTable): string[] {\n return [parseAlias(t.col1), parseAlias(t.col2)].filter((alias) => alias !== t.alias);\n}\n\n/** Marks aliases used by select strings, including generated CTI expressions like `COALESCE(st0.col, st1.col)`. */\nfunction markSelectAliases(dt: DependencyTracker, parsed: ParsedFindQuery, select: string): void {\n for (const table of parsed.tables) {\n if (selectReferencesAlias(select, table.alias)) {\n dt.markRequired(table.alias);\n }\n }\n}\n\n/** Returns true if a raw select expression references `alias.column` or the whole-row `alias`. */\nexport function selectReferencesAlias(select: string, alias: string): boolean {\n // Most selects are simple `a.*`, but CTI adds expressions like\n // `COALESCE(p_s0.shared_column, p_s1.shared_column) as shared_column`.\n // Those expressions must keep the subtype joins, but `parseAlias` only sees\n // the leading function name. Instead of parsing SQL, scan for the only alias\n // forms Joist generates in selects: `alias.column`, `\"alias\".column`, and whole-row aliases.\n return (\n selectReferencesCandidate(select, `${alias}.`) ||\n selectReferencesCandidate(select, `\"${alias}\".`) ||\n selectReferencesCandidate(select, alias) ||\n selectReferencesCandidate(select, `\"${alias}\"`)\n );\n}\n\n/**\n * Returns true when `candidate` is present at a SQL identifier boundary.\n *\n * Scans the select string for literal candidate matches, then verifies the characters before/after the match are not\n * part of a larger identifier or dotted path. I.e. `row_to_json(\"ap\")` matches, but `foo_\"ap\"` and `foo.ap` do not.\n */\nfunction selectReferencesCandidate(select: string, candidate: string): boolean {\n let index = select.indexOf(candidate);\n const quoted = candidate.startsWith('\"');\n while (index !== -1) {\n // Each loop inspects one literal occurrence of `candidate`, then either accepts it as a real alias reference or\n // advances to the next occurrence if the surrounding characters show it is part of a larger token.\n // Avoid treating `foo.a.id` as a reference to `a`; Joist-generated aliases\n // appear at the start of an expression or after punctuation/whitespace.\n const previous = select[index - 1];\n const next = select[index + candidate.length];\n if (\n (index === 0 || (previous !== \".\" && !isSqlIdentifierChar(previous))) &&\n !isSqlIdentifierChar(next) &&\n (quoted || (previous !== '\"' && next !== '\"'))\n ) {\n return true;\n }\n // Continue scanning after the current occurrence; `indexOf` returns -1 once there are no more candidates.\n index = select.indexOf(candidate, index + candidate.length);\n }\n return false;\n}\n\n/** Returns true for characters that can be part of an unquoted SQL identifier. */\nfunction isSqlIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[A-Za-z0-9_]/.test(char);\n}\n\n/** Track join dependencies for `pruneUnusedJoins`. */\nclass DependencyTracker {\n private nodes: Map<string, string[]> = new Map();\n required: Set<string> = new Set();\n\n addAlias(alias: string, dependencies: string[] = []): void {\n this.nodes.set(alias, dependencies);\n }\n\n markRequired(alias: string): void {\n const marked = new Set<string>();\n const todo = [alias];\n while (todo.length > 0) {\n const alias = todo.pop()!;\n if (!marked.has(alias)) {\n marked.add(alias);\n todo.push(...(this.nodes.get(alias) || []));\n }\n }\n this.required = new Set([...this.required, ...marked]);\n }\n}\n"],"mappings":";;;;AAKA,SAAgB,iBAAiB,QAAyB,aAA6B;CACrF,MA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|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"build"
|
|
43
43
|
],
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"joist-utils": "2.5.0
|
|
45
|
+
"joist-utils": "2.5.0"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"ansis": "^4.4.0",
|