plugin-data-source-postgres 0.0.0-stage → 2.0.0
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 +28 -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 +147 -0
- package/dist/server/collections/tree-collection.js +118 -0
- package/dist/server/hooks/field-hooks.js +392 -0
- package/dist/server/index.js +38 -0
- package/dist/server/plugin.js +690 -0
- package/dist/server/postgres-collection-manager.js +701 -0
- package/dist/server/postgres-datasource.js +327 -0
- package/dist/server/utils/sql-validator.js +203 -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 +1538 -0
- package/src/server/__tests__/sql-model.test.ts +115 -0
- package/src/server/__tests__/sql-validator.test.ts +119 -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 +514 -0
- package/src/server/index.ts +13 -0
- package/src/server/plugin.ts +764 -0
- package/src/server/postgres-collection-manager.ts +827 -0
- package/src/server/postgres-datasource.ts +365 -0
- package/src/server/utils/sql-validator.ts +203 -0
- package/src/server/utils/validation-error.ts +38 -0
|
@@ -0,0 +1,372 @@
|
|
|
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 React from 'react';
|
|
11
|
+
import { createMockClient } from '@nocobase/client-v2';
|
|
12
|
+
import { FlowEngineProvider } from '@nocobase/flow-engine';
|
|
13
|
+
import NativeManager from '@nocobase/plugin-data-source-manager/client-v2';
|
|
14
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
15
|
+
import { Form } from 'antd';
|
|
16
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
17
|
+
import { DATA_SOURCE_TYPE, NAMESPACE } from '../../constants';
|
|
18
|
+
import { toCollectionOptions } from '../collection-options';
|
|
19
|
+
import { PostgresAddCollection } from '../PostgresAddCollection';
|
|
20
|
+
import PostgresConfigForm from '../PostgresConfigForm';
|
|
21
|
+
import { PostgresDeleteCollection } from '../PostgresDeleteCollection';
|
|
22
|
+
import Plugin from '../plugin';
|
|
23
|
+
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
cleanup();
|
|
26
|
+
vi.restoreAllMocks();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
window.matchMedia = vi.fn().mockImplementation((media: string) => ({
|
|
31
|
+
matches: false,
|
|
32
|
+
media,
|
|
33
|
+
onchange: null,
|
|
34
|
+
addListener: vi.fn(),
|
|
35
|
+
removeListener: vi.fn(),
|
|
36
|
+
addEventListener: vi.fn(),
|
|
37
|
+
removeEventListener: vi.fn(),
|
|
38
|
+
dispatchEvent: vi.fn(),
|
|
39
|
+
}));
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
function registerPostgresType() {
|
|
43
|
+
const app = createMockClient();
|
|
44
|
+
app.flowEngine.context.defineProperty('message', { value: { error: vi.fn() } });
|
|
45
|
+
const manager = new NativeManager({}, app);
|
|
46
|
+
vi.spyOn(app.pm, 'get').mockReturnValue(manager);
|
|
47
|
+
return { app, manager };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('PostgreSQL native client v2', () => {
|
|
51
|
+
it('registers the datasource type and preserves legacy selected-table settings', async () => {
|
|
52
|
+
expect(NAMESPACE).toBe('plugin-data-source-postgres');
|
|
53
|
+
const { app, manager } = registerPostgresType();
|
|
54
|
+
await new Plugin({}, app).load();
|
|
55
|
+
|
|
56
|
+
const type = manager.getType(DATA_SOURCE_TYPE);
|
|
57
|
+
expect(type.SettingsForm).toBeDefined();
|
|
58
|
+
expect(type.defaultValues).toMatchObject({
|
|
59
|
+
options: {
|
|
60
|
+
host: 'localhost',
|
|
61
|
+
port: 5432,
|
|
62
|
+
schema: 'public',
|
|
63
|
+
ssl: false,
|
|
64
|
+
addAllCollections: true,
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
expect(type.AddCollection).toBe(PostgresAddCollection);
|
|
68
|
+
expect(type.DeleteCollection).toBe(PostgresDeleteCollection);
|
|
69
|
+
expect(type.allowCollectionCreate).toBe(true);
|
|
70
|
+
expect(type.allowCollectionDeletion).toBe(true);
|
|
71
|
+
expect(typeof type.createFieldInterfaces).toBe('function');
|
|
72
|
+
const tableFilter = (
|
|
73
|
+
type.createFieldInterfaces as (ctx: { collection: Record<string, unknown> }) => Record<string, unknown>
|
|
74
|
+
)({
|
|
75
|
+
collection: { name: 'orders', template: 'general' },
|
|
76
|
+
});
|
|
77
|
+
expect(tableFilter.exclude).toEqual(
|
|
78
|
+
expect.arrayContaining(['formula', 'sequence', 'tableoid', 'createdBy', 'attachment']),
|
|
79
|
+
);
|
|
80
|
+
const viewFilter = (
|
|
81
|
+
type.createFieldInterfaces as (ctx: { collection: Record<string, unknown> }) => Record<string, unknown>
|
|
82
|
+
)({
|
|
83
|
+
collection: { name: 'order_view', view: true, template: 'view' },
|
|
84
|
+
});
|
|
85
|
+
expect(viewFilter).toEqual({ include: ['__none__'] });
|
|
86
|
+
|
|
87
|
+
const legacy = type.normalizeValues({
|
|
88
|
+
options: { autoDiscover: false },
|
|
89
|
+
__postgresPreserveLegacySelection: true,
|
|
90
|
+
});
|
|
91
|
+
expect(legacy.collections).toBeUndefined();
|
|
92
|
+
expect(legacy.options).toMatchObject({ addAllCollections: false, autoDiscover: false });
|
|
93
|
+
expect(legacy.options.selectedCollections).toBeUndefined();
|
|
94
|
+
|
|
95
|
+
const selected = type.normalizeValues({ options: { addAllCollections: false }, collections: ['orders'] });
|
|
96
|
+
expect(selected.options.selectedCollections).toEqual(['orders']);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('reads available tables when opening the setup selection and keeps SSL CA options without initialValue warnings', async () => {
|
|
100
|
+
const { app } = registerPostgresType();
|
|
101
|
+
app.apiMock.onPost('dataSources:readTables').reply(200, { data: [{ name: 'orders' }] });
|
|
102
|
+
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
103
|
+
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
|
104
|
+
|
|
105
|
+
render(
|
|
106
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
107
|
+
<Form
|
|
108
|
+
initialValues={{
|
|
109
|
+
key: 'external',
|
|
110
|
+
options: {
|
|
111
|
+
host: 'db.test',
|
|
112
|
+
port: 5432,
|
|
113
|
+
database: 'sales',
|
|
114
|
+
username: 'postgres',
|
|
115
|
+
password: 'secret',
|
|
116
|
+
ssl: true,
|
|
117
|
+
sslCa: 'test certificate',
|
|
118
|
+
addAllCollections: false,
|
|
119
|
+
},
|
|
120
|
+
}}
|
|
121
|
+
>
|
|
122
|
+
<PostgresConfigForm mode="create" type={{ label: 'PostgreSQL' }} loadCollections={vi.fn()} />
|
|
123
|
+
</Form>
|
|
124
|
+
</FlowEngineProvider>,
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
expect(screen.getByLabelText('CA certificate (PEM)')).toBeTruthy();
|
|
128
|
+
fireEvent.focus(await screen.findByRole('combobox'));
|
|
129
|
+
await waitFor(() => expect(app.apiMock.history.post).toHaveLength(1));
|
|
130
|
+
|
|
131
|
+
const logged = [...errorSpy.mock.calls, ...warnSpy.mock.calls].flat().map(String);
|
|
132
|
+
expect(logged.some((line) => line.includes("already set 'initialValues'"))).toBe(false);
|
|
133
|
+
|
|
134
|
+
expect(JSON.parse(app.apiMock.history.post[0].data)).toMatchObject({
|
|
135
|
+
dataSourceKey: 'external',
|
|
136
|
+
dbOptions: {
|
|
137
|
+
type: DATA_SOURCE_TYPE,
|
|
138
|
+
host: 'db.test',
|
|
139
|
+
database: 'sales',
|
|
140
|
+
ssl: true,
|
|
141
|
+
sslCa: 'test certificate',
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('uses loadCollections in edit mode when saved options omit default schema and ssl', async () => {
|
|
147
|
+
const { app } = registerPostgresType();
|
|
148
|
+
const loadCollections = vi.fn().mockResolvedValue([{ name: 'orders' }]);
|
|
149
|
+
const savedInitial = {
|
|
150
|
+
key: 'legacy',
|
|
151
|
+
options: {
|
|
152
|
+
host: 'db.test',
|
|
153
|
+
port: 5432,
|
|
154
|
+
database: 'sales',
|
|
155
|
+
username: 'postgres',
|
|
156
|
+
addAllCollections: false,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
render(
|
|
161
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
162
|
+
<Form initialValues={savedInitial}>
|
|
163
|
+
<PostgresConfigForm
|
|
164
|
+
mode="edit"
|
|
165
|
+
type={{ label: 'PostgreSQL' }}
|
|
166
|
+
initialValues={savedInitial}
|
|
167
|
+
loadCollections={loadCollections}
|
|
168
|
+
/>
|
|
169
|
+
</Form>
|
|
170
|
+
</FlowEngineProvider>,
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
fireEvent.focus(await screen.findByRole('combobox'));
|
|
174
|
+
await waitFor(() => expect(loadCollections).toHaveBeenCalledWith('legacy'));
|
|
175
|
+
expect(app.apiMock.history.post).toHaveLength(0);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('maps discovered tables and views into import selection options', () => {
|
|
179
|
+
expect(toCollectionOptions([{ name: 'orders' }, { name: 'active_orders' }])).toEqual([
|
|
180
|
+
{ label: 'orders', value: 'orders' },
|
|
181
|
+
{ label: 'active_orders', value: 'active_orders' },
|
|
182
|
+
]);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('creates a native calendar collection with PostgreSQL-compatible field definitions', async () => {
|
|
186
|
+
const { app } = registerPostgresType();
|
|
187
|
+
app.apiMock.onPost('dataSources/external/collections:create').reply(200, { data: {} });
|
|
188
|
+
const submitted = vi.fn();
|
|
189
|
+
|
|
190
|
+
render(
|
|
191
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
192
|
+
<PostgresAddCollection dataSourceKey="external" onSubmitted={submitted} />
|
|
193
|
+
</FlowEngineProvider>,
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
fireEvent.mouseEnter(screen.getByRole('button', { name: /Add collection/i }));
|
|
197
|
+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Create collection' }));
|
|
198
|
+
fireEvent.change(screen.getByLabelText('Collection name'), { target: { value: 'events' } });
|
|
199
|
+
fireEvent.change(screen.getByLabelText('Collection display name'), { target: { value: 'Events' } });
|
|
200
|
+
|
|
201
|
+
const template = screen.getByLabelText('Collection template');
|
|
202
|
+
fireEvent.mouseDown(template);
|
|
203
|
+
fireEvent.click(await screen.findByText('Calendar collection'));
|
|
204
|
+
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
|
|
205
|
+
|
|
206
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
207
|
+
const payload = JSON.parse(app.apiMock.history.post[0].data);
|
|
208
|
+
expect(payload).toMatchObject({ name: 'events', title: 'Events', template: 'calendar' });
|
|
209
|
+
expect(payload.fields).toEqual(
|
|
210
|
+
expect.arrayContaining([
|
|
211
|
+
expect.objectContaining({ name: 'start', type: 'date', interface: 'datetime' }),
|
|
212
|
+
expect.objectContaining({ name: 'end', type: 'date', interface: 'datetime' }),
|
|
213
|
+
]),
|
|
214
|
+
);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it('creates a general collection with an identity key and timestamp fields', async () => {
|
|
218
|
+
const { app } = registerPostgresType();
|
|
219
|
+
app.apiMock.onPost('dataSources/external/collections:create').reply(200, { data: {} });
|
|
220
|
+
const submitted = vi.fn();
|
|
221
|
+
|
|
222
|
+
render(
|
|
223
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
224
|
+
<PostgresAddCollection dataSourceKey="external" onSubmitted={submitted} />
|
|
225
|
+
</FlowEngineProvider>,
|
|
226
|
+
);
|
|
227
|
+
|
|
228
|
+
fireEvent.mouseEnter(screen.getByRole('button', { name: /Add collection/i }));
|
|
229
|
+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Create collection' }));
|
|
230
|
+
fireEvent.change(screen.getByLabelText('Collection name'), { target: { value: 'notes' } });
|
|
231
|
+
fireEvent.change(screen.getByLabelText('Collection display name'), { target: { value: 'Notes' } });
|
|
232
|
+
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
|
|
233
|
+
|
|
234
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
235
|
+
const payload = JSON.parse(app.apiMock.history.post[0].data);
|
|
236
|
+
expect(payload).toMatchObject({
|
|
237
|
+
name: 'notes',
|
|
238
|
+
title: 'Notes',
|
|
239
|
+
template: 'general',
|
|
240
|
+
autoGenId: true,
|
|
241
|
+
createdAt: true,
|
|
242
|
+
updatedAt: true,
|
|
243
|
+
});
|
|
244
|
+
expect(payload.fields).toEqual(
|
|
245
|
+
expect.arrayContaining([
|
|
246
|
+
expect.objectContaining({ name: 'id', type: 'bigInt', primaryKey: true, autoIncrement: true }),
|
|
247
|
+
expect.objectContaining({ name: 'createdAt', type: 'date' }),
|
|
248
|
+
expect.objectContaining({ name: 'updatedAt', type: 'date' }),
|
|
249
|
+
]),
|
|
250
|
+
);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it('creates a file collection with PostgreSQL-compatible file metadata fields', async () => {
|
|
254
|
+
const { app } = registerPostgresType();
|
|
255
|
+
app.apiMock.onPost('dataSources/external/collections:create').reply(200, { data: {} });
|
|
256
|
+
const submitted = vi.fn();
|
|
257
|
+
|
|
258
|
+
render(
|
|
259
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
260
|
+
<PostgresAddCollection dataSourceKey="external" onSubmitted={submitted} />
|
|
261
|
+
</FlowEngineProvider>,
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
fireEvent.mouseEnter(screen.getByRole('button', { name: /Add collection/i }));
|
|
265
|
+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Create collection' }));
|
|
266
|
+
fireEvent.change(screen.getByLabelText('Collection name'), { target: { value: 'attachments' } });
|
|
267
|
+
fireEvent.change(screen.getByLabelText('Collection display name'), { target: { value: 'Attachments' } });
|
|
268
|
+
fireEvent.mouseDown(screen.getByLabelText('Collection template'));
|
|
269
|
+
fireEvent.click(await screen.findByText('File collection'));
|
|
270
|
+
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
|
|
271
|
+
|
|
272
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
273
|
+
const payload = JSON.parse(app.apiMock.history.post[0].data);
|
|
274
|
+
expect(payload).toMatchObject({ name: 'attachments', title: 'Attachments', template: 'file' });
|
|
275
|
+
expect(payload.fields).toEqual(
|
|
276
|
+
expect.arrayContaining([
|
|
277
|
+
expect.objectContaining({ name: 'id', type: 'bigInt', primaryKey: true, autoIncrement: true }),
|
|
278
|
+
expect.objectContaining({ name: 'filename', type: 'string' }),
|
|
279
|
+
expect.objectContaining({ name: 'title', type: 'string' }),
|
|
280
|
+
expect.objectContaining({ name: 'url', type: 'string', interface: 'url' }),
|
|
281
|
+
expect.objectContaining({ name: 'mimetype', type: 'string' }),
|
|
282
|
+
expect.objectContaining({ name: 'size', type: 'bigInt' }),
|
|
283
|
+
]),
|
|
284
|
+
);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it('creates read-only SQL collections with declared query fields', async () => {
|
|
288
|
+
const { app } = registerPostgresType();
|
|
289
|
+
app.apiMock.onPost('dataSources/external/collections:create').reply(200, { data: {} });
|
|
290
|
+
const submitted = vi.fn();
|
|
291
|
+
|
|
292
|
+
render(
|
|
293
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
294
|
+
<PostgresAddCollection dataSourceKey="external" onSubmitted={submitted} />
|
|
295
|
+
</FlowEngineProvider>,
|
|
296
|
+
);
|
|
297
|
+
|
|
298
|
+
fireEvent.mouseEnter(screen.getByRole('button', { name: /Add collection/i }));
|
|
299
|
+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Create collection' }));
|
|
300
|
+
fireEvent.change(screen.getByLabelText('Collection name'), { target: { value: 'query_results' } });
|
|
301
|
+
fireEvent.change(screen.getByLabelText('Collection display name'), { target: { value: 'Query results' } });
|
|
302
|
+
fireEvent.mouseDown(screen.getByLabelText('Collection template'));
|
|
303
|
+
fireEvent.click(await screen.findByText('SQL collection'));
|
|
304
|
+
fireEvent.change(screen.getByLabelText('SQL query'), {
|
|
305
|
+
target: { value: "SELECT 1 AS id, 'row' AS value" },
|
|
306
|
+
});
|
|
307
|
+
fireEvent.change(screen.getByLabelText('Column name 1'), { target: { value: 'id' } });
|
|
308
|
+
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
|
|
309
|
+
|
|
310
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
311
|
+
const payload = JSON.parse(app.apiMock.history.post[0].data);
|
|
312
|
+
expect(payload).toMatchObject({
|
|
313
|
+
name: 'query_results',
|
|
314
|
+
template: 'sql',
|
|
315
|
+
autoGenId: false,
|
|
316
|
+
createdAt: false,
|
|
317
|
+
updatedAt: false,
|
|
318
|
+
sql: "SELECT 1 AS id, 'row' AS value",
|
|
319
|
+
});
|
|
320
|
+
expect(payload.fields).toEqual([expect.objectContaining({ name: 'id', type: 'string' })]);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it('creates tree collections with a self-referencing parent field', async () => {
|
|
324
|
+
const { app } = registerPostgresType();
|
|
325
|
+
app.apiMock.onPost('dataSources/external/collections:create').reply(200, { data: {} });
|
|
326
|
+
const submitted = vi.fn();
|
|
327
|
+
|
|
328
|
+
render(
|
|
329
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
330
|
+
<PostgresAddCollection dataSourceKey="external" onSubmitted={submitted} />
|
|
331
|
+
</FlowEngineProvider>,
|
|
332
|
+
);
|
|
333
|
+
|
|
334
|
+
fireEvent.mouseEnter(screen.getByRole('button', { name: /Add collection/i }));
|
|
335
|
+
fireEvent.click(await screen.findByRole('menuitem', { name: 'Create collection' }));
|
|
336
|
+
fireEvent.change(screen.getByLabelText('Collection name'), { target: { value: 'categories' } });
|
|
337
|
+
fireEvent.change(screen.getByLabelText('Collection display name'), { target: { value: 'Categories' } });
|
|
338
|
+
fireEvent.mouseDown(screen.getByLabelText('Collection template'));
|
|
339
|
+
fireEvent.click(await screen.findByText('Tree collection'));
|
|
340
|
+
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
|
|
341
|
+
|
|
342
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
343
|
+
const payload = JSON.parse(app.apiMock.history.post[0].data);
|
|
344
|
+
expect(payload).toMatchObject({ name: 'categories', template: 'tree', tree: 'parentId' });
|
|
345
|
+
expect(payload.fields).toEqual(
|
|
346
|
+
expect.arrayContaining([
|
|
347
|
+
expect.objectContaining({ name: 'parentId', type: 'bigInt' }),
|
|
348
|
+
expect.objectContaining({ name: 'parent', type: 'belongsTo', target: 'categories', foreignKey: 'parentId' }),
|
|
349
|
+
expect.objectContaining({ name: 'children', type: 'hasMany', target: 'categories', foreignKey: 'parentId' }),
|
|
350
|
+
]),
|
|
351
|
+
);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it('leaves cascade off by default for collection deletion', async () => {
|
|
355
|
+
const { app } = registerPostgresType();
|
|
356
|
+
app.apiMock.onPost('dataSources/external/collections:destroy').reply(200, { data: {} });
|
|
357
|
+
const submitted = vi.fn();
|
|
358
|
+
|
|
359
|
+
render(
|
|
360
|
+
<FlowEngineProvider engine={app.flowEngine}>
|
|
361
|
+
<PostgresDeleteCollection dataSourceKey="external" record={{ name: 'orders' }} onSubmitted={submitted} />
|
|
362
|
+
</FlowEngineProvider>,
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
|
366
|
+
expect((screen.getByRole('checkbox') as HTMLInputElement).checked).toBe(false);
|
|
367
|
+
fireEvent.click(screen.getByRole('button', { name: /OK/i }));
|
|
368
|
+
|
|
369
|
+
await waitFor(() => expect(submitted).toHaveBeenCalledOnce());
|
|
370
|
+
expect(app.apiMock.history.post[0].params).toEqual({ filterByTk: ['orders'], cascade: false });
|
|
371
|
+
});
|
|
372
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
11
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function toCollectionOptions(result: unknown): { label: string; value: string }[] {
|
|
15
|
+
const data = isRecord(result) ? result.data : result;
|
|
16
|
+
const list = isRecord(data) ? data.data : data;
|
|
17
|
+
if (!Array.isArray(list)) return [];
|
|
18
|
+
return list.flatMap((item: unknown) => {
|
|
19
|
+
const name = typeof item === 'string' ? item : isRecord(item) ? item.name : undefined;
|
|
20
|
+
return typeof name === 'string' ? [{ label: name, value: name }] : [];
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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';
|
|
@@ -0,0 +1,71 @@
|
|
|
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 React from 'react';
|
|
11
|
+
import { Application, Plugin } from '@nocobase/client-v2';
|
|
12
|
+
import PluginDataSourceManagerClientV2 from '@nocobase/plugin-data-source-manager/client-v2';
|
|
13
|
+
import { DATA_SOURCE_TYPE, DEFAULT_PORT, DEFAULT_SCHEMA } from '../constants';
|
|
14
|
+
import { PostgresAddCollection } from './PostgresAddCollection';
|
|
15
|
+
import { PostgresDeleteCollection } from './PostgresDeleteCollection';
|
|
16
|
+
|
|
17
|
+
const UNSUPPORTED_CREATE_FIELD_INTERFACES = [
|
|
18
|
+
'formula',
|
|
19
|
+
'sequence',
|
|
20
|
+
'tableoid',
|
|
21
|
+
'snapshot',
|
|
22
|
+
'subTable',
|
|
23
|
+
'linkTo',
|
|
24
|
+
'createdBy',
|
|
25
|
+
'updatedBy',
|
|
26
|
+
'attachment',
|
|
27
|
+
'o2o',
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
export class PluginDataSourcePostgresClientV2 extends Plugin<Record<string, never>, Application> {
|
|
31
|
+
async load() {
|
|
32
|
+
const manager = this.app.pm.get(PluginDataSourceManagerClientV2);
|
|
33
|
+
manager?.registerType(DATA_SOURCE_TYPE, {
|
|
34
|
+
label: String(this.t('External PostgreSQL Database')),
|
|
35
|
+
defaultValues: {
|
|
36
|
+
options: {
|
|
37
|
+
host: 'localhost',
|
|
38
|
+
port: DEFAULT_PORT,
|
|
39
|
+
schema: DEFAULT_SCHEMA,
|
|
40
|
+
ssl: false,
|
|
41
|
+
addAllCollections: true,
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
SettingsForm: React.lazy(() => import('./PostgresConfigForm')),
|
|
45
|
+
allowCollectionCreate: true,
|
|
46
|
+
allowCollectionDeletion: true,
|
|
47
|
+
disableAddFields: false,
|
|
48
|
+
createFieldInterfaces: ({ collection }) => {
|
|
49
|
+
if (collection?.view || collection?.template === 'view' || collection?.sql || collection?.template === 'sql') {
|
|
50
|
+
return { include: ['__none__'] };
|
|
51
|
+
}
|
|
52
|
+
return { exclude: UNSUPPORTED_CREATE_FIELD_INTERFACES };
|
|
53
|
+
},
|
|
54
|
+
AddCollection: PostgresAddCollection,
|
|
55
|
+
DeleteCollection: PostgresDeleteCollection,
|
|
56
|
+
normalizeValues: (values) => {
|
|
57
|
+
const { __postgresPreserveLegacySelection, ...normalized } = values;
|
|
58
|
+
const addAllCollections = values.options?.addAllCollections ?? values.options?.autoDiscover !== false;
|
|
59
|
+
const options = { ...values.options, addAllCollections, autoDiscover: addAllCollections };
|
|
60
|
+
if (__postgresPreserveLegacySelection && !addAllCollections) {
|
|
61
|
+
delete normalized.collections;
|
|
62
|
+
} else if (!addAllCollections) {
|
|
63
|
+
options.selectedCollections = values.collections;
|
|
64
|
+
}
|
|
65
|
+
return { ...normalized, options };
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export default PluginDataSourcePostgresClientV2;
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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
|
+
* Constants shared between client and server
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const DATA_SOURCE_TYPE = 'postgres-external';
|
|
15
|
+
|
|
16
|
+
export const NAMESPACE = 'plugin-data-source-postgres';
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_PORT = 5432;
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_SCHEMA = 'public';
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
{
|
|
2
|
+
"External PostgreSQL Database": "External PostgreSQL Database",
|
|
3
|
+
"Display Name": "Display Name",
|
|
4
|
+
"Host": "Host",
|
|
5
|
+
"Port": "Port",
|
|
6
|
+
"Database": "Database",
|
|
7
|
+
"Username": "Username",
|
|
8
|
+
"Password": "Password",
|
|
9
|
+
"Schema": "Schema",
|
|
10
|
+
"PostgreSQL schema name, defaults to public": "PostgreSQL schema name, defaults to public",
|
|
11
|
+
"Use SSL": "Use SSL",
|
|
12
|
+
"Enable SSL/TLS connection": "Enable SSL/TLS connection",
|
|
13
|
+
"Connection Settings": "Connection Settings",
|
|
14
|
+
"Advanced Settings": "Advanced Settings",
|
|
15
|
+
"Auto Discover Tables": "Auto Discover Tables",
|
|
16
|
+
"Automatically discover tables from the database": "Automatically discover tables from the database",
|
|
17
|
+
"The connection name to display in NocoBase": "The connection name to display in NocoBase",
|
|
18
|
+
"PostgreSQL server hostname or IP address": "PostgreSQL server hostname or IP address",
|
|
19
|
+
"PostgreSQL server port number": "PostgreSQL server port number",
|
|
20
|
+
"Name of the PostgreSQL database": "Name of the PostgreSQL database",
|
|
21
|
+
"Database username for authentication": "Database username for authentication",
|
|
22
|
+
"Database password for authentication": "Database password for authentication",
|
|
23
|
+
"CA certificate (PEM)": "CA certificate (PEM)",
|
|
24
|
+
"Load all collections": "Load all collections",
|
|
25
|
+
"Collections": "Collections",
|
|
26
|
+
"Unable to load collections": "Unable to load collections",
|
|
27
|
+
"Create collection": "Create collection",
|
|
28
|
+
"Load existing tables and views": "Load existing tables and views",
|
|
29
|
+
"Add collection": "Add collection",
|
|
30
|
+
"Collection name": "Collection name",
|
|
31
|
+
"Collection display name": "Collection display name",
|
|
32
|
+
"Collection template": "Collection template",
|
|
33
|
+
"General collection": "General collection",
|
|
34
|
+
"Calendar collection": "Calendar collection",
|
|
35
|
+
"File collection": "File collection",
|
|
36
|
+
"Tree collection": "Tree collection",
|
|
37
|
+
"SQL collection": "SQL collection",
|
|
38
|
+
"SQL query": "SQL query",
|
|
39
|
+
"Use a SELECT query. SQL collections are read-only.": "Use a SELECT query. SQL collections are read-only.",
|
|
40
|
+
"Add at least one query column": "Add at least one query column",
|
|
41
|
+
"Column names must be unique": "Column names must be unique",
|
|
42
|
+
"Column name {{number}}": "Column name {{number}}",
|
|
43
|
+
"Column type {{number}}": "Column type {{number}}",
|
|
44
|
+
"Remove query column {{number}}": "Remove query column {{number}}",
|
|
45
|
+
"Add query column": "Add query column",
|
|
46
|
+
"Text": "Text",
|
|
47
|
+
"Long text": "Long text",
|
|
48
|
+
"Integer": "Integer",
|
|
49
|
+
"Big integer": "Big integer",
|
|
50
|
+
"Decimal": "Decimal",
|
|
51
|
+
"Boolean": "Boolean",
|
|
52
|
+
"Date and time": "Date and time",
|
|
53
|
+
"JSON": "JSON",
|
|
54
|
+
"UUID": "UUID",
|
|
55
|
+
"Name": "Name",
|
|
56
|
+
"Title": "Title",
|
|
57
|
+
"Start date": "Start date",
|
|
58
|
+
"End date": "End date",
|
|
59
|
+
"Filename": "Filename",
|
|
60
|
+
"URL": "URL",
|
|
61
|
+
"MIME type": "MIME type",
|
|
62
|
+
"File size": "File size",
|
|
63
|
+
"Create timestamp fields": "Create timestamp fields",
|
|
64
|
+
"Create": "Create",
|
|
65
|
+
"Load": "Load",
|
|
66
|
+
"Delete": "Delete",
|
|
67
|
+
"Delete collection": "Delete collection",
|
|
68
|
+
"Delete the selected collection and its PostgreSQL table or view?": "Delete the selected collection and its PostgreSQL table or view?",
|
|
69
|
+
"Also drop dependent PostgreSQL objects": "Also drop dependent PostgreSQL objects",
|
|
70
|
+
"Failed to create collection": "Failed to create collection",
|
|
71
|
+
"Failed to delete collection": "Failed to delete collection",
|
|
72
|
+
"A collection name is required": "A collection name is required",
|
|
73
|
+
"Collection name is required": "Collection name is required",
|
|
74
|
+
"Unknown preset field {{name}}": "Unknown preset field {{name}}",
|
|
75
|
+
"This collection is read-only": "This collection is read-only",
|
|
76
|
+
"Collection {{name}} does not exist": "Collection {{name}} does not exist",
|
|
77
|
+
"Collection {{name}} already exists": "Collection {{name}} already exists",
|
|
78
|
+
"Table {{name}} already exists": "Table {{name}} already exists",
|
|
79
|
+
"Use Load tables to import an existing view": "Use Load tables to import an existing view",
|
|
80
|
+
"Delete one field at a time": "Delete one field at a time",
|
|
81
|
+
"Field {{name}} is referenced by another field": "Field {{name}} is referenced by another field",
|
|
82
|
+
"Field name is required": "Field name is required",
|
|
83
|
+
"Field name and type are required": "Field name and type are required",
|
|
84
|
+
"A generated field cannot also have a default value": "A generated field cannot also have a default value",
|
|
85
|
+
"Field {{name}} cannot change generated-id or primary-key settings": "Field {{name}} cannot change generated-id or primary-key settings",
|
|
86
|
+
"Field {{name}} does not exist": "Field {{name}} does not exist",
|
|
87
|
+
"Field {{name}} already exists": "Field {{name}} already exists",
|
|
88
|
+
"Field {{name}} is referenced by {{collection}}.{{field}}": "Field {{name}} is referenced by {{collection}}.{{field}}",
|
|
89
|
+
"Field {{name}} cannot be changed between a relation and a physical column": "Field {{name}} cannot be changed between a relation and a physical column",
|
|
90
|
+
"Relation field {{name}} requires a target": "Relation field {{name}} requires a target",
|
|
91
|
+
"Field type {{type}} does not represent a PostgreSQL column": "Field type {{type}} does not represent a PostgreSQL column",
|
|
92
|
+
"Cannot determine PostgreSQL type for field {{name}}": "Cannot determine PostgreSQL type for field {{name}}",
|
|
93
|
+
"Unsupported PostgreSQL default value": "Unsupported PostgreSQL default value",
|
|
94
|
+
"Invalid PostgreSQL foreign key action": "Invalid PostgreSQL foreign key action",
|
|
95
|
+
"Target column {{collection}}.{{field}} does not exist": "Target column {{collection}}.{{field}} does not exist",
|
|
96
|
+
"Conflicting foreign key exists for {{collection}}.{{field}}": "Conflicting foreign key exists for {{collection}}.{{field}}",
|
|
97
|
+
"Invalid PostgreSQL port": "Invalid PostgreSQL port",
|
|
98
|
+
"Test connection failed: {{reason}}": "Test connection failed: {{reason}}",
|
|
99
|
+
"Data source {{name}} does not exist": "Data source {{name}} does not exist",
|
|
100
|
+
"A tree collection requires one primary key": "A tree collection requires one primary key",
|
|
101
|
+
"Cycle detected in tree collection {{name}}": "Cycle detected in tree collection {{name}}",
|
|
102
|
+
"Tree parent changes require a transaction": "Tree parent changes require a transaction",
|
|
103
|
+
"Bulk changes to a tree parent require individual hooks": "Bulk changes to a tree parent require individual hooks",
|
|
104
|
+
"SQL collection queries require a read-only transaction": "SQL collection queries require a read-only transaction",
|
|
105
|
+
"SQL query is required": "SQL query is required",
|
|
106
|
+
"SQL query cannot be empty": "SQL query cannot be empty",
|
|
107
|
+
"Invalid or unsupported SQL syntax": "Invalid or unsupported SQL syntax",
|
|
108
|
+
"Only SELECT statements or WITH clauses are supported": "Only SELECT statements or WITH clauses are supported",
|
|
109
|
+
"SQL statement contains dangerous keyword: {{keyword}}": "SQL statement contains dangerous keyword: {{keyword}}",
|
|
110
|
+
"Multiple SQL statements are not allowed": "Multiple SQL statements are not allowed",
|
|
111
|
+
"Only SQL collections can update SQL queries": "Only SQL collections can update SQL queries",
|
|
112
|
+
"Join table {{name}} cannot match source or target collection": "Join table {{name}} cannot match source or target collection",
|
|
113
|
+
"Many-to-many foreign key and other key must be different": "Many-to-many foreign key and other key must be different",
|
|
114
|
+
"Cancel": "Cancel",
|
|
115
|
+
"Submit": "Submit",
|
|
116
|
+
"ID": "ID",
|
|
117
|
+
"Description": "Description",
|
|
118
|
+
"Please input collection name": "Please input collection name",
|
|
119
|
+
"Must start with a letter and can only contain letters, numbers, and underscores": "Must start with a letter and can only contain letters, numbers, and underscores",
|
|
120
|
+
"Use letters, numbers and underscores, must start with a letter. Example: users, products, orders": "Use letters, numbers and underscores, must start with a letter. Example: users, products, orders",
|
|
121
|
+
"Use letters, numbers and underscores, must start with a letter. Example: events, meetings, tasks": "Use letters, numbers and underscores, must start with a letter. Example: events, meetings, tasks",
|
|
122
|
+
"Use letters, numbers and underscores, must start with a letter. Example: documents, images, attachments": "Use letters, numbers and underscores, must start with a letter. Example: documents, images, attachments",
|
|
123
|
+
"Use letters, numbers and underscores, must start with a letter. Example: analytics, reports, queries": "Use letters, numbers and underscores, must start with a letter. Example: analytics, reports, queries",
|
|
124
|
+
"Use letters, numbers and underscores, must start with a letter. Example: categories, departments": "Use letters, numbers and underscores, must start with a letter. Example: categories, departments",
|
|
125
|
+
"Preset fields": "Preset fields",
|
|
126
|
+
"Select default fields to include in this collection": "Select default fields to include in this collection",
|
|
127
|
+
"ID - Primary key (auto-increment)": "ID - Primary key (auto-increment)",
|
|
128
|
+
"Created At - Timestamp when record is created": "Created At - Timestamp when record is created",
|
|
129
|
+
"Updated At - Timestamp when record is updated": "Updated At - Timestamp when record is updated",
|
|
130
|
+
"Collections used for calendar events, with start and end date fields": "Collections used for calendar events, with start and end date fields",
|
|
131
|
+
"Collections for storing file metadata and attachments": "Collections for storing file metadata and attachments",
|
|
132
|
+
"Collections created from custom SQL queries, read-only by default": "Collections created from custom SQL queries, read-only by default",
|
|
133
|
+
"Collections organized in parent-child tree structure, like categories, departments, etc": "Collections organized in parent-child tree structure, like categories, departments, etc",
|
|
134
|
+
"SELECT * FROM your_table WHERE ...": "SELECT * FROM your_table WHERE ...",
|
|
135
|
+
"Custom SQL query to retrieve data. Must be a SELECT statement. The collection will be read-only.": "Custom SQL query to retrieve data. Must be a SELECT statement. The collection will be read-only.",
|
|
136
|
+
"Query columns": "Query columns",
|
|
137
|
+
"Column name": "Column name",
|
|
138
|
+
"Column name is required": "Column name is required",
|
|
139
|
+
"Foreign key {{foreignKey}} cannot have the same name as relation field {{name}}": "Foreign key {{foreignKey}} cannot have the same name as relation field {{name}}",
|
|
140
|
+
"Foreign key {{collection}}.{{field}} has incompatible PostgreSQL type {{type}}": "Foreign key {{collection}}.{{field}} has incompatible PostgreSQL type {{type}}"
|
|
141
|
+
}
|