plugin-data-source-postgres 0.0.0-stage → 2.0.1
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 +9 -3
- package/client-v2.js +1 -0
- package/client.js +1 -0
- package/dist/client/index.js +10 -0
- package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/constants.js +45 -0
- package/dist/externalVersion.js +29 -0
- package/dist/locale/en-US.json +141 -0
- package/dist/locale/zh-CN.json +141 -0
- package/dist/server/collections/adjacency-list-repository.js +340 -0
- package/dist/server/collections/index.js +45 -0
- package/dist/server/collections/sql-collection.js +84 -0
- package/dist/server/collections/sql-model.js +149 -0
- package/dist/server/collections/tree-collection.js +118 -0
- package/dist/server/hooks/field-hooks.js +412 -0
- package/dist/server/index.js +38 -0
- package/dist/server/plugin.js +1273 -0
- package/dist/server/postgres-collection-manager.js +868 -0
- package/dist/server/postgres-datasource.js +361 -0
- package/dist/server/utils/sql-validator.js +253 -0
- package/dist/server/utils/validation-error.js +59 -0
- package/package.json +51 -4
- package/server.js +1 -0
- package/src/client/AddCollectionAction.tsx +307 -0
- package/src/client/ConfigurationForm.tsx +203 -0
- package/src/client/PostgresCollectionTemplate.tsx +109 -0
- package/src/client/__tests__/client-v1.test.tsx +265 -0
- package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
- package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
- package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
- package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
- package/src/client/collection-templates/base-template-helper.ts +62 -0
- package/src/client/collection-templates/field-interfaces-config.ts +73 -0
- package/src/client/collection-templates/index.ts +19 -0
- package/src/client/index.tsx +69 -0
- package/src/client-v2/PostgresAddCollection.tsx +422 -0
- package/src/client-v2/PostgresConfigForm.tsx +178 -0
- package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
- package/src/client-v2/__tests__/plugin.test.tsx +372 -0
- package/src/client-v2/collection-options.ts +22 -0
- package/src/client-v2/index.tsx +10 -0
- package/src/client-v2/plugin.tsx +71 -0
- package/src/constants.ts +20 -0
- package/src/locale/en-US.json +141 -0
- package/src/locale/zh-CN.json +141 -0
- package/src/server/__tests__/field-hooks.test.ts +357 -0
- package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
- package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
- package/src/server/__tests__/sql-model.test.ts +159 -0
- package/src/server/__tests__/sql-validator.test.ts +126 -0
- package/src/server/collections/adjacency-list-repository.ts +378 -0
- package/src/server/collections/index.ts +19 -0
- package/src/server/collections/sql-collection.ts +66 -0
- package/src/server/collections/sql-model.ts +158 -0
- package/src/server/collections/tree-collection.ts +102 -0
- package/src/server/hooks/field-hooks.ts +548 -0
- package/src/server/index.ts +13 -0
- package/src/server/plugin.ts +1499 -0
- package/src/server/postgres-collection-manager.ts +1027 -0
- package/src/server/postgres-datasource.ts +410 -0
- package/src/server/utils/sql-validator.ts +258 -0
- package/src/server/utils/validation-error.ts +38 -0
|
@@ -0,0 +1,159 @@
|
|
|
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 { Database } from '@nocobase/database';
|
|
11
|
+
import { afterAll, describe, expect, it } from 'vitest';
|
|
12
|
+
import { PostgresSQLCollection } from '../collections/sql-collection';
|
|
13
|
+
import { SQLModel } from '../collections/sql-model';
|
|
14
|
+
|
|
15
|
+
type SqlGeneratorStub = {
|
|
16
|
+
selectQuery: (tableName: string, options: Record<string, unknown>, model: typeof SQLModel) => string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
describe('SQLModel selectQuery', () => {
|
|
20
|
+
const db = new Database({
|
|
21
|
+
dialect: 'postgres',
|
|
22
|
+
host: '127.0.0.1',
|
|
23
|
+
port: 5432,
|
|
24
|
+
database: 'unused',
|
|
25
|
+
username: 'unused',
|
|
26
|
+
logging: false,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
afterAll(async () => {
|
|
30
|
+
await db.close();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
db.collectionFactory.registerCollectionType(PostgresSQLCollection, {
|
|
34
|
+
condition: (options) => Boolean(options.sql),
|
|
35
|
+
async onSync() {},
|
|
36
|
+
async onDump() {},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const collection = db.collection({
|
|
40
|
+
name: 'order_summary',
|
|
41
|
+
sql: 'SELECT id, name FROM orders;',
|
|
42
|
+
fields: [
|
|
43
|
+
{ name: 'id', type: 'integer' },
|
|
44
|
+
{ name: 'name', type: 'string' },
|
|
45
|
+
],
|
|
46
|
+
}) as PostgresSQLCollection;
|
|
47
|
+
|
|
48
|
+
const model = collection.model as unknown as typeof SQLModel;
|
|
49
|
+
const queryInterface = model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub };
|
|
50
|
+
|
|
51
|
+
it('selects matching attributes with where, order, limit, and offset', () => {
|
|
52
|
+
const sql = queryInterface.queryGenerator.selectQuery(
|
|
53
|
+
'order_summary',
|
|
54
|
+
{
|
|
55
|
+
attributes: ['id', 'unknown_col'],
|
|
56
|
+
where: { id: 10 },
|
|
57
|
+
order: [['id', 'DESC']],
|
|
58
|
+
limit: 5,
|
|
59
|
+
offset: 10,
|
|
60
|
+
},
|
|
61
|
+
model,
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
expect(sql).toContain('SELECT "id" FROM (SELECT id, name FROM orders\n)');
|
|
65
|
+
expect(sql).toContain('WHERE "order_summary"."id" = 10');
|
|
66
|
+
expect(sql).toContain('ORDER BY "order_summary"."id" DESC');
|
|
67
|
+
expect(sql).toContain('LIMIT 5 OFFSET 10');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('falls back to * when filtered attributes are empty so SELECT FROM syntax stays valid', () => {
|
|
71
|
+
const sql = queryInterface.queryGenerator.selectQuery(
|
|
72
|
+
'order_summary',
|
|
73
|
+
{
|
|
74
|
+
attributes: ['nonexistent_column'],
|
|
75
|
+
where: { id: 1 },
|
|
76
|
+
},
|
|
77
|
+
model,
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
expect(sql).toContain('SELECT * FROM (SELECT id, name FROM orders\n)');
|
|
81
|
+
expect(sql).not.toMatch(/SELECT\s+FROM/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('updates model SQL in place on updateOptions without losing field attributes or filterTargetKey', () => {
|
|
85
|
+
const updatable = db.collection({
|
|
86
|
+
name: 'updatable_summary',
|
|
87
|
+
sql: 'SELECT id, name FROM orders;',
|
|
88
|
+
fields: [
|
|
89
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
90
|
+
{ name: 'name', type: 'string' },
|
|
91
|
+
],
|
|
92
|
+
}) as PostgresSQLCollection;
|
|
93
|
+
|
|
94
|
+
updatable.updateOptions({
|
|
95
|
+
name: 'updatable_summary',
|
|
96
|
+
sql: 'SELECT id, name FROM updated_orders;',
|
|
97
|
+
fields: [
|
|
98
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
99
|
+
{ name: 'name', type: 'string' },
|
|
100
|
+
],
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
expect(updatable.model.getAttributes().id).toBeDefined();
|
|
104
|
+
expect(updatable.filterTargetKey).toBe('id');
|
|
105
|
+
const updatedQuery = (
|
|
106
|
+
updatable.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
|
|
107
|
+
).queryGenerator.selectQuery(
|
|
108
|
+
'updatable_summary',
|
|
109
|
+
{ attributes: ['id'], where: { id: 42 } },
|
|
110
|
+
updatable.model as unknown as typeof SQLModel,
|
|
111
|
+
);
|
|
112
|
+
expect(updatedQuery).toContain('SELECT "id" FROM (SELECT id, name FROM updated_orders\n)');
|
|
113
|
+
expect(updatedQuery).toContain('WHERE "updatable_summary"."id" = 42');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('normalizes trailing semicolons before comments and isolates trailing line comments from closing parenthesis', () => {
|
|
117
|
+
const withBlockComment = db.collection({
|
|
118
|
+
name: 'commented_block_summary',
|
|
119
|
+
sql: 'SELECT id FROM orders; /* trailing note */',
|
|
120
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
121
|
+
}) as PostgresSQLCollection;
|
|
122
|
+
|
|
123
|
+
const withLineComment = db.collection({
|
|
124
|
+
name: 'commented_line_summary',
|
|
125
|
+
sql: "SELECT id, ';' AS sep FROM orders; -- trailing line comment",
|
|
126
|
+
fields: [
|
|
127
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
128
|
+
{ name: 'sep', type: 'string' },
|
|
129
|
+
],
|
|
130
|
+
}) as PostgresSQLCollection;
|
|
131
|
+
|
|
132
|
+
const blockSql = (
|
|
133
|
+
withBlockComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
|
|
134
|
+
).queryGenerator.selectQuery(
|
|
135
|
+
'commented_block_summary',
|
|
136
|
+
{ attributes: ['id'], where: { id: 1 }, limit: 10, offset: 0 },
|
|
137
|
+
withBlockComment.model as unknown as typeof SQLModel,
|
|
138
|
+
);
|
|
139
|
+
expect(blockSql).toBe(
|
|
140
|
+
'SELECT "id" FROM (SELECT id FROM orders /* trailing note */\n) AS "commented_block_summary" WHERE "commented_block_summary"."id" = 1 LIMIT 10 OFFSET 0;',
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
const lineSql = (
|
|
144
|
+
withLineComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
|
|
145
|
+
).queryGenerator.selectQuery(
|
|
146
|
+
'commented_line_summary',
|
|
147
|
+
{ attributes: ['id', 'sep'], where: { id: 1 }, limit: 5 },
|
|
148
|
+
withLineComment.model as unknown as typeof SQLModel,
|
|
149
|
+
);
|
|
150
|
+
expect(lineSql).toBe(
|
|
151
|
+
`SELECT "id", "sep" FROM (SELECT id, ';' AS sep FROM orders -- trailing line comment\n) AS "commented_line_summary" WHERE "commented_line_summary"."id" = 1 LIMIT 5;`,
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
const emptyOptsSql = (
|
|
155
|
+
withLineComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
|
|
156
|
+
).queryGenerator.selectQuery('commented_line_summary', {}, withLineComment.model as unknown as typeof SQLModel);
|
|
157
|
+
expect(emptyOptsSql).toBe("SELECT id, ';' AS sep FROM orders -- trailing line comment\n;");
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -0,0 +1,126 @@
|
|
|
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 { describe, expect, it } from 'vitest';
|
|
11
|
+
import { checkSQL, normalizeSqlCollectionQuery } from '../utils/sql-validator';
|
|
12
|
+
import { PostgresValidationError } from '../utils/validation-error';
|
|
13
|
+
|
|
14
|
+
function expectValidationError(fn: () => void, message?: string) {
|
|
15
|
+
try {
|
|
16
|
+
fn();
|
|
17
|
+
expect.fail('Expected checkSQL to throw PostgresValidationError');
|
|
18
|
+
} catch (error) {
|
|
19
|
+
expect(error).toBeInstanceOf(PostgresValidationError);
|
|
20
|
+
expect((error as PostgresValidationError).status).toBe(400);
|
|
21
|
+
if (message) expect((error as Error).message).toContain(message);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('checkSQL', () => {
|
|
26
|
+
it('allows valid SELECT and WITH ... SELECT statements', () => {
|
|
27
|
+
expect(() => checkSQL('SELECT id, name FROM orders WHERE active = true;')).not.toThrow();
|
|
28
|
+
expect(() =>
|
|
29
|
+
checkSQL(`
|
|
30
|
+
WITH recent_orders AS (
|
|
31
|
+
SELECT id, total FROM orders
|
|
32
|
+
)
|
|
33
|
+
SELECT id, total FROM recent_orders
|
|
34
|
+
`),
|
|
35
|
+
).not.toThrow();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('allows column or table identifiers containing copy', () => {
|
|
39
|
+
expect(() => checkSQL('SELECT copyright, copy_count FROM articles')).not.toThrow();
|
|
40
|
+
expect(() => checkSQL('WITH cte AS (SELECT copyright FROM books) SELECT * FROM cte')).not.toThrow();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('ignores comments, string literals, dollar-quoted strings, and benign quoted aliases', () => {
|
|
44
|
+
expect(() =>
|
|
45
|
+
checkSQL(`
|
|
46
|
+
-- pg_read_file comment; DROP TABLE orders
|
|
47
|
+
/* nested /* pg_sleep(10) */ comment */
|
|
48
|
+
SELECT 'pg_read_file; DROP TABLE orders' AS note,
|
|
49
|
+
E'escaped\\'pg_sleep' AS esc,
|
|
50
|
+
$$hello;world$$ AS msg,
|
|
51
|
+
$tag$it's fine$tag$ AS quoted_tag,
|
|
52
|
+
1 AS "a;b"
|
|
53
|
+
FROM items
|
|
54
|
+
`),
|
|
55
|
+
).not.toThrow();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('rejects empty, comment-only, and non-SELECT statements with HTTP 400 status', () => {
|
|
59
|
+
expectValidationError(() => checkSQL(''), 'SQL query is required');
|
|
60
|
+
expectValidationError(() => checkSQL(' -- only comment\n/* block */ '), 'SQL query cannot be empty');
|
|
61
|
+
expectValidationError(() => checkSQL('DELETE FROM orders'), 'Only SELECT statements or WITH clauses are supported');
|
|
62
|
+
expectValidationError(
|
|
63
|
+
() => checkSQL('UPDATE orders SET name = 1'),
|
|
64
|
+
'Only SELECT statements or WITH clauses are supported',
|
|
65
|
+
);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('rejects multiple statements separated by semicolons', () => {
|
|
69
|
+
expectValidationError(() => checkSQL('SELECT 1; DROP TABLE orders'), 'Multiple SQL statements are not allowed');
|
|
70
|
+
expectValidationError(() => checkSQL('SELECT 1;;'), 'Multiple SQL statements are not allowed');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('rejects dollar-quote, double-quote, identifier-tag, Unicode-escape, and unclosed token bypasses', () => {
|
|
74
|
+
for (const sql of [
|
|
75
|
+
'SELECT $$\'$$ ) AS "t"; COMMIT; DROP TABLE orders; BEGIN; SELECT * FROM (SELECT $$\'$$',
|
|
76
|
+
"SELECT $$'$$, pg_read_file($$/etc/passwd$$), $$'$$",
|
|
77
|
+
'SELECT 1 AS "\'" ) AS "t"; COMMIT; DROP TABLE orders; BEGIN; SELECT * FROM (SELECT 1 AS "\'"',
|
|
78
|
+
'SELECT "pg_read_file"(\'/etc/passwd\')',
|
|
79
|
+
'SELECT * FROM "information_schema"."tables"',
|
|
80
|
+
'SELECT a$tag$; COMMIT; DROP TABLE orders; --$tag$',
|
|
81
|
+
'SELECT U&"pg\\005fread_file"(\'/etc/passwd\')',
|
|
82
|
+
"SELECT u&'test; DROP TABLE orders'",
|
|
83
|
+
'SELECT /* unclosed comment 1',
|
|
84
|
+
"SELECT 'unclosed string",
|
|
85
|
+
'SELECT "unclosed identifier',
|
|
86
|
+
'SELECT $tag$unclosed dollar quote',
|
|
87
|
+
]) {
|
|
88
|
+
expectValidationError(() => checkSQL(sql));
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('rejects data-modifying CTEs', () => {
|
|
93
|
+
expectValidationError(
|
|
94
|
+
() => checkSQL('WITH deleted AS (DELETE FROM orders RETURNING *) SELECT * FROM deleted'),
|
|
95
|
+
'SQL statement contains dangerous keyword: delete',
|
|
96
|
+
);
|
|
97
|
+
expectValidationError(
|
|
98
|
+
() => checkSQL('WITH ins AS (INSERT INTO audit VALUES (1) RETURNING id) SELECT * FROM ins'),
|
|
99
|
+
'SQL statement contains dangerous keyword: insert',
|
|
100
|
+
);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('rejects pg_ catalogs/functions, information_schema, dblink, and COPY', () => {
|
|
104
|
+
for (const sql of [
|
|
105
|
+
'SELECT * FROM pg_settings',
|
|
106
|
+
'SELECT * FROM pg_stat_activity',
|
|
107
|
+
'SELECT * FROM pg_roles',
|
|
108
|
+
"SELECT pg_read_file('/etc/passwd')",
|
|
109
|
+
'SELECT pg_sleep(10)',
|
|
110
|
+
'SELECT * FROM information_schema.tables',
|
|
111
|
+
"SELECT * FROM dblink('conn', 'SELECT 1') AS t(a int)",
|
|
112
|
+
"WITH c AS (COPY orders TO PROGRAM 'id') SELECT 1",
|
|
113
|
+
"SELECT current_setting('data_directory')",
|
|
114
|
+
"SELECT lo_import('/etc/passwd')",
|
|
115
|
+
]) {
|
|
116
|
+
expectValidationError(() => checkSQL(sql), 'SQL statement contains dangerous keyword');
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('normalizes trailing semicolons across comments without altering semicolons inside literals', () => {
|
|
121
|
+
expect(normalizeSqlCollectionQuery('SELECT 1; /* note */')).toBe('SELECT 1 /* note */');
|
|
122
|
+
expect(normalizeSqlCollectionQuery('SELECT 1; -- note\n')).toBe('SELECT 1 -- note');
|
|
123
|
+
expect(normalizeSqlCollectionQuery("SELECT ';' AS sep; /* note */")).toBe("SELECT ';' AS sep /* note */");
|
|
124
|
+
expect(normalizeSqlCollectionQuery('SELECT $$a;b$$;')).toBe('SELECT $$a;b$$');
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,378 @@
|
|
|
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 { CountOptions, FindAndCountOptions, FindOptions, Model, Repository } from '@nocobase/database';
|
|
11
|
+
import { QueryTypes, Transaction } from 'sequelize';
|
|
12
|
+
import { PostgresTreeCollection } from './tree-collection';
|
|
13
|
+
import { PostgresValidationError } from '../utils/validation-error';
|
|
14
|
+
|
|
15
|
+
type TreeOptions = FindOptions & { tree?: boolean; addIndex?: boolean };
|
|
16
|
+
type TreeNode = Model & { _options?: { includeNames?: string[] } };
|
|
17
|
+
type NodeLinkRow = { id: unknown; parentId: unknown; hasCycle: boolean };
|
|
18
|
+
|
|
19
|
+
function quoteIdentifier(value: string): string {
|
|
20
|
+
return `"${value.replace(/"/g, '""')}"`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function hasValidFilter(condition: unknown): boolean {
|
|
24
|
+
if (!condition || typeof condition !== 'object' || Array.isArray(condition)) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
const record = condition as Record<string, unknown>;
|
|
28
|
+
if (Object.keys(record).some((key) => key !== '$and' && key !== '$or' && record[key] !== undefined)) {
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
const groups = [record.$and, record.$or].filter(Boolean);
|
|
32
|
+
if (!groups.length) return false;
|
|
33
|
+
return groups.some((group) =>
|
|
34
|
+
Array.isArray(group) ? group.some((item) => hasValidFilter(item)) : hasValidFilter(group),
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class PostgresAdjacencyListRepository extends Repository {
|
|
39
|
+
declare collection: PostgresTreeCollection;
|
|
40
|
+
|
|
41
|
+
private getTreeMeta() {
|
|
42
|
+
const primaryKeys = this.collection.model.primaryKeyAttributes;
|
|
43
|
+
if (primaryKeys.length !== 1) throw new PostgresValidationError('A tree collection requires one primary key');
|
|
44
|
+
const primaryKey = primaryKeys[0];
|
|
45
|
+
const foreignKey = this.collection.treeForeignKey;
|
|
46
|
+
const pkCol = this.collection.getField(primaryKey)?.columnName() || primaryKey;
|
|
47
|
+
const fkCol = this.collection.getField(foreignKey)?.columnName() || foreignKey;
|
|
48
|
+
const modelTable = this.collection.model.getTableName();
|
|
49
|
+
const schema =
|
|
50
|
+
typeof modelTable === 'object' && modelTable
|
|
51
|
+
? modelTable.schema || this.collection.db.options.schema || 'public'
|
|
52
|
+
: this.collection.db.options.schema || 'public';
|
|
53
|
+
const tableName =
|
|
54
|
+
typeof modelTable === 'object' && modelTable ? modelTable.tableName : String(modelTable || this.collection.name);
|
|
55
|
+
const tableSql = `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}`;
|
|
56
|
+
return { primaryKey, foreignKey, pkCol, fkCol, tableSql };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private withRequiredTreeFields(options: TreeOptions, primaryKey: string, foreignKey: string): Partial<TreeOptions> {
|
|
60
|
+
const result: Partial<TreeOptions> = {};
|
|
61
|
+
if (Array.isArray(options.fields)) {
|
|
62
|
+
result.fields = [...new Set([...options.fields, primaryKey, foreignKey])];
|
|
63
|
+
}
|
|
64
|
+
if (Array.isArray(options.except)) {
|
|
65
|
+
result.except = options.except.filter((field) => field !== primaryKey && field !== foreignKey);
|
|
66
|
+
}
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private buildRootOrderSql(sort: unknown, pkCol: string): string {
|
|
71
|
+
const items = Array.isArray(sort) ? sort : typeof sort === 'string' ? [sort] : [];
|
|
72
|
+
const clauses: string[] = [];
|
|
73
|
+
for (const item of items) {
|
|
74
|
+
if (typeof item !== 'string' || !item.trim()) continue;
|
|
75
|
+
const desc = item.startsWith('-');
|
|
76
|
+
const fieldName = desc ? item.slice(1) : item;
|
|
77
|
+
const field = this.collection.getField(fieldName);
|
|
78
|
+
if (field && !field.isRelationField() && field.dataType) {
|
|
79
|
+
clauses.push(`t.${quoteIdentifier(field.columnName())} ${desc ? 'DESC' : 'ASC'}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const pkOrder = `t.${quoteIdentifier(pkCol)} ASC`;
|
|
83
|
+
if (!clauses.some((clause) => clause.startsWith(`t.${quoteIdentifier(pkCol)} `))) {
|
|
84
|
+
clauses.push(pkOrder);
|
|
85
|
+
}
|
|
86
|
+
return clauses.join(', ');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private async fetchDownwardSubtree(
|
|
90
|
+
tableSql: string,
|
|
91
|
+
pkCol: string,
|
|
92
|
+
fkCol: string,
|
|
93
|
+
seedIds: unknown[],
|
|
94
|
+
transaction?: Transaction,
|
|
95
|
+
): Promise<NodeLinkRow[]> {
|
|
96
|
+
if (!seedIds.length) return [];
|
|
97
|
+
const pk = quoteIdentifier(pkCol);
|
|
98
|
+
const fk = quoteIdentifier(fkCol);
|
|
99
|
+
const rows = await this.database.sequelize.query<NodeLinkRow>(
|
|
100
|
+
`WITH RECURSIVE tree AS (
|
|
101
|
+
SELECT t.${pk} AS id, t.${fk} AS "parentId", ARRAY[t.${pk}] AS path, FALSE AS is_cycle
|
|
102
|
+
FROM ${tableSql} t
|
|
103
|
+
WHERE t.${pk} IN (:seedIds)
|
|
104
|
+
UNION ALL
|
|
105
|
+
SELECT c.${pk} AS id, c.${fk} AS "parentId", tree.path || c.${pk}, c.${pk} = ANY(tree.path)
|
|
106
|
+
FROM ${tableSql} c
|
|
107
|
+
JOIN tree ON c.${fk} = tree.id
|
|
108
|
+
WHERE NOT tree.is_cycle
|
|
109
|
+
)
|
|
110
|
+
SELECT id, "parentId", BOOL_OR(is_cycle) AS "hasCycle"
|
|
111
|
+
FROM tree
|
|
112
|
+
GROUP BY id, "parentId"`,
|
|
113
|
+
{ replacements: { seedIds }, type: QueryTypes.SELECT, transaction },
|
|
114
|
+
);
|
|
115
|
+
if (rows.some((row) => row.hasCycle)) {
|
|
116
|
+
throw new PostgresValidationError('Cycle detected in tree collection {{name}}', { name: this.collection.name });
|
|
117
|
+
}
|
|
118
|
+
return rows;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private assembleTree(
|
|
122
|
+
nodes: TreeNode[],
|
|
123
|
+
rootOrder: string[],
|
|
124
|
+
primaryKey: string,
|
|
125
|
+
foreignKey: string,
|
|
126
|
+
addIndex: boolean,
|
|
127
|
+
): Model[] {
|
|
128
|
+
const nodesById = new Map(nodes.map((node) => [String(node.get(primaryKey)), node]));
|
|
129
|
+
const children = new Map<string, TreeNode[]>();
|
|
130
|
+
const rootsById = new Map<string, TreeNode>();
|
|
131
|
+
for (const node of nodes) {
|
|
132
|
+
const idKey = String(node.get(primaryKey));
|
|
133
|
+
const parent = node.get(foreignKey);
|
|
134
|
+
if (parent === null || parent === undefined || !nodesById.has(String(parent))) {
|
|
135
|
+
rootsById.set(idKey, node);
|
|
136
|
+
} else {
|
|
137
|
+
const parentKey = String(parent);
|
|
138
|
+
const siblings = children.get(parentKey) || [];
|
|
139
|
+
siblings.push(node);
|
|
140
|
+
children.set(parentKey, siblings);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const roots: TreeNode[] = [];
|
|
145
|
+
for (const idKey of rootOrder) {
|
|
146
|
+
const root = rootsById.get(idKey);
|
|
147
|
+
if (root) {
|
|
148
|
+
roots.push(root);
|
|
149
|
+
rootsById.delete(idKey);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const remaining of rootsById.values()) {
|
|
153
|
+
roots.push(remaining);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const childrenKey = this.collection.treeChildrenField?.name || 'children';
|
|
157
|
+
const visited = new Set<string>();
|
|
158
|
+
const attachChildren = (node: TreeNode, index: string) => {
|
|
159
|
+
const key = String(node.get(primaryKey));
|
|
160
|
+
if (visited.has(key)) {
|
|
161
|
+
throw new PostgresValidationError('Cycle detected in tree collection {{name}}', { name: this.collection.name });
|
|
162
|
+
}
|
|
163
|
+
visited.add(key);
|
|
164
|
+
const childNodes = children.get(key) || [];
|
|
165
|
+
if (addIndex) node.setDataValue('__index', index);
|
|
166
|
+
if (childNodes.length) {
|
|
167
|
+
node._options = node._options || {};
|
|
168
|
+
node._options.includeNames = node._options.includeNames || [];
|
|
169
|
+
if (!node._options.includeNames.includes(childrenKey)) node._options.includeNames.push(childrenKey);
|
|
170
|
+
node.setDataValue(childrenKey, childNodes);
|
|
171
|
+
childNodes.forEach((child, childIndex) => attachChildren(child, `${index}.${childrenKey}.${childIndex}`));
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
roots.forEach((node, index) => attachChildren(node, String(index)));
|
|
175
|
+
if (visited.size !== nodes.length) {
|
|
176
|
+
throw new PostgresValidationError('Cycle detected in tree collection {{name}}', { name: this.collection.name });
|
|
177
|
+
}
|
|
178
|
+
return roots;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private async countUnfilteredRoots(
|
|
182
|
+
tableSql: string,
|
|
183
|
+
pkCol: string,
|
|
184
|
+
fkCol: string,
|
|
185
|
+
transaction?: Transaction,
|
|
186
|
+
): Promise<number> {
|
|
187
|
+
const pk = quoteIdentifier(pkCol);
|
|
188
|
+
const fk = quoteIdentifier(fkCol);
|
|
189
|
+
const rows = await this.database.sequelize.query<{ count: number }>(
|
|
190
|
+
`SELECT COUNT(*)::int AS count
|
|
191
|
+
FROM ${tableSql} t
|
|
192
|
+
WHERE t.${fk} IS NULL OR NOT EXISTS (SELECT 1 FROM ${tableSql} p WHERE p.${pk} = t.${fk})`,
|
|
193
|
+
{ type: QueryTypes.SELECT, transaction },
|
|
194
|
+
);
|
|
195
|
+
return Number(rows[0]?.count || 0);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private async findUnfilteredPaged(options: TreeOptions): Promise<Model[]> {
|
|
199
|
+
const { primaryKey, foreignKey, pkCol, fkCol, tableSql } = this.getTreeMeta();
|
|
200
|
+
const limit = typeof options.limit === 'number' ? options.limit : undefined;
|
|
201
|
+
const offset = typeof options.offset === 'number' && options.offset > 0 ? options.offset : 0;
|
|
202
|
+
if (limit === 0) return [];
|
|
203
|
+
|
|
204
|
+
const pk = quoteIdentifier(pkCol);
|
|
205
|
+
const fk = quoteIdentifier(fkCol);
|
|
206
|
+
const orderBy = this.buildRootOrderSql(options.sort, pkCol);
|
|
207
|
+
const replacements: Record<string, unknown> = {};
|
|
208
|
+
let paginationSql = '';
|
|
209
|
+
if (limit !== undefined) {
|
|
210
|
+
paginationSql += ' LIMIT :limit';
|
|
211
|
+
replacements.limit = limit;
|
|
212
|
+
}
|
|
213
|
+
if (offset > 0) {
|
|
214
|
+
paginationSql += ' OFFSET :offset';
|
|
215
|
+
replacements.offset = offset;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const rootRows = await this.database.sequelize.query<{ id: unknown }>(
|
|
219
|
+
`SELECT t.${pk} AS id
|
|
220
|
+
FROM ${tableSql} t
|
|
221
|
+
WHERE t.${fk} IS NULL OR NOT EXISTS (SELECT 1 FROM ${tableSql} p WHERE p.${pk} = t.${fk})
|
|
222
|
+
ORDER BY ${orderBy}${paginationSql}`,
|
|
223
|
+
{ replacements, type: QueryTypes.SELECT, transaction: options.transaction },
|
|
224
|
+
);
|
|
225
|
+
const rootIds = rootRows.map((row) => row.id);
|
|
226
|
+
if (!rootIds.length) return [];
|
|
227
|
+
|
|
228
|
+
const subtreeRows = await this.fetchDownwardSubtree(tableSql, pkCol, fkCol, rootIds, options.transaction);
|
|
229
|
+
const collectedIds = subtreeRows.map((row) => row.id);
|
|
230
|
+
const nodes = (await super.find({
|
|
231
|
+
...options,
|
|
232
|
+
...this.withRequiredTreeFields(options, primaryKey, foreignKey),
|
|
233
|
+
tree: false,
|
|
234
|
+
filter: { [primaryKey]: collectedIds },
|
|
235
|
+
filterByTk: undefined,
|
|
236
|
+
limit: undefined,
|
|
237
|
+
offset: undefined,
|
|
238
|
+
})) as TreeNode[];
|
|
239
|
+
|
|
240
|
+
return this.assembleTree(nodes, rootIds.map(String), primaryKey, foreignKey, options.addIndex !== false);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private async resolveFilteredTree(options: TreeOptions): Promise<{
|
|
244
|
+
rootIds: unknown[];
|
|
245
|
+
subtreeRows: NodeLinkRow[];
|
|
246
|
+
primaryKey: string;
|
|
247
|
+
foreignKey: string;
|
|
248
|
+
}> {
|
|
249
|
+
const { primaryKey, foreignKey, pkCol, fkCol, tableSql } = this.getTreeMeta();
|
|
250
|
+
const matchedNodes = (await super.find({
|
|
251
|
+
...options,
|
|
252
|
+
fields: [primaryKey, foreignKey],
|
|
253
|
+
except: undefined,
|
|
254
|
+
appends: undefined,
|
|
255
|
+
tree: false,
|
|
256
|
+
limit: undefined,
|
|
257
|
+
offset: undefined,
|
|
258
|
+
})) as TreeNode[];
|
|
259
|
+
if (!matchedNodes.length) {
|
|
260
|
+
return { rootIds: [], subtreeRows: [], primaryKey, foreignKey };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const seedIds = matchedNodes.map((node) => node.get(primaryKey));
|
|
264
|
+
const subtreeRows = await this.fetchDownwardSubtree(tableSql, pkCol, fkCol, seedIds, options.transaction);
|
|
265
|
+
const visibleIds = new Set(subtreeRows.map((row) => String(row.id)));
|
|
266
|
+
const seenRoots = new Set<string>();
|
|
267
|
+
const rootIds: unknown[] = [];
|
|
268
|
+
|
|
269
|
+
for (const node of matchedNodes) {
|
|
270
|
+
const id = node.get(primaryKey);
|
|
271
|
+
const idKey = String(id);
|
|
272
|
+
if (seenRoots.has(idKey)) continue;
|
|
273
|
+
const parent = node.get(foreignKey);
|
|
274
|
+
if (parent === null || parent === undefined || !visibleIds.has(String(parent))) {
|
|
275
|
+
seenRoots.add(idKey);
|
|
276
|
+
rootIds.push(id);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return { rootIds, subtreeRows, primaryKey, foreignKey };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private async loadFilteredPage(
|
|
284
|
+
options: TreeOptions,
|
|
285
|
+
resolved: { rootIds: unknown[]; subtreeRows: NodeLinkRow[]; primaryKey: string; foreignKey: string },
|
|
286
|
+
): Promise<Model[]> {
|
|
287
|
+
const offset = typeof options.offset === 'number' && options.offset > 0 ? options.offset : 0;
|
|
288
|
+
const limit = typeof options.limit === 'number' ? options.limit : undefined;
|
|
289
|
+
const pagedRootIds = resolved.rootIds.slice(offset, limit === undefined ? undefined : offset + limit);
|
|
290
|
+
if (!pagedRootIds.length) return [];
|
|
291
|
+
|
|
292
|
+
const childrenByParent = new Map<string, unknown[]>();
|
|
293
|
+
for (const row of resolved.subtreeRows) {
|
|
294
|
+
if (row.parentId !== null && row.parentId !== undefined) {
|
|
295
|
+
const parentKey = String(row.parentId);
|
|
296
|
+
const list = childrenByParent.get(parentKey) || [];
|
|
297
|
+
list.push(row.id);
|
|
298
|
+
childrenByParent.set(parentKey, list);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const pageIds: unknown[] = [];
|
|
303
|
+
const queued = new Set<string>();
|
|
304
|
+
const queue = [...pagedRootIds];
|
|
305
|
+
while (queue.length) {
|
|
306
|
+
const current = queue.shift();
|
|
307
|
+
const key = String(current);
|
|
308
|
+
if (queued.has(key)) continue;
|
|
309
|
+
queued.add(key);
|
|
310
|
+
pageIds.push(current);
|
|
311
|
+
const kids = childrenByParent.get(key);
|
|
312
|
+
if (kids) queue.push(...kids);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const nodes = (await super.find({
|
|
316
|
+
...options,
|
|
317
|
+
...this.withRequiredTreeFields(options, resolved.primaryKey, resolved.foreignKey),
|
|
318
|
+
tree: false,
|
|
319
|
+
filter: { [resolved.primaryKey]: pageIds },
|
|
320
|
+
filterByTk: undefined,
|
|
321
|
+
limit: undefined,
|
|
322
|
+
offset: undefined,
|
|
323
|
+
})) as TreeNode[];
|
|
324
|
+
|
|
325
|
+
return this.assembleTree(
|
|
326
|
+
nodes,
|
|
327
|
+
pagedRootIds.map(String),
|
|
328
|
+
resolved.primaryKey,
|
|
329
|
+
resolved.foreignKey,
|
|
330
|
+
options.addIndex !== false,
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private hasWhereClause(where: unknown): boolean {
|
|
335
|
+
if (typeof where === 'string') return where.trim().length > 0;
|
|
336
|
+
if (!where || typeof where !== 'object') return false;
|
|
337
|
+
return Reflect.ownKeys(where).length > 0;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private isFiltered(options: { filter?: unknown; filterByTk?: unknown; where?: unknown }): boolean {
|
|
341
|
+
return options.filterByTk !== undefined || hasValidFilter(options.filter) || this.hasWhereClause(options.where);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async find(options: TreeOptions = {}): Promise<Model[]> {
|
|
345
|
+
if (!options.tree || options.raw) return super.find(options);
|
|
346
|
+
if (!this.isFiltered(options)) {
|
|
347
|
+
return this.findUnfilteredPaged(options);
|
|
348
|
+
}
|
|
349
|
+
const resolved = await this.resolveFilteredTree(options);
|
|
350
|
+
return this.loadFilteredPage(options, resolved);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async count(options: CountOptions & { tree?: boolean; raw?: boolean } = {}): Promise<number> {
|
|
354
|
+
if (!options.tree || options.raw) return super.count(options);
|
|
355
|
+
if (!this.isFiltered(options)) {
|
|
356
|
+
const { pkCol, fkCol, tableSql } = this.getTreeMeta();
|
|
357
|
+
return this.countUnfilteredRoots(tableSql, pkCol, fkCol, options.transaction);
|
|
358
|
+
}
|
|
359
|
+
const resolved = await this.resolveFilteredTree(options as TreeOptions);
|
|
360
|
+
return resolved.rootIds.length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async findAndCount(
|
|
364
|
+
options: FindAndCountOptions & { tree?: boolean; addIndex?: boolean } = {},
|
|
365
|
+
): Promise<[Model[], number]> {
|
|
366
|
+
if (!options.tree || options.raw) return super.findAndCount(options);
|
|
367
|
+
if (!this.isFiltered(options)) {
|
|
368
|
+
const { pkCol, fkCol, tableSql } = this.getTreeMeta();
|
|
369
|
+
const total = await this.countUnfilteredRoots(tableSql, pkCol, fkCol, options.transaction);
|
|
370
|
+
if (!total) return [[], 0];
|
|
371
|
+
const rows = await this.findUnfilteredPaged(options);
|
|
372
|
+
return [rows, total];
|
|
373
|
+
}
|
|
374
|
+
const resolved = await this.resolveFilteredTree(options);
|
|
375
|
+
const rows = await this.loadFilteredPage(options, resolved);
|
|
376
|
+
return [rows, resolved.rootIds.length];
|
|
377
|
+
}
|
|
378
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
/**
|
|
11
|
+
* Collection Types Export
|
|
12
|
+
*
|
|
13
|
+
* Exports all custom collection type implementations for PostgreSQL datasource.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export { PostgresSQLCollection } from './sql-collection';
|
|
17
|
+
export { SQLModel } from './sql-model';
|
|
18
|
+
export { PostgresTreeCollection } from './tree-collection';
|
|
19
|
+
export { PostgresAdjacencyListRepository } from './adjacency-list-repository';
|