metal-orm 1.1.11 → 1.1.18
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/README.md +758 -769
- package/dist/index.cjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +100 -96
- package/scripts/generate-entities/schema.mjs +122 -122
- package/scripts/generate-entities/tree-detection.mjs +92 -92
- package/scripts/inflection/pt-br.mjs +468 -468
- package/scripts/run-eslint.mjs +33 -34
- package/scripts/show-sql-seed.sql +102 -0
- package/scripts/show-sql.mjs +321 -325
- package/src/codegen/naming-strategy.ts +54 -54
- package/src/codegen/typescript.ts +482 -482
- package/src/core/ast/adapters.ts +1 -1
- package/src/core/ast/builders.ts +123 -123
- package/src/core/ast/expression-builders.ts +745 -745
- package/src/core/ast/expression-nodes.ts +304 -304
- package/src/core/ast/expression-visitor.ts +212 -212
- package/src/core/ast/expression.ts +20 -20
- package/src/core/ast/helpers.ts +14 -14
- package/src/core/ast/join.ts +18 -18
- package/src/core/ast/query.ts +200 -200
- package/src/core/ddl/dialects/base-schema-dialect.ts +1 -1
- package/src/core/ddl/dialects/mssql-schema-dialect.ts +1 -1
- package/src/core/ddl/dialects/mysql-schema-dialect.ts +1 -1
- package/src/core/ddl/dialects/postgres-schema-dialect.ts +1 -1
- package/src/core/ddl/dialects/render-reference.test.ts +70 -70
- package/src/core/ddl/dialects/sqlite-schema-dialect.ts +1 -1
- package/src/core/ddl/introspect/catalogs/index.ts +5 -5
- package/src/core/ddl/introspect/catalogs/postgres.ts +146 -146
- package/src/core/ddl/introspect/context.ts +15 -15
- package/src/core/ddl/introspect/functions/postgres.ts +35 -35
- package/src/core/ddl/introspect/registry.ts +40 -40
- package/src/core/ddl/introspect/run-select.ts +35 -35
- package/src/core/ddl/introspect/utils.ts +56 -56
- package/src/core/ddl/naming-strategy.ts +16 -16
- package/src/core/ddl/schema-dialect.ts +56 -56
- package/src/core/ddl/schema-diff.ts +234 -234
- package/src/core/ddl/schema-generator.ts +1 -1
- package/src/core/ddl/schema-introspect.ts +25 -25
- package/src/core/ddl/sql-writing.ts +171 -171
- package/src/core/dialect/abstract.ts +541 -541
- package/src/core/dialect/base/cte-compiler.ts +33 -33
- package/src/core/dialect/base/function-table-formatter.ts +103 -103
- package/src/core/dialect/base/groupby-compiler.ts +21 -21
- package/src/core/dialect/base/join-compiler.ts +25 -25
- package/src/core/dialect/base/orderby-compiler.ts +35 -35
- package/src/core/dialect/base/pagination-strategy.ts +32 -32
- package/src/core/dialect/base/returning-strategy.ts +57 -57
- package/src/core/dialect/base/sql-dialect.ts +294 -294
- package/src/core/dialect/dialect-factory.ts +91 -91
- package/src/core/dialect/mssql/functions.ts +120 -120
- package/src/core/dialect/mssql/index.ts +317 -317
- package/src/core/dialect/mysql/functions.ts +103 -103
- package/src/core/dialect/mysql/index.ts +105 -105
- package/src/core/dialect/postgres/functions.ts +108 -108
- package/src/core/dialect/postgres/index.ts +91 -91
- package/src/core/dialect/sqlite/functions.ts +129 -129
- package/src/core/dialect/sqlite/index.ts +67 -67
- package/src/core/driver/database-driver.ts +19 -19
- package/src/core/driver/mssql-driver.ts +23 -23
- package/src/core/driver/mysql-driver.ts +23 -23
- package/src/core/driver/postgres-driver.ts +23 -23
- package/src/core/driver/sqlite-driver.ts +23 -23
- package/src/core/execution/db-executor.ts +92 -92
- package/src/core/execution/executors/better-sqlite3-executor.ts +90 -90
- package/src/core/execution/executors/mssql-executor.ts +184 -184
- package/src/core/execution/executors/mysql-executor.ts +88 -88
- package/src/core/execution/executors/postgres-executor.ts +26 -26
- package/src/core/execution/executors/sqlite-executor.ts +42 -42
- package/src/core/execution/pooling/pool-types.ts +30 -30
- package/src/core/execution/pooling/pool.ts +275 -275
- package/src/core/functions/array.ts +35 -35
- package/src/core/functions/control-flow.ts +79 -79
- package/src/core/functions/datetime.ts +237 -237
- package/src/core/functions/json.ts +70 -70
- package/src/core/functions/numeric.ts +297 -297
- package/src/core/functions/text.ts +334 -334
- package/src/core/functions/types.ts +33 -33
- package/src/core/hydration/types.ts +51 -51
- package/src/core/sql/sql-operator-config.ts +39 -39
- package/src/core/sql/sql.ts +152 -152
- package/src/decorators/column-decorator.ts +87 -87
- package/src/decorators/decorator-metadata.ts +143 -143
- package/src/decorators/entity.ts +93 -93
- package/src/decorators/index.ts +39 -39
- package/src/decorators/relations.ts +231 -231
- package/src/decorators/transformers/built-in/string-transformers.ts +231 -231
- package/src/decorators/transformers/transformer-decorators.ts +134 -134
- package/src/decorators/transformers/transformer-executor.ts +171 -171
- package/src/decorators/transformers/transformer-metadata.ts +73 -73
- package/src/decorators/validators/built-in/br-cep-validator.ts +55 -55
- package/src/decorators/validators/built-in/br-cnpj-validator.ts +105 -105
- package/src/decorators/validators/built-in/br-cpf-validator.ts +103 -103
- package/src/decorators/validators/country-validator-registry.ts +64 -64
- package/src/decorators/validators/country-validators-decorators.ts +203 -203
- package/src/decorators/validators/country-validators.ts +105 -105
- package/src/decorators/validators/validator-metadata.ts +59 -59
- package/src/dto/dto-types.ts +226 -226
- package/src/dto/filter-types.ts +141 -141
- package/src/dto/index.ts +95 -95
- package/src/dto/openapi/generators/base.ts +29 -29
- package/src/dto/openapi/generators/column.ts +37 -37
- package/src/dto/openapi/generators/dto.ts +91 -91
- package/src/dto/openapi/generators/filter.ts +75 -75
- package/src/dto/openapi/generators/nested-dto.ts +618 -618
- package/src/dto/openapi/generators/pagination.ts +111 -111
- package/src/dto/openapi/generators/relation-filter.ts +228 -228
- package/src/dto/openapi/index.ts +12 -12
- package/src/dto/openapi/types.ts +101 -101
- package/src/dto/openapi/utilities.ts +95 -95
- package/src/dto/pagination-utils.ts +150 -150
- package/src/dto/transform.ts +197 -197
- package/src/index.ts +86 -86
- package/src/orm/als.ts +58 -58
- package/src/orm/domain-event-bus.ts +119 -119
- package/src/orm/entity-context.ts +86 -86
- package/src/orm/entity-materializer.ts +159 -159
- package/src/orm/entity-meta.ts +97 -97
- package/src/orm/entity-registry.ts +39 -39
- package/src/orm/entity-relation-cache.ts +39 -39
- package/src/orm/execute.ts +194 -194
- package/src/orm/execution-context.ts +18 -18
- package/src/orm/hydration-context.ts +26 -26
- package/src/orm/hydration.ts +112 -112
- package/src/orm/identity-map.ts +61 -61
- package/src/orm/interceptor-pipeline.ts +16 -16
- package/src/orm/lazy-batch/belongs-to-many.ts +119 -119
- package/src/orm/lazy-batch/belongs-to.ts +108 -108
- package/src/orm/lazy-batch/has-many.ts +69 -69
- package/src/orm/lazy-batch/has-one.ts +68 -68
- package/src/orm/lazy-batch/shared.ts +125 -125
- package/src/orm/orm-session.ts +620 -620
- package/src/orm/orm.ts +34 -34
- package/src/orm/pooled-executor-factory.ts +121 -121
- package/src/orm/query-logger.ts +40 -40
- package/src/orm/relation-change-processor.ts +420 -420
- package/src/orm/relations/belongs-to.ts +143 -143
- package/src/orm/relations/has-many.ts +204 -204
- package/src/orm/relations/has-one.ts +174 -174
- package/src/orm/relations/many-to-many.ts +288 -288
- package/src/orm/relations/morph-many.ts +156 -156
- package/src/orm/relations/morph-one.ts +151 -151
- package/src/orm/relations/morph-to.ts +162 -162
- package/src/orm/runtime-types.ts +92 -92
- package/src/orm/save-graph.ts +561 -561
- package/src/orm/transaction-runner.ts +24 -24
- package/src/orm/unit-of-work.ts +426 -426
- package/src/query/index.ts +69 -69
- package/src/query/target.ts +46 -46
- package/src/query-builder/column-selector.ts +81 -81
- package/src/query-builder/delete.ts +141 -141
- package/src/query-builder/insert-query-state.ts +149 -149
- package/src/query-builder/insert.ts +117 -117
- package/src/query-builder/query-ast-service.ts +287 -287
- package/src/query-builder/query-resolution.ts +78 -78
- package/src/query-builder/raw-column-parser.ts +38 -38
- package/src/query-builder/relation-filter-utils.ts +153 -153
- package/src/query-builder/relation-join-planner.ts +10 -10
- package/src/query-builder/relation-manager.ts +87 -87
- package/src/query-builder/relation-projection-helper.ts +102 -102
- package/src/query-builder/relation-types.ts +9 -9
- package/src/query-builder/relation-utils.ts +15 -15
- package/src/query-builder/select/cte-facet.ts +40 -40
- package/src/query-builder/select/from-facet.ts +80 -80
- package/src/query-builder/select/join-facet.ts +62 -62
- package/src/query-builder/select/predicate-facet.ts +104 -104
- package/src/query-builder/select/projection-facet.ts +70 -70
- package/src/query-builder/select/relation-facet.ts +81 -81
- package/src/query-builder/select/setop-facet.ts +36 -36
- package/src/query-builder/select-helpers.ts +1 -1
- package/src/query-builder/select-query-builder-deps.ts +130 -130
- package/src/query-builder/select-query-state.ts +207 -207
- package/src/query-builder/update.ts +151 -151
- package/src/schema/column-types.ts +322 -322
- package/src/schema/table-guards.ts +37 -37
- package/src/schema/table.ts +281 -281
- package/src/tree/index.ts +13 -13
- package/src/tree/nested-set-strategy.ts +545 -545
- package/src/tree/tree-decorator.ts +397 -397
- package/src/tree/tree-manager.ts +754 -754
- package/src/tree/tree-query.ts +427 -427
- package/src/tree/tree-types.ts +299 -299
package/src/tree/tree-query.ts
CHANGED
|
@@ -1,427 +1,427 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tree Query Builder
|
|
3
|
-
*
|
|
4
|
-
* Level 1 API: Pure query builders for tree operations.
|
|
5
|
-
* Returns SelectQueryBuilder instances that can be compiled to any dialect.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { SelectQueryBuilder } from '../query-builder/select.js';
|
|
9
|
-
import { selectFrom } from '../query/index.js';
|
|
10
|
-
import { and, eq, gt, gte, lt, lte, isNull, neq, sub } from '../core/ast/expression.js';
|
|
11
|
-
import type { TableDef } from '../schema/table.js';
|
|
12
|
-
import type {
|
|
13
|
-
TreeConfig,
|
|
14
|
-
FindPathOptions,
|
|
15
|
-
TreeListOptions,
|
|
16
|
-
TreeScope,
|
|
17
|
-
ThreadedNode,
|
|
18
|
-
NestedSetBounds,
|
|
19
|
-
} from './tree-types.js';
|
|
20
|
-
import {
|
|
21
|
-
resolveTreeConfig,
|
|
22
|
-
getTreeColumns,
|
|
23
|
-
validateTreeTable,
|
|
24
|
-
} from './tree-types.js';
|
|
25
|
-
import {
|
|
26
|
-
NestedSetStrategy,
|
|
27
|
-
buildScopeConditions,
|
|
28
|
-
} from './nested-set-strategy.js';
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Tree query helper bound to a specific table and configuration.
|
|
32
|
-
* @typeParam T - The table definition type
|
|
33
|
-
*/
|
|
34
|
-
export interface TreeQuery<T extends TableDef> {
|
|
35
|
-
/** The underlying table definition */
|
|
36
|
-
readonly table: T;
|
|
37
|
-
/** The resolved tree configuration */
|
|
38
|
-
readonly config: TreeConfig;
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Finds ancestors of a node given its bounds.
|
|
42
|
-
* Returns ancestors ordered from root to node (or reverse if order: 'desc').
|
|
43
|
-
*
|
|
44
|
-
* @param bounds - The lft/rght values of the target node
|
|
45
|
-
* @param options - Path options
|
|
46
|
-
*/
|
|
47
|
-
findAncestors(
|
|
48
|
-
bounds: NestedSetBounds,
|
|
49
|
-
options?: FindPathOptions
|
|
50
|
-
): SelectQueryBuilder<unknown, T>;
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Finds all descendants of a node given its bounds.
|
|
54
|
-
*
|
|
55
|
-
* @param bounds - The lft/rght values of the parent node
|
|
56
|
-
*/
|
|
57
|
-
findDescendants(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T>;
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Finds direct children of a node by parent ID.
|
|
61
|
-
*/
|
|
62
|
-
findDirectChildren(parentId: unknown): SelectQueryBuilder<unknown, T>;
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Finds the parent of a node by parent ID reference.
|
|
66
|
-
*/
|
|
67
|
-
findParentById(parentId: unknown): SelectQueryBuilder<unknown, T>;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Finds all siblings of a node by parent ID.
|
|
71
|
-
*/
|
|
72
|
-
findSiblings(
|
|
73
|
-
parentId: unknown,
|
|
74
|
-
excludeId?: unknown
|
|
75
|
-
): SelectQueryBuilder<unknown, T>;
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Finds all root nodes (nodes with no parent).
|
|
79
|
-
*/
|
|
80
|
-
findRoots(): SelectQueryBuilder<unknown, T>;
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Finds all leaf nodes (nodes with no children).
|
|
84
|
-
*/
|
|
85
|
-
findLeaves(): SelectQueryBuilder<unknown, T>;
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Finds a subtree: the node and all its descendants.
|
|
89
|
-
*
|
|
90
|
-
* @param bounds - The lft/rght values of the root node
|
|
91
|
-
*/
|
|
92
|
-
findSubtree(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T>;
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Creates a tree list query for dropdown/select rendering.
|
|
96
|
-
* Returns all nodes ordered by lft.
|
|
97
|
-
*/
|
|
98
|
-
findTreeList(options?: TreeListOptions): SelectQueryBuilder<unknown, T>;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Finds nodes at a specific depth level.
|
|
102
|
-
* Requires depthKey to be configured.
|
|
103
|
-
*/
|
|
104
|
-
findAtDepth(depth: number): SelectQueryBuilder<unknown, T>;
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Finds a node by ID.
|
|
108
|
-
*/
|
|
109
|
-
findById(id: unknown): SelectQueryBuilder<unknown, T>;
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Sets scope values for multi-tree tables.
|
|
113
|
-
* Returns a new TreeQuery with the scope applied.
|
|
114
|
-
*/
|
|
115
|
-
withScope(scope: TreeScope): TreeQuery<T>;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Internal state for tree query builder.
|
|
120
|
-
*/
|
|
121
|
-
interface TreeQueryState<T extends TableDef> {
|
|
122
|
-
table: T;
|
|
123
|
-
config: TreeConfig;
|
|
124
|
-
scopeValues: TreeScope;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Creates a tree query helper for a table.
|
|
129
|
-
*
|
|
130
|
-
* @example
|
|
131
|
-
* ```ts
|
|
132
|
-
* const tree = treeQuery(categories, {
|
|
133
|
-
* parentKey: 'parentId',
|
|
134
|
-
* leftKey: 'lft',
|
|
135
|
-
* rightKey: 'rght',
|
|
136
|
-
* });
|
|
137
|
-
*
|
|
138
|
-
* // Find direct children
|
|
139
|
-
* const childrenQuery = tree.findDirectChildren(1);
|
|
140
|
-
*
|
|
141
|
-
* // Find descendants (requires bounds)
|
|
142
|
-
* const node = await getNode(1); // { lft: 1, rght: 14 }
|
|
143
|
-
* const descendantsQuery = tree.findDescendants({ lft: node.lft, rght: node.rght });
|
|
144
|
-
* ```
|
|
145
|
-
*/
|
|
146
|
-
export function treeQuery<T extends TableDef>(
|
|
147
|
-
table: T,
|
|
148
|
-
config: Partial<TreeConfig> = {}
|
|
149
|
-
): TreeQuery<T> {
|
|
150
|
-
const resolvedConfig = resolveTreeConfig(config);
|
|
151
|
-
const validation = validateTreeTable(table, resolvedConfig);
|
|
152
|
-
|
|
153
|
-
if (!validation.valid) {
|
|
154
|
-
throw new Error(
|
|
155
|
-
`Invalid tree table '${table.name}': missing columns ${validation.missingColumns.join(', ')}`
|
|
156
|
-
);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
return createTreeQuery({
|
|
160
|
-
table,
|
|
161
|
-
config: resolvedConfig,
|
|
162
|
-
scopeValues: {},
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function createTreeQuery<T extends TableDef>(state: TreeQueryState<T>): TreeQuery<T> {
|
|
167
|
-
const { table, config, scopeValues } = state;
|
|
168
|
-
const columns = getTreeColumns(table, config);
|
|
169
|
-
const pkName = getPrimaryKeyName(table);
|
|
170
|
-
|
|
171
|
-
const applyScope = (qb: SelectQueryBuilder<unknown, T>): SelectQueryBuilder<unknown, T> => {
|
|
172
|
-
const conditions = buildScopeConditions(config.scope, scopeValues);
|
|
173
|
-
let result = qb;
|
|
174
|
-
for (const [key, value] of Object.entries(conditions)) {
|
|
175
|
-
const col = table.columns[key];
|
|
176
|
-
if (col) {
|
|
177
|
-
result = result.where(eq(col, value)) as SelectQueryBuilder<unknown, T>;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
return result;
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
const tq: TreeQuery<T> = {
|
|
184
|
-
table,
|
|
185
|
-
config,
|
|
186
|
-
|
|
187
|
-
findAncestors(bounds: NestedSetBounds, options: FindPathOptions = {}): SelectQueryBuilder<unknown, T> {
|
|
188
|
-
const { includeSelf = true, order = 'asc' } = options;
|
|
189
|
-
|
|
190
|
-
let qb = selectFrom(table) as unknown as SelectQueryBuilder<unknown, T>;
|
|
191
|
-
|
|
192
|
-
if (includeSelf) {
|
|
193
|
-
qb = qb.where(
|
|
194
|
-
and(
|
|
195
|
-
lte(columns.leftColumn, bounds.lft),
|
|
196
|
-
gte(columns.rightColumn, bounds.rght)
|
|
197
|
-
)
|
|
198
|
-
) as SelectQueryBuilder<unknown, T>;
|
|
199
|
-
} else {
|
|
200
|
-
qb = qb.where(
|
|
201
|
-
and(
|
|
202
|
-
lt(columns.leftColumn, bounds.lft),
|
|
203
|
-
gt(columns.rightColumn, bounds.rght)
|
|
204
|
-
)
|
|
205
|
-
) as SelectQueryBuilder<unknown, T>;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
qb = qb.orderBy(columns.leftColumn, order === 'asc' ? 'ASC' : 'DESC') as SelectQueryBuilder<unknown, T>;
|
|
209
|
-
|
|
210
|
-
return applyScope(qb);
|
|
211
|
-
},
|
|
212
|
-
|
|
213
|
-
findDescendants(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T> {
|
|
214
|
-
const qb = selectFrom(table)
|
|
215
|
-
.where(
|
|
216
|
-
and(
|
|
217
|
-
gt(columns.leftColumn, bounds.lft),
|
|
218
|
-
lt(columns.rightColumn, bounds.rght)
|
|
219
|
-
)
|
|
220
|
-
)
|
|
221
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
222
|
-
|
|
223
|
-
return applyScope(qb);
|
|
224
|
-
},
|
|
225
|
-
|
|
226
|
-
findDirectChildren(parentId: unknown): SelectQueryBuilder<unknown, T> {
|
|
227
|
-
const qb = selectFrom(table)
|
|
228
|
-
.where(eq(columns.parentColumn, parentId))
|
|
229
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
230
|
-
|
|
231
|
-
return applyScope(qb);
|
|
232
|
-
},
|
|
233
|
-
|
|
234
|
-
findParentById(parentId: unknown): SelectQueryBuilder<unknown, T> {
|
|
235
|
-
const qb = selectFrom(table)
|
|
236
|
-
.where(eq(table.columns[pkName], parentId)) as SelectQueryBuilder<unknown, T>;
|
|
237
|
-
|
|
238
|
-
return applyScope(qb);
|
|
239
|
-
},
|
|
240
|
-
|
|
241
|
-
findSiblings(parentId: unknown, excludeId?: unknown): SelectQueryBuilder<unknown, T> {
|
|
242
|
-
let qb = selectFrom(table)
|
|
243
|
-
.where(eq(columns.parentColumn, parentId)) as SelectQueryBuilder<unknown, T>;
|
|
244
|
-
|
|
245
|
-
if (excludeId !== undefined) {
|
|
246
|
-
qb = qb.where(neq(table.columns[pkName], excludeId)) as SelectQueryBuilder<unknown, T>;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
qb = qb.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
250
|
-
|
|
251
|
-
return applyScope(qb);
|
|
252
|
-
},
|
|
253
|
-
|
|
254
|
-
findRoots(): SelectQueryBuilder<unknown, T> {
|
|
255
|
-
const qb = selectFrom(table)
|
|
256
|
-
.where(isNull(columns.parentColumn))
|
|
257
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
258
|
-
|
|
259
|
-
return applyScope(qb);
|
|
260
|
-
},
|
|
261
|
-
|
|
262
|
-
findLeaves(): SelectQueryBuilder<unknown, T> {
|
|
263
|
-
const qb = selectFrom(table)
|
|
264
|
-
.where(eq(sub(columns.rightColumn, columns.leftColumn), 1))
|
|
265
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
266
|
-
|
|
267
|
-
return applyScope(qb);
|
|
268
|
-
},
|
|
269
|
-
|
|
270
|
-
findSubtree(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T> {
|
|
271
|
-
const qb = selectFrom(table)
|
|
272
|
-
.where(
|
|
273
|
-
and(
|
|
274
|
-
gte(columns.leftColumn, bounds.lft),
|
|
275
|
-
lte(columns.rightColumn, bounds.rght)
|
|
276
|
-
)
|
|
277
|
-
)
|
|
278
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
279
|
-
|
|
280
|
-
return applyScope(qb);
|
|
281
|
-
},
|
|
282
|
-
|
|
283
|
-
findTreeList(): SelectQueryBuilder<unknown, T> {
|
|
284
|
-
const qb = selectFrom(table)
|
|
285
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
286
|
-
|
|
287
|
-
return applyScope(qb);
|
|
288
|
-
},
|
|
289
|
-
|
|
290
|
-
findAtDepth(depth: number): SelectQueryBuilder<unknown, T> {
|
|
291
|
-
if (!config.depthKey) {
|
|
292
|
-
throw new Error('findAtDepth requires depthKey to be configured');
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
const qb = selectFrom(table)
|
|
296
|
-
.where(eq(columns.depthColumn!, depth))
|
|
297
|
-
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
298
|
-
|
|
299
|
-
return applyScope(qb);
|
|
300
|
-
},
|
|
301
|
-
|
|
302
|
-
findById(id: unknown): SelectQueryBuilder<unknown, T> {
|
|
303
|
-
const qb = selectFrom(table)
|
|
304
|
-
.where(eq(table.columns[pkName], id)) as SelectQueryBuilder<unknown, T>;
|
|
305
|
-
|
|
306
|
-
return applyScope(qb);
|
|
307
|
-
},
|
|
308
|
-
|
|
309
|
-
withScope(scope: TreeScope): TreeQuery<T> {
|
|
310
|
-
return createTreeQuery({
|
|
311
|
-
...state,
|
|
312
|
-
scopeValues: { ...scopeValues, ...scope },
|
|
313
|
-
});
|
|
314
|
-
},
|
|
315
|
-
};
|
|
316
|
-
|
|
317
|
-
return tq;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* Gets the primary key column name from a table.
|
|
322
|
-
*/
|
|
323
|
-
function getPrimaryKeyName(table: TableDef): string {
|
|
324
|
-
for (const [name, col] of Object.entries(table.columns)) {
|
|
325
|
-
if (col.primary) {
|
|
326
|
-
return name;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
if (table.primaryKey && table.primaryKey.length > 0) {
|
|
330
|
-
return table.primaryKey[0];
|
|
331
|
-
}
|
|
332
|
-
return 'id';
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* Utility to thread flat query results into a nested structure.
|
|
337
|
-
* Use after executing a query that returns nodes ordered by lft.
|
|
338
|
-
*
|
|
339
|
-
* @example
|
|
340
|
-
* ```ts
|
|
341
|
-
* const rows = await executor.executeSql(sql, params);
|
|
342
|
-
* const threaded = threadResults(rows, 'lft', 'rght');
|
|
343
|
-
* ```
|
|
344
|
-
*/
|
|
345
|
-
export function threadResults<T extends Record<string, unknown>>(
|
|
346
|
-
rows: T[],
|
|
347
|
-
leftKey: string = 'lft',
|
|
348
|
-
rightKey: string = 'rght'
|
|
349
|
-
): ThreadedNode<T>[] {
|
|
350
|
-
return NestedSetStrategy.toThreaded(
|
|
351
|
-
rows,
|
|
352
|
-
row => row[leftKey] as number,
|
|
353
|
-
row => row[rightKey] as number
|
|
354
|
-
);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/**
|
|
358
|
-
* Utility to format query results as a tree list for dropdowns.
|
|
359
|
-
*
|
|
360
|
-
* @example
|
|
361
|
-
* ```ts
|
|
362
|
-
* const rows = await executor.executeSql(sql, params);
|
|
363
|
-
* const list = formatTreeList(rows, {
|
|
364
|
-
* keyPath: 'id',
|
|
365
|
-
* valuePath: 'name',
|
|
366
|
-
* spacer: '—',
|
|
367
|
-
* });
|
|
368
|
-
* // Returns: [{ key: 1, value: 'Root', depth: 0 }, { key: 2, value: '—Child', depth: 1 }, ...]
|
|
369
|
-
* ```
|
|
370
|
-
*/
|
|
371
|
-
export function formatTreeList<T extends Record<string, unknown>>(
|
|
372
|
-
rows: T[],
|
|
373
|
-
options: TreeListOptions & {
|
|
374
|
-
leftKey?: string;
|
|
375
|
-
rightKey?: string;
|
|
376
|
-
depthKey?: string;
|
|
377
|
-
} = {}
|
|
378
|
-
): Array<{ key: unknown; value: string; depth: number }> {
|
|
379
|
-
const {
|
|
380
|
-
keyPath = 'id',
|
|
381
|
-
valuePath = 'id',
|
|
382
|
-
spacer = '__',
|
|
383
|
-
leftKey = 'lft',
|
|
384
|
-
rightKey = 'rght',
|
|
385
|
-
depthKey,
|
|
386
|
-
} = options;
|
|
387
|
-
|
|
388
|
-
let depthsCache: Map<T, number> | null = null;
|
|
389
|
-
|
|
390
|
-
const getDepth = (row: T): number => {
|
|
391
|
-
if (depthKey && row[depthKey] !== undefined) {
|
|
392
|
-
return row[depthKey] as number;
|
|
393
|
-
}
|
|
394
|
-
if (!depthsCache) {
|
|
395
|
-
depthsCache = NestedSetStrategy.calculateDepths(
|
|
396
|
-
rows,
|
|
397
|
-
r => r[leftKey] as number,
|
|
398
|
-
r => r[rightKey] as number
|
|
399
|
-
);
|
|
400
|
-
}
|
|
401
|
-
return depthsCache.get(row) ?? 0;
|
|
402
|
-
};
|
|
403
|
-
|
|
404
|
-
return NestedSetStrategy.toTreeList(
|
|
405
|
-
rows,
|
|
406
|
-
row => row[keyPath],
|
|
407
|
-
row => String(row[valuePath]),
|
|
408
|
-
getDepth,
|
|
409
|
-
spacer
|
|
410
|
-
);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/**
|
|
414
|
-
* Calculates and caches depths for a set of rows.
|
|
415
|
-
* Useful when depth is not stored in the database.
|
|
416
|
-
*/
|
|
417
|
-
export function calculateRowDepths<T extends Record<string, unknown>>(
|
|
418
|
-
rows: T[],
|
|
419
|
-
leftKey: string = 'lft',
|
|
420
|
-
rightKey: string = 'rght'
|
|
421
|
-
): Map<T, number> {
|
|
422
|
-
return NestedSetStrategy.calculateDepths(
|
|
423
|
-
rows,
|
|
424
|
-
row => row[leftKey] as number,
|
|
425
|
-
row => row[rightKey] as number
|
|
426
|
-
);
|
|
427
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Tree Query Builder
|
|
3
|
+
*
|
|
4
|
+
* Level 1 API: Pure query builders for tree operations.
|
|
5
|
+
* Returns SelectQueryBuilder instances that can be compiled to any dialect.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { SelectQueryBuilder } from '../query-builder/select.js';
|
|
9
|
+
import { selectFrom } from '../query/index.js';
|
|
10
|
+
import { and, eq, gt, gte, lt, lte, isNull, neq, sub } from '../core/ast/expression.js';
|
|
11
|
+
import type { TableDef } from '../schema/table.js';
|
|
12
|
+
import type {
|
|
13
|
+
TreeConfig,
|
|
14
|
+
FindPathOptions,
|
|
15
|
+
TreeListOptions,
|
|
16
|
+
TreeScope,
|
|
17
|
+
ThreadedNode,
|
|
18
|
+
NestedSetBounds,
|
|
19
|
+
} from './tree-types.js';
|
|
20
|
+
import {
|
|
21
|
+
resolveTreeConfig,
|
|
22
|
+
getTreeColumns,
|
|
23
|
+
validateTreeTable,
|
|
24
|
+
} from './tree-types.js';
|
|
25
|
+
import {
|
|
26
|
+
NestedSetStrategy,
|
|
27
|
+
buildScopeConditions,
|
|
28
|
+
} from './nested-set-strategy.js';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Tree query helper bound to a specific table and configuration.
|
|
32
|
+
* @typeParam T - The table definition type
|
|
33
|
+
*/
|
|
34
|
+
export interface TreeQuery<T extends TableDef> {
|
|
35
|
+
/** The underlying table definition */
|
|
36
|
+
readonly table: T;
|
|
37
|
+
/** The resolved tree configuration */
|
|
38
|
+
readonly config: TreeConfig;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Finds ancestors of a node given its bounds.
|
|
42
|
+
* Returns ancestors ordered from root to node (or reverse if order: 'desc').
|
|
43
|
+
*
|
|
44
|
+
* @param bounds - The lft/rght values of the target node
|
|
45
|
+
* @param options - Path options
|
|
46
|
+
*/
|
|
47
|
+
findAncestors(
|
|
48
|
+
bounds: NestedSetBounds,
|
|
49
|
+
options?: FindPathOptions
|
|
50
|
+
): SelectQueryBuilder<unknown, T>;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Finds all descendants of a node given its bounds.
|
|
54
|
+
*
|
|
55
|
+
* @param bounds - The lft/rght values of the parent node
|
|
56
|
+
*/
|
|
57
|
+
findDescendants(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T>;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Finds direct children of a node by parent ID.
|
|
61
|
+
*/
|
|
62
|
+
findDirectChildren(parentId: unknown): SelectQueryBuilder<unknown, T>;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Finds the parent of a node by parent ID reference.
|
|
66
|
+
*/
|
|
67
|
+
findParentById(parentId: unknown): SelectQueryBuilder<unknown, T>;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Finds all siblings of a node by parent ID.
|
|
71
|
+
*/
|
|
72
|
+
findSiblings(
|
|
73
|
+
parentId: unknown,
|
|
74
|
+
excludeId?: unknown
|
|
75
|
+
): SelectQueryBuilder<unknown, T>;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Finds all root nodes (nodes with no parent).
|
|
79
|
+
*/
|
|
80
|
+
findRoots(): SelectQueryBuilder<unknown, T>;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Finds all leaf nodes (nodes with no children).
|
|
84
|
+
*/
|
|
85
|
+
findLeaves(): SelectQueryBuilder<unknown, T>;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Finds a subtree: the node and all its descendants.
|
|
89
|
+
*
|
|
90
|
+
* @param bounds - The lft/rght values of the root node
|
|
91
|
+
*/
|
|
92
|
+
findSubtree(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T>;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Creates a tree list query for dropdown/select rendering.
|
|
96
|
+
* Returns all nodes ordered by lft.
|
|
97
|
+
*/
|
|
98
|
+
findTreeList(options?: TreeListOptions): SelectQueryBuilder<unknown, T>;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Finds nodes at a specific depth level.
|
|
102
|
+
* Requires depthKey to be configured.
|
|
103
|
+
*/
|
|
104
|
+
findAtDepth(depth: number): SelectQueryBuilder<unknown, T>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Finds a node by ID.
|
|
108
|
+
*/
|
|
109
|
+
findById(id: unknown): SelectQueryBuilder<unknown, T>;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Sets scope values for multi-tree tables.
|
|
113
|
+
* Returns a new TreeQuery with the scope applied.
|
|
114
|
+
*/
|
|
115
|
+
withScope(scope: TreeScope): TreeQuery<T>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Internal state for tree query builder.
|
|
120
|
+
*/
|
|
121
|
+
interface TreeQueryState<T extends TableDef> {
|
|
122
|
+
table: T;
|
|
123
|
+
config: TreeConfig;
|
|
124
|
+
scopeValues: TreeScope;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Creates a tree query helper for a table.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* const tree = treeQuery(categories, {
|
|
133
|
+
* parentKey: 'parentId',
|
|
134
|
+
* leftKey: 'lft',
|
|
135
|
+
* rightKey: 'rght',
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* // Find direct children
|
|
139
|
+
* const childrenQuery = tree.findDirectChildren(1);
|
|
140
|
+
*
|
|
141
|
+
* // Find descendants (requires bounds)
|
|
142
|
+
* const node = await getNode(1); // { lft: 1, rght: 14 }
|
|
143
|
+
* const descendantsQuery = tree.findDescendants({ lft: node.lft, rght: node.rght });
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
export function treeQuery<T extends TableDef>(
|
|
147
|
+
table: T,
|
|
148
|
+
config: Partial<TreeConfig> = {}
|
|
149
|
+
): TreeQuery<T> {
|
|
150
|
+
const resolvedConfig = resolveTreeConfig(config);
|
|
151
|
+
const validation = validateTreeTable(table, resolvedConfig);
|
|
152
|
+
|
|
153
|
+
if (!validation.valid) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`Invalid tree table '${table.name}': missing columns ${validation.missingColumns.join(', ')}`
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return createTreeQuery({
|
|
160
|
+
table,
|
|
161
|
+
config: resolvedConfig,
|
|
162
|
+
scopeValues: {},
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function createTreeQuery<T extends TableDef>(state: TreeQueryState<T>): TreeQuery<T> {
|
|
167
|
+
const { table, config, scopeValues } = state;
|
|
168
|
+
const columns = getTreeColumns(table, config);
|
|
169
|
+
const pkName = getPrimaryKeyName(table);
|
|
170
|
+
|
|
171
|
+
const applyScope = (qb: SelectQueryBuilder<unknown, T>): SelectQueryBuilder<unknown, T> => {
|
|
172
|
+
const conditions = buildScopeConditions(config.scope, scopeValues);
|
|
173
|
+
let result = qb;
|
|
174
|
+
for (const [key, value] of Object.entries(conditions)) {
|
|
175
|
+
const col = table.columns[key];
|
|
176
|
+
if (col) {
|
|
177
|
+
result = result.where(eq(col, value)) as SelectQueryBuilder<unknown, T>;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const tq: TreeQuery<T> = {
|
|
184
|
+
table,
|
|
185
|
+
config,
|
|
186
|
+
|
|
187
|
+
findAncestors(bounds: NestedSetBounds, options: FindPathOptions = {}): SelectQueryBuilder<unknown, T> {
|
|
188
|
+
const { includeSelf = true, order = 'asc' } = options;
|
|
189
|
+
|
|
190
|
+
let qb = selectFrom(table) as unknown as SelectQueryBuilder<unknown, T>;
|
|
191
|
+
|
|
192
|
+
if (includeSelf) {
|
|
193
|
+
qb = qb.where(
|
|
194
|
+
and(
|
|
195
|
+
lte(columns.leftColumn, bounds.lft),
|
|
196
|
+
gte(columns.rightColumn, bounds.rght)
|
|
197
|
+
)
|
|
198
|
+
) as SelectQueryBuilder<unknown, T>;
|
|
199
|
+
} else {
|
|
200
|
+
qb = qb.where(
|
|
201
|
+
and(
|
|
202
|
+
lt(columns.leftColumn, bounds.lft),
|
|
203
|
+
gt(columns.rightColumn, bounds.rght)
|
|
204
|
+
)
|
|
205
|
+
) as SelectQueryBuilder<unknown, T>;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
qb = qb.orderBy(columns.leftColumn, order === 'asc' ? 'ASC' : 'DESC') as SelectQueryBuilder<unknown, T>;
|
|
209
|
+
|
|
210
|
+
return applyScope(qb);
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
findDescendants(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T> {
|
|
214
|
+
const qb = selectFrom(table)
|
|
215
|
+
.where(
|
|
216
|
+
and(
|
|
217
|
+
gt(columns.leftColumn, bounds.lft),
|
|
218
|
+
lt(columns.rightColumn, bounds.rght)
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
222
|
+
|
|
223
|
+
return applyScope(qb);
|
|
224
|
+
},
|
|
225
|
+
|
|
226
|
+
findDirectChildren(parentId: unknown): SelectQueryBuilder<unknown, T> {
|
|
227
|
+
const qb = selectFrom(table)
|
|
228
|
+
.where(eq(columns.parentColumn, parentId))
|
|
229
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
230
|
+
|
|
231
|
+
return applyScope(qb);
|
|
232
|
+
},
|
|
233
|
+
|
|
234
|
+
findParentById(parentId: unknown): SelectQueryBuilder<unknown, T> {
|
|
235
|
+
const qb = selectFrom(table)
|
|
236
|
+
.where(eq(table.columns[pkName], parentId)) as SelectQueryBuilder<unknown, T>;
|
|
237
|
+
|
|
238
|
+
return applyScope(qb);
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
findSiblings(parentId: unknown, excludeId?: unknown): SelectQueryBuilder<unknown, T> {
|
|
242
|
+
let qb = selectFrom(table)
|
|
243
|
+
.where(eq(columns.parentColumn, parentId)) as SelectQueryBuilder<unknown, T>;
|
|
244
|
+
|
|
245
|
+
if (excludeId !== undefined) {
|
|
246
|
+
qb = qb.where(neq(table.columns[pkName], excludeId)) as SelectQueryBuilder<unknown, T>;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
qb = qb.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
250
|
+
|
|
251
|
+
return applyScope(qb);
|
|
252
|
+
},
|
|
253
|
+
|
|
254
|
+
findRoots(): SelectQueryBuilder<unknown, T> {
|
|
255
|
+
const qb = selectFrom(table)
|
|
256
|
+
.where(isNull(columns.parentColumn))
|
|
257
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
258
|
+
|
|
259
|
+
return applyScope(qb);
|
|
260
|
+
},
|
|
261
|
+
|
|
262
|
+
findLeaves(): SelectQueryBuilder<unknown, T> {
|
|
263
|
+
const qb = selectFrom(table)
|
|
264
|
+
.where(eq(sub(columns.rightColumn, columns.leftColumn), 1))
|
|
265
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
266
|
+
|
|
267
|
+
return applyScope(qb);
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
findSubtree(bounds: NestedSetBounds): SelectQueryBuilder<unknown, T> {
|
|
271
|
+
const qb = selectFrom(table)
|
|
272
|
+
.where(
|
|
273
|
+
and(
|
|
274
|
+
gte(columns.leftColumn, bounds.lft),
|
|
275
|
+
lte(columns.rightColumn, bounds.rght)
|
|
276
|
+
)
|
|
277
|
+
)
|
|
278
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
279
|
+
|
|
280
|
+
return applyScope(qb);
|
|
281
|
+
},
|
|
282
|
+
|
|
283
|
+
findTreeList(): SelectQueryBuilder<unknown, T> {
|
|
284
|
+
const qb = selectFrom(table)
|
|
285
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
286
|
+
|
|
287
|
+
return applyScope(qb);
|
|
288
|
+
},
|
|
289
|
+
|
|
290
|
+
findAtDepth(depth: number): SelectQueryBuilder<unknown, T> {
|
|
291
|
+
if (!config.depthKey) {
|
|
292
|
+
throw new Error('findAtDepth requires depthKey to be configured');
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const qb = selectFrom(table)
|
|
296
|
+
.where(eq(columns.depthColumn!, depth))
|
|
297
|
+
.orderBy(columns.leftColumn, 'ASC') as SelectQueryBuilder<unknown, T>;
|
|
298
|
+
|
|
299
|
+
return applyScope(qb);
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
findById(id: unknown): SelectQueryBuilder<unknown, T> {
|
|
303
|
+
const qb = selectFrom(table)
|
|
304
|
+
.where(eq(table.columns[pkName], id)) as SelectQueryBuilder<unknown, T>;
|
|
305
|
+
|
|
306
|
+
return applyScope(qb);
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
withScope(scope: TreeScope): TreeQuery<T> {
|
|
310
|
+
return createTreeQuery({
|
|
311
|
+
...state,
|
|
312
|
+
scopeValues: { ...scopeValues, ...scope },
|
|
313
|
+
});
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
return tq;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Gets the primary key column name from a table.
|
|
322
|
+
*/
|
|
323
|
+
function getPrimaryKeyName(table: TableDef): string {
|
|
324
|
+
for (const [name, col] of Object.entries(table.columns)) {
|
|
325
|
+
if (col.primary) {
|
|
326
|
+
return name;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (table.primaryKey && table.primaryKey.length > 0) {
|
|
330
|
+
return table.primaryKey[0];
|
|
331
|
+
}
|
|
332
|
+
return 'id';
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Utility to thread flat query results into a nested structure.
|
|
337
|
+
* Use after executing a query that returns nodes ordered by lft.
|
|
338
|
+
*
|
|
339
|
+
* @example
|
|
340
|
+
* ```ts
|
|
341
|
+
* const rows = await executor.executeSql(sql, params);
|
|
342
|
+
* const threaded = threadResults(rows, 'lft', 'rght');
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
345
|
+
export function threadResults<T extends Record<string, unknown>>(
|
|
346
|
+
rows: T[],
|
|
347
|
+
leftKey: string = 'lft',
|
|
348
|
+
rightKey: string = 'rght'
|
|
349
|
+
): ThreadedNode<T>[] {
|
|
350
|
+
return NestedSetStrategy.toThreaded(
|
|
351
|
+
rows,
|
|
352
|
+
row => row[leftKey] as number,
|
|
353
|
+
row => row[rightKey] as number
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Utility to format query results as a tree list for dropdowns.
|
|
359
|
+
*
|
|
360
|
+
* @example
|
|
361
|
+
* ```ts
|
|
362
|
+
* const rows = await executor.executeSql(sql, params);
|
|
363
|
+
* const list = formatTreeList(rows, {
|
|
364
|
+
* keyPath: 'id',
|
|
365
|
+
* valuePath: 'name',
|
|
366
|
+
* spacer: '—',
|
|
367
|
+
* });
|
|
368
|
+
* // Returns: [{ key: 1, value: 'Root', depth: 0 }, { key: 2, value: '—Child', depth: 1 }, ...]
|
|
369
|
+
* ```
|
|
370
|
+
*/
|
|
371
|
+
export function formatTreeList<T extends Record<string, unknown>>(
|
|
372
|
+
rows: T[],
|
|
373
|
+
options: TreeListOptions & {
|
|
374
|
+
leftKey?: string;
|
|
375
|
+
rightKey?: string;
|
|
376
|
+
depthKey?: string;
|
|
377
|
+
} = {}
|
|
378
|
+
): Array<{ key: unknown; value: string; depth: number }> {
|
|
379
|
+
const {
|
|
380
|
+
keyPath = 'id',
|
|
381
|
+
valuePath = 'id',
|
|
382
|
+
spacer = '__',
|
|
383
|
+
leftKey = 'lft',
|
|
384
|
+
rightKey = 'rght',
|
|
385
|
+
depthKey,
|
|
386
|
+
} = options;
|
|
387
|
+
|
|
388
|
+
let depthsCache: Map<T, number> | null = null;
|
|
389
|
+
|
|
390
|
+
const getDepth = (row: T): number => {
|
|
391
|
+
if (depthKey && row[depthKey] !== undefined) {
|
|
392
|
+
return row[depthKey] as number;
|
|
393
|
+
}
|
|
394
|
+
if (!depthsCache) {
|
|
395
|
+
depthsCache = NestedSetStrategy.calculateDepths(
|
|
396
|
+
rows,
|
|
397
|
+
r => r[leftKey] as number,
|
|
398
|
+
r => r[rightKey] as number
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
return depthsCache.get(row) ?? 0;
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
return NestedSetStrategy.toTreeList(
|
|
405
|
+
rows,
|
|
406
|
+
row => row[keyPath],
|
|
407
|
+
row => String(row[valuePath]),
|
|
408
|
+
getDepth,
|
|
409
|
+
spacer
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Calculates and caches depths for a set of rows.
|
|
415
|
+
* Useful when depth is not stored in the database.
|
|
416
|
+
*/
|
|
417
|
+
export function calculateRowDepths<T extends Record<string, unknown>>(
|
|
418
|
+
rows: T[],
|
|
419
|
+
leftKey: string = 'lft',
|
|
420
|
+
rightKey: string = 'rght'
|
|
421
|
+
): Map<T, number> {
|
|
422
|
+
return NestedSetStrategy.calculateDepths(
|
|
423
|
+
rows,
|
|
424
|
+
row => row[leftKey] as number,
|
|
425
|
+
row => row[rightKey] as number
|
|
426
|
+
);
|
|
427
|
+
}
|