sonamu 0.13.8 → 0.13.10
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/dist/database/base-model.d.ts +5 -8
- package/dist/database/base-model.d.ts.map +1 -1
- package/dist/database/base-model.js +56 -24
- package/dist/database/puri.d.ts +1 -2
- package/dist/database/puri.d.ts.map +1 -1
- package/dist/database/puri.js +65 -58
- package/dist/entity/entity.d.ts +13 -1
- package/dist/entity/entity.d.ts.map +1 -1
- package/dist/entity/entity.js +42 -4
- package/dist/stream/__tests__/ws-test-helpers.d.ts +2 -1
- package/dist/stream/__tests__/ws-test-helpers.d.ts.map +1 -1
- package/dist/stream/__tests__/ws-test-helpers.js +5 -1
- package/dist/stream/ws-cluster-bus.d.ts +21 -3
- package/dist/stream/ws-cluster-bus.d.ts.map +1 -1
- package/dist/stream/ws-cluster-bus.js +1 -1
- package/dist/stream/ws-delivery.d.ts +11 -0
- package/dist/stream/ws-delivery.d.ts.map +1 -1
- package/dist/stream/ws-delivery.js +95 -4
- package/dist/stream/ws-presence-index.d.ts +2 -0
- package/dist/stream/ws-presence-index.d.ts.map +1 -1
- package/dist/stream/ws-presence-index.js +9 -3
- package/dist/stream/ws-presence-store.d.ts +2 -0
- package/dist/stream/ws-presence-store.d.ts.map +1 -1
- package/dist/stream/ws-presence-store.js +4 -1
- package/dist/stream/ws-registry.d.ts +12 -0
- package/dist/stream/ws-registry.d.ts.map +1 -1
- package/dist/stream/ws-registry.js +49 -3
- package/dist/stream/ws.d.ts +2 -1
- package/dist/stream/ws.d.ts.map +1 -1
- package/dist/stream/ws.js +4 -1
- package/package.json +1 -1
- package/src/database/__tests__/puri-hydration.test.ts +113 -76
- package/src/database/base-model.ts +75 -43
- package/src/database/puri.ts +84 -106
- package/src/entity/__tests__/entity-subset-query.test.ts +118 -0
- package/src/entity/entity.ts +64 -3
- package/src/stream/__tests__/ws-contracts.test.ts +1 -0
- package/src/stream/__tests__/ws-leave-user.test.ts +293 -0
- package/src/stream/__tests__/ws-multinode.test.ts +3 -1
- package/src/stream/__tests__/ws-test-helpers.ts +6 -0
- package/src/stream/ws-cluster-bus.ts +26 -3
- package/src/stream/ws-delivery.ts +117 -6
- package/src/stream/ws-presence-index.ts +10 -1
- package/src/stream/ws-presence-store.ts +6 -0
- package/src/stream/ws-registry.ts +78 -2
- package/src/stream/ws.ts +9 -0
|
@@ -9,7 +9,6 @@ import { EntityManager } from "../entity/entity-manager";
|
|
|
9
9
|
import { type FilterOperator, type FilterQuery } from "../filter/types";
|
|
10
10
|
import { normalizeFilterQuery, validateSonamuFilters } from "../filter/utils";
|
|
11
11
|
import { convertDomainToCategory } from "../logger/category";
|
|
12
|
-
import { Naite } from "../naite/naite";
|
|
13
12
|
import { type DatabaseSchemaExtend, type SonamuQueryMode } from "../types/types";
|
|
14
13
|
import { type ListResult } from "../utils/model";
|
|
15
14
|
import { isObjectValue } from "../utils/runtime-value";
|
|
@@ -48,6 +47,30 @@ type DatabaseRecord = Record<string, DatabaseRecordValue | undefined>;
|
|
|
48
47
|
* @template TSubsetQueries - 서브셋 쿼리 함수 객체
|
|
49
48
|
* @template TLoaderQueries - 서브셋별 로더 쿼리 배열 객체
|
|
50
49
|
*/
|
|
50
|
+
// 로더 정의의 refId(부모 줄에서 꺼낼 값)와 as(결과를 넣을 자리)는 생성 코드에서
|
|
51
|
+
// "content__ref"처럼 __로 이은 문자열입니다. 본 쿼리와 로더 쿼리는 Puri가 이미 접은
|
|
52
|
+
// 객체를 돌려주므로, 여기서 __를 객체 경계로 보고 그 객체 속 위치로 번역해 읽고 씁니다.
|
|
53
|
+
// 중간 관계가 null이면(관계가 비었으면) 읽기는 null, 쓰기는 건너뜁니다.
|
|
54
|
+
function readLoaderPath(row: any, path: string): any {
|
|
55
|
+
let value = row;
|
|
56
|
+
for (const key of path.split("__")) {
|
|
57
|
+
if (!isObjectValue(value) || Array.isArray(value)) return null;
|
|
58
|
+
value = value[key];
|
|
59
|
+
}
|
|
60
|
+
return value ?? null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function writeLoaderPath(row: any, path: string, value: any[]): void {
|
|
64
|
+
const keys = path.split("__");
|
|
65
|
+
const last = keys.pop();
|
|
66
|
+
let parent = row;
|
|
67
|
+
for (const key of keys) {
|
|
68
|
+
if (!isObjectValue(parent) || Array.isArray(parent)) return;
|
|
69
|
+
parent = parent[key];
|
|
70
|
+
}
|
|
71
|
+
if (last !== undefined && isObjectValue(parent) && !Array.isArray(parent)) parent[last] = value;
|
|
72
|
+
}
|
|
73
|
+
|
|
51
74
|
export class BaseModelClass<
|
|
52
75
|
TSubsetKey extends string = never,
|
|
53
76
|
TSubsetMapping extends { [K in TSubsetKey]: TSubsetMapping[K] } = never,
|
|
@@ -263,7 +286,10 @@ export class BaseModelClass<
|
|
|
263
286
|
|
|
264
287
|
// Internal 필드 제거
|
|
265
288
|
const entity = EntityManager.get(this.modelName);
|
|
266
|
-
const internalFields =
|
|
289
|
+
const internalFields = [
|
|
290
|
+
...(entity.subsetsInternal[subset] ?? []),
|
|
291
|
+
...entity.getSubsetAutoInternalFields(subset),
|
|
292
|
+
];
|
|
267
293
|
const rows =
|
|
268
294
|
internalFields.length > 0
|
|
269
295
|
? enhancedRows.map((row) => this.omitInternalFields(row, internalFields))
|
|
@@ -518,9 +544,7 @@ export class BaseModelClass<
|
|
|
518
544
|
return qb.limit(num).offset(num * (page - 1));
|
|
519
545
|
}
|
|
520
546
|
})();
|
|
521
|
-
|
|
522
|
-
Naite.t("puri:executed-query", limitedQb.toQuery());
|
|
523
|
-
let unloadedRows = await limitedQb.rawQuery();
|
|
547
|
+
let rows: any[] = await limitedQb;
|
|
524
548
|
|
|
525
549
|
if (debug) {
|
|
526
550
|
qb.debug();
|
|
@@ -530,10 +554,10 @@ export class BaseModelClass<
|
|
|
530
554
|
// SAFETY: 쿼리 빌더의 제네릭 계약과 선행 검증이 이 타입을 보장합니다.
|
|
531
555
|
const loaders = (this.loaderQueries as any)[subset];
|
|
532
556
|
if (loaders && Array.isArray(loaders)) {
|
|
533
|
-
|
|
557
|
+
rows = await this.processLoaders(rows, loaders, debug, puriWrapper);
|
|
534
558
|
}
|
|
535
559
|
|
|
536
|
-
return
|
|
560
|
+
return rows;
|
|
537
561
|
}
|
|
538
562
|
|
|
539
563
|
/**
|
|
@@ -550,16 +574,14 @@ export class BaseModelClass<
|
|
|
550
574
|
|
|
551
575
|
const resolveLoaderQb = resolveLoaderQbFn(
|
|
552
576
|
puriWrapper,
|
|
553
|
-
rows.map((row) => row
|
|
577
|
+
rows.map((row) => readLoaderPath(row, refId)).filter((id) => id !== null),
|
|
554
578
|
);
|
|
555
579
|
|
|
556
580
|
if (debug) {
|
|
557
581
|
resolveLoaderQb.debug();
|
|
558
582
|
}
|
|
559
583
|
|
|
560
|
-
|
|
561
|
-
// SAFETY: 로더의 select 쿼리는 평평한 레코드 배열을 반환합니다.
|
|
562
|
-
let loadedRows = (await resolveLoaderQb.rawQuery()) as any[];
|
|
584
|
+
let loadedRows: any[] = await resolveLoaderQb;
|
|
563
585
|
|
|
564
586
|
// 중첩 loaders가 있으면 재귀 처리
|
|
565
587
|
if (nestedLoaders && nestedLoaders.length > 0) {
|
|
@@ -569,7 +591,12 @@ export class BaseModelClass<
|
|
|
569
591
|
const subRowGroups = group(loadedRows, (row) => row.refId);
|
|
570
592
|
|
|
571
593
|
rows = rows.map((row) => {
|
|
572
|
-
|
|
594
|
+
const refValue = readLoaderPath(row, refId);
|
|
595
|
+
writeLoaderPath(
|
|
596
|
+
row,
|
|
597
|
+
as,
|
|
598
|
+
(refValue === null ? [] : (subRowGroups[refValue] ?? [])).map((r) => omit(r, ["refId"])),
|
|
599
|
+
);
|
|
573
600
|
return row;
|
|
574
601
|
});
|
|
575
602
|
}
|
|
@@ -582,34 +609,45 @@ export class BaseModelClass<
|
|
|
582
609
|
*
|
|
583
610
|
* - `user__name` → `{ user: { name } }`
|
|
584
611
|
* - nullable relation의 경우 id 필드가 null이면 객체 자체를 null로
|
|
612
|
+
*
|
|
613
|
+
* @deprecated 키 이름의 `__`와 id·칸 값으로 관계가 있는지 추측해 접습니다. 그래서 id 없는
|
|
614
|
+
* 중첩 그룹은 비어 있어도 null이 아니라 칸이 전부 null인 객체가 되고, jsonb 값이나 raw
|
|
615
|
+
* 별칭에 든 `__`도 접어 버립니다. Puri 쿼리를 직접 `await`하면 select에 적은 중첩 모양
|
|
616
|
+
* 그대로 접힌 결과를 받습니다.
|
|
585
617
|
*/
|
|
586
618
|
hydrate<T extends object>(rows: T[]): T[] {
|
|
619
|
+
const toObjPath = (key: string) => {
|
|
620
|
+
const [head, ...rest] = key.split("__");
|
|
621
|
+
return head + rest.map((part) => `[${part}]`).join("");
|
|
622
|
+
};
|
|
587
623
|
// SAFETY: 쿼리 빌더의 제네릭 계약과 선행 검증이 이 타입을 보장합니다.
|
|
588
624
|
return rows.map((row: T) => {
|
|
589
625
|
const rowValues = new Map(Object.entries(row));
|
|
590
|
-
// nullable relation 처리: 그룹의 id 필드가 null이면 객체 전체를 null로
|
|
591
626
|
const nestedKeys = Object.keys(row).filter((key) => key.includes("__"));
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
627
|
+
// 중첩 관계마다 접두사를 모읍니다 (예: shop__country__id → shop, shop__country)
|
|
628
|
+
const prefixes = new Set(
|
|
629
|
+
nestedKeys.flatMap((key) => {
|
|
630
|
+
const parts = key.split("__");
|
|
631
|
+
return parts.slice(1).map((_, i) => parts.slice(0, i + 1).join("__"));
|
|
632
|
+
}),
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
// 관계의 id 필드가 null이면 그 관계 객체 전체를 null로 (예: shop__country__id → shop.country)
|
|
636
|
+
const nullKeys = [...prefixes].filter((prefix) => {
|
|
637
|
+
const idField = `${prefix}__id`;
|
|
638
|
+
if (idField in row) {
|
|
639
|
+
return rowValues.get(idField) === null;
|
|
640
|
+
}
|
|
605
641
|
|
|
606
|
-
|
|
607
|
-
|
|
642
|
+
// 첫 단계 관계에 id 필드가 없으면 기존 로직: 모든 필드가 null인지 확인
|
|
643
|
+
if (prefix.includes("__")) return false;
|
|
644
|
+
return nestedKeys
|
|
645
|
+
.filter((key) => key.startsWith(`${prefix}__`))
|
|
646
|
+
.every((field) => {
|
|
608
647
|
const fieldValue = rowValues.get(field);
|
|
609
648
|
return fieldValue === null || (Array.isArray(fieldValue) && fieldValue.length === 0);
|
|
610
649
|
});
|
|
611
|
-
|
|
612
|
-
.map(([key]) => key);
|
|
650
|
+
});
|
|
613
651
|
|
|
614
652
|
let hydrated: DatabaseRecord = Object.fromEntries([]);
|
|
615
653
|
for (const field of Object.keys(row)) {
|
|
@@ -624,27 +662,21 @@ export class BaseModelClass<
|
|
|
624
662
|
}
|
|
625
663
|
|
|
626
664
|
// 중첩 필드 처리: user__name → user[name]
|
|
627
|
-
const parts = field.split("__");
|
|
628
|
-
const objPath =
|
|
629
|
-
parts[0] +
|
|
630
|
-
parts
|
|
631
|
-
.slice(1)
|
|
632
|
-
.map((part) => `[${part}]`)
|
|
633
|
-
.join("");
|
|
634
|
-
|
|
635
665
|
hydrated = set(
|
|
636
666
|
hydrated,
|
|
637
|
-
|
|
667
|
+
toObjPath(field),
|
|
638
668
|
fieldValue && Array.isArray(fieldValue) && isObject(fieldValue[0])
|
|
639
669
|
? this.hydrate(fieldValue)
|
|
640
670
|
: fieldValue,
|
|
641
671
|
);
|
|
642
672
|
}
|
|
643
673
|
|
|
644
|
-
// null relation
|
|
645
|
-
nullKeys
|
|
646
|
-
|
|
647
|
-
|
|
674
|
+
// null relation 처리: 안쪽부터 적용해야 바깥 null이 안쪽 경로에 덮여 객체로 되살아나지 않습니다.
|
|
675
|
+
nullKeys
|
|
676
|
+
.sort((a, b) => b.split("__").length - a.split("__").length)
|
|
677
|
+
.forEach((nullKey) => {
|
|
678
|
+
hydrated = set(hydrated, toObjPath(nullKey), null);
|
|
679
|
+
});
|
|
648
680
|
|
|
649
681
|
return hydrated;
|
|
650
682
|
}) as T[];
|
package/src/database/puri.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
/* oxlint-disable @typescript-eslint/no-explicit-any */ // Puri는 다양한 타입을 사용하고 있습니다.
|
|
2
2
|
|
|
3
3
|
import assert from "assert";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { type EventEmitter } from "node:events";
|
|
6
4
|
|
|
7
5
|
import chalk from "chalk";
|
|
8
6
|
import inflection from "inflection";
|
|
@@ -199,30 +197,73 @@ type SelectResultValue =
|
|
|
199
197
|
type SelectRow = { [column: string]: SelectResultValue };
|
|
200
198
|
type SelectResult = SelectRow | SelectRow[] | undefined;
|
|
201
199
|
|
|
202
|
-
|
|
203
|
-
|
|
200
|
+
type SelectGroupRule = {
|
|
201
|
+
/** LEFT JOIN 때문에 비어 있을 수 있어 `id`로 null을 판정하는 그룹 */
|
|
202
|
+
nullable: boolean;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 중첩 select 그룹마다 null 판정 규칙을 정하고, 판정할 수 없는 모양이면 오류를 냅니다.
|
|
207
|
+
*
|
|
208
|
+
* - 그룹 경로가 LEFT JOIN 별칭이거나 그룹 칸이 LEFT JOIN 별칭을 가리키면, 그 그룹의 `id`가
|
|
209
|
+
* null인지로만 그룹 전체가 null인지 판정합니다. 그래서 그런 그룹에는 `id`가 있어야 합니다.
|
|
210
|
+
* - 서브쿼리를 LEFT JOIN한 별칭도 같습니다. 서브쿼리가 `id`를 골라 와야 중첩 그룹으로 고를 수 있습니다.
|
|
211
|
+
* - `rawQuery().joinRaw()`처럼 Puri가 모르게 붙인 별칭은 조인 종류를 알 수 없으므로, 그룹에 `id`가
|
|
212
|
+
* 있으면 그 `id`가 null일 때 null로 판정하고 `id`가 없으면 그대로 객체로 둡니다.
|
|
213
|
+
* - 칸이 전부 raw 식이면 별칭을 알 수 없으므로 판정하지 않고 늘 객체로 둡니다.
|
|
214
|
+
*/
|
|
215
|
+
function resolveSelectGroupRules(
|
|
216
|
+
paths: ReadonlyMap<string, readonly string[]>,
|
|
217
|
+
sources: ReadonlyMap<string, string | null>,
|
|
204
218
|
correlations: ReadonlyMap<string, CorrelationRegistration>,
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
219
|
+
): Map<string, SelectGroupRule> {
|
|
220
|
+
const groups = new Map<string, { aliases: Set<string>; hasLeaf: boolean; hasId: boolean }>();
|
|
221
|
+
for (const [key, path] of paths) {
|
|
222
|
+
for (let length = 1; length < path.length; length++) {
|
|
223
|
+
const groupPath = path.slice(0, length).join("__");
|
|
224
|
+
let group = groups.get(groupPath);
|
|
225
|
+
if (group === undefined) {
|
|
226
|
+
group = { aliases: new Set(), hasLeaf: false, hasId: false };
|
|
227
|
+
groups.set(groupPath, group);
|
|
228
|
+
}
|
|
229
|
+
if (length === path.length - 1) {
|
|
230
|
+
group.hasLeaf = true;
|
|
231
|
+
group.hasId ||= path[length] === "id";
|
|
232
|
+
const alias = sources.get(key);
|
|
233
|
+
if (alias !== undefined && alias !== null) group.aliases.add(alias);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const rules = new Map<string, SelectGroupRule>();
|
|
239
|
+
for (const [groupPath, group] of groups) {
|
|
240
|
+
if (group.hasLeaf && group.aliases.size === 0) {
|
|
241
|
+
rules.set(groupPath, { nullable: false });
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const leftJoins = [...new Set([groupPath, ...group.aliases])].flatMap((alias) => {
|
|
245
|
+
const relation = correlations.get(alias);
|
|
246
|
+
return relation?.kind === "join" && relation.joinType === "leftJoin" ? [relation] : [];
|
|
247
|
+
});
|
|
248
|
+
if (leftJoins.length > 0 && !group.hasId) {
|
|
249
|
+
const aliases = leftJoins.map((relation) => `"${relation.alias}"`).join(", ");
|
|
250
|
+
throw new Error(
|
|
251
|
+
`Nested select group "${groupPath}" needs an "id" field because it reads LEFT JOIN ${aliases}. Select the id of that alias in the group, or select its columns flat instead.`,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
const unregistered = [...group.aliases].some((alias) => !correlations.has(alias));
|
|
255
|
+
rules.set(groupPath, { nullable: leftJoins.length > 0 || (group.hasId && unregistered) });
|
|
256
|
+
}
|
|
257
|
+
return rules;
|
|
214
258
|
}
|
|
215
259
|
|
|
216
260
|
function hydrateSelectResult(
|
|
217
261
|
result: SelectResult,
|
|
218
262
|
paths: ReadonlyMap<string, readonly string[]>,
|
|
219
|
-
|
|
220
|
-
presenceColumns: ReadonlyMap<string, string>,
|
|
221
|
-
identitySources: ReadonlyMap<string, string>,
|
|
263
|
+
rules: ReadonlyMap<string, SelectGroupRule>,
|
|
222
264
|
): SelectResult {
|
|
223
265
|
if (paths.size === 0 || result === undefined) return result;
|
|
224
266
|
|
|
225
|
-
const hiddenColumns = new Set(presenceColumns.values());
|
|
226
267
|
const projection: SelectProjection = new Map();
|
|
227
268
|
for (const [alias, path] of paths) {
|
|
228
269
|
let parent = projection;
|
|
@@ -250,24 +291,12 @@ function hydrateSelectResult(
|
|
|
250
291
|
}
|
|
251
292
|
}
|
|
252
293
|
const value = Object.fromEntries(entries);
|
|
253
|
-
//
|
|
254
|
-
|
|
255
|
-
const presenceColumn =
|
|
256
|
-
relationAlias === undefined ? undefined : presenceColumns.get(relationAlias);
|
|
257
|
-
if (
|
|
258
|
-
relationAlias !== undefined &&
|
|
259
|
-
(presenceColumn !== undefined
|
|
260
|
-
? row[presenceColumn] === false
|
|
261
|
-
: Object.hasOwn(value, "id") && value.id === null)
|
|
262
|
-
) {
|
|
263
|
-
return null;
|
|
264
|
-
}
|
|
294
|
+
// LEFT JOIN 그룹은 id가 null일 때만 관계가 비었다고 봅니다.
|
|
295
|
+
if (rules.get(path.join("__"))?.nullable === true && value.id === null) return null;
|
|
265
296
|
return value;
|
|
266
297
|
};
|
|
267
298
|
return {
|
|
268
|
-
...Object.fromEntries(
|
|
269
|
-
Object.entries(row).filter(([key]) => !paths.has(key) && !hiddenColumns.has(key)),
|
|
270
|
-
),
|
|
299
|
+
...Object.fromEntries(Object.entries(row).filter(([key]) => !paths.has(key))),
|
|
271
300
|
...Object.fromEntries(
|
|
272
301
|
[...projection].map(([key, fields]) => {
|
|
273
302
|
assert(fields instanceof Map);
|
|
@@ -285,7 +314,8 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
285
314
|
private knexQuery: Knex.QueryBuilder;
|
|
286
315
|
private tableSpec: TableSpec | null = null;
|
|
287
316
|
private nestedSelectPaths = new Map<string, readonly string[]>();
|
|
288
|
-
|
|
317
|
+
// 중첩 select 칸이 가리키는 별칭(raw 식이면 null)
|
|
318
|
+
private nestedSelectSources = new Map<string, string | null>();
|
|
289
319
|
private correlationRegistry = new Map<string, CorrelationRegistration>();
|
|
290
320
|
|
|
291
321
|
// 생성자 시그니처들
|
|
@@ -727,11 +757,17 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
727
757
|
if (isNestedSelectObject(value)) {
|
|
728
758
|
yield* this.flattenSelectEntries(value, fieldPath);
|
|
729
759
|
} else {
|
|
730
|
-
if (fieldPath.length > 1)
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
760
|
+
if (fieldPath.length > 1) {
|
|
761
|
+
this.nestedSelectPaths.set(fullKey, fieldPath);
|
|
762
|
+
this.nestedSelectSources.set(
|
|
763
|
+
fullKey,
|
|
764
|
+
isStringValue(value) && value.includes(".")
|
|
765
|
+
? value.slice(0, value.lastIndexOf("."))
|
|
766
|
+
: null,
|
|
767
|
+
);
|
|
768
|
+
} else {
|
|
769
|
+
this.nestedSelectPaths.delete(fullKey);
|
|
770
|
+
this.nestedSelectSources.delete(fullKey);
|
|
735
771
|
}
|
|
736
772
|
yield [fullKey, value];
|
|
737
773
|
}
|
|
@@ -791,7 +827,7 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
791
827
|
this.knexQuery.clear(statement);
|
|
792
828
|
if (statement === "select" || statement === "columns") {
|
|
793
829
|
this.nestedSelectPaths.clear();
|
|
794
|
-
this.
|
|
830
|
+
this.nestedSelectSources.clear();
|
|
795
831
|
}
|
|
796
832
|
if (statement === "join") {
|
|
797
833
|
this.clearJoinRegistrations();
|
|
@@ -1596,74 +1632,16 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
1596
1632
|
return this;
|
|
1597
1633
|
}
|
|
1598
1634
|
|
|
1599
|
-
private executeSelect(): Promise<SelectResult> {
|
|
1635
|
+
private async executeSelect(): Promise<SelectResult> {
|
|
1600
1636
|
if (this.nestedSelectPaths.size === 0) return this.knexQuery.then();
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
for (const path of this.nestedSelectPaths.values()) {
|
|
1607
|
-
for (let length = 1; length < path.length; length++) {
|
|
1608
|
-
const alias = getSelectRelationAlias(
|
|
1609
|
-
path.slice(0, length).join("__"),
|
|
1610
|
-
this.correlationRegistry,
|
|
1611
|
-
this.nestedSelectIdentitySources,
|
|
1612
|
-
);
|
|
1613
|
-
if (alias === undefined || presenceColumns.has(alias)) continue;
|
|
1614
|
-
let column: string;
|
|
1615
|
-
do {
|
|
1616
|
-
column = `__sonamu_presence_${randomUUID().replaceAll("-", "")}`;
|
|
1617
|
-
} while (sql.includes(column));
|
|
1618
|
-
if (presenceColumns.size === 0) {
|
|
1619
|
-
executable = this.knexQuery.clone();
|
|
1620
|
-
// Knex.clone이 복제하지 않는 실행 제한과 이벤트는 원본의 계약을 유지합니다.
|
|
1621
|
-
// SAFETY: timeout은 Knex QueryBuilder가 보관하는 실행 옵션입니다.
|
|
1622
|
-
const timeout = (this.knexQuery as any)._timeout;
|
|
1623
|
-
if (isNumberValue(timeout)) {
|
|
1624
|
-
// SAFETY: cancelOnTimeout은 timeout 옵션과 함께 Knex가 기록하는 불리언입니다.
|
|
1625
|
-
executable.timeout(timeout, {
|
|
1626
|
-
cancel: (this.knexQuery as any)._cancelOnTimeout === true,
|
|
1627
|
-
});
|
|
1628
|
-
}
|
|
1629
|
-
// SAFETY: Knex QueryBuilder는 EventEmitter를 상속하지만 공개 타입에는 일부 메서드만 있습니다.
|
|
1630
|
-
const emitter = this.knexQuery as Knex.QueryBuilder & EventEmitter;
|
|
1631
|
-
// SAFETY: 실행 복제본도 동일한 Knex EventEmitter 구현입니다.
|
|
1632
|
-
const executionEmitter: EventEmitter = executable as Knex.QueryBuilder & EventEmitter;
|
|
1633
|
-
for (const event of emitter.eventNames()) {
|
|
1634
|
-
executionEmitter.on(event, (...args: any[]) => emitter.emit(event, ...args));
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
presenceColumns.set(alias, column);
|
|
1638
|
-
executable.select(this.knex.raw("??.* IS DISTINCT FROM NULL AS ??", [alias, column]));
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
return executable.then((result) =>
|
|
1643
|
-
hydrateSelectResult(
|
|
1644
|
-
result,
|
|
1645
|
-
this.nestedSelectPaths,
|
|
1646
|
-
this.correlationRegistry,
|
|
1647
|
-
presenceColumns,
|
|
1648
|
-
this.nestedSelectIdentitySources,
|
|
1649
|
-
),
|
|
1637
|
+
// select와 join이 모두 정해진 실행 시점에 그룹 규칙을 정합니다.
|
|
1638
|
+
const rules = resolveSelectGroupRules(
|
|
1639
|
+
this.nestedSelectPaths,
|
|
1640
|
+
this.nestedSelectSources,
|
|
1641
|
+
this.correlationRegistry,
|
|
1650
1642
|
);
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
private canSelectRelationPresence(): boolean {
|
|
1654
|
-
// 그룹·집계·DISTINCT·원시 표현식에는 열을 추가하면 SQL 의미가 바뀔 수 있습니다.
|
|
1655
|
-
// SAFETY: Knex의 statement 구조는 다른 JOIN/벡터 처리와 동일한 내부 계약으로 읽습니다.
|
|
1656
|
-
const statements = (this.knexQuery as any)._statements;
|
|
1657
|
-
return statements.every((statement: any) => {
|
|
1658
|
-
if (["group", "having", "union"].includes(statement.grouping)) return false;
|
|
1659
|
-
if (statement.grouping !== "columns") return true;
|
|
1660
|
-
if (statement.distinct || statement.distinctOn || statement.type) return false;
|
|
1661
|
-
return statement.value.every((column: string | { ref?: string }) =>
|
|
1662
|
-
isStringValue(column)
|
|
1663
|
-
? !column.includes("*")
|
|
1664
|
-
: isObjectValue(column) && isStringValue(column.ref),
|
|
1665
|
-
);
|
|
1666
|
-
});
|
|
1643
|
+
const result = await this.knexQuery.then();
|
|
1644
|
+
return hydrateSelectResult(result, this.nestedSelectPaths, rules);
|
|
1667
1645
|
}
|
|
1668
1646
|
|
|
1669
1647
|
// 실행 메서드들 - thenable 구현
|
|
@@ -1816,7 +1794,7 @@ export class Puri<TSchema, TTables extends object, TResult> {
|
|
|
1816
1794
|
newPuri.knexQuery = this.knexQuery.clone();
|
|
1817
1795
|
newPuri.tableSpec = this.tableSpec;
|
|
1818
1796
|
newPuri.nestedSelectPaths = new Map(this.nestedSelectPaths);
|
|
1819
|
-
newPuri.
|
|
1797
|
+
newPuri.nestedSelectSources = new Map(this.nestedSelectSources);
|
|
1820
1798
|
newPuri.correlationRegistry = new Map(this.correlationRegistry);
|
|
1821
1799
|
return newPuri;
|
|
1822
1800
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { type EntityJson } from "../../types/types";
|
|
4
|
+
import { Entity } from "../entity";
|
|
5
|
+
import { EntityManager } from "../entity-manager";
|
|
6
|
+
|
|
7
|
+
const chatRoomJson: EntityJson = {
|
|
8
|
+
id: "ChatRoom",
|
|
9
|
+
table: "chat_rooms",
|
|
10
|
+
props: [
|
|
11
|
+
{ name: "id", type: "integer", desc: "ID" },
|
|
12
|
+
{ name: "name", type: "string", desc: "이름" },
|
|
13
|
+
{ name: "case", type: "relation", relationType: "BelongsToOne", with: "Case", desc: "케이스" },
|
|
14
|
+
{
|
|
15
|
+
name: "owned_cases",
|
|
16
|
+
type: "relation",
|
|
17
|
+
relationType: "HasMany",
|
|
18
|
+
with: "Case",
|
|
19
|
+
joinColumn: "owner_id",
|
|
20
|
+
desc: "소유 케이스",
|
|
21
|
+
},
|
|
22
|
+
],
|
|
23
|
+
indexes: [],
|
|
24
|
+
subsets: {},
|
|
25
|
+
enums: {},
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const caseJson: EntityJson = {
|
|
29
|
+
id: "Case",
|
|
30
|
+
table: "cases",
|
|
31
|
+
props: [
|
|
32
|
+
{ name: "id", type: "integer", desc: "ID" },
|
|
33
|
+
{
|
|
34
|
+
name: "chat_room",
|
|
35
|
+
type: "relation",
|
|
36
|
+
relationType: "OneToOne",
|
|
37
|
+
with: "ChatRoom",
|
|
38
|
+
hasJoinColumn: false,
|
|
39
|
+
nullable: true,
|
|
40
|
+
desc: "채팅방",
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "owner",
|
|
44
|
+
type: "relation",
|
|
45
|
+
relationType: "BelongsToOne",
|
|
46
|
+
with: "ChatRoom",
|
|
47
|
+
desc: "소유 채팅방",
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
indexes: [],
|
|
51
|
+
subsets: {},
|
|
52
|
+
enums: {},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
describe("Entity.resolveSubsetQuery", () => {
|
|
56
|
+
afterEach(() => {
|
|
57
|
+
vi.restoreAllMocks();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
function setup() {
|
|
61
|
+
const chatRoom = new Entity(chatRoomJson);
|
|
62
|
+
const caseEntity = new Entity(caseJson);
|
|
63
|
+
vi.spyOn(EntityManager, "get").mockImplementation((id: string) =>
|
|
64
|
+
id === "ChatRoom" ? chatRoom : caseEntity,
|
|
65
|
+
);
|
|
66
|
+
return caseEntity;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
it("조인 컬럼 없는 역방향 OneToOne의 id 단독 조회는 존재하지 않는 FK 컬럼 대신 JOIN으로 id를 선택한다", () => {
|
|
70
|
+
const result = setup().resolveSubsetQuery("", ["chat_room.id"]);
|
|
71
|
+
|
|
72
|
+
expect(result.select).toEqual(["chat_room.id as chat_room__id"]);
|
|
73
|
+
expect(result.select.join(" ")).not.toContain("cases.chat_room_id");
|
|
74
|
+
expect(result.joins).toEqual([
|
|
75
|
+
{
|
|
76
|
+
as: "chat_room",
|
|
77
|
+
join: "outer",
|
|
78
|
+
table: "chat_rooms",
|
|
79
|
+
from: "cases.id",
|
|
80
|
+
to: "chat_room.case_id",
|
|
81
|
+
},
|
|
82
|
+
]);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("BelongsToOne의 id 단독 조회는 기존처럼 FK 컬럼만 선택한다", () => {
|
|
86
|
+
const result = setup().resolveSubsetQuery("", ["owner.id"]);
|
|
87
|
+
|
|
88
|
+
expect(result.select).toEqual(["cases.owner_id"]);
|
|
89
|
+
expect(result.joins).toEqual([]);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("JOIN으로 붙는 관계 그룹에 id가 없으면 계산된 internal id로 넣고 subsetsInternal에는 쓰지 않는다", () => {
|
|
93
|
+
const caseEntity = setup();
|
|
94
|
+
caseEntity.subsets = {
|
|
95
|
+
A: ["id", "owner.name", "owner.case.id", "chat_room.id"],
|
|
96
|
+
B: ["owner.id", "owner.name"],
|
|
97
|
+
};
|
|
98
|
+
caseEntity.subsetsInternal = { A: [], B: [] };
|
|
99
|
+
|
|
100
|
+
expect(caseEntity.getSubsetAutoInternalFields("A")).toEqual(["owner.id"]);
|
|
101
|
+
expect(caseEntity.getSubsetFieldsForQuery("A")).toContain("owner.id");
|
|
102
|
+
expect(caseEntity.getSubsetAutoInternalFields("B")).toEqual([]);
|
|
103
|
+
expect(caseEntity.subsetsInternal).toEqual({ A: [], B: [] });
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("로더 부모 줄에는 refId 칸을, 로더 줄의 관계 그룹에는 id를 넣는다", () => {
|
|
107
|
+
const caseEntity = setup();
|
|
108
|
+
const chatRoom = EntityManager.get("ChatRoom");
|
|
109
|
+
chatRoom.subsets = { A: ["name", "owned_cases.owner.name"] };
|
|
110
|
+
chatRoom.subsetsInternal = { A: [] };
|
|
111
|
+
caseEntity.subsets = { A: ["owner.owned_cases.id"] };
|
|
112
|
+
caseEntity.subsetsInternal = { A: [] };
|
|
113
|
+
|
|
114
|
+
expect(chatRoom.getSubsetAutoInternalFields("A")).toEqual(["id", "owned_cases.owner.id"]);
|
|
115
|
+
// 로더가 owner__id로 자식을 붙이므로 owner 그룹의 id 하나로 둘 다 충족합니다.
|
|
116
|
+
expect(caseEntity.getSubsetAutoInternalFields("A")).toEqual(["owner.id"]);
|
|
117
|
+
});
|
|
118
|
+
});
|
package/src/entity/entity.ts
CHANGED
|
@@ -179,10 +179,66 @@ export class Entity {
|
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
/**
|
|
182
|
-
* 쿼리용 서브셋 필드를 반환합니다 (subsets + subsetsInternal
|
|
182
|
+
* 쿼리용 서브셋 필드를 반환합니다 (subsets + subsetsInternal + 자동 internal id)
|
|
183
183
|
*/
|
|
184
184
|
getSubsetFieldsForQuery(subsetKey: string): string[] {
|
|
185
|
-
|
|
185
|
+
const fields = [...(this.subsets[subsetKey] ?? []), ...(this.subsetsInternal[subsetKey] ?? [])];
|
|
186
|
+
return [...fields, ...this.getRequiredIdFields(fields)];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 서브셋 쿼리에 자동으로 넣고 결과에서는 지우는 id 필드를 반환합니다.
|
|
191
|
+
* 계산 값이라 subsetsInternal에 쓰지 않습니다(entity.json으로 되써지지 않도록).
|
|
192
|
+
*/
|
|
193
|
+
getSubsetAutoInternalFields(subsetKey: string): string[] {
|
|
194
|
+
return this.getRequiredIdFields([
|
|
195
|
+
...(this.subsets[subsetKey] ?? []),
|
|
196
|
+
...(this.subsetsInternal[subsetKey] ?? []),
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 주어진 필드에 없지만 결과를 접는 데 필요한 id 필드를 계산합니다.
|
|
202
|
+
*
|
|
203
|
+
* - JOIN으로 붙는 -One 관계 그룹마다 `<그룹>.id`: Puri가 그 id로만 관계가 비었는지 판정합니다.
|
|
204
|
+
* - -Many 관계를 가진 줄마다 로더 refId가 가리키는 칸(`id` 또는 fromColumn): 로더가 그 값으로 자식을 붙입니다.
|
|
205
|
+
*/
|
|
206
|
+
private getRequiredIdFields(fields: string[]): string[] {
|
|
207
|
+
const ownFields = new Set(fields.filter((field) => !field.includes(".")));
|
|
208
|
+
const required: string[] = [];
|
|
209
|
+
const requireOwn = (field: string) => {
|
|
210
|
+
if (!ownFields.has(field) && !required.includes(field)) required.push(field);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const relationGroups = group(
|
|
214
|
+
fields.filter((field) => field.includes(".")),
|
|
215
|
+
(field) => field.slice(0, field.indexOf(".")),
|
|
216
|
+
);
|
|
217
|
+
for (const [groupKey, groupedFields = []] of Object.entries(relationGroups)) {
|
|
218
|
+
const relation = this.relations[groupKey];
|
|
219
|
+
// 없는 관계는 resolveSubsetQuery가 오류를 냅니다.
|
|
220
|
+
if (relation === undefined) continue;
|
|
221
|
+
const relFields = groupedFields.map((field) => field.slice(field.indexOf(".") + 1));
|
|
222
|
+
const relEntity = EntityManager.get(relation.with);
|
|
223
|
+
|
|
224
|
+
if (isOneToOneRelationProp(relation) || isBelongsToOneRelationProp(relation)) {
|
|
225
|
+
// id 단독 지름길(JOIN 없이 FK만 고름)은 그대로 둡니다.
|
|
226
|
+
const isIdShortcut =
|
|
227
|
+
relFields.length === 1 &&
|
|
228
|
+
relFields[0] === "id" &&
|
|
229
|
+
!(isOneToOneRelationProp(relation) && !relation.hasJoinColumn);
|
|
230
|
+
if (isIdShortcut) continue;
|
|
231
|
+
const nested = relEntity.getRequiredIdFields(relFields);
|
|
232
|
+
const relRequired = relFields.includes("id") || nested.includes("id") ? [] : ["id"];
|
|
233
|
+
required.push(...[...relRequired, ...nested].map((field) => `${groupKey}.${field}`));
|
|
234
|
+
} else if (isHasManyRelationProp(relation) || isManyToManyRelationProp(relation)) {
|
|
235
|
+
requireOwn(isHasManyRelationProp(relation) ? (relation.fromColumn ?? "id") : "id");
|
|
236
|
+
required.push(
|
|
237
|
+
...relEntity.getRequiredIdFields(relFields).map((field) => `${groupKey}.${field}`),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return required;
|
|
186
242
|
}
|
|
187
243
|
|
|
188
244
|
/**
|
|
@@ -502,7 +558,12 @@ export class Entity {
|
|
|
502
558
|
const relFields = groupedFields.map((field) => field.split(".").slice(1).join("."));
|
|
503
559
|
|
|
504
560
|
// -One Relation에서 id 필드만 참조하는 경우 릴레이션 넘기지 않고 리턴
|
|
505
|
-
|
|
561
|
+
// 조인 컬럼 없는 역방향 OneToOne은 현재 테이블에 FK 컬럼이 없으므로 JOIN으로 처리
|
|
562
|
+
if (
|
|
563
|
+
relFields.length === 1 &&
|
|
564
|
+
relFields[0] === "id" &&
|
|
565
|
+
!(isOneToOneRelationProp(relation) && !relation.hasJoinColumn)
|
|
566
|
+
) {
|
|
506
567
|
if (prefix === "") {
|
|
507
568
|
r.select = r.select.concat(`${this.table}.${groupKey}_id`);
|
|
508
569
|
} else {
|