plugin-block-cross-join 0.1.7 → 0.1.8

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.
@@ -1,246 +1,287 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { Context } from '@nocobase/actions';
11
-
12
- interface JoinConfig {
13
- dataSource: string;
14
- collection: string;
15
- joinType: 'left' | 'inner';
16
- leftField: string;
17
- rightField: string;
18
- }
19
-
20
- interface ColumnConfig {
21
- source: number; // 0 = primary, 1 = join[0], ...
22
- field: string;
23
- alias?: string;
24
- jsonExpand?: string[];
25
- }
26
-
27
- interface CrossJoinConfig {
28
- primarySource: {
29
- dataSource: string;
30
- collection: string;
31
- filter?: Record<string, any>;
32
- };
33
- joins: JoinConfig[];
34
- columns: ColumnConfig[];
35
- defaultSort?: string[];
36
- }
37
-
38
- function toPlainObject(row: any): Record<string, any> {
39
- if (row && typeof row.toJSON === 'function') {
40
- return row.toJSON();
41
- }
42
- return row;
43
- }
44
-
45
- function buildJoinMap(rows: Record<string, any>[], keyField: string): Map<string, Record<string, any>[]> {
46
- const map = new Map<string, Record<string, any>[]>();
47
- for (const row of rows) {
48
- const key = String(row[keyField] ?? '');
49
- if (!map.has(key)) {
50
- map.set(key, []);
51
- }
52
- map.get(key)!.push(row);
53
- }
54
- return map;
55
- }
56
-
57
- function prefixRow(row: Record<string, any>, prefix: string): Record<string, any> {
58
- const result: Record<string, any> = {};
59
- for (const [k, v] of Object.entries(row)) {
60
- result[`${prefix}.${k}`] = v;
61
- }
62
- return result;
63
- }
64
-
65
- function applyJoin(
66
- leftRows: Record<string, any>[],
67
- rightRows: Record<string, any>[],
68
- joinConfig: JoinConfig,
69
- joinIndex: number,
70
- ): Record<string, any>[] {
71
- const rightMap = buildJoinMap(rightRows, joinConfig.rightField);
72
- const rightPrefix = `join${joinIndex}`;
73
- const result: Record<string, any>[] = [];
74
-
75
- for (const leftRow of leftRows) {
76
- const key = String(leftRow[`primary.${joinConfig.leftField}`] ?? leftRow[joinConfig.leftField] ?? '');
77
- const matches = rightMap.get(key);
78
-
79
- if (matches && matches.length > 0) {
80
- for (const match of matches) {
81
- result.push({ ...leftRow, ...prefixRow(match, rightPrefix) });
82
- }
83
- } else if (joinConfig.joinType === 'left') {
84
- result.push({ ...leftRow });
85
- }
86
- // inner join: skip rows with no match
87
- }
88
-
89
- return result;
90
- }
91
-
92
- function applyColumnMapping(rows: Record<string, any>[], columns: ColumnConfig[]): Record<string, any>[] {
93
- return rows.map((row) => {
94
- const mapped: Record<string, any> = {};
95
-
96
- for (const col of columns) {
97
- const prefix = col.source === 0 ? 'primary' : `join${col.source - 1}`;
98
- const fullKey = `${prefix}.${col.field}`;
99
- const value = row[fullKey];
100
-
101
- // JSON expansion
102
- if (col.jsonExpand?.length && value != null) {
103
- try {
104
- const parsed = typeof value === 'string' ? JSON.parse(value) : value;
105
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
106
- for (const jsonKey of col.jsonExpand) {
107
- const alias = col.alias ? `${col.alias}.${jsonKey}` : `${col.field}.${jsonKey}`;
108
- mapped[alias] = parsed[jsonKey] ?? null;
109
- }
110
- continue;
111
- }
112
- } catch {
113
- // not valid JSON, fall through to display raw value
114
- }
115
- }
116
-
117
- const outputKey = col.alias || col.field;
118
- mapped[outputKey] = value ?? null;
119
- }
120
-
121
- return mapped;
122
- });
123
- }
124
-
125
- export async function crossJoinQuery(ctx: Context, next: () => Promise<void>) {
126
- const { config, page = 1, pageSize = 20, sort } = ctx.action.params.values || ctx.action.params;
127
-
128
- if (!config?.primarySource) {
129
- ctx.throw(400, 'Missing primarySource in config');
130
- }
131
-
132
- const dsManager = ctx.app.dataSourceManager;
133
- const { primarySource, joins = [], columns = [] } = config as CrossJoinConfig;
134
-
135
- // 1. Get primary datasource and repository
136
- const primaryDS = dsManager.get(primarySource.dataSource);
137
- if (!primaryDS) {
138
- ctx.throw(400, `Datasource "${primarySource.dataSource}" not found`);
139
- }
140
-
141
- const primaryRepo = primaryDS.collectionManager.getRepository(primarySource.collection);
142
- if (!primaryRepo) {
143
- ctx.throw(400, `Collection "${primarySource.collection}" not found in datasource "${primarySource.dataSource}"`);
144
- }
145
-
146
- // 2. Determine if we need full-fetch (INNER join) or can paginate primary
147
- const hasInnerJoin = joins.some((j) => j.joinType === 'inner');
148
-
149
- let primaryRows: Record<string, any>[];
150
- let totalPrimaryCount: number;
151
-
152
- if (hasInnerJoin) {
153
- // Full fetch with cap for INNER joins
154
- const MAX_ROWS = 10000;
155
- const rawRows = await primaryRepo.find({
156
- filter: primarySource.filter || {},
157
- sort: sort || config.defaultSort,
158
- limit: MAX_ROWS,
159
- });
160
- primaryRows = rawRows.map(toPlainObject);
161
- totalPrimaryCount = primaryRows.length;
162
- } else {
163
- // Paginate at primary level for LEFT-only joins
164
- const [rawRows, count] = await Promise.all([
165
- primaryRepo.find({
166
- filter: primarySource.filter || {},
167
- sort: sort || config.defaultSort,
168
- limit: Number(pageSize),
169
- offset: (Number(page) - 1) * Number(pageSize),
170
- }),
171
- primaryRepo.count({
172
- filter: primarySource.filter || {},
173
- }),
174
- ]);
175
- primaryRows = rawRows.map(toPlainObject);
176
- totalPrimaryCount = Number(count);
177
- }
178
-
179
- // 3. Prefix primary rows
180
- let joinedRows: Record<string, any>[] = primaryRows.map((row) => prefixRow(row, 'primary'));
181
-
182
- // 4. Process each join
183
- for (let i = 0; i < joins.length; i++) {
184
- const joinDef = joins[i];
185
-
186
- const joinDS = dsManager.get(joinDef.dataSource);
187
- if (!joinDS) {
188
- ctx.throw(400, `Datasource "${joinDef.dataSource}" not found`);
189
- }
190
-
191
- const joinRepo = joinDS.collectionManager.getRepository(joinDef.collection);
192
- if (!joinRepo) {
193
- ctx.throw(400, `Collection "${joinDef.collection}" not found in datasource "${joinDef.dataSource}"`);
194
- }
195
-
196
- // Collect distinct join keys from current result
197
- // leftField always refers to the primary source column (prefixed with "primary.")
198
- const leftKeyPath = `primary.${joinDef.leftField}`;
199
- const distinctKeys = [...new Set(joinedRows.map((r) => r[leftKeyPath]).filter((v) => v != null))];
200
-
201
- if (distinctKeys.length === 0) {
202
- // No keys to join on
203
- joinedRows = joinDef.joinType === 'left' ? joinedRows : [];
204
- continue;
205
- }
206
-
207
- // Batch fetch from join table
208
- const joinRawRows = await joinRepo.find({
209
- filter: {
210
- [joinDef.rightField]: { $in: distinctKeys.map(String) },
211
- },
212
- limit: 10000,
213
- });
214
- const joinRows = joinRawRows.map(toPlainObject);
215
-
216
- // Apply join
217
- joinedRows = applyJoin(joinedRows, joinRows, joinDef, i);
218
- }
219
-
220
- // 5. Paginate if we did full-fetch (INNER join case)
221
- let totalCount: number;
222
- let paginatedRows: Record<string, any>[];
223
-
224
- if (hasInnerJoin) {
225
- totalCount = joinedRows.length;
226
- const start = (Number(page) - 1) * Number(pageSize);
227
- paginatedRows = joinedRows.slice(start, start + Number(pageSize));
228
- } else {
229
- totalCount = totalPrimaryCount;
230
- paginatedRows = joinedRows;
231
- }
232
-
233
- // 6. Apply column mapping
234
- const finalRows = columns.length > 0 ? applyColumnMapping(paginatedRows, columns) : paginatedRows;
235
-
236
- ctx.body = {
237
- data: finalRows,
238
- meta: {
239
- page: Number(page),
240
- pageSize: Number(pageSize),
241
- count: totalCount,
242
- },
243
- };
244
-
245
- await next();
246
- }
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { Context } from '@nocobase/actions';
4
+ import { NoPermissionError } from '@nocobase/acl';
5
+
6
+ interface JoinConfig {
7
+ dataSource: string;
8
+ collection: string;
9
+ joinType: 'left' | 'inner';
10
+ leftField: string;
11
+ rightField: string;
12
+ }
13
+
14
+ interface ColumnConfig {
15
+ source: number; // 0 = primary, 1 = join[0], ...
16
+ field: string;
17
+ alias?: string;
18
+ jsonExpand?: string[];
19
+ }
20
+
21
+ interface CrossJoinConfig {
22
+ primarySource: {
23
+ dataSource: string;
24
+ collection: string;
25
+ filter?: Record<string, unknown>;
26
+ };
27
+ joins: JoinConfig[];
28
+ columns: ColumnConfig[];
29
+ defaultSort?: string[];
30
+ }
31
+
32
+ function toPlainObject(row: Record<string, unknown>): Record<string, unknown> {
33
+ if (row && typeof row.toJSON === 'function') {
34
+ return row.toJSON();
35
+ }
36
+ return row;
37
+ }
38
+
39
+ function buildJoinMap(rows: Record<string, unknown>[], keyField: string): Map<string, Record<string, unknown>[]> {
40
+ const map = new Map<string, Record<string, unknown>[]>();
41
+ for (const row of rows) {
42
+ const key = String(row[keyField] ?? '');
43
+ const matches = map.get(key) || [];
44
+ matches.push(row);
45
+ map.set(key, matches);
46
+ }
47
+ return map;
48
+ }
49
+
50
+ function prefixRow(row: Record<string, unknown>, prefix: string): Record<string, unknown> {
51
+ const result: Record<string, unknown> = {};
52
+ for (const [k, v] of Object.entries(row)) {
53
+ result[`${prefix}.${k}`] = v;
54
+ }
55
+ return result;
56
+ }
57
+
58
+ function applyJoin(
59
+ leftRows: Record<string, unknown>[],
60
+ rightRows: Record<string, unknown>[],
61
+ joinConfig: JoinConfig,
62
+ joinIndex: number,
63
+ ): Record<string, unknown>[] {
64
+ const rightMap = buildJoinMap(rightRows, joinConfig.rightField);
65
+ const rightPrefix = `join${joinIndex}`;
66
+ const result: Record<string, unknown>[] = [];
67
+
68
+ for (const leftRow of leftRows) {
69
+ const key = String(leftRow[`primary.${joinConfig.leftField}`] ?? leftRow[joinConfig.leftField] ?? '');
70
+ const matches = rightMap.get(key);
71
+
72
+ if (matches && matches.length > 0) {
73
+ for (const match of matches) {
74
+ result.push({ ...leftRow, ...prefixRow(match, rightPrefix) });
75
+ }
76
+ } else if (joinConfig.joinType === 'left') {
77
+ result.push({ ...leftRow });
78
+ }
79
+ // inner join: skip rows with no match
80
+ }
81
+
82
+ return result;
83
+ }
84
+
85
+ function applyColumnMapping(rows: Record<string, unknown>[], columns: ColumnConfig[]): Record<string, unknown>[] {
86
+ return rows.map((row) => {
87
+ const mapped: Record<string, unknown> = {};
88
+
89
+ for (const col of columns) {
90
+ const prefix = col.source === 0 ? 'primary' : `join${col.source - 1}`;
91
+ const fullKey = `${prefix}.${col.field}`;
92
+ const value = row[fullKey];
93
+
94
+ // JSON expansion
95
+ if (col.jsonExpand?.length && value != null) {
96
+ try {
97
+ const parsed = typeof value === 'string' ? JSON.parse(value) : value;
98
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
99
+ for (const jsonKey of col.jsonExpand) {
100
+ const alias = col.alias ? `${col.alias}.${jsonKey}` : `${col.field}.${jsonKey}`;
101
+ mapped[alias] = parsed[jsonKey] ?? null;
102
+ }
103
+ continue;
104
+ }
105
+ } catch {
106
+ // not valid JSON, fall through to display raw value
107
+ }
108
+ }
109
+
110
+ const outputKey = col.alias || col.field;
111
+ mapped[outputKey] = value ?? null;
112
+ }
113
+
114
+ return mapped;
115
+ });
116
+ }
117
+
118
+ export async function crossJoinQuery(ctx: Context, next: () => Promise<void>) {
119
+ const { config, page = 1, pageSize = 20, sort } = ctx.action.params.values || ctx.action.params;
120
+
121
+ if (!config?.primarySource) {
122
+ ctx.throw(400, 'Missing primarySource in config');
123
+ }
124
+
125
+ const dsManager = ctx.app.dataSourceManager;
126
+ const { primarySource, joins = [], columns = [] } = config as CrossJoinConfig;
127
+
128
+ // 1. Get primary datasource and repository
129
+ const primaryDS = dsManager.get(primarySource.dataSource);
130
+ if (!primaryDS) {
131
+ ctx.throw(400, `Datasource "${primarySource.dataSource}" not found`);
132
+ }
133
+
134
+ const primaryRepo = primaryDS.collectionManager.getRepository(primarySource.collection);
135
+ if (!primaryRepo) {
136
+ ctx.throw(400, `Collection "${primarySource.collection}" not found in datasource "${primarySource.dataSource}"`);
137
+ }
138
+
139
+ // Resolve every source before querying, including joins whose input might be empty.
140
+ const sources = [primarySource, ...joins];
141
+ const permissions = await Promise.all(
142
+ sources.map(async (source, index) => {
143
+ const dataSource = dsManager.get(source.dataSource);
144
+ if (!dataSource?.acl) ctx.throw(403);
145
+ const permissionContext = Object.create(ctx);
146
+ Object.defineProperties(permissionContext, {
147
+ dataSource: { value: dataSource },
148
+ database: { value: dataSource.collectionManager.db },
149
+ });
150
+ const resolved = await dataSource.acl
151
+ .resolveActionParams(permissionContext, {
152
+ resourceName: source.collection,
153
+ actionName: 'list',
154
+ params: index === 0 ? { filter: primarySource.filter || {}, sort: sort || config.defaultSort } : {},
155
+ })
156
+ .catch((error: unknown) => {
157
+ if (error instanceof NoPermissionError) ctx.throw(403);
158
+ throw error;
159
+ });
160
+ const fields: string[] | undefined = resolved.parsedParams?.fields;
161
+ const except: string[] = resolved.parsedParams?.except || [];
162
+ const assertField = (field: string) => {
163
+ const name = field.replace(/^[+-]/, '').split('.')[0];
164
+ if ((fields && !fields.includes(name)) || except.includes(name)) ctx.throw(403);
165
+ };
166
+ columns.filter((column) => column.source === index).forEach((column) => assertField(column.field));
167
+ if (index === 0) {
168
+ joins.forEach((join) => assertField(join.leftField));
169
+ const requestedSort = sort || config.defaultSort || [];
170
+ (Array.isArray(requestedSort) ? requestedSort : [requestedSort]).forEach(assertField);
171
+ const checkFilter = (filter: unknown) => {
172
+ if (!filter || typeof filter !== 'object') return;
173
+ for (const [key, value] of Object.entries(filter)) {
174
+ if (key.startsWith('$') || Array.isArray(filter)) checkFilter(value);
175
+ else assertField(key);
176
+ }
177
+ };
178
+ checkFilter(primarySource.filter);
179
+ } else {
180
+ assertField(joins[index - 1].rightField);
181
+ }
182
+ return resolved.mergedParams;
183
+ }),
184
+ );
185
+
186
+ // 2. Determine if we need full-fetch (INNER join) or can paginate primary
187
+ const hasInnerJoin = joins.some((j) => j.joinType === 'inner');
188
+
189
+ let primaryRows: Record<string, unknown>[];
190
+ let totalPrimaryCount: number;
191
+
192
+ if (hasInnerJoin) {
193
+ // Full fetch with cap for INNER joins
194
+ const MAX_ROWS = 10000;
195
+ const rawRows = await primaryRepo.find({
196
+ ...permissions[0],
197
+ context: ctx,
198
+ limit: MAX_ROWS,
199
+ });
200
+ primaryRows = rawRows.map(toPlainObject);
201
+ totalPrimaryCount = primaryRows.length;
202
+ } else {
203
+ // Paginate at primary level for LEFT-only joins
204
+ const [rawRows, count] = await Promise.all([
205
+ primaryRepo.find({
206
+ ...permissions[0],
207
+ context: ctx,
208
+ limit: Number(pageSize),
209
+ offset: (Number(page) - 1) * Number(pageSize),
210
+ }),
211
+ primaryRepo.count({
212
+ filter: permissions[0].filter,
213
+ context: ctx,
214
+ }),
215
+ ]);
216
+ primaryRows = rawRows.map(toPlainObject);
217
+ totalPrimaryCount = Number(count);
218
+ }
219
+
220
+ // 3. Prefix primary rows
221
+ let joinedRows: Record<string, unknown>[] = primaryRows.map((row) => prefixRow(row, 'primary'));
222
+
223
+ // 4. Process each join
224
+ for (let i = 0; i < joins.length; i++) {
225
+ const joinDef = joins[i];
226
+
227
+ const joinDS = dsManager.get(joinDef.dataSource);
228
+ if (!joinDS) {
229
+ ctx.throw(400, `Datasource "${joinDef.dataSource}" not found`);
230
+ }
231
+
232
+ const joinRepo = joinDS.collectionManager.getRepository(joinDef.collection);
233
+ if (!joinRepo) {
234
+ ctx.throw(400, `Collection "${joinDef.collection}" not found in datasource "${joinDef.dataSource}"`);
235
+ }
236
+
237
+ // Collect distinct join keys from current result
238
+ // leftField always refers to the primary source column (prefixed with "primary.")
239
+ const leftKeyPath = `primary.${joinDef.leftField}`;
240
+ const distinctKeys = [...new Set(joinedRows.map((r) => r[leftKeyPath]).filter((v) => v != null))];
241
+
242
+ if (distinctKeys.length === 0) {
243
+ // No keys to join on
244
+ joinedRows = joinDef.joinType === 'left' ? joinedRows : [];
245
+ continue;
246
+ }
247
+
248
+ // Batch fetch from join table
249
+ const joinRawRows = await joinRepo.find({
250
+ ...permissions[i + 1],
251
+ context: ctx,
252
+ filter: {
253
+ $and: [permissions[i + 1].filter || {}, { [joinDef.rightField]: { $in: distinctKeys.map(String) } }],
254
+ },
255
+ limit: 10000,
256
+ });
257
+ const joinRows = joinRawRows.map(toPlainObject);
258
+
259
+ // Apply join
260
+ joinedRows = applyJoin(joinedRows, joinRows, joinDef, i);
261
+ }
262
+
263
+ // 5. Paginate if we did full-fetch (INNER join case)
264
+ let totalCount: number;
265
+ let paginatedRows: Record<string, unknown>[];
266
+
267
+ if (hasInnerJoin) {
268
+ totalCount = joinedRows.length;
269
+ const start = (Number(page) - 1) * Number(pageSize);
270
+ paginatedRows = joinedRows.slice(start, start + Number(pageSize));
271
+ } else {
272
+ totalCount = totalPrimaryCount;
273
+ paginatedRows = joinedRows;
274
+ }
275
+
276
+ // 6. Apply column mapping
277
+ const finalRows = columns.length > 0 ? applyColumnMapping(paginatedRows, columns) : paginatedRows;
278
+
279
+ ctx.body = {
280
+ rows: finalRows,
281
+ page: Number(page),
282
+ pageSize: Number(pageSize),
283
+ count: totalCount,
284
+ };
285
+
286
+ await next();
287
+ }
@@ -1,10 +1,3 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- export { default } from './plugin';
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ export { default } from './plugin';
@@ -1,36 +1,44 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { Plugin } from '@nocobase/server';
11
- import { crossJoinQuery } from './actions/cross-join-query';
12
-
13
- import path from 'path';
14
-
15
- export class PluginBlockCrossJoinServer extends Plugin {
16
- async beforeLoad() {
17
- await this.db.import({ directory: path.resolve(__dirname, 'collections') });
18
- }
19
-
20
- async load() {
21
- this.app.resourcer.define({
22
- name: 'crossJoin',
23
- actions: {
24
- query: crossJoinQuery,
25
- },
26
- });
27
-
28
- this.app.acl.allow('crossJoin', 'query', 'loggedIn');
29
- this.app.acl.registerSnippet({
30
- name: 'ui.crossJoin',
31
- actions: ['crossJoin:*'],
32
- });
33
- }
34
- }
35
-
36
- export default PluginBlockCrossJoinServer;
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { Plugin } from '@nocobase/server';
4
+ import { crossJoinQuery } from './actions/cross-join-query';
5
+
6
+ import path from 'path';
7
+
8
+ export class PluginBlockCrossJoinServer extends Plugin {
9
+ readonly hotReloadMeta = {
10
+ supported: true as const,
11
+ };
12
+
13
+ async beforeLoad() {
14
+ if (!this.options?.hotReloading) {
15
+ await this.db.import({ directory: path.resolve(__dirname, 'collections') });
16
+ }
17
+ }
18
+
19
+ async load() {
20
+ this.app.resourcer.define({
21
+ name: 'crossJoin',
22
+ actions: {
23
+ query: crossJoinQuery,
24
+ },
25
+ });
26
+
27
+ this.app.acl.allow('crossJoin', 'query', 'loggedIn');
28
+ // This action accepts join configuration, not the SQL query schema used by the generic query guard.
29
+ // crossJoinQuery resolves collection, row and field permissions for every source itself.
30
+ if (!this.options?.hotReloading) {
31
+ this.app.resourcer.registerPreActionHandler('crossJoin:query', async (_ctx, next) => {
32
+ await next();
33
+ });
34
+ }
35
+ this.app.acl.registerSnippet({
36
+ name: 'ui.crossJoin',
37
+ actions: ['crossJoin:*'],
38
+ });
39
+ }
40
+
41
+ async beforeHotReload() {}
42
+ }
43
+
44
+ export default PluginBlockCrossJoinServer;