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.
Files changed (63) hide show
  1. package/README.md +9 -3
  2. package/client-v2.js +1 -0
  3. package/client.js +1 -0
  4. package/dist/client/index.js +10 -0
  5. package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
  6. package/dist/client-v2/index.js +10 -0
  7. package/dist/constants.js +45 -0
  8. package/dist/externalVersion.js +29 -0
  9. package/dist/locale/en-US.json +141 -0
  10. package/dist/locale/zh-CN.json +141 -0
  11. package/dist/server/collections/adjacency-list-repository.js +340 -0
  12. package/dist/server/collections/index.js +45 -0
  13. package/dist/server/collections/sql-collection.js +84 -0
  14. package/dist/server/collections/sql-model.js +149 -0
  15. package/dist/server/collections/tree-collection.js +118 -0
  16. package/dist/server/hooks/field-hooks.js +412 -0
  17. package/dist/server/index.js +38 -0
  18. package/dist/server/plugin.js +1273 -0
  19. package/dist/server/postgres-collection-manager.js +868 -0
  20. package/dist/server/postgres-datasource.js +361 -0
  21. package/dist/server/utils/sql-validator.js +253 -0
  22. package/dist/server/utils/validation-error.js +59 -0
  23. package/package.json +51 -4
  24. package/server.js +1 -0
  25. package/src/client/AddCollectionAction.tsx +307 -0
  26. package/src/client/ConfigurationForm.tsx +203 -0
  27. package/src/client/PostgresCollectionTemplate.tsx +109 -0
  28. package/src/client/__tests__/client-v1.test.tsx +265 -0
  29. package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
  30. package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
  31. package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
  32. package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
  33. package/src/client/collection-templates/base-template-helper.ts +62 -0
  34. package/src/client/collection-templates/field-interfaces-config.ts +73 -0
  35. package/src/client/collection-templates/index.ts +19 -0
  36. package/src/client/index.tsx +69 -0
  37. package/src/client-v2/PostgresAddCollection.tsx +422 -0
  38. package/src/client-v2/PostgresConfigForm.tsx +178 -0
  39. package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
  40. package/src/client-v2/__tests__/plugin.test.tsx +372 -0
  41. package/src/client-v2/collection-options.ts +22 -0
  42. package/src/client-v2/index.tsx +10 -0
  43. package/src/client-v2/plugin.tsx +71 -0
  44. package/src/constants.ts +20 -0
  45. package/src/locale/en-US.json +141 -0
  46. package/src/locale/zh-CN.json +141 -0
  47. package/src/server/__tests__/field-hooks.test.ts +357 -0
  48. package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
  49. package/src/server/__tests__/postgres-datasource.unit.test.ts +2423 -0
  50. package/src/server/__tests__/sql-model.test.ts +159 -0
  51. package/src/server/__tests__/sql-validator.test.ts +126 -0
  52. package/src/server/collections/adjacency-list-repository.ts +378 -0
  53. package/src/server/collections/index.ts +19 -0
  54. package/src/server/collections/sql-collection.ts +66 -0
  55. package/src/server/collections/sql-model.ts +158 -0
  56. package/src/server/collections/tree-collection.ts +102 -0
  57. package/src/server/hooks/field-hooks.ts +548 -0
  58. package/src/server/index.ts +13 -0
  59. package/src/server/plugin.ts +1499 -0
  60. package/src/server/postgres-collection-manager.ts +1027 -0
  61. package/src/server/postgres-datasource.ts +410 -0
  62. package/src/server/utils/sql-validator.ts +258 -0
  63. package/src/server/utils/validation-error.ts +38 -0
