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,543 @@
|
|
|
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 { Client } from 'pg';
|
|
11
|
+
import { createMockServer, MockServer } from '@nocobase/test';
|
|
12
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
13
|
+
import { DATA_SOURCE_TYPE, NAMESPACE } from '../../constants';
|
|
14
|
+
import { PostgresDataSource } from '../postgres-datasource';
|
|
15
|
+
import { PluginDataSourcePostgresServer } from '../plugin';
|
|
16
|
+
|
|
17
|
+
const disposablePostgresEnabled = process.env.NOCOBASE_POSTGRES_DISPOSABLE_TEST === '1';
|
|
18
|
+
const host = process.env.NOCOBASE_POSTGRES_TEST_HOST;
|
|
19
|
+
const port = Number(process.env.NOCOBASE_POSTGRES_TEST_PORT);
|
|
20
|
+
const database = process.env.NOCOBASE_POSTGRES_TEST_DATABASE;
|
|
21
|
+
const username = process.env.NOCOBASE_POSTGRES_TEST_USERNAME;
|
|
22
|
+
const password = process.env.NOCOBASE_POSTGRES_TEST_PASSWORD;
|
|
23
|
+
const testSchema = `codex_pg_test_${process.pid}_${Date.now()}`;
|
|
24
|
+
const sourceKey = 'postgres-resource-test';
|
|
25
|
+
|
|
26
|
+
const hasPostgresConfig = Boolean(host && port && database && username);
|
|
27
|
+
const testOptions = {
|
|
28
|
+
host,
|
|
29
|
+
port,
|
|
30
|
+
database,
|
|
31
|
+
username,
|
|
32
|
+
password,
|
|
33
|
+
schema: testSchema,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
describe.skipIf(!disposablePostgresEnabled || !hasPostgresConfig)('PostgreSQL data source integration', () => {
|
|
37
|
+
let setupClient: Client;
|
|
38
|
+
let dataSource: PostgresDataSource;
|
|
39
|
+
let app: MockServer;
|
|
40
|
+
|
|
41
|
+
beforeAll(async () => {
|
|
42
|
+
setupClient = new Client({ host, port, database, user: username, password });
|
|
43
|
+
await setupClient.connect();
|
|
44
|
+
await setupClient.query(`CREATE SCHEMA "${testSchema}"`);
|
|
45
|
+
await setupClient.query(`
|
|
46
|
+
CREATE TABLE "${testSchema}".orders (
|
|
47
|
+
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
48
|
+
name TEXT NOT NULL,
|
|
49
|
+
external_code TEXT
|
|
50
|
+
)
|
|
51
|
+
`);
|
|
52
|
+
await setupClient.query(`INSERT INTO "${testSchema}".orders (name) VALUES ('Existing order')`);
|
|
53
|
+
await setupClient.query(`
|
|
54
|
+
CREATE TABLE "${testSchema}".composite_records (
|
|
55
|
+
tenant_id INTEGER NOT NULL,
|
|
56
|
+
record_id INTEGER NOT NULL,
|
|
57
|
+
value TEXT,
|
|
58
|
+
PRIMARY KEY (tenant_id, record_id)
|
|
59
|
+
)
|
|
60
|
+
`);
|
|
61
|
+
await setupClient.query(`
|
|
62
|
+
CREATE TABLE "${testSchema}".uuid_identity_records (
|
|
63
|
+
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
|
64
|
+
sequence_number BIGINT GENERATED BY DEFAULT AS IDENTITY,
|
|
65
|
+
external_key UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE
|
|
66
|
+
)
|
|
67
|
+
`);
|
|
68
|
+
await setupClient.query(`
|
|
69
|
+
CREATE VIEW "${testSchema}".order_names AS
|
|
70
|
+
SELECT id, name FROM "${testSchema}".orders
|
|
71
|
+
`);
|
|
72
|
+
|
|
73
|
+
dataSource = new PostgresDataSource({ ...testOptions, name: 'postgres-test' });
|
|
74
|
+
await dataSource.load();
|
|
75
|
+
|
|
76
|
+
app = await createMockServer({
|
|
77
|
+
plugins: ['nocobase', 'data-source-manager', [PluginDataSourcePostgresServer, { name: NAMESPACE }]],
|
|
78
|
+
});
|
|
79
|
+
const sourceOptions = {
|
|
80
|
+
...testOptions,
|
|
81
|
+
addAllCollections: false,
|
|
82
|
+
autoDiscover: false,
|
|
83
|
+
selectedCollections: [],
|
|
84
|
+
};
|
|
85
|
+
const createSourceResponse = await app
|
|
86
|
+
.agent()
|
|
87
|
+
.resource('dataSources')
|
|
88
|
+
.create({
|
|
89
|
+
values: {
|
|
90
|
+
key: sourceKey,
|
|
91
|
+
type: DATA_SOURCE_TYPE,
|
|
92
|
+
displayName: 'PostgreSQL test source',
|
|
93
|
+
enabled: true,
|
|
94
|
+
options: sourceOptions,
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
expect(createSourceResponse.status, createSourceResponse.text).toBe(200);
|
|
98
|
+
for (let attempt = 0; attempt < 100 && !app.dataSourceManager.get(sourceKey); attempt++) {
|
|
99
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
|
100
|
+
}
|
|
101
|
+
const createdSource = app.dataSourceManager.get(sourceKey) as PostgresDataSource | undefined;
|
|
102
|
+
if (!createdSource) throw new Error('The host did not finish loading the PostgreSQL data source');
|
|
103
|
+
await createdSource.collectionManager.db.sequelize.authenticate();
|
|
104
|
+
}, 120000);
|
|
105
|
+
|
|
106
|
+
afterAll(async () => {
|
|
107
|
+
if (app) await app.destroy();
|
|
108
|
+
if (dataSource) await dataSource.close();
|
|
109
|
+
if (setupClient) {
|
|
110
|
+
await setupClient.query(`DROP SCHEMA IF EXISTS "${testSchema}" CASCADE`);
|
|
111
|
+
await setupClient.end();
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('discovers tables and views, and loads a table selected by the host action', async () => {
|
|
116
|
+
const tables = await dataSource.readTables();
|
|
117
|
+
expect(tables.map(({ name }) => name)).toEqual([
|
|
118
|
+
'composite_records',
|
|
119
|
+
'order_names',
|
|
120
|
+
'orders',
|
|
121
|
+
'uuid_identity_records',
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
const selected = new PostgresDataSource({
|
|
125
|
+
...testOptions,
|
|
126
|
+
name: 'postgres-selected-test',
|
|
127
|
+
addAllCollections: false,
|
|
128
|
+
autoDiscover: false,
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await selected.load();
|
|
132
|
+
expect(selected.collectionManager.getCollections()).toHaveLength(0);
|
|
133
|
+
|
|
134
|
+
await selected.loadTables({} as never, ['orders']);
|
|
135
|
+
expect(selected.collectionManager.getCollections().map((collection) => collection.name)).toEqual(['orders']);
|
|
136
|
+
} finally {
|
|
137
|
+
await selected.close();
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('uses the host HTTP resources to import tables, create collections and fields, and reject dependent deletes', async () => {
|
|
142
|
+
const readResponse = await app
|
|
143
|
+
.agent()
|
|
144
|
+
.resource('dataSources')
|
|
145
|
+
.readTables({
|
|
146
|
+
values: {
|
|
147
|
+
dataSourceKey: sourceKey,
|
|
148
|
+
dbOptions: { type: DATA_SOURCE_TYPE, ...testOptions },
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
expect(readResponse.status).toBe(200);
|
|
152
|
+
expect(readResponse.body.data.map((table: { name: string }) => table.name)).toContain('orders');
|
|
153
|
+
expect(readResponse.body.data.map((table: { name: string }) => table.name)).toContain('order_names');
|
|
154
|
+
|
|
155
|
+
const source = app.dataSourceManager.dataSources.get(sourceKey) as PostgresDataSource;
|
|
156
|
+
const loadResponse = await app
|
|
157
|
+
.agent()
|
|
158
|
+
.resource('dataSources')
|
|
159
|
+
.loadTables({
|
|
160
|
+
values: { dataSourceKey: sourceKey, tables: ['orders', 'order_names', 'composite_records'] },
|
|
161
|
+
});
|
|
162
|
+
expect(loadResponse.status).toBe(200);
|
|
163
|
+
expect(source.collectionManager.hasCollection('orders')).toBe(true);
|
|
164
|
+
expect(source.collectionManager.getCollection('order_names')?.options.view).toBe(true);
|
|
165
|
+
expect(source.collectionManager.getCollection('order_names')?.filterTargetKey).toBe('id');
|
|
166
|
+
expect(source.collectionManager.hasCollection('composite_records')).toBe(true);
|
|
167
|
+
|
|
168
|
+
const collections = app.agent().resource('dataSources.collections', sourceKey);
|
|
169
|
+
const createResponse = await collections.create({
|
|
170
|
+
values: {
|
|
171
|
+
name: 'managed_items',
|
|
172
|
+
title: 'Managed items',
|
|
173
|
+
fields: [{ name: 'name', type: 'string', interface: 'input', allowNull: false }],
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
expect(createResponse.status, createResponse.text).toBe(200);
|
|
177
|
+
const currentSource = app.dataSourceManager.dataSources.get(sourceKey) as PostgresDataSource;
|
|
178
|
+
expect(
|
|
179
|
+
currentSource.collectionManager.hasCollection('managed_items'),
|
|
180
|
+
JSON.stringify({
|
|
181
|
+
status: createResponse.status,
|
|
182
|
+
response: createResponse.text,
|
|
183
|
+
collections: currentSource.collectionManager.getCollections().map((collection) => collection.name),
|
|
184
|
+
}),
|
|
185
|
+
).toBe(true);
|
|
186
|
+
expect(await dataSource.collectionManager.discoverTables()).toContain('managed_items');
|
|
187
|
+
const fields = app.agent().resource('dataSourcesCollections.fields', `${sourceKey}.managed_items`);
|
|
188
|
+
const createFieldResponse = await fields.create({
|
|
189
|
+
values: { name: 'note', type: 'string', interface: 'input' },
|
|
190
|
+
});
|
|
191
|
+
expect(createFieldResponse.status, createFieldResponse.text).toBe(200);
|
|
192
|
+
const updateFieldResponse = await fields.update({ filterByTk: 'note', values: { unique: true } });
|
|
193
|
+
expect(updateFieldResponse.status, updateFieldResponse.text).toBe(200);
|
|
194
|
+
await expect(
|
|
195
|
+
setupClient.query(
|
|
196
|
+
`INSERT INTO "${testSchema}".managed_items (name, note) VALUES ('one', 'same'), ('two', 'same')`,
|
|
197
|
+
),
|
|
198
|
+
).rejects.toThrow();
|
|
199
|
+
|
|
200
|
+
const deleteFieldResponse = await fields.destroy({ filterByTk: 'note' });
|
|
201
|
+
expect(deleteFieldResponse.status, deleteFieldResponse.text).toBe(200);
|
|
202
|
+
const remainingFields = await dataSource.collectionManager.discoverColumns('managed_items');
|
|
203
|
+
expect(remainingFields.map((field) => field.column_name)).not.toContain('note');
|
|
204
|
+
|
|
205
|
+
const zhI18n = await app.localeManager.getI18nInstance('zh-CN');
|
|
206
|
+
zhI18n.addResourceBundle('zh-CN', NAMESPACE, { 'This collection is read-only': '此数据表为只读' }, true, true);
|
|
207
|
+
const readOnlyFieldResponse = await app
|
|
208
|
+
.agent()
|
|
209
|
+
.resource('dataSourcesCollections.fields', `${sourceKey}.order_names`)
|
|
210
|
+
.create({ locale: 'zh-CN', values: { name: 'extra', type: 'string', interface: 'input' } });
|
|
211
|
+
expect(readOnlyFieldResponse.status).toBe(403);
|
|
212
|
+
expect(readOnlyFieldResponse.text).toContain('此数据表为只读');
|
|
213
|
+
expect(
|
|
214
|
+
await app.db.getRepository('dataSourcesFields').findOne({
|
|
215
|
+
filter: { name: 'extra', collectionName: 'order_names', dataSourceKey: sourceKey },
|
|
216
|
+
}),
|
|
217
|
+
).toBeNull();
|
|
218
|
+
const deniedPhysicalColumn = await setupClient.query(
|
|
219
|
+
`SELECT column_name FROM information_schema.columns
|
|
220
|
+
WHERE table_schema = $1 AND table_name = 'order_names' AND column_name = 'extra'`,
|
|
221
|
+
[testSchema],
|
|
222
|
+
);
|
|
223
|
+
expect(deniedPhysicalColumn.rows).toHaveLength(0);
|
|
224
|
+
|
|
225
|
+
const compositeFields = app.agent().resource('dataSourcesCollections.fields', `${sourceKey}.composite_records`);
|
|
226
|
+
const applyFieldResponse = await compositeFields.apply({
|
|
227
|
+
values: {
|
|
228
|
+
name: 'sequence_number',
|
|
229
|
+
type: 'integer',
|
|
230
|
+
interface: 'integer',
|
|
231
|
+
autoIncrement: true,
|
|
232
|
+
allowNull: false,
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
expect(applyFieldResponse.status, applyFieldResponse.text).toBe(200);
|
|
236
|
+
const generatedRows = await setupClient.query<{ sequence_number: number }>(
|
|
237
|
+
`INSERT INTO "${testSchema}".composite_records (tenant_id, record_id, value)
|
|
238
|
+
VALUES (1, 1, 'identity field') RETURNING sequence_number`,
|
|
239
|
+
);
|
|
240
|
+
expect(generatedRows.rows[0].sequence_number).toBeGreaterThan(0);
|
|
241
|
+
|
|
242
|
+
const rejectedIdentityUpdate = await compositeFields.update({
|
|
243
|
+
filterByTk: 'sequence_number',
|
|
244
|
+
values: { autoIncrement: false },
|
|
245
|
+
});
|
|
246
|
+
expect(rejectedIdentityUpdate.status).toBeGreaterThanOrEqual(400);
|
|
247
|
+
const identityColumn = await setupClient.query<{ is_identity: string }>(
|
|
248
|
+
`SELECT is_identity FROM information_schema.columns
|
|
249
|
+
WHERE table_schema = $1 AND table_name = 'composite_records' AND column_name = 'sequence_number'`,
|
|
250
|
+
[testSchema],
|
|
251
|
+
);
|
|
252
|
+
expect(identityColumn.rows[0].is_identity).toBe('YES');
|
|
253
|
+
const savedIdentityField = await app.db.getRepository('dataSourcesFields').findOne({
|
|
254
|
+
filter: { name: 'sequence_number', collectionName: 'composite_records', dataSourceKey: sourceKey },
|
|
255
|
+
});
|
|
256
|
+
expect(savedIdentityField?.get('autoIncrement')).toBe(true);
|
|
257
|
+
|
|
258
|
+
const metadataRepo = app.db.getRepository('dataSourcesCollections');
|
|
259
|
+
const collectionMetadata = await metadataRepo.findOne({
|
|
260
|
+
filter: { name: 'orders', dataSourceKey: sourceKey },
|
|
261
|
+
});
|
|
262
|
+
if (!collectionMetadata) {
|
|
263
|
+
await metadataRepo.create({ values: { name: 'orders', dataSourceKey: sourceKey } });
|
|
264
|
+
}
|
|
265
|
+
const rejectedDelete = await collections.destroy({ filterByTk: 'orders' });
|
|
266
|
+
expect(rejectedDelete.status).toBe(500);
|
|
267
|
+
expect(await metadataRepo.findOne({ filter: { name: 'orders', dataSourceKey: sourceKey } })).toBeTruthy();
|
|
268
|
+
|
|
269
|
+
const deleteCollectionResponse = await collections.destroy({ filterByTk: 'managed_items', cascade: false });
|
|
270
|
+
expect(deleteCollectionResponse.status).toBe(200);
|
|
271
|
+
const remainingTables = await dataSource.collectionManager.discoverTables();
|
|
272
|
+
expect(remainingTables).toContain('orders');
|
|
273
|
+
expect(remainingTables).not.toContain('managed_items');
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it('runs filtered and paginated SQL collections in read-only transactions', async () => {
|
|
277
|
+
const collections = app.agent().resource('dataSources.collections', sourceKey);
|
|
278
|
+
const createResponse = await collections.create({
|
|
279
|
+
values: {
|
|
280
|
+
name: 'paged_order_query',
|
|
281
|
+
template: 'sql',
|
|
282
|
+
sql: `
|
|
283
|
+
SELECT id, name FROM orders
|
|
284
|
+
UNION ALL SELECT 100, 'Page A'
|
|
285
|
+
UNION ALL SELECT 101, 'Page B'
|
|
286
|
+
UNION ALL SELECT 102, 'Page C'
|
|
287
|
+
`,
|
|
288
|
+
autoGenId: false,
|
|
289
|
+
createdAt: false,
|
|
290
|
+
updatedAt: false,
|
|
291
|
+
createdBy: false,
|
|
292
|
+
updatedBy: false,
|
|
293
|
+
fields: [
|
|
294
|
+
{ name: 'id', type: 'integer', interface: 'integer' },
|
|
295
|
+
{ name: 'name', type: 'string', interface: 'input' },
|
|
296
|
+
],
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
expect(createResponse.status, createResponse.text).toBe(200);
|
|
300
|
+
|
|
301
|
+
const source = app.dataSourceManager.get(sourceKey) as PostgresDataSource;
|
|
302
|
+
const collection = source.collectionManager.getCollection('paged_order_query');
|
|
303
|
+
expect(collection?.constructor.name).toBe('PostgresSQLCollection');
|
|
304
|
+
const rows = await collection.repository.find({
|
|
305
|
+
filter: { id: { $gte: 100 } },
|
|
306
|
+
sort: ['id'],
|
|
307
|
+
limit: 1,
|
|
308
|
+
offset: 1,
|
|
309
|
+
});
|
|
310
|
+
expect(rows.map((row) => row.get('id'))).toEqual([101]);
|
|
311
|
+
const [pageRows, count] = await collection.repository.findAndCount({
|
|
312
|
+
filter: { id: { $gte: 100 } },
|
|
313
|
+
sort: ['id'],
|
|
314
|
+
limit: 1,
|
|
315
|
+
offset: 1,
|
|
316
|
+
});
|
|
317
|
+
expect(pageRows.map((row) => row.get('id'))).toEqual([101]);
|
|
318
|
+
expect(count).toBe(3);
|
|
319
|
+
|
|
320
|
+
const rejectedWrite = await app
|
|
321
|
+
.agent()
|
|
322
|
+
.post('/api/paged_order_query:create')
|
|
323
|
+
.set('x-data-source', sourceKey)
|
|
324
|
+
.send({ id: 200, name: 'Forbidden write' });
|
|
325
|
+
expect(rejectedWrite.status).toBeGreaterThanOrEqual(400);
|
|
326
|
+
expect(await collection.repository.find({ filter: { id: 200 } })).toHaveLength(0);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it('registers tree collections and preserves root and child reachability under filters', async () => {
|
|
330
|
+
const collections = app.agent().resource('dataSources.collections', sourceKey);
|
|
331
|
+
const createResponse = await collections.create({
|
|
332
|
+
values: {
|
|
333
|
+
name: 'category_tree',
|
|
334
|
+
template: 'tree',
|
|
335
|
+
tree: 'parentId',
|
|
336
|
+
autoGenId: true,
|
|
337
|
+
createdAt: false,
|
|
338
|
+
updatedAt: false,
|
|
339
|
+
createdBy: false,
|
|
340
|
+
updatedBy: false,
|
|
341
|
+
fields: [
|
|
342
|
+
{
|
|
343
|
+
name: 'id',
|
|
344
|
+
type: 'integer',
|
|
345
|
+
interface: 'id',
|
|
346
|
+
primaryKey: true,
|
|
347
|
+
autoIncrement: true,
|
|
348
|
+
allowNull: false,
|
|
349
|
+
},
|
|
350
|
+
{ name: 'name', type: 'string', interface: 'input', allowNull: false },
|
|
351
|
+
{ name: 'parentId', type: 'integer', interface: 'integer' },
|
|
352
|
+
{
|
|
353
|
+
name: 'parent',
|
|
354
|
+
type: 'belongsTo',
|
|
355
|
+
interface: 'm2o',
|
|
356
|
+
target: 'category_tree',
|
|
357
|
+
foreignKey: 'parentId',
|
|
358
|
+
targetKey: 'id',
|
|
359
|
+
treeParent: true,
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
name: 'children',
|
|
363
|
+
type: 'hasMany',
|
|
364
|
+
interface: 'o2m',
|
|
365
|
+
target: 'category_tree',
|
|
366
|
+
foreignKey: 'parentId',
|
|
367
|
+
sourceKey: 'id',
|
|
368
|
+
treeChildren: true,
|
|
369
|
+
},
|
|
370
|
+
],
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
expect(createResponse.status, createResponse.text).toBe(200);
|
|
374
|
+
|
|
375
|
+
const source = app.dataSourceManager.get(sourceKey) as PostgresDataSource;
|
|
376
|
+
const collection = source.collectionManager.getCollection('category_tree');
|
|
377
|
+
expect(collection?.constructor.name).toBe('PostgresTreeCollection');
|
|
378
|
+
expect(collection?.options.postgresTree).toBe('parentId');
|
|
379
|
+
expect(collection?.options.tree).toBeUndefined();
|
|
380
|
+
expect(await dataSource.collectionManager.discoverTables()).toContain('category_tree');
|
|
381
|
+
|
|
382
|
+
const repository = collection.repository;
|
|
383
|
+
await source.collectionManager.db.sequelize.transaction(async (transaction) => {
|
|
384
|
+
const root = await repository.create({ values: { name: 'Root' }, transaction });
|
|
385
|
+
await repository.create({ values: { name: 'Child', parentId: root.get('id') }, transaction });
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
const tree = await repository.find({ tree: true });
|
|
389
|
+
const root = tree.find((node) => node.get('name') === 'Root');
|
|
390
|
+
expect(root?.get('children').map((node) => node.get('name'))).toEqual(['Child']);
|
|
391
|
+
const filtered = await repository.find({ tree: true, filter: { name: 'Child' } });
|
|
392
|
+
expect(filtered.map((node) => node.get('name'))).toEqual(['Child']);
|
|
393
|
+
|
|
394
|
+
const child = await repository.findOne({ filter: { name: 'Child' } });
|
|
395
|
+
await expect(
|
|
396
|
+
source.collectionManager.db.sequelize.transaction((transaction) =>
|
|
397
|
+
repository.update({ filterByTk: root?.get('id'), values: { parentId: child?.get('id') }, transaction }),
|
|
398
|
+
),
|
|
399
|
+
).rejects.toThrow('Cycle detected in tree collection');
|
|
400
|
+
const unchangedTree = await repository.find({ tree: true });
|
|
401
|
+
const unchangedRoot = unchangedTree.find((node) => node.get('name') === 'Root');
|
|
402
|
+
expect(unchangedRoot?.get('children').map((node) => node.get('name'))).toEqual(['Child']);
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
it('restores saved collection and field metadata when auto discovery is disabled', async () => {
|
|
406
|
+
const selected = new PostgresDataSource({
|
|
407
|
+
...testOptions,
|
|
408
|
+
name: 'postgres-local-data-test',
|
|
409
|
+
addAllCollections: false,
|
|
410
|
+
autoDiscover: false,
|
|
411
|
+
});
|
|
412
|
+
try {
|
|
413
|
+
await selected.load({
|
|
414
|
+
localData: {
|
|
415
|
+
orders: {
|
|
416
|
+
name: 'orders',
|
|
417
|
+
tableName: 'orders',
|
|
418
|
+
title: 'Saved order title',
|
|
419
|
+
fields: [{ name: 'name', type: 'string', interface: 'input', title: 'Saved field title' }],
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
const collections = selected.collectionManager.getCollections();
|
|
425
|
+
expect(collections.map((collection) => collection.name)).toEqual(['orders']);
|
|
426
|
+
expect(collections[0].options.title).toBe('Saved order title');
|
|
427
|
+
expect(collections[0].getField('name')?.options.title).toBe('Saved field title');
|
|
428
|
+
} finally {
|
|
429
|
+
await selected.close();
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
it('uses the PostgreSQL repository for CRUD on an introspected collection', async () => {
|
|
434
|
+
const collection = dataSource.collectionManager.getCollection('orders');
|
|
435
|
+
if (!collection) throw new Error('Expected the discovered orders collection');
|
|
436
|
+
|
|
437
|
+
const repository = collection.repository;
|
|
438
|
+
const created = await repository.create({ values: { name: 'Added order', external_code: 'new-code' } });
|
|
439
|
+
const id = created.get('id');
|
|
440
|
+
|
|
441
|
+
expect((await repository.find({ filter: { id } })).map((record) => record.get('name'))).toEqual(['Added order']);
|
|
442
|
+
|
|
443
|
+
await repository.update({ filterByTk: id, values: { name: 'Updated order' } });
|
|
444
|
+
expect((await repository.findOne({ filterByTk: id })).get('name')).toBe('Updated order');
|
|
445
|
+
|
|
446
|
+
await repository.destroy({ filterByTk: id });
|
|
447
|
+
expect(await repository.findOne({ filterByTk: id })).toBeNull();
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it('preserves composite primary keys discovered from PostgreSQL', async () => {
|
|
451
|
+
const collection = dataSource.collectionManager.getCollection('composite_records');
|
|
452
|
+
const primaryKeyFields = collection
|
|
453
|
+
?.getFields()
|
|
454
|
+
.filter((field) => field.options.primaryKey)
|
|
455
|
+
.map((field) => field.name);
|
|
456
|
+
|
|
457
|
+
expect(primaryKeyFields).toEqual(['tenant_id', 'record_id']);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
it('prefers a UUID primary key over a separate identity column and preserves a saved target key', async () => {
|
|
461
|
+
const inferred = dataSource.collectionManager.getCollection('uuid_identity_records');
|
|
462
|
+
expect(inferred?.options.filterTargetKey).toBe('id');
|
|
463
|
+
|
|
464
|
+
const selected = new PostgresDataSource({
|
|
465
|
+
...testOptions,
|
|
466
|
+
name: 'postgres-saved-filter-target-test',
|
|
467
|
+
addAllCollections: false,
|
|
468
|
+
autoDiscover: false,
|
|
469
|
+
});
|
|
470
|
+
try {
|
|
471
|
+
await selected.load({
|
|
472
|
+
localData: {
|
|
473
|
+
uuid_identity_records: {
|
|
474
|
+
name: 'uuid_identity_records',
|
|
475
|
+
tableName: 'uuid_identity_records',
|
|
476
|
+
filterTargetKey: 'external_key',
|
|
477
|
+
},
|
|
478
|
+
},
|
|
479
|
+
});
|
|
480
|
+
expect(selected.collectionManager.getCollection('uuid_identity_records')?.options.filterTargetKey).toBe(
|
|
481
|
+
'external_key',
|
|
482
|
+
);
|
|
483
|
+
} finally {
|
|
484
|
+
await selected.close();
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
it('adds, changes and removes physical fields, including unique indexes', async () => {
|
|
489
|
+
const manager = dataSource.collectionManager;
|
|
490
|
+
await manager.addField('orders', { name: 'nickname', type: 'string' });
|
|
491
|
+
await manager.addField('orders', { name: 'unique_code', type: 'string' });
|
|
492
|
+
await manager.updateField('orders', 'unique_code', { unique: true });
|
|
493
|
+
|
|
494
|
+
const duplicateInsert = setupClient.query(
|
|
495
|
+
`INSERT INTO "${testSchema}".orders (name, unique_code) VALUES ('First', 'duplicate')`,
|
|
496
|
+
);
|
|
497
|
+
await duplicateInsert;
|
|
498
|
+
|
|
499
|
+
await expect(
|
|
500
|
+
setupClient.query(`INSERT INTO "${testSchema}".orders (name, unique_code) VALUES ('Second', 'duplicate')`),
|
|
501
|
+
).rejects.toThrow();
|
|
502
|
+
|
|
503
|
+
await manager.updateField('orders', 'unique_code', { unique: false });
|
|
504
|
+
await setupClient.query(`INSERT INTO "${testSchema}".orders (name, unique_code) VALUES ('Second', 'duplicate')`);
|
|
505
|
+
await manager.removeField('orders', 'nickname');
|
|
506
|
+
|
|
507
|
+
const columns = await manager.discoverColumns('orders');
|
|
508
|
+
expect(columns.map((column) => column.column_name)).not.toContain('nickname');
|
|
509
|
+
expect(columns.map((column) => column.column_name)).toContain('unique_code');
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
it('refuses to drop a table with dependent objects unless cascade was selected', async () => {
|
|
513
|
+
await expect(dataSource.collectionManager.dropTable('orders', false)).rejects.toThrow();
|
|
514
|
+
|
|
515
|
+
const rows = await setupClient.query<{ table_name: string }>(
|
|
516
|
+
`SELECT table_name FROM information_schema.tables WHERE table_schema = $1 AND table_name IN ('orders', 'order_names') ORDER BY table_name`,
|
|
517
|
+
[testSchema],
|
|
518
|
+
);
|
|
519
|
+
expect(rows.rows.map((row) => row.table_name)).toEqual(['order_names', 'orders']);
|
|
520
|
+
});
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
describe('PostgreSQL connection configuration', () => {
|
|
524
|
+
it('verifies SSL certificates and applies a configured CA', async () => {
|
|
525
|
+
const dataSource = new PostgresDataSource({
|
|
526
|
+
host: '127.0.0.1',
|
|
527
|
+
port: 5432,
|
|
528
|
+
database: 'unused',
|
|
529
|
+
username: 'unused',
|
|
530
|
+
ssl: true,
|
|
531
|
+
sslCa: 'test CA',
|
|
532
|
+
});
|
|
533
|
+
try {
|
|
534
|
+
expect(dataSource.collectionManager.db.options.dialectOptions.ssl).toEqual({
|
|
535
|
+
rejectUnauthorized: true,
|
|
536
|
+
ca: 'test CA',
|
|
537
|
+
});
|
|
538
|
+
expect(dataSource.collectionManager.db.options.dialectOptions.connectionTimeoutMillis).toBeGreaterThan(0);
|
|
539
|
+
} finally {
|
|
540
|
+
await dataSource.close();
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
});
|