joist-core 2.5.0-next.21 → 2.5.0-next.23
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/BaseEntity.cjs +5 -2
- package/build/BaseEntity.cjs.map +1 -1
- package/build/BaseEntity.d.cts +2 -0
- package/build/BaseEntity.d.cts.map +1 -1
- package/build/BaseEntity.d.mts +2 -0
- package/build/BaseEntity.d.mts.map +1 -1
- package/build/BaseEntity.js +5 -2
- package/build/BaseEntity.js.map +1 -1
- package/build/Entity.cjs.map +1 -1
- package/build/Entity.d.cts +6 -0
- package/build/Entity.d.cts.map +1 -1
- package/build/Entity.d.mts +6 -0
- package/build/Entity.d.mts.map +1 -1
- package/build/Entity.js.map +1 -1
- package/build/EntityManager.cjs +83 -22
- package/build/EntityManager.cjs.map +1 -1
- package/build/EntityManager.d.cts +7 -4
- package/build/EntityManager.d.cts.map +1 -1
- package/build/EntityManager.d.mts +7 -4
- package/build/EntityManager.d.mts.map +1 -1
- package/build/EntityManager.js +83 -22
- package/build/EntityManager.js.map +1 -1
- package/build/InstanceData.cjs +2 -2
- package/build/InstanceData.cjs.map +1 -1
- package/build/InstanceData.d.cts +2 -2
- package/build/InstanceData.d.mts +2 -2
- package/build/InstanceData.js +2 -2
- package/build/InstanceData.js.map +1 -1
- package/build/PluginManager.cjs +6 -0
- package/build/PluginManager.cjs.map +1 -1
- package/build/PluginManager.d.cts +10 -0
- package/build/PluginManager.d.cts.map +1 -1
- package/build/PluginManager.d.mts +10 -0
- package/build/PluginManager.d.mts.map +1 -1
- package/build/PluginManager.js +6 -0
- package/build/PluginManager.js.map +1 -1
- package/build/clientIds.cjs +47 -0
- package/build/clientIds.cjs.map +1 -0
- package/build/clientIds.d.cts +26 -0
- package/build/clientIds.d.cts.map +1 -0
- package/build/clientIds.d.mts +26 -0
- package/build/clientIds.d.mts.map +1 -0
- package/build/clientIds.js +42 -0
- package/build/clientIds.js.map +1 -0
- package/build/configure.cjs +3 -0
- package/build/configure.cjs.map +1 -1
- package/build/configure.d.cts.map +1 -1
- package/build/configure.d.mts.map +1 -1
- package/build/configure.js +3 -0
- package/build/configure.js.map +1 -1
- package/build/getProperties.cjs +4 -1
- package/build/getProperties.cjs.map +1 -1
- package/build/getProperties.js +4 -1
- package/build/getProperties.js.map +1 -1
- package/build/index.cjs +15 -4
- package/build/index.cjs.map +1 -1
- package/build/index.d.cts +9 -7
- package/build/index.d.cts.map +1 -1
- package/build/index.d.mts +9 -7
- package/build/index.d.mts.map +1 -1
- package/build/index.js +11 -5
- package/build/index.js.map +1 -1
- package/build/keys.cjs +4 -0
- package/build/keys.cjs.map +1 -1
- package/build/keys.d.cts.map +1 -1
- package/build/keys.d.mts.map +1 -1
- package/build/keys.js +4 -0
- package/build/keys.js.map +1 -1
- package/build/newTestInstance.cjs +8 -8
- package/build/newTestInstance.cjs.map +1 -1
- package/build/newTestInstance.d.cts.map +1 -1
- package/build/newTestInstance.d.mts.map +1 -1
- package/build/newTestInstance.js +8 -8
- package/build/newTestInstance.js.map +1 -1
- package/build/queries/ConditionBuilder.cjs +2 -1
- package/build/queries/ConditionBuilder.cjs.map +1 -1
- package/build/queries/ConditionBuilder.d.cts +9 -1
- package/build/queries/ConditionBuilder.d.cts.map +1 -1
- package/build/queries/ConditionBuilder.d.mts +9 -1
- package/build/queries/ConditionBuilder.d.mts.map +1 -1
- package/build/queries/ConditionBuilder.js +2 -2
- package/build/queries/ConditionBuilder.js.map +1 -1
- package/build/queries/conditions.cjs.map +1 -1
- package/build/queries/conditions.d.cts +4 -1
- package/build/queries/conditions.d.cts.map +1 -1
- package/build/queries/conditions.d.mts +4 -1
- package/build/queries/conditions.d.mts.map +1 -1
- package/build/queries/conditions.js.map +1 -1
- package/build/queries/sql/Expr.cjs +79 -134
- package/build/queries/sql/Expr.cjs.map +1 -1
- package/build/queries/sql/Expr.d.cts +26 -34
- package/build/queries/sql/Expr.d.cts.map +1 -1
- package/build/queries/sql/Expr.d.mts +26 -34
- package/build/queries/sql/Expr.d.mts.map +1 -1
- package/build/queries/sql/Expr.js +80 -133
- package/build/queries/sql/Expr.js.map +1 -1
- package/build/queries/sql/ParsedQuery.cjs +119 -0
- package/build/queries/sql/ParsedQuery.cjs.map +1 -0
- package/build/queries/sql/ParsedQuery.d.cts +105 -0
- package/build/queries/sql/ParsedQuery.d.cts.map +1 -0
- package/build/queries/sql/ParsedQuery.d.mts +105 -0
- package/build/queries/sql/ParsedQuery.d.mts.map +1 -0
- package/build/queries/sql/ParsedQuery.js +116 -0
- package/build/queries/sql/ParsedQuery.js.map +1 -0
- package/build/queries/sql/ParsedSqlExpression.cjs +74 -0
- package/build/queries/sql/ParsedSqlExpression.cjs.map +1 -0
- package/build/queries/sql/ParsedSqlExpression.d.cts +65 -0
- package/build/queries/sql/ParsedSqlExpression.d.cts.map +1 -0
- package/build/queries/sql/ParsedSqlExpression.d.mts +65 -0
- package/build/queries/sql/ParsedSqlExpression.d.mts.map +1 -0
- package/build/queries/sql/ParsedSqlExpression.js +69 -0
- package/build/queries/sql/ParsedSqlExpression.js.map +1 -0
- package/build/queries/sql/Tables.cjs +61 -46
- package/build/queries/sql/Tables.cjs.map +1 -1
- package/build/queries/sql/Tables.d.cts.map +1 -1
- package/build/queries/sql/Tables.d.mts.map +1 -1
- package/build/queries/sql/Tables.js +61 -46
- package/build/queries/sql/Tables.js.map +1 -1
- package/build/queries/sql/execute.cjs +45 -62
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts +4 -3
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts +4 -3
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +47 -64
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.cjs +14 -15
- package/build/queries/sql/expressions/arrayAgg.cjs.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.d.cts +3 -2
- package/build/queries/sql/expressions/arrayAgg.d.cts.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.d.mts +3 -2
- package/build/queries/sql/expressions/arrayAgg.d.mts.map +1 -1
- package/build/queries/sql/expressions/arrayAgg.js +15 -16
- package/build/queries/sql/expressions/arrayAgg.js.map +1 -1
- package/build/queries/sql/expressions/case.cjs +11 -16
- package/build/queries/sql/expressions/case.cjs.map +1 -1
- package/build/queries/sql/expressions/case.d.cts +3 -2
- package/build/queries/sql/expressions/case.d.cts.map +1 -1
- package/build/queries/sql/expressions/case.d.mts +3 -2
- package/build/queries/sql/expressions/case.d.mts.map +1 -1
- package/build/queries/sql/expressions/case.js +11 -16
- package/build/queries/sql/expressions/case.js.map +1 -1
- package/build/queries/sql/expressions/coalesce.cjs.map +1 -1
- package/build/queries/sql/expressions/coalesce.d.cts +3 -2
- package/build/queries/sql/expressions/coalesce.d.cts.map +1 -1
- package/build/queries/sql/expressions/coalesce.d.mts +3 -2
- package/build/queries/sql/expressions/coalesce.d.mts.map +1 -1
- package/build/queries/sql/expressions/coalesce.js.map +1 -1
- package/build/queries/sql/expressions/expression.cjs +10 -12
- package/build/queries/sql/expressions/expression.cjs.map +1 -1
- package/build/queries/sql/expressions/expression.d.cts +4 -3
- package/build/queries/sql/expressions/expression.d.cts.map +1 -1
- package/build/queries/sql/expressions/expression.d.mts +4 -3
- package/build/queries/sql/expressions/expression.d.mts.map +1 -1
- package/build/queries/sql/expressions/expression.js +11 -13
- package/build/queries/sql/expressions/expression.js.map +1 -1
- package/build/queries/sql/expressions/greatest.cjs.map +1 -1
- package/build/queries/sql/expressions/greatest.d.cts +3 -2
- package/build/queries/sql/expressions/greatest.d.cts.map +1 -1
- package/build/queries/sql/expressions/greatest.d.mts +3 -2
- package/build/queries/sql/expressions/greatest.d.mts.map +1 -1
- package/build/queries/sql/expressions/greatest.js.map +1 -1
- package/build/queries/sql/expressions/least.cjs.map +1 -1
- package/build/queries/sql/expressions/least.d.cts +3 -2
- package/build/queries/sql/expressions/least.d.cts.map +1 -1
- package/build/queries/sql/expressions/least.d.mts +3 -2
- package/build/queries/sql/expressions/least.d.mts.map +1 -1
- package/build/queries/sql/expressions/least.js.map +1 -1
- package/build/queries/sql/expressions/nullIf.cjs.map +1 -1
- package/build/queries/sql/expressions/nullIf.d.cts +3 -2
- package/build/queries/sql/expressions/nullIf.d.cts.map +1 -1
- package/build/queries/sql/expressions/nullIf.d.mts +3 -2
- package/build/queries/sql/expressions/nullIf.d.mts.map +1 -1
- package/build/queries/sql/expressions/nullIf.js.map +1 -1
- package/build/queries/sql/query.cjs +168 -381
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +44 -45
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +44 -45
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +172 -383
- package/build/queries/sql/query.js.map +1 -1
- package/build/queries/sql/renderSql.cjs +321 -0
- package/build/queries/sql/renderSql.cjs.map +1 -0
- package/build/queries/sql/renderSql.d.cts +14 -0
- package/build/queries/sql/renderSql.d.cts.map +1 -0
- package/build/queries/sql/renderSql.d.mts +14 -0
- package/build/queries/sql/renderSql.d.mts.map +1 -0
- package/build/queries/sql/renderSql.js +318 -0
- package/build/queries/sql/renderSql.js.map +1 -0
- package/build/resurrection.cjs +5 -3
- package/build/resurrection.cjs.map +1 -1
- package/build/resurrection.d.cts.map +1 -1
- package/build/resurrection.d.mts.map +1 -1
- package/build/resurrection.js +5 -3
- package/build/resurrection.js.map +1 -1
- package/build/upsert.cjs +6 -3
- package/build/upsert.cjs.map +1 -1
- package/build/upsert.d.cts +6 -3
- package/build/upsert.d.cts.map +1 -1
- package/build/upsert.d.mts +6 -3
- package/build/upsert.d.mts.map +1 -1
- package/build/upsert.js +6 -3
- package/build/upsert.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { buildRawQuery } from "../find/buildFindQuery.js";
|
|
2
|
+
import { buildWhereClause } from "../renderConditions.js";
|
|
3
|
+
import { kq, safeKq } from "./keywords.js";
|
|
4
|
+
import { queryRefs } from "./ParsedQuery.js";
|
|
5
|
+
import { joinSql, sourceRefs, sqlRefs } from "./ParsedSqlExpression.js";
|
|
6
|
+
import { tableSqlName } from "./Tables.js";
|
|
7
|
+
import { assertNever, fail } from "../../utils.js";
|
|
8
|
+
// src/queries/sql/renderSql.ts
|
|
9
|
+
/** Prunes unused joins/CTEs, validates joins, and renders a read statement. */
|
|
10
|
+
function renderQuery(query) {
|
|
11
|
+
return renderSql({
|
|
12
|
+
kind: "query",
|
|
13
|
+
query
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/** Prunes unused joins/CTEs, validates joins, and renders a read or mutation statement. */
|
|
17
|
+
function renderStatement(query) {
|
|
18
|
+
return query.kind === "select" || query.kind === "set" ? renderQuery(query) : renderSql(buildStatementSql(query));
|
|
19
|
+
}
|
|
20
|
+
/** Renders an expression and its bindings, pruning and validating any embedded queries. */
|
|
21
|
+
function renderSql(node) {
|
|
22
|
+
let result;
|
|
23
|
+
switch (node.kind) {
|
|
24
|
+
case "column":
|
|
25
|
+
result = {
|
|
26
|
+
sql: `${safeKq(node.alias)}.${safeKq(node.column)}`,
|
|
27
|
+
bindings: []
|
|
28
|
+
};
|
|
29
|
+
break;
|
|
30
|
+
case "star":
|
|
31
|
+
result = {
|
|
32
|
+
sql: `${safeKq(node.alias)}.*`,
|
|
33
|
+
bindings: []
|
|
34
|
+
};
|
|
35
|
+
break;
|
|
36
|
+
case "joined":
|
|
37
|
+
case "raw": {
|
|
38
|
+
const parts = node.parts.map((part) => typeof part === "string" ? {
|
|
39
|
+
sql: part,
|
|
40
|
+
bindings: []
|
|
41
|
+
} : "kind" in part ? renderSql(part) : {
|
|
42
|
+
sql: "?",
|
|
43
|
+
bindings: [part.value]
|
|
44
|
+
});
|
|
45
|
+
result = {
|
|
46
|
+
sql: parts.map((part) => part.sql).join(""),
|
|
47
|
+
bindings: parts.flatMap((part) => part.bindings)
|
|
48
|
+
};
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case "query":
|
|
52
|
+
result = renderSql(buildQuerySql(node.query));
|
|
53
|
+
break;
|
|
54
|
+
case "condition": {
|
|
55
|
+
const condition = renderCondition(node.condition);
|
|
56
|
+
const rendered = buildWhereClause(condition, node.topLevel, (query) => buildRawQuery(query, {}));
|
|
57
|
+
result = {
|
|
58
|
+
sql: rendered?.[0] ?? "",
|
|
59
|
+
bindings: rendered?.[1] ?? []
|
|
60
|
+
};
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
default: return assertNever(node);
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
/** Converts expression leaves to rendered predicates for the shared condition renderer. */
|
|
68
|
+
function renderCondition(condition) {
|
|
69
|
+
if (condition.kind === "exp") return {
|
|
70
|
+
...condition,
|
|
71
|
+
conditions: condition.conditions.map((child) => renderCondition(child))
|
|
72
|
+
};
|
|
73
|
+
if (condition.kind === "expression") {
|
|
74
|
+
const rendered = renderSql(condition.expression);
|
|
75
|
+
return {
|
|
76
|
+
kind: "raw",
|
|
77
|
+
condition: rendered.sql,
|
|
78
|
+
bindings: rendered.bindings,
|
|
79
|
+
aliases: [],
|
|
80
|
+
pruneable: false
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return condition;
|
|
84
|
+
}
|
|
85
|
+
/** Prunes unused joins/CTEs, validates joins, and builds the SELECT SQL. */
|
|
86
|
+
function buildQuerySql(query) {
|
|
87
|
+
if (query.kind === "set") return renderSetQuery(query);
|
|
88
|
+
const { from, selects, groupBys, orderBys, where, having } = query;
|
|
89
|
+
const { joins: kept, ctes: keptCtes } = pruneJoins(query, from, query.joins, query.ctes, [
|
|
90
|
+
...selects,
|
|
91
|
+
...groupBys,
|
|
92
|
+
...orderBys,
|
|
93
|
+
where,
|
|
94
|
+
having
|
|
95
|
+
].filter((expression) => expression !== void 0));
|
|
96
|
+
const laterAliases = new Set(kept.map((j) => j.source.alias));
|
|
97
|
+
for (const j of kept) {
|
|
98
|
+
if (!j.on) fail(`Join ${describeSource(j.source)} has no ON condition left (they all pruned), but the query still references it`);
|
|
99
|
+
laterAliases.delete(j.source.alias);
|
|
100
|
+
const forward = sqlRefs(j.on).find((r) => laterAliases.has(r));
|
|
101
|
+
if (forward) fail(`Join ${describeSource(j.source)} references '${forward}', which is joined later; move that join earlier in the join array`);
|
|
102
|
+
}
|
|
103
|
+
const out = [];
|
|
104
|
+
if (keptCtes.length > 0) out.push(withFragment(keptCtes));
|
|
105
|
+
out.push(`SELECT ${query.distinct ? "DISTINCT " : ""}`);
|
|
106
|
+
out.push(joinSql(selects, ", "));
|
|
107
|
+
out.push(joinSql([" FROM ", sourceSql(from)]));
|
|
108
|
+
for (const j of kept) {
|
|
109
|
+
const keyword = j.kind === "inner" ? "JOIN" : "LEFT OUTER JOIN";
|
|
110
|
+
out.push(joinSql([
|
|
111
|
+
` ${keyword} `,
|
|
112
|
+
sourceSql(j.source),
|
|
113
|
+
" ON ",
|
|
114
|
+
j.on
|
|
115
|
+
]));
|
|
116
|
+
}
|
|
117
|
+
if (where) out.push(joinSql([" WHERE ", where]));
|
|
118
|
+
if (groupBys.length > 0) out.push(joinSql([" GROUP BY ", joinSql(groupBys, ", ")]));
|
|
119
|
+
if (having) out.push(joinSql([" HAVING ", having]));
|
|
120
|
+
if (orderBys.length > 0) out.push(joinSql([" ORDER BY ", joinSql(orderBys, ", ")]));
|
|
121
|
+
if (query.limit !== void 0) out.push(joinSql([" LIMIT ", { value: query.limit }]));
|
|
122
|
+
if (query.offset !== void 0) out.push(joinSql([" OFFSET ", { value: query.offset }]));
|
|
123
|
+
return joinSql(out);
|
|
124
|
+
}
|
|
125
|
+
/** Builds INSERT, UPDATE, or DELETE SQL from the rewritten AST. */
|
|
126
|
+
function buildStatementSql(query) {
|
|
127
|
+
const parts = [`${query.kind === "delete" ? "DELETE FROM" : query.kind === "insert" ? "INSERT INTO" : "UPDATE"} ${tableSqlName({
|
|
128
|
+
tableName: query.target.table,
|
|
129
|
+
schema: query.target.schema
|
|
130
|
+
})} AS ${kq(query.target.alias)}`];
|
|
131
|
+
if (query.kind === "insert") {
|
|
132
|
+
parts.push(` (${query.columns.map(kq).join(", ")})`);
|
|
133
|
+
if (query.values) {
|
|
134
|
+
const rows = query.values.map((row) => joinSql([
|
|
135
|
+
"(",
|
|
136
|
+
joinSql(row, ", "),
|
|
137
|
+
")"
|
|
138
|
+
]));
|
|
139
|
+
parts.push(" VALUES ", joinSql(rows, ", "));
|
|
140
|
+
} else {
|
|
141
|
+
const source = query.source;
|
|
142
|
+
const alias = safeKq(source.alias);
|
|
143
|
+
const columns = source.columns.map((key) => `${alias}.${safeKq(key)}`).join(", ");
|
|
144
|
+
parts.push(` SELECT ${columns} FROM (`, {
|
|
145
|
+
kind: "query",
|
|
146
|
+
query: source.query
|
|
147
|
+
}, `) AS ${alias}`);
|
|
148
|
+
}
|
|
149
|
+
} else if (query.kind === "update") {
|
|
150
|
+
const assignments = query.assignments.map((entry) => joinSql([`${kq(entry.column)} = `, entry.value]));
|
|
151
|
+
parts.push(" SET ", joinSql(assignments, ", "));
|
|
152
|
+
}
|
|
153
|
+
if (query.conditions.length) {
|
|
154
|
+
const conditions = query.conditions.map((condition) => joinSql([
|
|
155
|
+
"(",
|
|
156
|
+
condition,
|
|
157
|
+
")"
|
|
158
|
+
]));
|
|
159
|
+
parts.push(" WHERE ", joinSql(conditions, " AND "));
|
|
160
|
+
}
|
|
161
|
+
if (query.returning.length) parts.push(" RETURNING ", joinSql(query.returning, ", "));
|
|
162
|
+
const body = joinSql(parts);
|
|
163
|
+
const ctes = pruneCtes(query.ctes, new Set(sqlRefs(body)));
|
|
164
|
+
return ctes.length ? joinSql([withFragment(ctes), body]) : body;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Pruning: em.find's paradigm, on a flat join list.
|
|
168
|
+
*
|
|
169
|
+
* A condition given `undefined` was already dropped by `ConditionBuilder`. Now a join that nothing
|
|
170
|
+
* references anymore drops with it: a join is required if the source, a select, a surviving condition,
|
|
171
|
+
* a group-by, an order-by, or another required join's ON references it, or if it is pinned with
|
|
172
|
+
* `keep: true`. Marking follows ON dependencies transitively, exactly like `pruneUnusedJoins`'s
|
|
173
|
+
* `DependencyTracker`.
|
|
174
|
+
*
|
|
175
|
+
* em.find's joins almost never filter rows by themselves, so pruning them is semantics-preserving. An
|
|
176
|
+
* explicit `{ inner: b, on }` here does filter rows, so pruning it when unreferenced drops that filter;
|
|
177
|
+
* that matches `{ books: { title: undefined } }` in em.find and is deliberate. `keep: true` pins it, and
|
|
178
|
+
* a pure existence filter is better written as `a.id.in(query({ ... }))`, which is never `undefined`.
|
|
179
|
+
*
|
|
180
|
+
* CTEs prune on the same rule and through the same dependency map: a `with` entry nothing reads
|
|
181
|
+
* anymore drops with the join that read it, and a CTE read only by another CTE survives with it.
|
|
182
|
+
* A CTE joined into the query shares its alias with that join, so their dependencies are merged.
|
|
183
|
+
*
|
|
184
|
+
* The one join that never prunes is a recursive term's reference to its own CTE: PostgreSQL requires
|
|
185
|
+
* it, so it is not the caller's optional filter (see `Ctx.recursiveSelf`).
|
|
186
|
+
*/
|
|
187
|
+
function pruneJoins(q, from, joins, ctes, used) {
|
|
188
|
+
if (q.pruneJoins === false) return {
|
|
189
|
+
joins,
|
|
190
|
+
ctes
|
|
191
|
+
};
|
|
192
|
+
const deps = /* @__PURE__ */ new Map();
|
|
193
|
+
function addDeps(alias, refs) {
|
|
194
|
+
const own = refs.filter((r) => r !== alias);
|
|
195
|
+
const existing = deps.get(alias);
|
|
196
|
+
if (existing) existing.push(...own);
|
|
197
|
+
else deps.set(alias, own);
|
|
198
|
+
}
|
|
199
|
+
for (const j of joins) addDeps(j.source.alias, [...j.on ? sqlRefs(j.on) : [], ...sourceRefs(j.source)]);
|
|
200
|
+
for (const c of ctes) addDeps(c.alias, queryRefs(c.query));
|
|
201
|
+
const required = /* @__PURE__ */ new Set();
|
|
202
|
+
function markRequired(alias) {
|
|
203
|
+
if (required.has(alias)) return;
|
|
204
|
+
required.add(alias);
|
|
205
|
+
for (const dep of deps.get(alias) ?? []) markRequired(dep);
|
|
206
|
+
}
|
|
207
|
+
markRequired(from.alias);
|
|
208
|
+
for (const ref of sourceRefs(from)) markRequired(ref);
|
|
209
|
+
for (const r of used.flatMap(sqlRefs)) markRequired(r);
|
|
210
|
+
for (const j of joins) if (j.keep) markRequired(j.source.alias);
|
|
211
|
+
if (q.recursiveAlias) markRequired(q.recursiveAlias);
|
|
212
|
+
return {
|
|
213
|
+
joins: joins.filter((j) => required.has(j.source.alias)),
|
|
214
|
+
ctes: ctes.filter((c) => required.has(c.alias))
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Drops the CTEs that nothing reads, given the aliases the rest of the statement referenced.
|
|
219
|
+
*
|
|
220
|
+
* A CTE can only read earlier siblings, so going last to first means every CTE that could read this one
|
|
221
|
+
* was already visited, and its own reads are already in `referenced`. That makes one pass enough; first
|
|
222
|
+
* to last would have to repeat until the set stopped growing. `unshift` restores WITH order.
|
|
223
|
+
*/
|
|
224
|
+
function pruneCtes(ctes, referenced) {
|
|
225
|
+
const kept = [];
|
|
226
|
+
for (let i = ctes.length - 1; i >= 0; i--) {
|
|
227
|
+
const cte = ctes[i];
|
|
228
|
+
if (!referenced.has(cte.alias)) continue;
|
|
229
|
+
for (const ref of queryRefs(cte.query)) referenced.add(ref);
|
|
230
|
+
kept.unshift(cte);
|
|
231
|
+
}
|
|
232
|
+
return kept;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Renders `WITH a AS (...), b AS (...) `, whose bindings lead the statement, as their SQL does.
|
|
236
|
+
*
|
|
237
|
+
* One recursive CTE makes the whole clause `WITH RECURSIVE`, PostgreSQL's rule: the keyword is on the
|
|
238
|
+
* clause, not on the entry that needs it, and it does not force the other entries to be recursive.
|
|
239
|
+
*/
|
|
240
|
+
function withFragment(ctes) {
|
|
241
|
+
const recursive = ctes.some((c) => c.recursive) ? " RECURSIVE" : "";
|
|
242
|
+
const bodies = ctes.map((c) => joinSql([
|
|
243
|
+
`${safeKq(c.alias)} AS (`,
|
|
244
|
+
{
|
|
245
|
+
kind: "query",
|
|
246
|
+
query: c.query
|
|
247
|
+
},
|
|
248
|
+
")"
|
|
249
|
+
]));
|
|
250
|
+
return joinSql([
|
|
251
|
+
`WITH${recursive} `,
|
|
252
|
+
joinSql(bodies, ", "),
|
|
253
|
+
" "
|
|
254
|
+
]);
|
|
255
|
+
}
|
|
256
|
+
/** Composes set operands after their SELECT nodes have been rewritten. */
|
|
257
|
+
function renderSetQuery(query) {
|
|
258
|
+
let body;
|
|
259
|
+
for (const operand of query.operands) {
|
|
260
|
+
let branch = {
|
|
261
|
+
kind: "query",
|
|
262
|
+
query: operand.query
|
|
263
|
+
};
|
|
264
|
+
if (operand.alignment) {
|
|
265
|
+
const alias = safeKq(operand.alignment.alias);
|
|
266
|
+
const columns = operand.alignment.columns.map((key) => `${alias}.${safeKq(key)} AS ${safeKq(key)}`).join(", ");
|
|
267
|
+
branch = joinSql([
|
|
268
|
+
`SELECT ${columns} FROM (`,
|
|
269
|
+
branch,
|
|
270
|
+
`) AS ${alias}`
|
|
271
|
+
]);
|
|
272
|
+
}
|
|
273
|
+
body = body ? joinSql([
|
|
274
|
+
"(",
|
|
275
|
+
body,
|
|
276
|
+
`) ${query.operation} (`,
|
|
277
|
+
branch,
|
|
278
|
+
")"
|
|
279
|
+
]) : branch;
|
|
280
|
+
}
|
|
281
|
+
const ctes = pruneCtes(query.ctes, new Set(query.operands.flatMap((operand) => queryRefs(operand.query))));
|
|
282
|
+
const parts = ctes.length ? [withFragment(ctes), body] : [body];
|
|
283
|
+
if (query.orderBys.length) parts.push(` ORDER BY ${query.orderBys.join(", ")}`);
|
|
284
|
+
if (query.limit !== void 0) parts.push(joinSql([" LIMIT ", { value: query.limit }]));
|
|
285
|
+
if (query.offset !== void 0) parts.push(joinSql([" OFFSET ", { value: query.offset }]));
|
|
286
|
+
return joinSql(parts);
|
|
287
|
+
}
|
|
288
|
+
/** Builds source syntax after plugins have rewritten its table, CTE, or query. */
|
|
289
|
+
function sourceSql(source) {
|
|
290
|
+
switch (source.kind) {
|
|
291
|
+
case "table": return joinSql([`${tableSqlName({
|
|
292
|
+
tableName: source.table,
|
|
293
|
+
schema: source.schema
|
|
294
|
+
})} AS ${safeKq(source.alias)}`]);
|
|
295
|
+
case "cte": return joinSql([safeKq(source.cte), ...source.cte === source.alias ? [] : [` AS ${safeKq(source.alias)}`]]);
|
|
296
|
+
case "query": return joinSql([
|
|
297
|
+
"(",
|
|
298
|
+
{
|
|
299
|
+
kind: "query",
|
|
300
|
+
query: source.query
|
|
301
|
+
},
|
|
302
|
+
`) AS ${safeKq(source.alias)}`
|
|
303
|
+
]);
|
|
304
|
+
default: return assertNever(source);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/** Names the rewritten source in join-validation errors. */
|
|
308
|
+
function describeSource(source) {
|
|
309
|
+
switch (source.kind) {
|
|
310
|
+
case "table": return `table ${source.schema ? `${source.schema}.` : ""}${source.table} AS ${source.alias}`;
|
|
311
|
+
case "cte": return `CTE ${source.cte} AS ${source.alias}`;
|
|
312
|
+
case "query": return `subquery AS ${source.alias}`;
|
|
313
|
+
default: return assertNever(source);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
export { renderQuery, renderSql, renderStatement };
|
|
317
|
+
|
|
318
|
+
//# sourceMappingURL=renderSql.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"renderSql.js","names":[],"sources":["../../../src/queries/sql/renderSql.ts"],"sourcesContent":["import { buildRawQuery } from \"src/queries/find/buildFindQuery.ts\";\nimport type { ParsedExpressionCondition, ParsedExpressionFilter } from \"src/queries/parsedConditions.ts\";\nimport { buildWhereClause } from \"src/queries/renderConditions.ts\";\nimport { kq, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type ParsedExecuteQuery,\n type ParsedReadQuery,\n type ParsedSelectQuery,\n type ParsedSetQuery,\n queryRefs,\n} from \"src/queries/sql/ParsedQuery.ts\";\nimport {\n type ParsedSql,\n type ParsedSqlCondition,\n joinSql,\n sourceRefs,\n sqlRefs,\n} from \"src/queries/sql/ParsedSqlExpression.ts\";\nimport type { ParsedCte, ParsedJoin, ParsedSource } from \"src/queries/sql/query.ts\";\nimport { tableSqlName } from \"src/queries/sql/Tables.ts\";\nimport { assertNever, fail } from \"src/utils.ts\";\n\n/** Rendered SQL and its positional bindings. */\nexport interface SqlFragment {\n sql: string;\n bindings: unknown[];\n}\n\n/** Prunes unused joins/CTEs, validates joins, and renders a read statement. */\nexport function renderQuery(query: ParsedReadQuery): SqlFragment {\n return renderSql({ kind: \"query\", query });\n}\n\n/** Prunes unused joins/CTEs, validates joins, and renders a read or mutation statement. */\nexport function renderStatement(query: ParsedReadQuery | ParsedExecuteQuery): SqlFragment {\n return query.kind === \"select\" || query.kind === \"set\" ? renderQuery(query) : renderSql(buildStatementSql(query));\n}\n\n/** Renders an expression and its bindings, pruning and validating any embedded queries. */\nexport function renderSql(node: ParsedSql): SqlFragment {\n let result: SqlFragment;\n switch (node.kind) {\n case \"column\":\n // Both identifiers can be user-provided: a subquery's `as` name or an `a.column(...)` argument.\n result = { sql: `${safeKq(node.alias)}.${safeKq(node.column)}`, bindings: [] };\n break;\n case \"star\":\n result = { sql: `${safeKq(node.alias)}.*`, bindings: [] };\n break;\n case \"joined\":\n case \"raw\": {\n const parts = node.parts.map((part) =>\n typeof part === \"string\"\n ? { sql: part, bindings: [] }\n : \"kind\" in part\n ? renderSql(part)\n : { sql: \"?\", bindings: [part.value] },\n );\n result = {\n sql: parts.map((part) => part.sql).join(\"\"),\n bindings: parts.flatMap((part) => part.bindings),\n };\n break;\n }\n case \"query\":\n result = renderSql(buildQuerySql(node.query));\n break;\n case \"condition\": {\n const condition = renderCondition(node.condition) as ParsedExpressionFilter;\n const rendered = buildWhereClause(condition, node.topLevel, (query) => buildRawQuery(query, {}));\n result = { sql: rendered?.[0] ?? \"\", bindings: rendered?.[1] ?? [] };\n break;\n }\n default:\n return assertNever(node);\n }\n\n return result;\n}\n\n/** Converts expression leaves to rendered predicates for the shared condition renderer. */\nfunction renderCondition(condition: ParsedSqlCondition): ParsedExpressionCondition {\n if (condition.kind === \"exp\") {\n return { ...condition, conditions: condition.conditions.map((child) => renderCondition(child)) };\n }\n if (condition.kind === \"expression\") {\n const rendered = renderSql(condition.expression);\n return {\n kind: \"raw\",\n condition: rendered.sql,\n bindings: rendered.bindings,\n // Pruning has finished; the shared condition renderer only needs SQL and bindings.\n aliases: [],\n pruneable: false,\n };\n }\n return condition;\n}\n\n/** Prunes unused joins/CTEs, validates joins, and builds the SELECT SQL. */\nfunction buildQuerySql(query: ParsedReadQuery): ParsedSql {\n if (query.kind === \"set\") return renderSetQuery(query);\n const { from, selects, groupBys, orderBys, where, having } = query;\n const { joins: kept, ctes: keptCtes } = pruneJoins(\n query,\n from,\n query.joins,\n query.ctes,\n [...selects, ...groupBys, ...orderBys, where, having].filter((expression) => expression !== undefined),\n );\n // Joins emit in declaration order, so an ON may only reference sources declared before it; a forward\n // reference would reach PG as invalid SQL (\"missing FROM-clause entry\"). Reordering is not offered:\n // it is not semantics-preserving once INNER and LEFT joins mix, and the caller's fix is trivial.\n const laterAliases = new Set(kept.map((j) => j.source.alias));\n for (const j of kept) {\n if (!j.on) {\n fail(\n `Join ${describeSource(j.source)} has no ON condition left (they all pruned), but the query still references it`,\n );\n }\n laterAliases.delete(j.source.alias);\n const forward = sqlRefs(j.on).find((r) => laterAliases.has(r));\n if (forward) {\n fail(\n `Join ${describeSource(j.source)} references '${forward}', which is joined later; move that join earlier in the join array`,\n );\n }\n }\n\n // Assemble the SELECT after pruning and join validation.\n const out: (string | ParsedSql)[] = [];\n // WITH leads the statement, so its bindings must be pushed before the SELECT's.\n if (keptCtes.length > 0) out.push(withFragment(keptCtes));\n out.push(`SELECT ${query.distinct ? \"DISTINCT \" : \"\"}`);\n out.push(joinSql(selects, \", \"));\n out.push(joinSql([\" FROM \", sourceSql(from)]));\n for (const j of kept) {\n const keyword = j.kind === \"inner\" ? \"JOIN\" : \"LEFT OUTER JOIN\";\n out.push(joinSql([` ${keyword} `, sourceSql(j.source), \" ON \", j.on!]));\n }\n if (where) out.push(joinSql([\" WHERE \", where]));\n if (groupBys.length > 0) out.push(joinSql([\" GROUP BY \", joinSql(groupBys, \", \")]));\n if (having) out.push(joinSql([\" HAVING \", having]));\n if (orderBys.length > 0) out.push(joinSql([\" ORDER BY \", joinSql(orderBys, \", \")]));\n if (query.limit !== undefined) out.push(joinSql([\" LIMIT \", { value: query.limit }]));\n if (query.offset !== undefined) out.push(joinSql([\" OFFSET \", { value: query.offset }]));\n return joinSql(out);\n}\n\n/** Builds INSERT, UPDATE, or DELETE SQL from the rewritten AST. */\nfunction buildStatementSql(query: ParsedExecuteQuery): ParsedSql {\n const operation = query.kind === \"delete\" ? \"DELETE FROM\" : query.kind === \"insert\" ? \"INSERT INTO\" : \"UPDATE\";\n const target = tableSqlName({ tableName: query.target.table, schema: query.target.schema });\n const parts: (string | ParsedSql)[] = [`${operation} ${target} AS ${kq(query.target.alias)}`];\n if (query.kind === \"insert\") {\n parts.push(` (${query.columns.map(kq).join(\", \")})`);\n if (query.values) {\n const rows = query.values.map((row) => joinSql([\"(\", joinSql(row, \", \"), \")\"]));\n parts.push(\" VALUES \", joinSql(rows, \", \"));\n } else {\n const source = query.source!;\n const alias = safeKq(source.alias);\n const columns = source.columns.map((key) => `${alias}.${safeKq(key)}`).join(\", \");\n parts.push(` SELECT ${columns} FROM (`, { kind: \"query\", query: source.query }, `) AS ${alias}`);\n }\n } else if (query.kind === \"update\") {\n const assignments = query.assignments.map((entry) => joinSql([`${kq(entry.column)} = `, entry.value]));\n parts.push(\" SET \", joinSql(assignments, \", \"));\n }\n\n if (query.conditions.length) {\n const conditions = query.conditions.map((condition) => joinSql([\"(\", condition, \")\"]));\n parts.push(\" WHERE \", joinSql(conditions, \" AND \"));\n }\n if (query.returning.length) parts.push(\" RETURNING \", joinSql(query.returning, \", \"));\n const body = joinSql(parts);\n const ctes = pruneCtes(query.ctes, new Set(sqlRefs(body)));\n return ctes.length ? joinSql([withFragment(ctes), body]) : body;\n}\n\n/**\n * Pruning: em.find's paradigm, on a flat join list.\n *\n * A condition given `undefined` was already dropped by `ConditionBuilder`. Now a join that nothing\n * references anymore drops with it: a join is required if the source, a select, a surviving condition,\n * a group-by, an order-by, or another required join's ON references it, or if it is pinned with\n * `keep: true`. Marking follows ON dependencies transitively, exactly like `pruneUnusedJoins`'s\n * `DependencyTracker`.\n *\n * em.find's joins almost never filter rows by themselves, so pruning them is semantics-preserving. An\n * explicit `{ inner: b, on }` here does filter rows, so pruning it when unreferenced drops that filter;\n * that matches `{ books: { title: undefined } }` in em.find and is deliberate. `keep: true` pins it, and\n * a pure existence filter is better written as `a.id.in(query({ ... }))`, which is never `undefined`.\n *\n * CTEs prune on the same rule and through the same dependency map: a `with` entry nothing reads\n * anymore drops with the join that read it, and a CTE read only by another CTE survives with it.\n * A CTE joined into the query shares its alias with that join, so their dependencies are merged.\n *\n * The one join that never prunes is a recursive term's reference to its own CTE: PostgreSQL requires\n * it, so it is not the caller's optional filter (see `Ctx.recursiveSelf`).\n */\nfunction pruneJoins(\n q: ParsedSelectQuery,\n from: ParsedSource,\n joins: ParsedJoin[],\n ctes: ParsedCte[],\n used: ParsedSql[],\n): { joins: ParsedJoin[]; ctes: ParsedCte[] } {\n if (q.pruneJoins === false) return { joins, ctes };\n const deps = new Map<string, string[]>();\n function addDeps(alias: string, refs: readonly string[]): void {\n const own = refs.filter((r) => r !== alias);\n const existing = deps.get(alias);\n if (existing) existing.push(...own);\n else deps.set(alias, own);\n }\n for (const j of joins) {\n addDeps(j.source.alias, [...(j.on ? sqlRefs(j.on) : []), ...sourceRefs(j.source)]);\n }\n for (const c of ctes) addDeps(c.alias, queryRefs(c.query));\n const required = new Set<string>();\n function markRequired(alias: string): void {\n if (required.has(alias)) return;\n required.add(alias);\n for (const dep of deps.get(alias) ?? []) markRequired(dep);\n }\n markRequired(from.alias);\n for (const ref of sourceRefs(from)) markRequired(ref);\n for (const r of used.flatMap(sqlRefs)) markRequired(r);\n for (const j of joins) if (j.keep) markRequired(j.source.alias);\n // A recursive term must keep its reference to its own CTE; PostgreSQL rejects a term without one,\n // and pruning it would quietly turn the recursion into a plain select over the base term's table.\n if (q.recursiveAlias) markRequired(q.recursiveAlias);\n return {\n joins: joins.filter((j) => required.has(j.source.alias)),\n ctes: ctes.filter((c) => required.has(c.alias)),\n };\n}\n\n/**\n * Drops the CTEs that nothing reads, given the aliases the rest of the statement referenced.\n *\n * A CTE can only read earlier siblings, so going last to first means every CTE that could read this one\n * was already visited, and its own reads are already in `referenced`. That makes one pass enough; first\n * to last would have to repeat until the set stopped growing. `unshift` restores WITH order.\n */\nfunction pruneCtes(ctes: ParsedCte[], referenced: Set<string>): ParsedCte[] {\n const kept: ParsedCte[] = [];\n for (let i = ctes.length - 1; i >= 0; i--) {\n const cte = ctes[i];\n if (!referenced.has(cte.alias)) continue;\n for (const ref of queryRefs(cte.query)) referenced.add(ref);\n kept.unshift(cte);\n }\n return kept;\n}\n\n/**\n * Renders `WITH a AS (...), b AS (...) `, whose bindings lead the statement, as their SQL does.\n *\n * One recursive CTE makes the whole clause `WITH RECURSIVE`, PostgreSQL's rule: the keyword is on the\n * clause, not on the entry that needs it, and it does not force the other entries to be recursive.\n */\nfunction withFragment(ctes: ParsedCte[]): ParsedSql {\n const recursive = ctes.some((c) => c.recursive) ? \" RECURSIVE\" : \"\";\n const bodies = ctes.map((c) => joinSql([`${safeKq(c.alias)} AS (`, { kind: \"query\", query: c.query }, \")\"]));\n return joinSql([`WITH${recursive} `, joinSql(bodies, \", \"), \" \"]);\n}\n\n/** Composes set operands after their SELECT nodes have been rewritten. */\nfunction renderSetQuery(query: ParsedSetQuery): ParsedSql {\n let body: ParsedSql | undefined;\n for (const operand of query.operands) {\n let branch: ParsedSql = { kind: \"query\", query: operand.query };\n if (operand.alignment) {\n const alias = safeKq(operand.alignment.alias);\n const columns = operand.alignment.columns.map((key) => `${alias}.${safeKq(key)} AS ${safeKq(key)}`).join(\", \");\n branch = joinSql([`SELECT ${columns} FROM (`, branch, `) AS ${alias}`]);\n }\n body = body ? joinSql([\"(\", body, `) ${query.operation} (`, branch, \")\"]) : branch;\n }\n const ctes = pruneCtes(query.ctes, new Set(query.operands.flatMap((operand) => queryRefs(operand.query))));\n const parts: (string | ParsedSql)[] = ctes.length ? [withFragment(ctes), body!] : [body!];\n if (query.orderBys.length) parts.push(` ORDER BY ${query.orderBys.join(\", \")}`);\n if (query.limit !== undefined) parts.push(joinSql([\" LIMIT \", { value: query.limit }]));\n if (query.offset !== undefined) parts.push(joinSql([\" OFFSET \", { value: query.offset }]));\n return joinSql(parts);\n}\n\n/** Builds source syntax after plugins have rewritten its table, CTE, or query. */\nfunction sourceSql(source: ParsedSource): ParsedSql {\n switch (source.kind) {\n case \"table\":\n return joinSql([\n `${tableSqlName({ tableName: source.table, schema: source.schema })} AS ${safeKq(source.alias)}`,\n ]);\n case \"cte\":\n return joinSql([safeKq(source.cte), ...(source.cte === source.alias ? [] : [` AS ${safeKq(source.alias)}`])]);\n case \"query\":\n return joinSql([\"(\", { kind: \"query\", query: source.query }, `) AS ${safeKq(source.alias)}`]);\n default:\n return assertNever(source);\n }\n}\n\n/** Names the rewritten source in join-validation errors. */\nfunction describeSource(source: ParsedSource): string {\n switch (source.kind) {\n case \"table\":\n return `table ${source.schema ? `${source.schema}.` : \"\"}${source.table} AS ${source.alias}`;\n case \"cte\":\n return `CTE ${source.cte} AS ${source.alias}`;\n case \"query\":\n return `subquery AS ${source.alias}`;\n default:\n return assertNever(source);\n }\n}\n"],"mappings":";;;;;;;;;AA6BA,SAAgB,YAAY,OAAqC;CAC/D,OAAO,UAAU;EAAE,MAAM;EAAS;CAAM,CAAC;AAC3C;;AA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,CAAC,CAAC,CAAC;CACzF,OAAO,QAAQ,KAAK;AACtB;;AAGA,SAAS,UAAU,QAAiC;CAClD,QAAQ,OAAO,MAAf;EACE,KAAK,SACH,OAAO,QAAQ,CACb,GAAG,aAAa;GAAE,WAAW,OAAO;GAAO,QAAQ,OAAO;EAAO,CAAC,EAAE,MAAM,OAAO,OAAO,KAAK,GAC/F,CAAC;EACH,KAAK,OACH,OAAO,QAAQ,CAAC,OAAO,OAAO,GAAG,GAAG,GAAI,OAAO,QAAQ,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,OAAO,OAAO,KAAK,GAAG,CAAE,CAAC;EAC9G,KAAK,SACH,OAAO,QAAQ;GAAC;GAAK;IAAE,MAAM;IAAS,OAAO,OAAO;GAAM;GAAG,QAAQ,OAAO,OAAO,KAAK;EAAG,CAAC;EAC9F,SACE,OAAO,YAAY,MAAM;CAC7B;AACF;;AAGA,SAAS,eAAe,QAA8B;CACpD,QAAQ,OAAO,MAAf;EACE,KAAK,SACH,OAAO,SAAS,OAAO,SAAS,GAAG,OAAO,OAAO,KAAK,KAAK,OAAO,MAAM,MAAM,OAAO;EACvF,KAAK,OACH,OAAO,OAAO,OAAO,IAAI,MAAM,OAAO;EACxC,KAAK,SACH,OAAO,eAAe,OAAO;EAC/B,SACE,OAAO,YAAY,MAAM;CAC7B;AACF"}
|
package/build/resurrection.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_clientIds = require("./clientIds.cjs");
|
|
2
3
|
const require_Entity = require("./Entity.cjs");
|
|
3
4
|
const require_EntityManager = require("./EntityManager.cjs");
|
|
4
5
|
const require_EntityMetadata = require("./EntityMetadata.cjs");
|
|
@@ -15,7 +16,7 @@ function resurrectIfSoftDeleted(entity) {
|
|
|
15
16
|
*/
|
|
16
17
|
async function findExistingIfUniqueBy(em, constructor, input) {
|
|
17
18
|
const meta = require_EntityMetadata.getMetadata(constructor);
|
|
18
|
-
const candidates = getUniqueByCandidates(meta, input);
|
|
19
|
+
const candidates = getUniqueByCandidates(em, meta, input);
|
|
19
20
|
for (const where of candidates) {
|
|
20
21
|
const inMemory = onlySoftDeleted(em.filterEntities(constructor, where));
|
|
21
22
|
if (inMemory.length > 1) throw new require_EntityManager.TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);
|
|
@@ -37,13 +38,14 @@ function onlySoftDeleted(entities) {
|
|
|
37
38
|
return entities.filter((entity) => !entity.isDeletedEntity && entity.isSoftDeletedEntity);
|
|
38
39
|
}
|
|
39
40
|
/** Builds pushdown-safe where clauses from configured identity fields. */
|
|
40
|
-
function getUniqueByCandidates(meta, input) {
|
|
41
|
+
function getUniqueByCandidates(em, meta, input) {
|
|
41
42
|
return (meta.uniqueBy ?? require_EntityMetadata.getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {
|
|
42
43
|
const where = {};
|
|
43
44
|
for (const fieldName of fields) {
|
|
44
45
|
const field = meta.allFields[fieldName];
|
|
45
46
|
if (!field || !isQueryableIdentityField(field)) return [];
|
|
46
|
-
|
|
47
|
+
let value = getIdentityValue(field, input);
|
|
48
|
+
if ((field.kind === "m2o" || field.kind === "poly") && require_clientIds.isClientId(value)) value = require_clientIds.resolveClientId(em, field, value);
|
|
47
49
|
if (value === void 0 || value === null) return [];
|
|
48
50
|
where[field.fieldName] = value;
|
|
49
51
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resurrection.cjs","names":["getBaseMeta","getMetadata","TooManyError","isEntity"],"sources":["../src/resurrection.ts"],"sourcesContent":["import { type Entity, isEntity } from \"src/Entity.ts\";\nimport { type EntityManager, type MaybeAbstractEntityConstructor, TooManyError } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { setField } from \"src/fields.ts\";\n\n/** Clears the soft-delete marker so a matched entity is updated instead of recreated. */\nexport function resurrectIfSoftDeleted(entity: Entity): void {\n const deletedAt = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n if (deletedAt && (entity as any).isSoftDeletedEntity) {\n setField(entity, deletedAt, undefined);\n }\n}\n\n/**\n * Finds an existing entity when the input fully covers one configured `uniqueBy` candidate.\n * I.e. with `uniqueBy = [[\"email\"], [\"author\", \"title\"]]`, `{ email }` or `{ authorId, title }` can lookup an existing row.\n */\nexport async function findExistingIfUniqueBy<T extends Entity>(\n em: EntityManager<any, any, any>,\n constructor: MaybeAbstractEntityConstructor<T>,\n input: object,\n): Promise<T | undefined> {\n const meta = getMetadata(constructor);\n const candidates = getUniqueByCandidates(meta, input);\n for (const where of candidates) {\n const inMemory = onlySoftDeleted(em.filterEntities(constructor as any, where as any) as T[]);\n if (inMemory.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (inMemory.length === 1) {\n resurrectIfSoftDeleted(inMemory[0]);\n return inMemory[0];\n }\n\n // I.e. `{ publisher: newPublisherEntity }` cannot already exist in the database, so skip the `em.find`.\n const hasNewEntityParam = Object.values(where).some((value) => isEntity(value) && value.isNewEntity);\n if (hasNewEntityParam) continue;\n\n const entities = onlySoftDeleted(\n await (em as any).find(constructor, newWhereEqual(meta, where), { softDeletes: \"include\" }),\n ) as T[];\n if (entities.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (entities.length === 1) {\n resurrectIfSoftDeleted(entities[0]);\n return entities[0];\n }\n }\n return undefined;\n}\n\n/** Returns soft-deleted entities that are safe for upsert to resurrect. */\nfunction onlySoftDeleted<T extends Entity>(entities: T[]): T[] {\n return entities.filter(\n (entity) => !entity.isDeletedEntity && (entity as T & { isSoftDeletedEntity?: boolean }).isSoftDeletedEntity,\n );\n}\n\n/** Builds pushdown-safe where clauses from configured identity fields. */\nfunction getUniqueByCandidates(meta: EntityMetadata, input: object): object[] {\n return (meta.uniqueBy ?? getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {\n const where: Record<string, unknown> = {};\n for (const fieldName of fields) {\n const field = meta.allFields[fieldName];\n if (!field || !isQueryableIdentityField(field)) return [];\n
|
|
1
|
+
{"version":3,"file":"resurrection.cjs","names":["getBaseMeta","getMetadata","TooManyError","isEntity","isClientId","resolveClientId"],"sources":["../src/resurrection.ts"],"sourcesContent":["import { isClientId, resolveClientId } from \"src/clientIds.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { type EntityManager, type MaybeAbstractEntityConstructor, TooManyError } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { setField } from \"src/fields.ts\";\n\n/** Clears the soft-delete marker so a matched entity is updated instead of recreated. */\nexport function resurrectIfSoftDeleted(entity: Entity): void {\n const deletedAt = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n if (deletedAt && (entity as any).isSoftDeletedEntity) {\n setField(entity, deletedAt, undefined);\n }\n}\n\n/**\n * Finds an existing entity when the input fully covers one configured `uniqueBy` candidate.\n * I.e. with `uniqueBy = [[\"email\"], [\"author\", \"title\"]]`, `{ email }` or `{ authorId, title }` can lookup an existing row.\n */\nexport async function findExistingIfUniqueBy<T extends Entity>(\n em: EntityManager<any, any, any>,\n constructor: MaybeAbstractEntityConstructor<T>,\n input: object,\n): Promise<T | undefined> {\n const meta = getMetadata(constructor);\n const candidates = getUniqueByCandidates(em, meta, input);\n for (const where of candidates) {\n const inMemory = onlySoftDeleted(em.filterEntities(constructor as any, where as any) as T[]);\n if (inMemory.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (inMemory.length === 1) {\n resurrectIfSoftDeleted(inMemory[0]);\n return inMemory[0];\n }\n\n // I.e. `{ publisher: newPublisherEntity }` cannot already exist in the database, so skip the `em.find`.\n const hasNewEntityParam = Object.values(where).some((value) => isEntity(value) && value.isNewEntity);\n if (hasNewEntityParam) continue;\n\n const entities = onlySoftDeleted(\n await (em as any).find(constructor, newWhereEqual(meta, where), { softDeletes: \"include\" }),\n ) as T[];\n if (entities.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (entities.length === 1) {\n resurrectIfSoftDeleted(entities[0]);\n return entities[0];\n }\n }\n return undefined;\n}\n\n/** Returns soft-deleted entities that are safe for upsert to resurrect. */\nfunction onlySoftDeleted<T extends Entity>(entities: T[]): T[] {\n return entities.filter(\n (entity) => !entity.isDeletedEntity && (entity as T & { isSoftDeletedEntity?: boolean }).isSoftDeletedEntity,\n );\n}\n\n/** Builds pushdown-safe where clauses from configured identity fields. */\nfunction getUniqueByCandidates(em: EntityManager, meta: EntityMetadata, input: object): object[] {\n return (meta.uniqueBy ?? getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {\n const where: Record<string, unknown> = {};\n for (const fieldName of fields) {\n const field = meta.allFields[fieldName];\n if (!field || !isQueryableIdentityField(field)) return [];\n let value = getIdentityValue(field, input);\n if ((field.kind === \"m2o\" || field.kind === \"poly\") && isClientId(value)) {\n value = resolveClientId(em, field, value);\n }\n if (value === undefined || value === null) return [];\n where[field.fieldName] = value;\n }\n return [where];\n });\n}\n\n/** Returns the identity value from the input. */\nfunction getIdentityValue(field: Field, input: object): unknown {\n if (Object.hasOwn(input, field.fieldName)) {\n return normalizeIdentityValue((input as Record<string, unknown>)[field.fieldName]);\n }\n if (field.fieldIdName && Object.hasOwn(input, field.fieldIdName)) {\n return normalizeIdentityValue((input as Record<string, unknown>)[field.fieldIdName]);\n }\n return undefined;\n}\n\n/** Returns raw ids from relation inputs, i.e. `{ publisher: { id: \"p:1\" } }` becomes `{ publisher: \"p:1\" }`. */\nfunction normalizeIdentityValue(value: unknown): unknown {\n if (!isEntity(value) && value && typeof value === \"object\" && Object.hasOwn(value, \"id\")) {\n return (value as { id?: unknown }).id;\n }\n return value;\n}\n\n/** Returns true if Joist can push this identity field into a flat find clause. */\nfunction isQueryableIdentityField(field: Field): boolean {\n return field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"m2o\" || field.kind === \"poly\";\n}\n\nfunction whereAsString(where: object): string {\n return Object.entries(where)\n .map(([key, value]) => `${key}=${value}`)\n .join(\", \");\n}\n\n/** Builds exact identity filters for primitives and relations. */\nexport function newWhereEqual(meta: EntityMetadata, input: object): object {\n const where: Record<string, unknown> = {};\n\n // Arrays need eq for exact equality; relations must stay as-is because eq would be a nested entity filter.\n // Unset values must match SQL NULL, e.g. publisher: undefined must not omit the publisher filter.\n for (const name of Object.keys(input)) {\n const value = (input as Record<string, unknown>)[name] ?? null;\n where[name] = meta.allFields[name]?.kind === \"primitive\" ? { eq: value } : value;\n }\n\n return where;\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,uBAAuB,QAAsB;CAC3D,MAAM,YAAYA,uBAAAA,YAAYC,uBAAAA,YAAY,MAAM,CAAC,CAAC,CAAC,iBAAiB;CACpE,IAAI,aAAc,OAAe,qBAC/B,eAAA,SAAS,QAAQ,WAAW,KAAA,CAAS;AAEzC;;;;;AAMA,eAAsB,uBACpB,IACA,aACA,OACwB;CACxB,MAAM,OAAOA,uBAAAA,YAAY,WAAW;CACpC,MAAM,aAAa,sBAAsB,IAAI,MAAM,KAAK;CACxD,KAAK,MAAM,SAAS,YAAY;EAC9B,MAAM,WAAW,gBAAgB,GAAG,eAAe,aAAoB,KAAY,CAAQ;EAC3F,IAAI,SAAS,SAAS,GACpB,MAAM,IAAIC,sBAAAA,aAAa,gCAAgC,KAAK,KAAK,QAAQ,cAAc,KAAK,GAAG;OAC1F,IAAI,SAAS,WAAW,GAAG;GAChC,uBAAuB,SAAS,EAAE;GAClC,OAAO,SAAS;EAClB;EAIA,IAD0B,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,UAAUC,eAAAA,SAAS,KAAK,KAAK,MAAM,WACpE,GAAG;EAEvB,MAAM,WAAW,gBACf,MAAO,GAAW,KAAK,aAAa,cAAc,MA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Y,OAAO,OAAO,OAAO,IAAI,GACrF,OAAQ,MAA2B;CAErC,OAAO;AACT;;AAGA,SAAS,yBAAyB,OAAuB;CACvD,OAAO,MAAM,SAAS,eAAe,MAAM,SAAS,UAAU,MAAM,SAAS,SAAS,MAAM,SAAS;AACvG;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,CACxC,KAAK,IAAI;AACd;;AAGA,SAAgB,cAAc,MAAsB,OAAuB;CACzE,MAAM,QAAiC,CAAC;CAIxC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,GAAG;EACrC,MAAM,QAAS,MAAkC,SAAS;EAC1D,MAAM,QAAQ,KAAK,UAAU,KAAK,EAAE,SAAS,cAAc,EAAE,IAAI,MAAM,IAAI;CAC7E;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resurrection.d.cts","names":[],"sources":["../src/resurrection.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"resurrection.d.cts","names":[],"sources":["../src/resurrection.ts"],"mappings":";;;;wBAOgB,uBAAuB,QAAQ;;;;;wBAWzB,uBAAuB,UAAU,QACrD,IAAI,8BACJ,aAAa,+BAA+B,IAC5C,gBACC,QAAQ;;wBAqFK,cAAc,MAAM,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resurrection.d.mts","names":[],"sources":["../src/resurrection.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"resurrection.d.mts","names":[],"sources":["../src/resurrection.ts"],"mappings":";;;;wBAOgB,uBAAuB,QAAQ;;;;;wBAWzB,uBAAuB,UAAU,QACrD,IAAI,8BACJ,aAAa,+BAA+B,IAC5C,gBACC,QAAQ;;wBAqFK,cAAc,MAAM,gBAAgB"}
|
package/build/resurrection.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isClientId, resolveClientId } from "./clientIds.js";
|
|
1
2
|
import { isEntity } from "./Entity.js";
|
|
2
3
|
import { TooManyError } from "./EntityManager.js";
|
|
3
4
|
import { getBaseMeta, getMetadata } from "./EntityMetadata.js";
|
|
@@ -14,7 +15,7 @@ function resurrectIfSoftDeleted(entity) {
|
|
|
14
15
|
*/
|
|
15
16
|
async function findExistingIfUniqueBy(em, constructor, input) {
|
|
16
17
|
const meta = getMetadata(constructor);
|
|
17
|
-
const candidates = getUniqueByCandidates(meta, input);
|
|
18
|
+
const candidates = getUniqueByCandidates(em, meta, input);
|
|
18
19
|
for (const where of candidates) {
|
|
19
20
|
const inMemory = onlySoftDeleted(em.filterEntities(constructor, where));
|
|
20
21
|
if (inMemory.length > 1) throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);
|
|
@@ -36,13 +37,14 @@ function onlySoftDeleted(entities) {
|
|
|
36
37
|
return entities.filter((entity) => !entity.isDeletedEntity && entity.isSoftDeletedEntity);
|
|
37
38
|
}
|
|
38
39
|
/** Builds pushdown-safe where clauses from configured identity fields. */
|
|
39
|
-
function getUniqueByCandidates(meta, input) {
|
|
40
|
+
function getUniqueByCandidates(em, meta, input) {
|
|
40
41
|
return (meta.uniqueBy ?? getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {
|
|
41
42
|
const where = {};
|
|
42
43
|
for (const fieldName of fields) {
|
|
43
44
|
const field = meta.allFields[fieldName];
|
|
44
45
|
if (!field || !isQueryableIdentityField(field)) return [];
|
|
45
|
-
|
|
46
|
+
let value = getIdentityValue(field, input);
|
|
47
|
+
if ((field.kind === "m2o" || field.kind === "poly") && isClientId(value)) value = resolveClientId(em, field, value);
|
|
46
48
|
if (value === void 0 || value === null) return [];
|
|
47
49
|
where[field.fieldName] = value;
|
|
48
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resurrection.js","names":[],"sources":["../src/resurrection.ts"],"sourcesContent":["import { type Entity, isEntity } from \"src/Entity.ts\";\nimport { type EntityManager, type MaybeAbstractEntityConstructor, TooManyError } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { setField } from \"src/fields.ts\";\n\n/** Clears the soft-delete marker so a matched entity is updated instead of recreated. */\nexport function resurrectIfSoftDeleted(entity: Entity): void {\n const deletedAt = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n if (deletedAt && (entity as any).isSoftDeletedEntity) {\n setField(entity, deletedAt, undefined);\n }\n}\n\n/**\n * Finds an existing entity when the input fully covers one configured `uniqueBy` candidate.\n * I.e. with `uniqueBy = [[\"email\"], [\"author\", \"title\"]]`, `{ email }` or `{ authorId, title }` can lookup an existing row.\n */\nexport async function findExistingIfUniqueBy<T extends Entity>(\n em: EntityManager<any, any, any>,\n constructor: MaybeAbstractEntityConstructor<T>,\n input: object,\n): Promise<T | undefined> {\n const meta = getMetadata(constructor);\n const candidates = getUniqueByCandidates(meta, input);\n for (const where of candidates) {\n const inMemory = onlySoftDeleted(em.filterEntities(constructor as any, where as any) as T[]);\n if (inMemory.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (inMemory.length === 1) {\n resurrectIfSoftDeleted(inMemory[0]);\n return inMemory[0];\n }\n\n // I.e. `{ publisher: newPublisherEntity }` cannot already exist in the database, so skip the `em.find`.\n const hasNewEntityParam = Object.values(where).some((value) => isEntity(value) && value.isNewEntity);\n if (hasNewEntityParam) continue;\n\n const entities = onlySoftDeleted(\n await (em as any).find(constructor, newWhereEqual(meta, where), { softDeletes: \"include\" }),\n ) as T[];\n if (entities.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (entities.length === 1) {\n resurrectIfSoftDeleted(entities[0]);\n return entities[0];\n }\n }\n return undefined;\n}\n\n/** Returns soft-deleted entities that are safe for upsert to resurrect. */\nfunction onlySoftDeleted<T extends Entity>(entities: T[]): T[] {\n return entities.filter(\n (entity) => !entity.isDeletedEntity && (entity as T & { isSoftDeletedEntity?: boolean }).isSoftDeletedEntity,\n );\n}\n\n/** Builds pushdown-safe where clauses from configured identity fields. */\nfunction getUniqueByCandidates(meta: EntityMetadata, input: object): object[] {\n return (meta.uniqueBy ?? getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {\n const where: Record<string, unknown> = {};\n for (const fieldName of fields) {\n const field = meta.allFields[fieldName];\n if (!field || !isQueryableIdentityField(field)) return [];\n
|
|
1
|
+
{"version":3,"file":"resurrection.js","names":[],"sources":["../src/resurrection.ts"],"sourcesContent":["import { isClientId, resolveClientId } from \"src/clientIds.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { type EntityManager, type MaybeAbstractEntityConstructor, TooManyError } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { setField } from \"src/fields.ts\";\n\n/** Clears the soft-delete marker so a matched entity is updated instead of recreated. */\nexport function resurrectIfSoftDeleted(entity: Entity): void {\n const deletedAt = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n if (deletedAt && (entity as any).isSoftDeletedEntity) {\n setField(entity, deletedAt, undefined);\n }\n}\n\n/**\n * Finds an existing entity when the input fully covers one configured `uniqueBy` candidate.\n * I.e. with `uniqueBy = [[\"email\"], [\"author\", \"title\"]]`, `{ email }` or `{ authorId, title }` can lookup an existing row.\n */\nexport async function findExistingIfUniqueBy<T extends Entity>(\n em: EntityManager<any, any, any>,\n constructor: MaybeAbstractEntityConstructor<T>,\n input: object,\n): Promise<T | undefined> {\n const meta = getMetadata(constructor);\n const candidates = getUniqueByCandidates(em, meta, input);\n for (const where of candidates) {\n const inMemory = onlySoftDeleted(em.filterEntities(constructor as any, where as any) as T[]);\n if (inMemory.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (inMemory.length === 1) {\n resurrectIfSoftDeleted(inMemory[0]);\n return inMemory[0];\n }\n\n // I.e. `{ publisher: newPublisherEntity }` cannot already exist in the database, so skip the `em.find`.\n const hasNewEntityParam = Object.values(where).some((value) => isEntity(value) && value.isNewEntity);\n if (hasNewEntityParam) continue;\n\n const entities = onlySoftDeleted(\n await (em as any).find(constructor, newWhereEqual(meta, where), { softDeletes: \"include\" }),\n ) as T[];\n if (entities.length > 1) {\n throw new TooManyError(`Found more than one existing ${meta.type} with ${whereAsString(where)}`);\n } else if (entities.length === 1) {\n resurrectIfSoftDeleted(entities[0]);\n return entities[0];\n }\n }\n return undefined;\n}\n\n/** Returns soft-deleted entities that are safe for upsert to resurrect. */\nfunction onlySoftDeleted<T extends Entity>(entities: T[]): T[] {\n return entities.filter(\n (entity) => !entity.isDeletedEntity && (entity as T & { isSoftDeletedEntity?: boolean }).isSoftDeletedEntity,\n );\n}\n\n/** Builds pushdown-safe where clauses from configured identity fields. */\nfunction getUniqueByCandidates(em: EntityManager, meta: EntityMetadata, input: object): object[] {\n return (meta.uniqueBy ?? getBaseMeta(meta).uniqueBy ?? []).flatMap((fields) => {\n const where: Record<string, unknown> = {};\n for (const fieldName of fields) {\n const field = meta.allFields[fieldName];\n if (!field || !isQueryableIdentityField(field)) return [];\n let value = getIdentityValue(field, input);\n if ((field.kind === \"m2o\" || field.kind === \"poly\") && isClientId(value)) {\n value = resolveClientId(em, field, value);\n }\n if (value === undefined || value === null) return [];\n where[field.fieldName] = value;\n }\n return [where];\n });\n}\n\n/** Returns the identity value from the input. */\nfunction getIdentityValue(field: Field, input: object): unknown {\n if (Object.hasOwn(input, field.fieldName)) {\n return normalizeIdentityValue((input as Record<string, unknown>)[field.fieldName]);\n }\n if (field.fieldIdName && Object.hasOwn(input, field.fieldIdName)) {\n return normalizeIdentityValue((input as Record<string, unknown>)[field.fieldIdName]);\n }\n return undefined;\n}\n\n/** Returns raw ids from relation inputs, i.e. `{ publisher: { id: \"p:1\" } }` becomes `{ publisher: \"p:1\" }`. */\nfunction normalizeIdentityValue(value: unknown): unknown {\n if (!isEntity(value) && value && typeof value === \"object\" && Object.hasOwn(value, \"id\")) {\n return (value as { id?: unknown }).id;\n }\n return value;\n}\n\n/** Returns true if Joist can push this identity field into a flat find clause. */\nfunction isQueryableIdentityField(field: Field): boolean {\n return field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"m2o\" || field.kind === \"poly\";\n}\n\nfunction whereAsString(where: object): string {\n return Object.entries(where)\n .map(([key, value]) => `${key}=${value}`)\n .join(\", \");\n}\n\n/** Builds exact identity filters for primitives and relations. */\nexport function newWhereEqual(meta: EntityMetadata, input: object): object {\n const where: Record<string, unknown> = {};\n\n // Arrays need eq for exact equality; relations must stay as-is because eq would be a nested entity filter.\n // Unset values must match SQL NULL, e.g. publisher: undefined must not omit the publisher filter.\n for (const name of Object.keys(input)) {\n const value = (input as Record<string, unknown>)[name] ?? null;\n where[name] = meta.allFields[name]?.kind === \"primitive\" ? { eq: value } : value;\n }\n\n return where;\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,uBAAuB,QAAsB;CAC3D,MAAM,YAAY,YAAY,YAAY,MAAM,CAAC,CAAC,CAAC,iBAAiB;CACpE,IAAI,aAAc,OAAe,qBAC/B,SAAS,QAAQ,WAAW,KAAA,CAAS;AAEzC;;;;;AAMA,eAAsB,uBACpB,IACA,aACA,OACwB;CACxB,MAAM,OAAO,YAAY,WAAW;CACpC,MAAM,aAAa,sBAAsB,IAAI,MAAM,KAAK;CACxD,KAAK,MAAM,SAAS,YAAY;EAC9B,MAAM,WAAW,gBAAgB,GAAG,eAAe,aAAoB,KAAY,CAAQ;EAC3F,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,aAAa,gCAAgC,KAAK,KAAK,QAAQ,cAAc,KAAK,GAAG;OAC1F,IAAI,SAAS,WAAW,GAAG;GAChC,uBAAuB,SAAS,EAAE;GAClC,OAAO,SAAS;EAClB;EAIA,IAD0B,OAAO,OAAO,KAAK,CAA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AAuB,OAAyB;CACvD,IAAI,CAAC,SAAS,KAAK,KAAK,SAAS,OAAO,UAAU,YAAY,OAAO,OAAO,OAAO,IAAI,GACrF,OAAQ,MAA2B;CAErC,OAAO;AACT;;AAGA,SAAS,yBAAyB,OAAuB;CACvD,OAAO,MAAM,SAAS,eAAe,MAAM,SAAS,UAAU,MAAM,SAAS,SAAS,MAAM,SAAS;AACvG;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,KAAK,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,CACxC,KAAK,IAAI;AACd;;AAGA,SAAgB,cAAc,MAAsB,OAAuB;CACzE,MAAM,QAAiC,CAAC;CAIxC,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,GAAG;EACrC,MAAM,QAAS,MAAkC,SAAS;EAC1D,MAAM,QAAQ,KAAK,UAAU,KAAK,EAAE,SAAS,cAAc,EAAE,IAAI,MAAM,IAAI;CAC7E;CAEA,OAAO;AACT"}
|
package/build/upsert.cjs
CHANGED
|
@@ -15,7 +15,7 @@ let joist_utils = require("joist-utils");
|
|
|
15
15
|
* A utility function to do partial-update style updates.
|
|
16
16
|
*
|
|
17
17
|
* The difference between this and `Entity.setPartial` is that we accept `DeepPartialOrNull`
|
|
18
|
-
* updates, similar to `
|
|
18
|
+
* updates, similar to `upsert`, instead of just a flat/shallow list of opts.
|
|
19
19
|
*/
|
|
20
20
|
async function updatePartial(entity, input) {
|
|
21
21
|
if (Object.keys(input).length === 0) return;
|
|
@@ -26,7 +26,7 @@ async function updatePartial(entity, input) {
|
|
|
26
26
|
const field = meta.allFields[key] || Object.values(meta.allFields).find((f) => f.fieldIdName === key);
|
|
27
27
|
if (!field) {
|
|
28
28
|
if (key === "delete" || key === "remove" || key === "op") return;
|
|
29
|
-
if (require_getProperties.getProperties(meta)[key]) {
|
|
29
|
+
if (require_getProperties.getProperties(meta)[key] || key === "$clientId") {
|
|
30
30
|
require_index.setOpt(meta, entity, key, value);
|
|
31
31
|
return;
|
|
32
32
|
} else throw new Error(`Unknown field ${key}`);
|
|
@@ -120,7 +120,10 @@ async function updatePartial(entity, input) {
|
|
|
120
120
|
}));
|
|
121
121
|
}
|
|
122
122
|
/**
|
|
123
|
-
*
|
|
123
|
+
* Creates or updates an entity from partial input.
|
|
124
|
+
*
|
|
125
|
+
* An id selects an existing entity by database ID or registered client ID. Omitting id keeps the
|
|
126
|
+
* existing creation and soft-delete resurrection behavior.
|
|
124
127
|
*/
|
|
125
128
|
async function upsert(em, constructor, input) {
|
|
126
129
|
const { id, ...rest } = input;
|