@@ -0,0 +1,422 @@
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, { useState } from 'react';
11
+ import { App, Button, Checkbox, Drawer, Dropdown, Form, Input, Modal, Select, Space } from 'antd';
12
+ import { DeleteOutlined, DownOutlined, PlusOutlined } from '@ant-design/icons';
13
+ import { useFlowContext } from '@nocobase/flow-engine';
14
+ import type { DataSourceCollectionActionProps } from '@nocobase/plugin-data-source-manager/client-v2';
15
+ import { useTranslation } from 'react-i18next';
16
+ import { NAMESPACE } from '../constants';
17
+ import { toCollectionOptions } from './collection-options';
18
+
19
+ interface CollectionFormValues {
20
+ name: string;
21
+ title: string;
22
+ timestamps: boolean;
23
+ template: 'general' | 'calendar' | 'file' | 'tree' | 'sql';
24
+ sql?: string;
25
+ sqlFields?: Array<{ name: string; type: SqlFieldType }>;
26
+ }
27
+
28
+ type SqlFieldType = 'string' | 'text' | 'integer' | 'bigInt' | 'decimal' | 'boolean' | 'date' | 'json' | 'uuid';
29
+
30
+ const SQL_FIELD_INTERFACES: Record<SqlFieldType, string> = {
31
+ string: 'input',
32
+ text: 'textarea',
33
+ integer: 'integer',
34
+ bigInt: 'integer',
35
+ decimal: 'number',
36
+ boolean: 'checkbox',
37
+ date: 'datetime',
38
+ json: 'json',
39
+ uuid: 'uuid',
40
+ };
41
+
42
+ interface CollectionField {
43
+ name: string;
44
+ type: string;
45
+ interface: string;
46
+ primaryKey?: boolean;
47
+ autoIncrement?: boolean;
48
+ allowNull?: boolean;
49
+ field?: string;
50
+ target?: string;
51
+ foreignKey?: string;
52
+ targetKey?: string;
53
+ sourceKey?: string;
54
+ treeParent?: boolean;
55
+ treeChildren?: boolean;
56
+ uiSchema?: Record<string, unknown>;
57
+ }
58
+
59
+ export function PostgresAddCollection({ dataSourceKey, onSubmitted, children }: DataSourceCollectionActionProps) {
60
+ const { t } = useTranslation(NAMESPACE);
61
+ const ctx = useFlowContext();
62
+ const { notification } = App.useApp();
63
+ const [form] = Form.useForm<CollectionFormValues>();
64
+ const template = Form.useWatch('template', form);
65
+ const [creating, setCreating] = useState(false);
66
+ const [loadingTables, setLoadingTables] = useState(false);
67
+ const [submitting, setSubmitting] = useState(false);
68
+ const [createOpen, setCreateOpen] = useState(false);
69
+ const [loadOpen, setLoadOpen] = useState(false);
70
+ const [tables, setTables] = useState<{ label: string; value: string }[]>([]);
71
+ const [selectedTables, setSelectedTables] = useState<string[]>([]);
72
+
73
+ const refresh = async () => {
74
+ await ctx.dataSourceManager.getDataSource(dataSourceKey)?.reload();
75
+ onSubmitted?.();
76
+ };
77
+
78
+ const createCollection = async (values: CollectionFormValues) => {
79
+ const isSql = values.template === 'sql';
80
+ const fields: CollectionField[] = isSql
81
+ ? (values.sqlFields || []).map(({ name, type }) => ({
82
+ name: name.trim(),
83
+ type,
84
+ interface: SQL_FIELD_INTERFACES[type],
85
+ }))
86
+ : [{ name: 'id', type: 'bigInt', interface: 'id', primaryKey: true, autoIncrement: true, allowNull: false }];
87
+ if (values.template === 'calendar') {
88
+ fields.push(
89
+ {
90
+ name: 'title',
91
+ type: 'string',
92
+ interface: 'input',
93
+ uiSchema: {
94
+ title: `{{t("Title", { ns: "${NAMESPACE}" })}}`,
95
+ type: 'string',
96
+ 'x-component': 'Input',
97
+ },
98
+ },
99
+ {
100
+ name: 'start',
101
+ type: 'date',
102
+ interface: 'datetime',
103
+ uiSchema: {
104
+ title: `{{t("Start date", { ns: "${NAMESPACE}" })}}`,
105
+ type: 'datetime',
106
+ 'x-component': 'DatePicker',
107
+ 'x-component-props': { showTime: true },
108
+ },
109
+ },
110
+ {
111
+ name: 'end',
112
+ type: 'date',
113
+ interface: 'datetime',
114
+ uiSchema: {
115
+ title: `{{t("End date", { ns: "${NAMESPACE}" })}}`,
116
+ type: 'datetime',
117
+ 'x-component': 'DatePicker',
118
+ 'x-component-props': { showTime: true },
119
+ },
120
+ },
121
+ );
122
+ }
123
+ if (values.template === 'file') {
124
+ fields.push(
125
+ {
126
+ name: 'filename',
127
+ type: 'string',
128
+ interface: 'input',
129
+ uiSchema: {
130
+ title: `{{t("Filename", { ns: "${NAMESPACE}" })}}`,
131
+ type: 'string',
132
+ 'x-component': 'Input',
133
+ },
134
+ },
135
+ {
136
+ name: 'title',
137
+ type: 'string',
138
+ interface: 'input',
139
+ uiSchema: {
140
+ title: `{{t("Title", { ns: "${NAMESPACE}" })}}`,
141
+ type: 'string',
142
+ 'x-component': 'Input',
143
+ },
144
+ },
145
+ {
146
+ name: 'url',
147
+ type: 'string',
148
+ interface: 'url',
149
+ uiSchema: {
150
+ title: `{{t("URL", { ns: "${NAMESPACE}" })}}`,
151
+ type: 'string',
152
+ 'x-component': 'Input.URL',
153
+ },
154
+ },
155
+ {
156
+ name: 'mimetype',
157
+ type: 'string',
158
+ interface: 'input',
159
+ uiSchema: {
160
+ title: `{{t("MIME type", { ns: "${NAMESPACE}" })}}`,
161
+ type: 'string',
162
+ 'x-component': 'Input',
163
+ },
164
+ },
165
+ {
166
+ name: 'size',
167
+ type: 'bigInt',
168
+ interface: 'integer',
169
+ uiSchema: {
170
+ title: `{{t("File size", { ns: "${NAMESPACE}" })}}`,
171
+ type: 'number',
172
+ 'x-component': 'InputNumber',
173
+ },
174
+ },
175
+ );
176
+ }
177
+ if (values.template === 'tree') {
178
+ fields.push(
179
+ {
180
+ name: 'name',
181
+ type: 'string',
182
+ interface: 'input',
183
+ uiSchema: {
184
+ title: `{{t("Name", { ns: "${NAMESPACE}" })}}`,
185
+ type: 'string',
186
+ 'x-component': 'Input',
187
+ },
188
+ },
189
+ { name: 'parentId', type: 'bigInt', interface: 'integer' },
190
+ {
191
+ name: 'parent',
192
+ type: 'belongsTo',
193
+ interface: 'm2o',
194
+ target: values.name,
195
+ foreignKey: 'parentId',
196
+ targetKey: 'id',
197
+ treeParent: true,
198
+ },
199
+ {
200
+ name: 'children',
201
+ type: 'hasMany',
202
+ interface: 'o2m',
203
+ target: values.name,
204
+ foreignKey: 'parentId',
205
+ sourceKey: 'id',
206
+ treeChildren: true,
207
+ },
208
+ );
209
+ }
210
+ if (!isSql && values.timestamps) {
211
+ fields.push(
212
+ { name: 'createdAt', type: 'date', interface: 'createdAt', field: 'createdAt' },
213
+ { name: 'updatedAt', type: 'date', interface: 'updatedAt', field: 'updatedAt' },
214
+ );
215
+ }
216
+ setCreating(true);
217
+ try {
218
+ await ctx.api.request({
219
+ url: `dataSources/${encodeURIComponent(dataSourceKey)}/collections:create`,
220
+ method: 'post',
221
+ data: {
222
+ name: values.name,
223
+ title: values.title,
224
+ template: values.template,
225
+ autoGenId: !isSql,
226
+ createdAt: !isSql && values.timestamps,
227
+ updatedAt: !isSql && values.timestamps,
228
+ createdBy: false,
229
+ updatedBy: false,
230
+ fields,
231
+ ...(values.template === 'tree' ? { tree: 'parentId' } : {}),
232
+ ...(isSql ? { sql: values.sql } : {}),
233
+ },
234
+ });
235
+ setCreateOpen(false);
236
+ form.resetFields();
237
+ await refresh();
238
+ } catch (error) {
239
+ notification.error({ message: String(t('Failed to create collection')), description: getErrorMessage(error) });
240
+ } finally {
241
+ setCreating(false);
242
+ }
243
+ };
244
+
245
+ const openTables = async () => {
246
+ setSelectedTables([]);
247
+ setTables([]);
248
+ setLoadOpen(true);
249
+ setLoadingTables(true);
250
+ try {
251
+ const response = await ctx.api.resource('dataSources').readTables({ values: { dataSourceKey } });
252
+ setTables(toCollectionOptions(response.data));
253
+ } catch (error) {
254
+ notification.error({ message: String(t('Unable to load collections')), description: getErrorMessage(error) });
255
+ } finally {
256
+ setLoadingTables(false);
257
+ }
258
+ };
259
+
260
+ const loadTables = async () => {
261
+ if (!selectedTables.length) return;
262
+ setSubmitting(true);
263
+ try {
264
+ await ctx.api.resource('dataSources').loadTables({ values: { dataSourceKey, tables: selectedTables } });
265
+ setLoadOpen(false);
266
+ await refresh();
267
+ } catch (error) {
268
+ notification.error({ message: String(t('Unable to load collections')), description: getErrorMessage(error) });
269
+ } finally {
270
+ setSubmitting(false);
271
+ }
272
+ };
273
+
274
+ return (
275
+ <>
276
+ <Dropdown
277
+ menu={{
278
+ items: [
279
+ { key: 'create', label: t('Create collection') },
280
+ { key: 'load', label: t('Load existing tables and views') },
281
+ ],
282
+ onClick: ({ key }) => {
283
+ if (key === 'create') setCreateOpen(true);
284
+ if (key === 'load') openTables();
285
+ },
286
+ }}
287
+ >
288
+ <Button icon={<PlusOutlined />}>
289
+ {children || t('Add collection')} <DownOutlined />
290
+ </Button>
291
+ </Dropdown>
292
+ <Drawer
293
+ open={createOpen}
294
+ title={t('Create collection')}
295
+ onClose={() => setCreateOpen(false)}
296
+ extra={
297
+ <Button type="primary" loading={creating} onClick={() => form.submit()}>
298
+ {t('Create')}
299
+ </Button>
300
+ }
301
+ destroyOnClose
302
+ >
303
+ <Form
304
+ form={form}
305
+ layout="vertical"
306
+ onFinish={createCollection}
307
+ initialValues={{ timestamps: true, template: 'general', sqlFields: [{ name: '', type: 'string' }] }}
308
+ >
309
+ <Form.Item name="template" label={t('Collection template')} rules={[{ required: true }]}>
310
+ <Select
311
+ options={[
312
+ { value: 'general', label: t('General collection') },
313
+ { value: 'calendar', label: t('Calendar collection') },
314
+ { value: 'file', label: t('File collection') },
315
+ { value: 'tree', label: t('Tree collection') },
316
+ { value: 'sql', label: t('SQL collection') },
317
+ ]}
318
+ />
319
+ </Form.Item>
320
+ <Form.Item name="name" label={t('Collection name')} rules={[{ required: true }]}>
321
+ <Input />
322
+ </Form.Item>
323
+ <Form.Item name="title" label={t('Collection display name')} rules={[{ required: true }]}>
324
+ <Input />
325
+ </Form.Item>
326
+ {template === 'sql' ? (
327
+ <>
328
+ <Form.Item
329
+ name="sql"
330
+ label={t('SQL query')}
331
+ extra={t('Use a SELECT query. SQL collections are read-only.')}
332
+ rules={[{ required: true, whitespace: true }]}
333
+ >
334
+ <Input.TextArea autoSize={{ minRows: 5, maxRows: 12 }} />
335
+ </Form.Item>
336
+ <Form.List
337
+ name="sqlFields"
338
+ rules={[
339
+ {
340
+ validator: async (_, fields: Array<{ name?: string }> = []) => {
341
+ if (!fields.length) throw new Error(String(t('Add at least one query column')));
342
+ const names = fields.map((field) => field?.name?.trim()).filter(Boolean);
343
+ if (new Set(names).size !== names.length)
344
+ throw new Error(String(t('Column names must be unique')));
345
+ },
346
+ },
347
+ ]}
348
+ >
349
+ {(fields, { add, remove }, { errors }) => (
350
+ <>
351
+ {fields.map((field, index) => (
352
+ <Space key={field.key} align="start" style={{ display: 'flex' }}>
353
+ <Form.Item name={[field.name, 'name']} rules={[{ required: true, whitespace: true }]}>
354
+ <Input aria-label={String(t('Column name {{number}}', { number: index + 1 }))} />
355
+ </Form.Item>
356
+ <Form.Item name={[field.name, 'type']} rules={[{ required: true }]}>
357
+ <Select
358
+ aria-label={String(t('Column type {{number}}', { number: index + 1 }))}
359
+ style={{ width: 150 }}
360
+ options={[
361
+ { value: 'string', label: t('Text') },
362
+ { value: 'text', label: t('Long text') },
363
+ { value: 'integer', label: t('Integer') },
364
+ { value: 'bigInt', label: t('Big integer') },
365
+ { value: 'decimal', label: t('Decimal') },
366
+ { value: 'boolean', label: t('Boolean') },
367
+ { value: 'date', label: t('Date and time') },
368
+ { value: 'json', label: t('JSON') },
369
+ { value: 'uuid', label: t('UUID') },
370
+ ]}
371
+ />
372
+ </Form.Item>
373
+ <Button
374
+ aria-label={String(t('Remove query column {{number}}', { number: index + 1 }))}
375
+ icon={<DeleteOutlined />}
376
+ onClick={() => remove(field.name)}
377
+ />
378
+ </Space>
379
+ ))}
380
+ <Form.ErrorList errors={errors} />
381
+ <Button type="dashed" icon={<PlusOutlined />} onClick={() => add({ name: '', type: 'string' })}>
382
+ {t('Add query column')}
383
+ </Button>
384
+ </>
385
+ )}
386
+ </Form.List>
387
+ </>
388
+ ) : (
389
+ <Form.Item name="timestamps" valuePropName="checked">
390
+ <Checkbox>{t('Create timestamp fields')}</Checkbox>
391
+ </Form.Item>
392
+ )}
393
+ </Form>
394
+ </Drawer>
395
+ <Modal
396
+ open={loadOpen}
397
+ title={t('Load existing tables and views')}
398
+ okText={t('Load')}
399
+ okButtonProps={{ disabled: !selectedTables.length || loadingTables }}
400
+ confirmLoading={submitting}
401
+ onOk={loadTables}
402
+ onCancel={() => setLoadOpen(false)}
403
+ >
404
+ <Select
405
+ aria-label={String(t('Collections'))}
406
+ mode="multiple"
407
+ allowClear
408
+ loading={loadingTables}
409
+ options={tables}
410
+ optionFilterProp="label"
411
+ value={selectedTables}
412
+ onChange={setSelectedTables}
413
+ style={{ width: '100%' }}
414
+ />
415
+ </Modal>
416
+ </>
417
+ );
418
+ }
419
+
420
+ function getErrorMessage(error: unknown): string | undefined {
421
+ return error instanceof Error ? error.message : undefined;
422
+ }
@@ -0,0 +1,178 @@
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, { useCallback, useEffect, useRef, useState } from 'react';
11
+ import { Checkbox, Form, Input, InputNumber, Select } from 'antd';
12
+ import { useFlowContext } from '@nocobase/flow-engine';
13
+ import type { DataSourceSettingsFormProps } from '@nocobase/plugin-data-source-manager/client-v2';
14
+ import { useTranslation } from 'react-i18next';
15
+ import { DATA_SOURCE_TYPE, DEFAULT_PORT, DEFAULT_SCHEMA, NAMESPACE } from '../constants';
16
+ import { toCollectionOptions } from './collection-options';
17
+
18
+ const CONNECTION_FIELDS = ['host', 'port', 'database', 'schema', 'username', 'password', 'ssl', 'sslCa'] as const;
19
+
20
+ function normalizeConnectionField(field: (typeof CONNECTION_FIELDS)[number], options?: Record<string, unknown>) {
21
+ const value = options?.[field];
22
+ if (field === 'port') return Number(value ?? DEFAULT_PORT);
23
+ if (field === 'schema') return typeof value === 'string' && value ? value : DEFAULT_SCHEMA;
24
+ if (field === 'ssl') return Boolean(value);
25
+ if (field === 'sslCa') return value ?? '';
26
+ return value;
27
+ }
28
+
29
+ export default function PostgresConfigForm({ mode, initialValues, loadCollections }: DataSourceSettingsFormProps) {
30
+ const { t } = useTranslation(NAMESPACE);
31
+ const ctx = useFlowContext();
32
+ const form = Form.useFormInstance();
33
+ const watchedAddAll = Form.useWatch(['options', 'addAllCollections'], form);
34
+ const host = Form.useWatch(['options', 'host'], form);
35
+ const port = Form.useWatch(['options', 'port'], form);
36
+ const database = Form.useWatch(['options', 'database'], form);
37
+ const schema = Form.useWatch(['options', 'schema'], form);
38
+ const username = Form.useWatch(['options', 'username'], form);
39
+ const password = Form.useWatch(['options', 'password'], form);
40
+ const ssl = Form.useWatch(['options', 'ssl'], form);
41
+ const sslCa = Form.useWatch(['options', 'sslCa'], form);
42
+ const [collectionOptions, setCollectionOptions] = useState<{ label: string; value: string }[]>([]);
43
+ const [loading, setLoading] = useState(false);
44
+ const requestGeneration = useRef(0);
45
+ const cachedConnection = useRef<unknown[]>();
46
+ const hasLoaded = useRef(false);
47
+ const isLoading = useRef(false);
48
+ const savedSelection = initialValues?.options?.selectedCollections;
49
+ const initialAddAll = initialValues?.options?.addAllCollections ?? initialValues?.options?.autoDiscover !== false;
50
+ const addAllCollections = watchedAddAll ?? initialAddAll;
51
+ const preserveLegacySelection = mode === 'edit' && !initialAddAll && !Array.isArray(savedSelection);
52
+
53
+ useEffect(() => {
54
+ if (form.getFieldValue(['options', 'host']) === undefined) {
55
+ form.setFieldValue(['options', 'host'], 'localhost');
56
+ }
57
+ if (form.getFieldValue(['options', 'port']) === undefined) {
58
+ form.setFieldValue(['options', 'port'], DEFAULT_PORT);
59
+ }
60
+ if (form.getFieldValue(['options', 'schema']) === undefined) {
61
+ form.setFieldValue(['options', 'schema'], DEFAULT_SCHEMA);
62
+ }
63
+ if (form.getFieldValue(['options', 'ssl']) === undefined) {
64
+ form.setFieldValue(['options', 'ssl'], false);
65
+ }
66
+ if (form.getFieldValue(['options', 'addAllCollections']) === undefined) {
67
+ form.setFieldValue(['options', 'addAllCollections'], initialAddAll);
68
+ }
69
+ if (form.getFieldValue('__postgresPreserveLegacySelection') === undefined) {
70
+ form.setFieldValue('__postgresPreserveLegacySelection', preserveLegacySelection);
71
+ }
72
+ if (mode === 'edit' && Array.isArray(savedSelection) && form.getFieldValue('collections') === undefined) {
73
+ form.setFieldValue('collections', savedSelection);
74
+ }
75
+ }, [form, initialAddAll, mode, preserveLegacySelection, savedSelection]);
76
+
77
+ useEffect(() => {
78
+ requestGeneration.current += 1;
79
+ cachedConnection.current = undefined;
80
+ hasLoaded.current = false;
81
+ isLoading.current = false;
82
+ setCollectionOptions([]);
83
+ setLoading(false);
84
+ }, [host, port, database, schema, username, password, ssl, sslCa]);
85
+
86
+ const handleLoadCollections = useCallback(async () => {
87
+ const values = form.getFieldsValue(true);
88
+ const connection = [
89
+ values.key,
90
+ ...CONNECTION_FIELDS.map((field) => normalizeConnectionField(field, values.options)),
91
+ ];
92
+ const sameConnection = cachedConnection.current?.every((value, index) => value === connection[index]);
93
+ if (sameConnection && (hasLoaded.current || isLoading.current)) return;
94
+ if (!sameConnection) {
95
+ requestGeneration.current += 1;
96
+ cachedConnection.current = connection;
97
+ hasLoaded.current = false;
98
+ }
99
+ const generation = requestGeneration.current;
100
+ isLoading.current = true;
101
+ setLoading(true);
102
+ try {
103
+ const connectionChanged = CONNECTION_FIELDS.some(
104
+ (field) =>
105
+ normalizeConnectionField(field, values.options) !== normalizeConnectionField(field, initialValues?.options),
106
+ );
107
+ const result =
108
+ mode === 'create' || connectionChanged
109
+ ? (
110
+ await ctx.api.resource('dataSources').readTables({
111
+ values: { dataSourceKey: values.key, dbOptions: { ...values.options, type: DATA_SOURCE_TYPE } },
112
+ })
113
+ ).data
114
+ : await loadCollections(String(initialValues?.key));
115
+ if (generation === requestGeneration.current) {
116
+ setCollectionOptions(toCollectionOptions(result));
117
+ hasLoaded.current = true;
118
+ }
119
+ } catch {
120
+ if (generation === requestGeneration.current) ctx.message.error(String(t('Unable to load collections')));
121
+ } finally {
122
+ if (generation === requestGeneration.current) {
123
+ isLoading.current = false;
124
+ setLoading(false);
125
+ }
126
+ }
127
+ }, [ctx, form, initialValues, loadCollections, mode, t]);
128
+
129
+ return (
130
+ <>
131
+ <Form.Item name={['options', 'host']} label={t('Host')} rules={[{ required: true }]}>
132
+ <Input />
133
+ </Form.Item>
134
+ <Form.Item name={['options', 'port']} label={t('Port')} rules={[{ required: true }]}>
135
+ <InputNumber min={1} max={65535} style={{ width: '100%' }} />
136
+ </Form.Item>
137
+ <Form.Item name={['options', 'database']} label={t('Database')} rules={[{ required: true }]}>
138
+ <Input />
139
+ </Form.Item>
140
+ <Form.Item name={['options', 'schema']} label={t('Schema')}>
141
+ <Input />
142
+ </Form.Item>
143
+ <Form.Item name={['options', 'username']} label={t('Username')} rules={[{ required: true }]}>
144
+ <Input />
145
+ </Form.Item>
146
+ <Form.Item name={['options', 'password']} label={t('Password')}>
147
+ <Input.Password />
148
+ </Form.Item>
149
+ <Form.Item name={['options', 'ssl']} label={t('Use SSL')} valuePropName="checked">
150
+ <Checkbox />
151
+ </Form.Item>
152
+ {ssl ? (
153
+ <Form.Item name={['options', 'sslCa']} label={t('CA certificate (PEM)')}>
154
+ <Input.TextArea autoSize={{ minRows: 3, maxRows: 8 }} />
155
+ </Form.Item>
156
+ ) : null}
157
+ <Form.Item name={['options', 'addAllCollections']} label={t('Load all collections')} valuePropName="checked">
158
+ <Checkbox />
159
+ </Form.Item>
160
+ <Form.Item name="__postgresPreserveLegacySelection" hidden>
161
+ <Input />
162
+ </Form.Item>
163
+ {!addAllCollections ? (
164
+ <Form.Item name="collections" label={t('Collections')}>
165
+ <Select
166
+ mode="multiple"
167
+ allowClear
168
+ loading={loading}
169
+ options={collectionOptions}
170
+ optionFilterProp="label"
171
+ onFocus={handleLoadCollections}
172
+ onChange={() => form.setFieldValue('__postgresPreserveLegacySelection', false)}
173
+ />
174
+ </Form.Item>
175
+ ) : null}
176
+ </>
177
+ );
178
+ }
@@ -0,0 +1,83 @@
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, { useState } from 'react';
11
+ import { App, Button, Checkbox, Modal } from 'antd';
12
+ import { useFlowContext } from '@nocobase/flow-engine';
13
+ import type { DataSourceCollectionActionProps } from '@nocobase/plugin-data-source-manager/client-v2';
14
+ import { useTranslation } from 'react-i18next';
15
+ import { NAMESPACE } from '../constants';
16
+
17
+ export function PostgresDeleteCollection({
18
+ dataSourceKey,
19
+ record,
20
+ selectedRowKeys,
21
+ onSubmitted,
22
+ children,
23
+ isBulk,
24
+ }: DataSourceCollectionActionProps) {
25
+ const { t } = useTranslation(NAMESPACE);
26
+ const ctx = useFlowContext();
27
+ const { notification } = App.useApp();
28
+ const [open, setOpen] = useState(false);
29
+ const [pending, setPending] = useState(false);
30
+ const [cascade, setCascade] = useState(false);
31
+ const keys = isBulk ? selectedRowKeys || [] : record?.name ? [record.name] : [];
32
+
33
+ const submit = async () => {
34
+ if (!keys.length) return;
35
+ setPending(true);
36
+ try {
37
+ await ctx.api.request({
38
+ url: `dataSources/${encodeURIComponent(dataSourceKey)}/collections:destroy`,
39
+ method: 'post',
40
+ params: { filterByTk: keys, cascade },
41
+ });
42
+ setOpen(false);
43
+ await ctx.dataSourceManager.getDataSource(dataSourceKey)?.reload();
44
+ onSubmitted?.();
45
+ } catch (error) {
46
+ notification.error({
47
+ message: String(t('Failed to delete collection')),
48
+ description: error instanceof Error ? error.message : undefined,
49
+ });
50
+ } finally {
51
+ setPending(false);
52
+ }
53
+ };
54
+
55
+ return (
56
+ <>
57
+ <Button
58
+ type={isBulk ? 'default' : 'link'}
59
+ danger
60
+ disabled={!keys.length}
61
+ onClick={() => {
62
+ setCascade(false);
63
+ setOpen(true);
64
+ }}
65
+ >
66
+ {children || t('Delete')}
67
+ </Button>
68
+ <Modal
69
+ open={open}
70
+ title={t('Delete collection')}
71
+ confirmLoading={pending}
72
+ okButtonProps={{ danger: true }}
73
+ onOk={submit}
74
+ onCancel={() => setOpen(false)}
75
+ >
76
+ <p>{t('Delete the selected collection and its PostgreSQL table or view?')}</p>
77
+ <Checkbox checked={cascade} onChange={(event) => setCascade(event.target.checked)}>
78
+ {t('Also drop dependent PostgreSQL objects')}
79
+ </Checkbox>
80
+ </Modal>
81
+ </>
82
+ );
83
+ }