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,1538 @@
|
|
|
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 { DataSourceManager } from '@nocobase/data-source-manager';
|
|
11
|
+
import { Database, Model, Repository } from '@nocobase/database';
|
|
12
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
13
|
+
import { DATA_SOURCE_TYPE, NAMESPACE } from '../../constants';
|
|
14
|
+
import { PostgresAdjacencyListRepository } from '../collections/adjacency-list-repository';
|
|
15
|
+
import { PostgresSQLCollection } from '../collections/sql-collection';
|
|
16
|
+
import { PostgresTreeCollection } from '../collections/tree-collection';
|
|
17
|
+
import { PluginDataSourcePostgresServer } from '../plugin';
|
|
18
|
+
import { PostgresDataSource } from '../postgres-datasource';
|
|
19
|
+
|
|
20
|
+
const sourcesToClose: PostgresDataSource[] = [];
|
|
21
|
+
|
|
22
|
+
function createDataSource(extra: Record<string, unknown> = {}) {
|
|
23
|
+
const ds = new PostgresDataSource({
|
|
24
|
+
name: 'pg-unit',
|
|
25
|
+
host: '127.0.0.1',
|
|
26
|
+
port: 5432,
|
|
27
|
+
database: 'sales',
|
|
28
|
+
username: 'postgres',
|
|
29
|
+
password: 'secret-password',
|
|
30
|
+
ssl: true,
|
|
31
|
+
sslCa: '-----BEGIN CERTIFICATE-----',
|
|
32
|
+
addAllCollections: false,
|
|
33
|
+
selectedCollections: ['orders'],
|
|
34
|
+
...extra,
|
|
35
|
+
});
|
|
36
|
+
sourcesToClose.push(ds);
|
|
37
|
+
return ds;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
afterEach(async () => {
|
|
41
|
+
while (sourcesToClose.length) {
|
|
42
|
+
const ds = sourcesToClose.pop();
|
|
43
|
+
if (ds) await ds.close();
|
|
44
|
+
}
|
|
45
|
+
vi.restoreAllMocks();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('PostgresDataSource unit behavior', () => {
|
|
49
|
+
it('returns null from publicOptions so secrets, hosts, certs, and tables are never exposed', () => {
|
|
50
|
+
const ds = createDataSource();
|
|
51
|
+
expect(ds.publicOptions()).toBeNull();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('batches identity and relkind queries in prepareTables instead of running N+1 queries', async () => {
|
|
55
|
+
const ds = createDataSource();
|
|
56
|
+
const querySpy = vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql) => {
|
|
57
|
+
const text = String(sql);
|
|
58
|
+
if (text.includes('information_schema.columns')) {
|
|
59
|
+
return [{ tableName: 'orders', name: 'id' }] as never;
|
|
60
|
+
}
|
|
61
|
+
if (text.includes('pg_catalog.pg_class')) {
|
|
62
|
+
return [
|
|
63
|
+
{ tableName: 'orders', kind: 'r' },
|
|
64
|
+
{ tableName: 'order_view', kind: 'v' },
|
|
65
|
+
{ tableName: 'order_mat_view', kind: 'm' },
|
|
66
|
+
] as never;
|
|
67
|
+
}
|
|
68
|
+
return [] as never;
|
|
69
|
+
});
|
|
70
|
+
vi.spyOn(ds.introspector, 'getCollection').mockImplementation(async ({ tableInfo }) => ({
|
|
71
|
+
name: tableInfo.tableName,
|
|
72
|
+
tableName: tableInfo.tableName,
|
|
73
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
74
|
+
}));
|
|
75
|
+
|
|
76
|
+
const prepared = await ds.prepareTables(['orders', 'order_view', 'order_mat_view']);
|
|
77
|
+
|
|
78
|
+
expect(querySpy).toHaveBeenCalledTimes(2);
|
|
79
|
+
expect(prepared.map((item) => item.name)).toEqual(['orders', 'order_view', 'order_mat_view']);
|
|
80
|
+
expect(prepared[0].fields?.[0]?.autoIncrement).toBe(true);
|
|
81
|
+
expect(prepared[1]).toMatchObject({ view: true, template: 'view', writableView: false });
|
|
82
|
+
expect(prepared[2]).toMatchObject({ view: true, template: 'view', writableView: false });
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('introspects materialized views via pg_catalog, sets filterTargetKey on views, and rejects matview collisions in createTable', async () => {
|
|
86
|
+
const ds = createDataSource();
|
|
87
|
+
const queryInterface = ds.collectionManager.db.sequelize.getQueryInterface();
|
|
88
|
+
vi.spyOn(queryInterface, 'describeTable').mockImplementation(async (tableName) => {
|
|
89
|
+
const name = typeof tableName === 'object' && tableName ? tableName.tableName : String(tableName);
|
|
90
|
+
if (name === 'transient_error_table') {
|
|
91
|
+
throw new Error('Connection terminated unexpectedly');
|
|
92
|
+
}
|
|
93
|
+
if (
|
|
94
|
+
name === 'order_mat_view' ||
|
|
95
|
+
name === 'bare_table' ||
|
|
96
|
+
name === 'restricted_table' ||
|
|
97
|
+
name === 'missing_table'
|
|
98
|
+
) {
|
|
99
|
+
throw new Error(`No description found for "${name}" table.`);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
id: {
|
|
103
|
+
type: 'BIGINT',
|
|
104
|
+
allowNull: true,
|
|
105
|
+
defaultValue: '',
|
|
106
|
+
primaryKey: false,
|
|
107
|
+
autoIncrement: false,
|
|
108
|
+
comment: null,
|
|
109
|
+
},
|
|
110
|
+
name: {
|
|
111
|
+
type: 'TEXT',
|
|
112
|
+
allowNull: true,
|
|
113
|
+
defaultValue: '',
|
|
114
|
+
primaryKey: false,
|
|
115
|
+
autoIncrement: false,
|
|
116
|
+
comment: null,
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const executedQueries: string[] = [];
|
|
122
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, queryOpts) => {
|
|
123
|
+
const text = String(sql);
|
|
124
|
+
executedQueries.push(text);
|
|
125
|
+
const tableName = (queryOpts as { replacements?: { tableName?: string } } | undefined)?.replacements?.tableName;
|
|
126
|
+
if (text.includes('is_identity')) return [] as never;
|
|
127
|
+
if (text.includes('SELECT c.relname AS "tableName", c.relkind AS kind')) {
|
|
128
|
+
return [
|
|
129
|
+
{ tableName: 'order_view', kind: 'v' },
|
|
130
|
+
{ tableName: 'order_mat_view', kind: 'm' },
|
|
131
|
+
{ tableName: 'bare_table', kind: 'r' },
|
|
132
|
+
] as never;
|
|
133
|
+
}
|
|
134
|
+
if (text.includes("c.relkind = 'm'") && text.includes('pg_catalog.pg_attribute')) {
|
|
135
|
+
if (tableName !== 'order_mat_view') return [] as never;
|
|
136
|
+
return [
|
|
137
|
+
{ name: 'id', type: 'BIGINT', elementType: null, allowNull: false, comment: null },
|
|
138
|
+
{ name: 'code', type: 'CHARACTER VARYING(64)', elementType: null, allowNull: false, comment: 'Order code' },
|
|
139
|
+
{ name: 'tags', type: 'ARRAY', elementType: 'text', allowNull: true, comment: null },
|
|
140
|
+
] as never;
|
|
141
|
+
}
|
|
142
|
+
if (text.includes('pg_catalog.pg_index') && text.includes('AS column_name')) {
|
|
143
|
+
expect(text).toContain('i.indisvalid AND i.indislive');
|
|
144
|
+
return (tableName === 'order_mat_view' ? [{ column_name: 'code', is_single_column: true }] : []) as never;
|
|
145
|
+
}
|
|
146
|
+
if (text.includes('pg_catalog.pg_index') && text.includes('AS "isValid"')) {
|
|
147
|
+
return [{ indexName: 'idx_bad', constraintName: null, isValid: false }] as never;
|
|
148
|
+
}
|
|
149
|
+
if (text.includes('AS empty')) {
|
|
150
|
+
if (tableName === 'bare_table') return [{ empty: true }] as never;
|
|
151
|
+
if (tableName === 'restricted_table') return [{ empty: false }] as never;
|
|
152
|
+
return [] as never;
|
|
153
|
+
}
|
|
154
|
+
if (text.includes('SELECT c.relkind AS kind')) {
|
|
155
|
+
if (tableName === 'order_mat_view') return [{ kind: 'm' }] as never;
|
|
156
|
+
return [] as never;
|
|
157
|
+
}
|
|
158
|
+
if (text.includes('has_table_privilege')) {
|
|
159
|
+
return [{ name: 'orders' }] as never;
|
|
160
|
+
}
|
|
161
|
+
return [] as never;
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const prepared = await ds.prepareTables(['order_view', 'order_mat_view', 'bare_table']);
|
|
165
|
+
expect(prepared[0]).toMatchObject({
|
|
166
|
+
name: 'order_view',
|
|
167
|
+
view: true,
|
|
168
|
+
template: 'view',
|
|
169
|
+
writableView: false,
|
|
170
|
+
filterTargetKey: 'id',
|
|
171
|
+
});
|
|
172
|
+
expect(prepared[1]).toMatchObject({
|
|
173
|
+
name: 'order_mat_view',
|
|
174
|
+
view: true,
|
|
175
|
+
template: 'view',
|
|
176
|
+
writableView: false,
|
|
177
|
+
filterTargetKey: 'code',
|
|
178
|
+
});
|
|
179
|
+
expect(prepared[1].fields).toEqual(
|
|
180
|
+
expect.arrayContaining([
|
|
181
|
+
expect.objectContaining({ name: 'id', type: 'bigInt' }),
|
|
182
|
+
expect.objectContaining({ name: 'code', type: 'string', unique: true }),
|
|
183
|
+
expect.objectContaining({ name: 'tags', type: 'array', elementType: 'text' }),
|
|
184
|
+
]),
|
|
185
|
+
);
|
|
186
|
+
expect(prepared[2]).toMatchObject({ name: 'bare_table', fields: [] });
|
|
187
|
+
|
|
188
|
+
const [concurrentA, concurrentB] = await Promise.all([
|
|
189
|
+
ds.prepareTables(['order_mat_view']),
|
|
190
|
+
ds.prepareTables(['order_mat_view']),
|
|
191
|
+
]);
|
|
192
|
+
expect(concurrentA[0].filterTargetKey).toBe('code');
|
|
193
|
+
expect(concurrentB[0].filterTargetKey).toBe('code');
|
|
194
|
+
|
|
195
|
+
await expect(ds.prepareTables(['restricted_table'])).rejects.toThrow(
|
|
196
|
+
'No description found for "restricted_table" table.',
|
|
197
|
+
);
|
|
198
|
+
await expect(ds.prepareTables(['transient_error_table'])).rejects.toThrow('Connection terminated unexpectedly');
|
|
199
|
+
await expect(ds.prepareTables(['missing_table'])).rejects.toThrow('missing_table');
|
|
200
|
+
|
|
201
|
+
const discovered = await ds.collectionManager.discoverTables();
|
|
202
|
+
expect(discovered).toEqual(['orders']);
|
|
203
|
+
const discoverQuery = executedQueries.find((q) => q.includes('ORDER BY c.relname'));
|
|
204
|
+
expect(discoverQuery).toContain('has_table_privilege');
|
|
205
|
+
expect(discoverQuery).toContain('has_any_column_privilege');
|
|
206
|
+
|
|
207
|
+
ds.collectionManager.defineCollection({
|
|
208
|
+
name: 'orders',
|
|
209
|
+
tableName: 'orders',
|
|
210
|
+
fields: [{ name: 'name', type: 'string' }],
|
|
211
|
+
});
|
|
212
|
+
await ds.collectionManager.updateField('orders', 'name', { unique: true }, {} as never);
|
|
213
|
+
expect(executedQueries.some((q) => q.startsWith('DROP INDEX "public"."idx_bad"'))).toBe(true);
|
|
214
|
+
expect(executedQueries.some((q) => q.startsWith('CREATE UNIQUE INDEX '))).toBe(true);
|
|
215
|
+
|
|
216
|
+
const created = await ds.collectionManager.createTable({ name: 'order_mat_view', fields: [] }, {} as never);
|
|
217
|
+
expect(created).toBe(false);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
describe('PostgresTreeCollection and PostgresAdjacencyListRepository', () => {
|
|
222
|
+
it('checks ancestors in a single CTE on beforeSave and skips work when parentId did not change', async () => {
|
|
223
|
+
const db = new Database({
|
|
224
|
+
dialect: 'postgres',
|
|
225
|
+
host: '127.0.0.1',
|
|
226
|
+
port: 5432,
|
|
227
|
+
database: 'unused',
|
|
228
|
+
username: 'unused',
|
|
229
|
+
logging: false,
|
|
230
|
+
});
|
|
231
|
+
try {
|
|
232
|
+
db.collectionFactory.registerCollectionType(PostgresTreeCollection, {
|
|
233
|
+
condition: (options) => Boolean(options.postgresTree || options.template === 'tree'),
|
|
234
|
+
});
|
|
235
|
+
const collection = db.collection({
|
|
236
|
+
name: 'categories',
|
|
237
|
+
template: 'tree',
|
|
238
|
+
tree: 'parentId',
|
|
239
|
+
fields: [
|
|
240
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
241
|
+
{ name: 'name', type: 'string' },
|
|
242
|
+
{ name: 'parentId', type: 'integer' },
|
|
243
|
+
],
|
|
244
|
+
}) as PostgresTreeCollection;
|
|
245
|
+
|
|
246
|
+
const querySpy = vi.spyOn(db.sequelize, 'query').mockImplementation(async (sql) => {
|
|
247
|
+
if (String(sql).includes('WITH RECURSIVE ancestors')) {
|
|
248
|
+
return [{ hasCycle: false }] as never;
|
|
249
|
+
}
|
|
250
|
+
return [] as never;
|
|
251
|
+
});
|
|
252
|
+
const findOneSpy = vi.spyOn(collection.repository, 'findOne');
|
|
253
|
+
|
|
254
|
+
const unchangedNode = collection.model.build({ id: 2, name: 'Updated', parentId: 1 }, { isNewRecord: false });
|
|
255
|
+
vi.spyOn(unchangedNode, 'changed').mockReturnValue(false);
|
|
256
|
+
await (collection.model as unknown as { runHooks: (name: string, ...args: unknown[]) => Promise<void> }).runHooks(
|
|
257
|
+
'beforeSave',
|
|
258
|
+
unchangedNode,
|
|
259
|
+
{},
|
|
260
|
+
);
|
|
261
|
+
expect(querySpy).not.toHaveBeenCalled();
|
|
262
|
+
|
|
263
|
+
const movedNode = collection.model.build({ id: 2, name: 'Moved', parentId: 3 }, { isNewRecord: false });
|
|
264
|
+
vi.spyOn(movedNode, 'changed').mockReturnValue(true);
|
|
265
|
+
const tx = {} as never;
|
|
266
|
+
await (collection.model as unknown as { runHooks: (name: string, ...args: unknown[]) => Promise<void> }).runHooks(
|
|
267
|
+
'beforeSave',
|
|
268
|
+
movedNode,
|
|
269
|
+
{ transaction: tx },
|
|
270
|
+
);
|
|
271
|
+
expect(querySpy).toHaveBeenCalledTimes(2);
|
|
272
|
+
expect(String(querySpy.mock.calls[0][0])).toContain('pg_advisory_xact_lock');
|
|
273
|
+
expect(String(querySpy.mock.calls[1][0])).toContain('WITH RECURSIVE ancestors');
|
|
274
|
+
expect(findOneSpy).not.toHaveBeenCalled();
|
|
275
|
+
|
|
276
|
+
const selfParent = collection.model.build({ id: 2, name: 'Self', parentId: 2 }, { isNewRecord: false });
|
|
277
|
+
vi.spyOn(selfParent, 'changed').mockReturnValue(true);
|
|
278
|
+
await expect(
|
|
279
|
+
(collection.model as unknown as { runHooks: (name: string, ...args: unknown[]) => Promise<void> }).runHooks(
|
|
280
|
+
'beforeSave',
|
|
281
|
+
selfParent,
|
|
282
|
+
{ transaction: tx },
|
|
283
|
+
),
|
|
284
|
+
).rejects.toMatchObject({ name: 'PostgresValidationError', status: 400 });
|
|
285
|
+
|
|
286
|
+
querySpy.mockResolvedValueOnce([] as never).mockResolvedValueOnce([{ hasCycle: true }] as never);
|
|
287
|
+
await expect(
|
|
288
|
+
(collection.model as unknown as { runHooks: (name: string, ...args: unknown[]) => Promise<void> }).runHooks(
|
|
289
|
+
'beforeSave',
|
|
290
|
+
movedNode,
|
|
291
|
+
{ transaction: tx },
|
|
292
|
+
),
|
|
293
|
+
).rejects.toThrow('Cycle detected in tree collection categories');
|
|
294
|
+
} finally {
|
|
295
|
+
await db.close();
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('paginates unfiltered roots with CTE, respects mixed empty $and filters, and keeps required tree fields', async () => {
|
|
300
|
+
const db = new Database({
|
|
301
|
+
dialect: 'postgres',
|
|
302
|
+
host: '127.0.0.1',
|
|
303
|
+
port: 5432,
|
|
304
|
+
database: 'unused',
|
|
305
|
+
username: 'unused',
|
|
306
|
+
logging: false,
|
|
307
|
+
});
|
|
308
|
+
try {
|
|
309
|
+
db.collectionFactory.registerCollectionType(PostgresTreeCollection, {
|
|
310
|
+
condition: (options) => Boolean(options.postgresTree || options.template === 'tree'),
|
|
311
|
+
});
|
|
312
|
+
const collection = db.collection({
|
|
313
|
+
name: 'categories',
|
|
314
|
+
template: 'tree',
|
|
315
|
+
tree: 'parentId',
|
|
316
|
+
fields: [
|
|
317
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
318
|
+
{ name: 'name', type: 'string' },
|
|
319
|
+
{ name: 'parentId', type: 'integer' },
|
|
320
|
+
],
|
|
321
|
+
}) as PostgresTreeCollection;
|
|
322
|
+
const repo = collection.repository as PostgresAdjacencyListRepository;
|
|
323
|
+
|
|
324
|
+
const root1 = collection.model.build({ id: 1, name: 'Root 1', parentId: null });
|
|
325
|
+
const child1 = collection.model.build({ id: 2, name: 'Child 1', parentId: 1 });
|
|
326
|
+
const root2 = collection.model.build({ id: 3, name: 'Root 2', parentId: null });
|
|
327
|
+
const child2 = collection.model.build({ id: 4, name: 'Child 2', parentId: 3 });
|
|
328
|
+
|
|
329
|
+
const querySpy = vi.spyOn(db.sequelize, 'query').mockImplementation(async (sql, queryOpts) => {
|
|
330
|
+
const text = String(sql);
|
|
331
|
+
if (text.includes('SELECT COUNT(*)::int AS count')) {
|
|
332
|
+
return [{ count: 2 }] as never;
|
|
333
|
+
}
|
|
334
|
+
if (text.includes('ORDER BY') && text.includes('LIMIT :limit')) {
|
|
335
|
+
return [{ id: 3 }] as never;
|
|
336
|
+
}
|
|
337
|
+
if (text.includes('WITH RECURSIVE tree')) {
|
|
338
|
+
const seedIds = ((queryOpts as { replacements?: { seedIds?: number[] } } | undefined)?.replacements
|
|
339
|
+
?.seedIds || []) as number[];
|
|
340
|
+
const all = [
|
|
341
|
+
{ id: 3, parentId: null, hasCycle: false },
|
|
342
|
+
{ id: 4, parentId: 3, hasCycle: false },
|
|
343
|
+
];
|
|
344
|
+
return (seedIds.includes(3) ? all : all.filter((row) => seedIds.includes(row.id))) as never;
|
|
345
|
+
}
|
|
346
|
+
return [] as never;
|
|
347
|
+
});
|
|
348
|
+
const superFindSpy = vi.spyOn(Repository.prototype, 'find').mockImplementation(async (opts) => {
|
|
349
|
+
const ids = (opts?.filter as { id?: number[] } | undefined)?.id;
|
|
350
|
+
if (ids) {
|
|
351
|
+
return [root1, child1, root2, child2].filter((item) => ids.includes(Number(item.get('id')))) as Model[];
|
|
352
|
+
}
|
|
353
|
+
if ((opts?.filter as { name?: string } | undefined)?.name === 'Root 2') {
|
|
354
|
+
return [root2] as Model[];
|
|
355
|
+
}
|
|
356
|
+
return [child2] as Model[];
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
const [pagedRoots, total] = await repo.findAndCount({ tree: true, limit: 1, offset: 1, fields: ['name'] });
|
|
360
|
+
expect(total).toBe(2);
|
|
361
|
+
expect(pagedRoots.map((node) => node.get('name'))).toEqual(['Root 2']);
|
|
362
|
+
expect(pagedRoots[0].get('children').map((node: Model) => node.get('name'))).toEqual(['Child 2']);
|
|
363
|
+
expect(superFindSpy).toHaveBeenCalledWith(
|
|
364
|
+
expect.objectContaining({ filter: { id: [3, 4] }, fields: ['name', 'id', 'parentId'] }),
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
const filteredParent = await repo.find({ tree: true, filter: { name: 'Root 2' } });
|
|
368
|
+
expect(filteredParent.map((node) => node.get('name'))).toEqual(['Root 2']);
|
|
369
|
+
expect(filteredParent[0].get('children').map((node: Model) => node.get('name'))).toEqual(['Child 2']);
|
|
370
|
+
|
|
371
|
+
const mixedFilter = await repo.find({ tree: true, filter: { name: 'Root 2', $and: [] } });
|
|
372
|
+
expect(mixedFilter.map((node) => node.get('name'))).toEqual(['Root 2']);
|
|
373
|
+
expect(superFindSpy).toHaveBeenCalledWith(
|
|
374
|
+
expect.objectContaining({ filter: { name: 'Root 2', $and: [] }, tree: false }),
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
const filteredChild = await repo.find({ tree: true, filter: { name: 'Child 2' } });
|
|
378
|
+
expect(filteredChild.map((node) => node.get('name'))).toEqual(['Child 2']);
|
|
379
|
+
|
|
380
|
+
querySpy
|
|
381
|
+
.mockResolvedValueOnce([{ id: 3 }] as never)
|
|
382
|
+
.mockResolvedValueOnce([{ id: 3, parentId: 4, hasCycle: true }] as never);
|
|
383
|
+
await expect(repo.find({ tree: true })).rejects.toThrow('Cycle detected in tree collection categories');
|
|
384
|
+
} finally {
|
|
385
|
+
await db.close();
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
describe('PluginDataSourcePostgresServer middleware and sync', () => {
|
|
391
|
+
function createPluginHarness() {
|
|
392
|
+
const preHandlers = new Map<string, (ctx: unknown, next: () => Promise<void>) => Promise<void>>();
|
|
393
|
+
const middlewares: Array<(ctx: unknown, next: () => Promise<void>) => Promise<void>> = [];
|
|
394
|
+
const dataSourceManager = new DataSourceManager();
|
|
395
|
+
dataSourceManager.registerDataSourceType(DATA_SOURCE_TYPE, PostgresDataSource);
|
|
396
|
+
|
|
397
|
+
const ds = createDataSource({ name: 'pg-ext' });
|
|
398
|
+
ds.collectionManager.defineCollection({
|
|
399
|
+
name: 'orders',
|
|
400
|
+
tableName: 'orders',
|
|
401
|
+
fields: [
|
|
402
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
403
|
+
{ name: 'note', type: 'string' },
|
|
404
|
+
],
|
|
405
|
+
});
|
|
406
|
+
dataSourceManager.dataSources.set('pg-ext', ds);
|
|
407
|
+
|
|
408
|
+
const fieldsRepo = {
|
|
409
|
+
find: vi.fn().mockResolvedValue([]),
|
|
410
|
+
findOne: vi.fn().mockResolvedValue(null),
|
|
411
|
+
destroy: vi.fn().mockResolvedValue(undefined),
|
|
412
|
+
};
|
|
413
|
+
const collectionsRepo = {
|
|
414
|
+
findOne: vi.fn().mockResolvedValue(null),
|
|
415
|
+
};
|
|
416
|
+
const dataSourcesRepo = {
|
|
417
|
+
findOne: vi.fn().mockResolvedValue(null),
|
|
418
|
+
};
|
|
419
|
+
const dbEvents = new Map<string, Array<(...args: unknown[]) => Promise<void> | void>>();
|
|
420
|
+
const sendSyncMessage = vi.fn().mockResolvedValue(undefined);
|
|
421
|
+
const app = {
|
|
422
|
+
dataSourceManager,
|
|
423
|
+
environment: {
|
|
424
|
+
renderJsonTemplate: vi.fn((val) => ({
|
|
425
|
+
...val,
|
|
426
|
+
password: val.password === '{{PG_PASS}}' ? 'resolved' : val.password,
|
|
427
|
+
})),
|
|
428
|
+
},
|
|
429
|
+
log: { warn: vi.fn() },
|
|
430
|
+
db: {
|
|
431
|
+
getRepository: (name: string) => {
|
|
432
|
+
if (name === 'dataSourcesFields') return fieldsRepo;
|
|
433
|
+
if (name === 'dataSources') return dataSourcesRepo;
|
|
434
|
+
return collectionsRepo;
|
|
435
|
+
},
|
|
436
|
+
on: (event: string, listener: (...args: unknown[]) => Promise<void> | void) => {
|
|
437
|
+
const list = dbEvents.get(event) || [];
|
|
438
|
+
list.push(listener);
|
|
439
|
+
dbEvents.set(event, list);
|
|
440
|
+
},
|
|
441
|
+
},
|
|
442
|
+
resourceManager: {
|
|
443
|
+
registerPreActionHandler: (name: string, fn: (ctx: unknown, next: () => Promise<void>) => Promise<void>) => {
|
|
444
|
+
preHandlers.set(name, fn);
|
|
445
|
+
},
|
|
446
|
+
use: (fn: (ctx: unknown, next: () => Promise<void>) => Promise<void>) => {
|
|
447
|
+
middlewares.push(fn);
|
|
448
|
+
},
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
const plugin = new PluginDataSourcePostgresServer(app as never, { name: NAMESPACE });
|
|
452
|
+
plugin.sendSyncMessage = sendSyncMessage;
|
|
453
|
+
return {
|
|
454
|
+
plugin,
|
|
455
|
+
ds,
|
|
456
|
+
preHandlers,
|
|
457
|
+
middlewares,
|
|
458
|
+
fieldsRepo,
|
|
459
|
+
collectionsRepo,
|
|
460
|
+
dataSourcesRepo,
|
|
461
|
+
dbEvents,
|
|
462
|
+
sendSyncMessage,
|
|
463
|
+
app,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
it('rejects nested options.sql on create/update and forbids converting table collections to SQL', async () => {
|
|
468
|
+
const { plugin, middlewares } = createPluginHarness();
|
|
469
|
+
await plugin.load();
|
|
470
|
+
const schemaMiddleware = middlewares[1];
|
|
471
|
+
|
|
472
|
+
await expect(
|
|
473
|
+
schemaMiddleware(
|
|
474
|
+
{
|
|
475
|
+
action: {
|
|
476
|
+
resourceName: 'dataSources.collections',
|
|
477
|
+
actionName: 'create',
|
|
478
|
+
params: {
|
|
479
|
+
associatedIndex: 'pg-ext',
|
|
480
|
+
values: { name: 'bad_sql', options: { sql: 'SELECT * FROM pg_settings' } },
|
|
481
|
+
},
|
|
482
|
+
},
|
|
483
|
+
},
|
|
484
|
+
vi.fn(),
|
|
485
|
+
),
|
|
486
|
+
).rejects.toThrow('SQL statement contains dangerous keyword: pg_settings');
|
|
487
|
+
|
|
488
|
+
const ctxThrow = vi.fn((status: number, message: string) => {
|
|
489
|
+
throw new Error(`${status}:${message}`);
|
|
490
|
+
});
|
|
491
|
+
await expect(
|
|
492
|
+
schemaMiddleware(
|
|
493
|
+
{
|
|
494
|
+
action: {
|
|
495
|
+
resourceName: 'dataSources.collections',
|
|
496
|
+
actionName: 'update',
|
|
497
|
+
params: {
|
|
498
|
+
associatedIndex: 'pg-ext',
|
|
499
|
+
filterByTk: 'orders',
|
|
500
|
+
values: { options: { sql: 'SELECT 1' } },
|
|
501
|
+
},
|
|
502
|
+
},
|
|
503
|
+
throw: ctxThrow,
|
|
504
|
+
},
|
|
505
|
+
vi.fn(),
|
|
506
|
+
),
|
|
507
|
+
).rejects.toThrow('400:Only SQL collections can update SQL queries');
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
it('intercepts standalone fields:apply from request.body and emits fieldRemoved sync on introspected field delete', async () => {
|
|
511
|
+
const { plugin, ds, middlewares, sendSyncMessage } = createPluginHarness();
|
|
512
|
+
await plugin.load();
|
|
513
|
+
const schemaMiddleware = middlewares[1];
|
|
514
|
+
|
|
515
|
+
const ensureForeignKey = vi.spyOn(ds.collectionManager, 'ensureForeignKey').mockResolvedValue(undefined);
|
|
516
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
517
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
518
|
+
) => cb({})) as never);
|
|
519
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
520
|
+
|
|
521
|
+
const body: Record<string, unknown> = {
|
|
522
|
+
dataSourceKey: 'pg-ext',
|
|
523
|
+
collectionName: 'orders',
|
|
524
|
+
name: 'customer',
|
|
525
|
+
interface: 'm2o',
|
|
526
|
+
target: 'customers',
|
|
527
|
+
};
|
|
528
|
+
const nextApply = vi.fn().mockResolvedValue(undefined);
|
|
529
|
+
await schemaMiddleware(
|
|
530
|
+
{
|
|
531
|
+
action: { resourceName: 'dataSourcesCollections.fields', actionName: 'apply', params: {} },
|
|
532
|
+
request: { body },
|
|
533
|
+
db: {
|
|
534
|
+
getRepository: () => ({ find: vi.fn().mockResolvedValue([]), findOne: vi.fn().mockResolvedValue(null) }),
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
nextApply,
|
|
538
|
+
);
|
|
539
|
+
expect(ensureForeignKey).toHaveBeenCalledOnce();
|
|
540
|
+
expect(body).toMatchObject({ type: 'belongsTo', foreignKey: 'customerId', targetKey: 'id' });
|
|
541
|
+
expect(nextApply).toHaveBeenCalledOnce();
|
|
542
|
+
|
|
543
|
+
vi.spyOn(ds.collectionManager, 'removeField').mockResolvedValue(undefined);
|
|
544
|
+
const nextDestroy = vi.fn().mockResolvedValue(undefined);
|
|
545
|
+
await schemaMiddleware(
|
|
546
|
+
{
|
|
547
|
+
action: {
|
|
548
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
549
|
+
actionName: 'destroy',
|
|
550
|
+
params: { associatedIndex: 'pg-ext.orders', filterByTk: 'note' },
|
|
551
|
+
},
|
|
552
|
+
db: {
|
|
553
|
+
getRepository: () => ({
|
|
554
|
+
find: vi.fn().mockResolvedValue([]),
|
|
555
|
+
findOne: vi.fn().mockResolvedValue({ key: 'f1' }),
|
|
556
|
+
}),
|
|
557
|
+
},
|
|
558
|
+
},
|
|
559
|
+
nextDestroy,
|
|
560
|
+
);
|
|
561
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
562
|
+
type: 'fieldRemoved',
|
|
563
|
+
dataSourceKey: 'pg-ext',
|
|
564
|
+
collectionName: 'orders',
|
|
565
|
+
fieldName: 'note',
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
ds.collectionManager.getCollection('orders')?.setField('extra', { name: 'extra', type: 'string' });
|
|
569
|
+
await plugin.handleSyncMessage({
|
|
570
|
+
type: 'fieldRemoved',
|
|
571
|
+
dataSourceKey: 'pg-ext',
|
|
572
|
+
collectionName: 'orders',
|
|
573
|
+
fieldName: 'extra',
|
|
574
|
+
});
|
|
575
|
+
expect(ds.collectionManager.getCollection('orders')?.getField('extra')).toBeUndefined();
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
it('broadcasts and handles collectionCreated and collectionRemoved sync messages across HA nodes', async () => {
|
|
579
|
+
const { plugin, ds, middlewares, collectionsRepo, sendSyncMessage } = createPluginHarness();
|
|
580
|
+
await plugin.load();
|
|
581
|
+
const schemaMiddleware = middlewares[1];
|
|
582
|
+
|
|
583
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
584
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
585
|
+
) => cb({})) as never);
|
|
586
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
587
|
+
vi.spyOn(ds.collectionManager, 'createTable').mockImplementation(async (values) => {
|
|
588
|
+
ds.collectionManager.defineCollection({ name: String(values.name), tableName: String(values.name), fields: [] });
|
|
589
|
+
return true;
|
|
590
|
+
});
|
|
591
|
+
vi.spyOn(ds, 'addSelectedTables').mockResolvedValue(undefined);
|
|
592
|
+
vi.spyOn(ds, 'removeSelectedTables').mockResolvedValue(undefined);
|
|
593
|
+
vi.spyOn(ds.collectionManager, 'dropTable').mockResolvedValue(undefined);
|
|
594
|
+
|
|
595
|
+
await schemaMiddleware(
|
|
596
|
+
{
|
|
597
|
+
action: {
|
|
598
|
+
resourceName: 'dataSources.collections',
|
|
599
|
+
actionName: 'create',
|
|
600
|
+
params: { associatedIndex: 'pg-ext', values: { name: 'invoices', fields: [{ name: 'id', type: 'bigInt' }] } },
|
|
601
|
+
},
|
|
602
|
+
},
|
|
603
|
+
vi.fn().mockResolvedValue(undefined),
|
|
604
|
+
);
|
|
605
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
606
|
+
type: 'collectionCreated',
|
|
607
|
+
dataSourceKey: 'pg-ext',
|
|
608
|
+
collectionName: 'invoices',
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
await schemaMiddleware(
|
|
612
|
+
{
|
|
613
|
+
action: {
|
|
614
|
+
resourceName: 'dataSources.collections',
|
|
615
|
+
actionName: 'destroy',
|
|
616
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'invoices' },
|
|
617
|
+
},
|
|
618
|
+
},
|
|
619
|
+
vi.fn().mockResolvedValue(undefined),
|
|
620
|
+
);
|
|
621
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
622
|
+
type: 'collectionRemoved',
|
|
623
|
+
dataSourceKey: 'pg-ext',
|
|
624
|
+
collectionNames: ['invoices'],
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
collectionsRepo.findOne.mockResolvedValueOnce({
|
|
628
|
+
toJSON: () => ({ name: 'invoices_sql', sql: 'SELECT 1 AS id' }),
|
|
629
|
+
});
|
|
630
|
+
await plugin.handleSyncMessage({
|
|
631
|
+
type: 'collectionCreated',
|
|
632
|
+
dataSourceKey: 'pg-ext',
|
|
633
|
+
collectionName: 'invoices_sql',
|
|
634
|
+
});
|
|
635
|
+
expect(ds.collectionManager.hasCollection('invoices_sql')).toBe(true);
|
|
636
|
+
|
|
637
|
+
await plugin.handleSyncMessage({
|
|
638
|
+
type: 'collectionRemoved',
|
|
639
|
+
dataSourceKey: 'pg-ext',
|
|
640
|
+
collectionNames: ['invoices_sql'],
|
|
641
|
+
});
|
|
642
|
+
expect(ds.collectionManager.hasCollection('invoices_sql')).toBe(false);
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
it('probes readTables with rendered templates and closes probe connection in finally', async () => {
|
|
646
|
+
const { plugin, preHandlers } = createPluginHarness();
|
|
647
|
+
await plugin.load();
|
|
648
|
+
const handler = preHandlers.get('dataSources:readTables');
|
|
649
|
+
expect(handler).toBeDefined();
|
|
650
|
+
|
|
651
|
+
const readTablesSpy = vi
|
|
652
|
+
.spyOn(PostgresDataSource.prototype, 'readTables')
|
|
653
|
+
.mockRejectedValue(new Error('auth failed'));
|
|
654
|
+
const closeSpy = vi.spyOn(PostgresDataSource.prototype, 'close').mockResolvedValue(undefined);
|
|
655
|
+
|
|
656
|
+
const ctx = {
|
|
657
|
+
action: {
|
|
658
|
+
params: {
|
|
659
|
+
values: {
|
|
660
|
+
dataSourceKey: 'probe-key',
|
|
661
|
+
dbOptions: {
|
|
662
|
+
type: DATA_SOURCE_TYPE,
|
|
663
|
+
host: '127.0.0.1',
|
|
664
|
+
database: 'sales',
|
|
665
|
+
username: 'postgres',
|
|
666
|
+
password: '{{PG_PASS}}',
|
|
667
|
+
},
|
|
668
|
+
},
|
|
669
|
+
},
|
|
670
|
+
},
|
|
671
|
+
body: undefined as unknown,
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
await expect(handler?.(ctx, vi.fn())).rejects.toThrow('auth failed');
|
|
675
|
+
expect(readTablesSpy).toHaveBeenCalledOnce();
|
|
676
|
+
expect(closeSpy).toHaveBeenCalled();
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
it('validates SQL update, preserves model attributes on sync, and notifies HA peers', async () => {
|
|
680
|
+
const { plugin, ds, middlewares, collectionsRepo, fieldsRepo, sendSyncMessage } = createPluginHarness();
|
|
681
|
+
await plugin.load();
|
|
682
|
+
ds.collectionManager.db.collectionFactory.registerCollectionType(PostgresSQLCollection, {
|
|
683
|
+
condition: (options) => Boolean(options.sql),
|
|
684
|
+
async onSync() {},
|
|
685
|
+
async onDump() {},
|
|
686
|
+
});
|
|
687
|
+
const sqlCollection = ds.collectionManager.defineCollection({
|
|
688
|
+
name: 'order_view_sql',
|
|
689
|
+
sql: 'SELECT id FROM orders',
|
|
690
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
691
|
+
}) as PostgresSQLCollection;
|
|
692
|
+
|
|
693
|
+
const schemaMiddleware = middlewares[1];
|
|
694
|
+
const next = vi.fn().mockResolvedValue(undefined);
|
|
695
|
+
await schemaMiddleware(
|
|
696
|
+
{
|
|
697
|
+
action: {
|
|
698
|
+
resourceName: 'dataSources.collections',
|
|
699
|
+
actionName: 'update',
|
|
700
|
+
params: {
|
|
701
|
+
associatedIndex: 'pg-ext',
|
|
702
|
+
filterByTk: 'order_view_sql',
|
|
703
|
+
values: { sql: 'SELECT id FROM paid_orders' },
|
|
704
|
+
},
|
|
705
|
+
},
|
|
706
|
+
},
|
|
707
|
+
next,
|
|
708
|
+
);
|
|
709
|
+
|
|
710
|
+
expect(next).toHaveBeenCalledOnce();
|
|
711
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
712
|
+
type: 'collectionCreated',
|
|
713
|
+
dataSourceKey: 'pg-ext',
|
|
714
|
+
collectionName: 'order_view_sql',
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
collectionsRepo.findOne.mockResolvedValueOnce({
|
|
718
|
+
toJSON: () => ({ name: 'order_view_sql', sql: 'SELECT id FROM paid_orders' }),
|
|
719
|
+
});
|
|
720
|
+
fieldsRepo.find.mockResolvedValueOnce([{ toJSON: () => ({ name: 'id', type: 'integer', primaryKey: true }) }]);
|
|
721
|
+
await plugin.handleSyncMessage({
|
|
722
|
+
type: 'collectionCreated',
|
|
723
|
+
dataSourceKey: 'pg-ext',
|
|
724
|
+
collectionName: 'order_view_sql',
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
expect((sqlCollection.model as unknown as { sql?: string }).sql).toBe('SELECT id FROM paid_orders');
|
|
728
|
+
expect(sqlCollection.model.getAttributes().id).toBeDefined();
|
|
729
|
+
expect(sqlCollection.filterTargetKey).toBe('id');
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
it('allows metadata field CRUD on SQL collections, keeps views locked, and syncs v1 general preset flags', async () => {
|
|
733
|
+
const { plugin, ds, middlewares, sendSyncMessage } = createPluginHarness();
|
|
734
|
+
await plugin.load();
|
|
735
|
+
ds.collectionManager.db.collectionFactory.registerCollectionType(PostgresSQLCollection, {
|
|
736
|
+
condition: (options) => Boolean(options.sql),
|
|
737
|
+
async onSync() {},
|
|
738
|
+
async onDump() {},
|
|
739
|
+
});
|
|
740
|
+
const sqlCollection = ds.collectionManager.defineCollection({
|
|
741
|
+
name: 'report_sql',
|
|
742
|
+
sql: 'SELECT id, total FROM orders',
|
|
743
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
744
|
+
}) as PostgresSQLCollection;
|
|
745
|
+
ds.collectionManager.defineCollection({
|
|
746
|
+
name: 'order_names_view',
|
|
747
|
+
view: true,
|
|
748
|
+
viewName: 'order_names_view',
|
|
749
|
+
fields: [{ name: 'id', type: 'bigInt' }],
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
const addFieldSpy = vi.spyOn(ds.collectionManager, 'addField');
|
|
753
|
+
const removeFieldSpy = vi.spyOn(ds.collectionManager, 'removeField');
|
|
754
|
+
const schemaMiddleware = middlewares[1];
|
|
755
|
+
|
|
756
|
+
const nextCreateSqlField = vi.fn().mockImplementation(async () => {
|
|
757
|
+
sqlCollection.setField('total', { name: 'total', type: 'decimal' });
|
|
758
|
+
});
|
|
759
|
+
await schemaMiddleware(
|
|
760
|
+
{
|
|
761
|
+
action: {
|
|
762
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
763
|
+
actionName: 'create',
|
|
764
|
+
params: { associatedIndex: 'pg-ext.report_sql', values: { name: 'total', type: 'decimal' } },
|
|
765
|
+
},
|
|
766
|
+
},
|
|
767
|
+
nextCreateSqlField,
|
|
768
|
+
);
|
|
769
|
+
expect(nextCreateSqlField).toHaveBeenCalledOnce();
|
|
770
|
+
expect(addFieldSpy).not.toHaveBeenCalled();
|
|
771
|
+
|
|
772
|
+
const nextDestroySqlField = vi.fn().mockImplementation(async () => {
|
|
773
|
+
sqlCollection.removeField('total');
|
|
774
|
+
});
|
|
775
|
+
await schemaMiddleware(
|
|
776
|
+
{
|
|
777
|
+
action: {
|
|
778
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
779
|
+
actionName: 'destroy',
|
|
780
|
+
params: { associatedIndex: 'pg-ext.report_sql', filterByTk: 'total' },
|
|
781
|
+
},
|
|
782
|
+
},
|
|
783
|
+
nextDestroySqlField,
|
|
784
|
+
);
|
|
785
|
+
expect(nextDestroySqlField).toHaveBeenCalledOnce();
|
|
786
|
+
expect(removeFieldSpy).not.toHaveBeenCalled();
|
|
787
|
+
expect(sqlCollection.getField('total')).toBeUndefined();
|
|
788
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
789
|
+
type: 'fieldRemoved',
|
|
790
|
+
dataSourceKey: 'pg-ext',
|
|
791
|
+
collectionName: 'report_sql',
|
|
792
|
+
fieldName: 'total',
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
const ctxThrow = vi.fn((status: number, message: string) => {
|
|
796
|
+
throw new Error(`${status}:${message}`);
|
|
797
|
+
});
|
|
798
|
+
await expect(
|
|
799
|
+
schemaMiddleware(
|
|
800
|
+
{
|
|
801
|
+
action: {
|
|
802
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
803
|
+
actionName: 'create',
|
|
804
|
+
params: { associatedIndex: 'pg-ext.order_names_view', values: { name: 'extra', type: 'string' } },
|
|
805
|
+
},
|
|
806
|
+
throw: ctxThrow,
|
|
807
|
+
},
|
|
808
|
+
vi.fn(),
|
|
809
|
+
),
|
|
810
|
+
).rejects.toThrow('403:This collection is read-only');
|
|
811
|
+
|
|
812
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
813
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
814
|
+
) => cb({})) as never);
|
|
815
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
816
|
+
const createTableSpy = vi.spyOn(ds.collectionManager, 'createTable').mockImplementation(async (values) => {
|
|
817
|
+
ds.collectionManager.defineCollection({ name: String(values.name), tableName: String(values.name), fields: [] });
|
|
818
|
+
return true;
|
|
819
|
+
});
|
|
820
|
+
vi.spyOn(ds, 'addSelectedTables').mockResolvedValue(undefined);
|
|
821
|
+
|
|
822
|
+
const v1Values: Record<string, unknown> = {
|
|
823
|
+
name: 'audit_logs',
|
|
824
|
+
template: 'general',
|
|
825
|
+
fields: ['id'],
|
|
826
|
+
autoGenId: true,
|
|
827
|
+
createdAt: true,
|
|
828
|
+
updatedAt: true,
|
|
829
|
+
};
|
|
830
|
+
await schemaMiddleware(
|
|
831
|
+
{
|
|
832
|
+
action: {
|
|
833
|
+
resourceName: 'dataSources.collections',
|
|
834
|
+
actionName: 'create',
|
|
835
|
+
params: { associatedIndex: 'pg-ext', values: v1Values },
|
|
836
|
+
},
|
|
837
|
+
},
|
|
838
|
+
vi.fn().mockResolvedValue(undefined),
|
|
839
|
+
);
|
|
840
|
+
expect(createTableSpy).toHaveBeenCalledWith(
|
|
841
|
+
expect.objectContaining({
|
|
842
|
+
name: 'audit_logs',
|
|
843
|
+
autoGenId: true,
|
|
844
|
+
createdAt: false,
|
|
845
|
+
updatedAt: false,
|
|
846
|
+
timestamps: false,
|
|
847
|
+
}),
|
|
848
|
+
expect.anything(),
|
|
849
|
+
);
|
|
850
|
+
|
|
851
|
+
const v1CalendarValues: Record<string, unknown> = {
|
|
852
|
+
name: 'events',
|
|
853
|
+
template: 'calendar',
|
|
854
|
+
fields: [
|
|
855
|
+
{ name: 'id', type: 'bigInt', primaryKey: true },
|
|
856
|
+
{ name: 'title', type: 'string' },
|
|
857
|
+
],
|
|
858
|
+
autoGenId: true,
|
|
859
|
+
createdAt: true,
|
|
860
|
+
updatedAt: true,
|
|
861
|
+
};
|
|
862
|
+
await schemaMiddleware(
|
|
863
|
+
{
|
|
864
|
+
action: {
|
|
865
|
+
resourceName: 'dataSources.collections',
|
|
866
|
+
actionName: 'create',
|
|
867
|
+
params: { associatedIndex: 'pg-ext', values: v1CalendarValues },
|
|
868
|
+
},
|
|
869
|
+
},
|
|
870
|
+
vi.fn().mockResolvedValue(undefined),
|
|
871
|
+
);
|
|
872
|
+
expect(createTableSpy).toHaveBeenLastCalledWith(
|
|
873
|
+
expect.objectContaining({
|
|
874
|
+
name: 'events',
|
|
875
|
+
fields: expect.arrayContaining([
|
|
876
|
+
expect.objectContaining({ name: 'createdAt', interface: 'createdAt' }),
|
|
877
|
+
expect.objectContaining({ name: 'updatedAt', interface: 'updatedAt' }),
|
|
878
|
+
]),
|
|
879
|
+
}),
|
|
880
|
+
expect.anything(),
|
|
881
|
+
);
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
it('blocks writes to read-only views and SQL collections on both direct and nested relation actions', async () => {
|
|
885
|
+
const { plugin, ds } = createPluginHarness();
|
|
886
|
+
const registeredMiddlewares: Array<(ctx: unknown, next: () => Promise<void>) => Promise<void>> = [];
|
|
887
|
+
vi.spyOn(ds.resourceManager, 'use').mockImplementation(
|
|
888
|
+
(fn: (ctx: unknown, next: () => Promise<void>) => Promise<void>) => {
|
|
889
|
+
registeredMiddlewares.push(fn);
|
|
890
|
+
return ds.resourceManager;
|
|
891
|
+
},
|
|
892
|
+
);
|
|
893
|
+
|
|
894
|
+
await plugin.beforeLoad();
|
|
895
|
+
const readOnlyMiddleware = registeredMiddlewares[1];
|
|
896
|
+
expect(readOnlyMiddleware).toBeDefined();
|
|
897
|
+
|
|
898
|
+
ds.collectionManager.defineCollection({
|
|
899
|
+
name: 'order_names_view',
|
|
900
|
+
tableName: 'order_names_view',
|
|
901
|
+
view: true,
|
|
902
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
903
|
+
});
|
|
904
|
+
ds.collectionManager.defineCollection({
|
|
905
|
+
name: 'order_sql',
|
|
906
|
+
tableName: 'order_sql',
|
|
907
|
+
sql: 'SELECT id FROM orders',
|
|
908
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
909
|
+
});
|
|
910
|
+
ds.collectionManager.getCollection('orders')?.setField('orderViews', {
|
|
911
|
+
name: 'orderViews',
|
|
912
|
+
type: 'hasMany',
|
|
913
|
+
target: 'order_names_view',
|
|
914
|
+
foreignKey: 'id',
|
|
915
|
+
sourceKey: 'id',
|
|
916
|
+
});
|
|
917
|
+
|
|
918
|
+
const ctxThrow = vi.fn((status: number, message: string) => {
|
|
919
|
+
throw new Error(`${status}:${message}`);
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
await expect(
|
|
923
|
+
readOnlyMiddleware(
|
|
924
|
+
{ action: { resourceName: 'order_names_view', actionName: 'move' }, throw: ctxThrow },
|
|
925
|
+
vi.fn(),
|
|
926
|
+
),
|
|
927
|
+
).rejects.toThrow('403:This collection is read-only');
|
|
928
|
+
|
|
929
|
+
await expect(
|
|
930
|
+
readOnlyMiddleware(
|
|
931
|
+
{ action: { resourceName: 'orders.orderViews', actionName: 'create' }, throw: ctxThrow },
|
|
932
|
+
vi.fn(),
|
|
933
|
+
),
|
|
934
|
+
).rejects.toThrow('403:This collection is read-only');
|
|
935
|
+
|
|
936
|
+
await expect(
|
|
937
|
+
readOnlyMiddleware(
|
|
938
|
+
{ action: { resourceName: 'orders.orderViews', actionName: 'update' }, throw: ctxThrow },
|
|
939
|
+
vi.fn(),
|
|
940
|
+
),
|
|
941
|
+
).rejects.toThrow('403:This collection is read-only');
|
|
942
|
+
|
|
943
|
+
const allowRead = vi.fn().mockResolvedValue(undefined);
|
|
944
|
+
await readOnlyMiddleware(
|
|
945
|
+
{ action: { resourceName: 'orders.orderViews', actionName: 'list' }, throw: ctxThrow },
|
|
946
|
+
allowRead,
|
|
947
|
+
);
|
|
948
|
+
expect(allowRead).toHaveBeenCalledOnce();
|
|
949
|
+
|
|
950
|
+
const allowParentWrite = vi.fn().mockResolvedValue(undefined);
|
|
951
|
+
await readOnlyMiddleware(
|
|
952
|
+
{ action: { resourceName: 'orders', actionName: 'create' }, throw: ctxThrow },
|
|
953
|
+
allowParentWrite,
|
|
954
|
+
);
|
|
955
|
+
expect(allowParentWrite).toHaveBeenCalledOnce();
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
it('cleans up orphaned dataSourcesFields rows when destroying a collection', async () => {
|
|
959
|
+
const { plugin, ds, middlewares, fieldsRepo } = createPluginHarness();
|
|
960
|
+
await plugin.load();
|
|
961
|
+
const schemaMiddleware = middlewares[1];
|
|
962
|
+
|
|
963
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
964
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
965
|
+
) => cb({})) as never);
|
|
966
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
967
|
+
vi.spyOn(ds.collectionManager, 'dropTable').mockResolvedValue(undefined);
|
|
968
|
+
vi.spyOn(ds, 'removeSelectedTables').mockResolvedValue(false);
|
|
969
|
+
|
|
970
|
+
await schemaMiddleware(
|
|
971
|
+
{
|
|
972
|
+
action: {
|
|
973
|
+
resourceName: 'dataSources.collections',
|
|
974
|
+
actionName: 'destroy',
|
|
975
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'orders' },
|
|
976
|
+
},
|
|
977
|
+
},
|
|
978
|
+
vi.fn().mockResolvedValue(undefined),
|
|
979
|
+
);
|
|
980
|
+
|
|
981
|
+
expect(fieldsRepo.destroy).toHaveBeenCalledWith({
|
|
982
|
+
filter: { dataSourceKey: 'pg-ext', collectionName: { $in: ['orders'] } },
|
|
983
|
+
individualHooks: false,
|
|
984
|
+
hooks: false,
|
|
985
|
+
});
|
|
986
|
+
});
|
|
987
|
+
|
|
988
|
+
it('closes PostgreSQL pools on dataSources.afterDestroy and on HA dataSourceRemoved sync messages', async () => {
|
|
989
|
+
const { plugin, ds, app, dbEvents, sendSyncMessage } = createPluginHarness();
|
|
990
|
+
await plugin.beforeLoad();
|
|
991
|
+
await plugin.load();
|
|
992
|
+
|
|
993
|
+
const closeSpy = vi.spyOn(ds, 'close').mockResolvedValue(undefined);
|
|
994
|
+
const destroyListeners = dbEvents.get('dataSources.afterDestroy') || [];
|
|
995
|
+
expect(destroyListeners).toHaveLength(1);
|
|
996
|
+
|
|
997
|
+
// Simulate upstream DataSourceManager removing the key from the map before our listener runs.
|
|
998
|
+
app.dataSourceManager.dataSources.delete('pg-ext');
|
|
999
|
+
let commitCallback: (() => Promise<void> | void) | undefined;
|
|
1000
|
+
const mockTx = {
|
|
1001
|
+
afterCommit: (fn: () => Promise<void> | void) => {
|
|
1002
|
+
commitCallback = fn;
|
|
1003
|
+
},
|
|
1004
|
+
};
|
|
1005
|
+
await destroyListeners[0](
|
|
1006
|
+
{ get: (field: string) => (field === 'type' ? DATA_SOURCE_TYPE : field === 'key' ? 'pg-ext' : undefined) },
|
|
1007
|
+
{ transaction: mockTx },
|
|
1008
|
+
);
|
|
1009
|
+
|
|
1010
|
+
expect(closeSpy).not.toHaveBeenCalled();
|
|
1011
|
+
await commitCallback?.();
|
|
1012
|
+
expect(closeSpy).toHaveBeenCalledOnce();
|
|
1013
|
+
expect(sendSyncMessage).toHaveBeenCalledWith(
|
|
1014
|
+
{ type: 'dataSourceRemoved', dataSourceKey: 'pg-ext' },
|
|
1015
|
+
{ transaction: mockTx },
|
|
1016
|
+
);
|
|
1017
|
+
|
|
1018
|
+
// Simulate HA peer closing its tracked pool when receiving dataSourceRemoved.
|
|
1019
|
+
const peerSource = createDataSource({ name: 'pg-peer' });
|
|
1020
|
+
const peerCloseSpy = vi.spyOn(peerSource, 'close').mockResolvedValue(undefined);
|
|
1021
|
+
app.dataSourceManager.dataSources.set('pg-peer', peerSource);
|
|
1022
|
+
await plugin.beforeLoad();
|
|
1023
|
+
app.dataSourceManager.dataSources.delete('pg-peer');
|
|
1024
|
+
|
|
1025
|
+
await plugin.handleSyncMessage({ type: 'dataSourceRemoved', dataSourceKey: 'pg-peer' });
|
|
1026
|
+
expect(peerCloseSpy).toHaveBeenCalledOnce();
|
|
1027
|
+
});
|
|
1028
|
+
|
|
1029
|
+
it('preserves localData metadata in loadTables, broadcasts tablesLoaded in load-all mode, and syncs peers', async () => {
|
|
1030
|
+
const { plugin, ds, dataSourcesRepo, sendSyncMessage } = createPluginHarness();
|
|
1031
|
+
await plugin.load();
|
|
1032
|
+
|
|
1033
|
+
const savedLocalData = {
|
|
1034
|
+
orders: {
|
|
1035
|
+
name: 'orders',
|
|
1036
|
+
tableName: 'orders',
|
|
1037
|
+
title: 'Custom Orders',
|
|
1038
|
+
fields: [{ name: 'note', type: 'string', title: 'Custom Note' }],
|
|
1039
|
+
},
|
|
1040
|
+
};
|
|
1041
|
+
dataSourcesRepo.findOne.mockResolvedValue({
|
|
1042
|
+
loadLocalData: vi.fn().mockResolvedValue(savedLocalData),
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
const prepareSpy = vi.spyOn(ds, 'prepareTables').mockResolvedValue([
|
|
1046
|
+
{
|
|
1047
|
+
name: 'orders',
|
|
1048
|
+
tableName: 'orders',
|
|
1049
|
+
title: 'Custom Orders',
|
|
1050
|
+
fields: [
|
|
1051
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
1052
|
+
{ name: 'note', type: 'string', title: 'Custom Note' },
|
|
1053
|
+
],
|
|
1054
|
+
},
|
|
1055
|
+
]);
|
|
1056
|
+
const removeSpy = vi.spyOn(ds.collectionManager, 'removeCollection');
|
|
1057
|
+
vi.spyOn(ds, 'addSelectedTables').mockResolvedValue(false);
|
|
1058
|
+
vi.spyOn(ds.introspector, 'getTables').mockResolvedValue(['orders']);
|
|
1059
|
+
|
|
1060
|
+
await ds.loadTables(
|
|
1061
|
+
{
|
|
1062
|
+
action: { resourceName: 'dataSources', actionName: 'loadTables', params: {} },
|
|
1063
|
+
db: { getRepository: () => dataSourcesRepo },
|
|
1064
|
+
app: { pm: { get: () => plugin } },
|
|
1065
|
+
} as never,
|
|
1066
|
+
['orders'],
|
|
1067
|
+
);
|
|
1068
|
+
|
|
1069
|
+
expect(prepareSpy).toHaveBeenCalledWith(['orders'], savedLocalData);
|
|
1070
|
+
expect(removeSpy).toHaveBeenCalledWith('orders');
|
|
1071
|
+
expect(ds.collectionManager.getCollection('orders')?.options.title).toBe('Custom Orders');
|
|
1072
|
+
expect(sendSyncMessage).toHaveBeenCalledWith({
|
|
1073
|
+
type: 'tablesLoaded',
|
|
1074
|
+
dataSourceKey: 'pg-ext',
|
|
1075
|
+
tableNames: ['orders'],
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
prepareSpy.mockClear();
|
|
1079
|
+
await plugin.handleSyncMessage({
|
|
1080
|
+
type: 'tablesLoaded',
|
|
1081
|
+
dataSourceKey: 'pg-ext',
|
|
1082
|
+
tableNames: ['orders'],
|
|
1083
|
+
});
|
|
1084
|
+
expect(prepareSpy).toHaveBeenCalledWith(['orders'], savedLocalData);
|
|
1085
|
+
});
|
|
1086
|
+
|
|
1087
|
+
it('rejects virtual fields in addField and creates join tables with foreign keys in ensureJoinTable', async () => {
|
|
1088
|
+
const ds = createDataSource({ name: 'pg-ddl' });
|
|
1089
|
+
ds.collectionManager.defineCollection({
|
|
1090
|
+
name: 'orders',
|
|
1091
|
+
tableName: 'orders',
|
|
1092
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1093
|
+
});
|
|
1094
|
+
ds.collectionManager.defineCollection({
|
|
1095
|
+
name: 'tags',
|
|
1096
|
+
tableName: 'tags',
|
|
1097
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1098
|
+
});
|
|
1099
|
+
|
|
1100
|
+
await expect(
|
|
1101
|
+
ds.collectionManager.addField('orders', { name: 'calc', type: 'virtual' }, {} as never),
|
|
1102
|
+
).rejects.toThrow('Field type virtual does not represent a PostgreSQL column');
|
|
1103
|
+
|
|
1104
|
+
const executed: string[] = [];
|
|
1105
|
+
let throughCreated = false;
|
|
1106
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, opts) => {
|
|
1107
|
+
const text = String(sql);
|
|
1108
|
+
executed.push(text);
|
|
1109
|
+
const replacements = (opts as { replacements?: { tableName?: string; columnName?: string } } | undefined)
|
|
1110
|
+
?.replacements;
|
|
1111
|
+
if (text.includes('pg_catalog.format_type')) {
|
|
1112
|
+
if (replacements?.tableName === 'orders' || replacements?.tableName === 'tags') {
|
|
1113
|
+
return [{ dataType: 'bigint' }] as never;
|
|
1114
|
+
}
|
|
1115
|
+
return (throughCreated ? [{ dataType: 'bigint' }] : []) as never;
|
|
1116
|
+
}
|
|
1117
|
+
if (text.includes('SELECT c.relkind AS kind')) {
|
|
1118
|
+
if (replacements?.tableName === 'orders_tags') {
|
|
1119
|
+
return (throughCreated ? [{ kind: 'r' }] : []) as never;
|
|
1120
|
+
}
|
|
1121
|
+
return [{ kind: 'r' }] as never;
|
|
1122
|
+
}
|
|
1123
|
+
if (text.startsWith('CREATE TABLE ')) {
|
|
1124
|
+
throughCreated = true;
|
|
1125
|
+
}
|
|
1126
|
+
return [] as never;
|
|
1127
|
+
});
|
|
1128
|
+
|
|
1129
|
+
await ds.collectionManager.ensureJoinTable(
|
|
1130
|
+
'orders',
|
|
1131
|
+
{
|
|
1132
|
+
through: 'orders_tags',
|
|
1133
|
+
foreignKey: 'orderId',
|
|
1134
|
+
otherKey: 'tagId',
|
|
1135
|
+
sourceKey: 'id',
|
|
1136
|
+
targetKey: 'id',
|
|
1137
|
+
target: 'tags',
|
|
1138
|
+
},
|
|
1139
|
+
{} as never,
|
|
1140
|
+
);
|
|
1141
|
+
|
|
1142
|
+
expect(executed.some((q) => q.startsWith('CREATE TABLE "public"."orders_tags"'))).toBe(true);
|
|
1143
|
+
expect(executed.some((q) => q.startsWith('CREATE INDEX '))).toBe(true);
|
|
1144
|
+
expect(executed.filter((q) => q.includes('FOREIGN KEY'))).toHaveLength(2);
|
|
1145
|
+
});
|
|
1146
|
+
|
|
1147
|
+
it('replaces an existing foreign key constraint when updating onDelete/onUpdate while preserving unspecified actions', async () => {
|
|
1148
|
+
const ds = createDataSource({ name: 'pg-fk-update' });
|
|
1149
|
+
ds.collectionManager.defineCollection({
|
|
1150
|
+
name: 'orders',
|
|
1151
|
+
tableName: 'orders',
|
|
1152
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1153
|
+
});
|
|
1154
|
+
ds.collectionManager.defineCollection({
|
|
1155
|
+
name: 'order_items',
|
|
1156
|
+
tableName: 'order_items',
|
|
1157
|
+
fields: [
|
|
1158
|
+
{ name: 'id', type: 'bigInt', primaryKey: true },
|
|
1159
|
+
{ name: 'orderId', type: 'bigInt' },
|
|
1160
|
+
],
|
|
1161
|
+
});
|
|
1162
|
+
|
|
1163
|
+
const executed: string[] = [];
|
|
1164
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql) => {
|
|
1165
|
+
const text = String(sql);
|
|
1166
|
+
executed.push(text);
|
|
1167
|
+
if (text.includes('SELECT c.relkind AS kind')) return [{ kind: 'r' }] as never;
|
|
1168
|
+
if (text.includes('pg_catalog.format_type')) return [{ dataType: 'bigint' }] as never;
|
|
1169
|
+
if (text.includes('FROM pg_catalog.pg_constraint')) {
|
|
1170
|
+
return [
|
|
1171
|
+
{
|
|
1172
|
+
constraintName: 'fk_existing_order',
|
|
1173
|
+
targetSchema: 'public',
|
|
1174
|
+
targetTable: 'orders',
|
|
1175
|
+
targetColumn: 'id',
|
|
1176
|
+
deleteAction: 'n',
|
|
1177
|
+
updateAction: 'r',
|
|
1178
|
+
columnCount: 1,
|
|
1179
|
+
},
|
|
1180
|
+
] as never;
|
|
1181
|
+
}
|
|
1182
|
+
return [] as never;
|
|
1183
|
+
});
|
|
1184
|
+
|
|
1185
|
+
await expect(
|
|
1186
|
+
ds.collectionManager.ensureForeignKey(
|
|
1187
|
+
'order_items',
|
|
1188
|
+
{ foreignKey: 'orderId', targetKey: 'id', target: 'orders', onDelete: 'CASCADE' },
|
|
1189
|
+
{} as never,
|
|
1190
|
+
),
|
|
1191
|
+
).rejects.toThrow('Conflicting foreign key exists');
|
|
1192
|
+
|
|
1193
|
+
await ds.collectionManager.ensureForeignKey(
|
|
1194
|
+
'order_items',
|
|
1195
|
+
{ foreignKey: 'orderId', targetKey: 'id', target: 'orders', onDelete: 'CASCADE', replaceActions: true },
|
|
1196
|
+
{} as never,
|
|
1197
|
+
);
|
|
1198
|
+
|
|
1199
|
+
expect(executed.some((q) => q === 'ALTER TABLE "public"."order_items" DROP CONSTRAINT "fk_existing_order"')).toBe(
|
|
1200
|
+
true,
|
|
1201
|
+
);
|
|
1202
|
+
expect(
|
|
1203
|
+
executed.some((q) => q.includes('ADD CONSTRAINT') && q.includes('ON DELETE CASCADE ON UPDATE RESTRICT')),
|
|
1204
|
+
).toBe(true);
|
|
1205
|
+
});
|
|
1206
|
+
|
|
1207
|
+
it('rolls back replaced and newly added collections if defineCollection throws during batch replacement', () => {
|
|
1208
|
+
const ds = createDataSource({ name: 'pg-rollback' });
|
|
1209
|
+
ds.collectionManager.defineCollection({
|
|
1210
|
+
name: 'orders',
|
|
1211
|
+
tableName: 'orders',
|
|
1212
|
+
title: 'Original Orders',
|
|
1213
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1214
|
+
});
|
|
1215
|
+
|
|
1216
|
+
const originalDefine = ds.collectionManager.defineCollection.bind(ds.collectionManager);
|
|
1217
|
+
vi.spyOn(ds.collectionManager, 'defineCollection').mockImplementation((options) => {
|
|
1218
|
+
if (options.name === 'broken') {
|
|
1219
|
+
throw new Error('Invalid saved relation');
|
|
1220
|
+
}
|
|
1221
|
+
return originalDefine(options);
|
|
1222
|
+
});
|
|
1223
|
+
|
|
1224
|
+
expect(() =>
|
|
1225
|
+
ds.collectionManager.replaceCollections([
|
|
1226
|
+
{
|
|
1227
|
+
name: 'orders',
|
|
1228
|
+
tableName: 'orders',
|
|
1229
|
+
title: 'Updated Orders',
|
|
1230
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1231
|
+
},
|
|
1232
|
+
{
|
|
1233
|
+
name: 'fresh_table',
|
|
1234
|
+
tableName: 'fresh_table',
|
|
1235
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1236
|
+
},
|
|
1237
|
+
{
|
|
1238
|
+
name: 'broken',
|
|
1239
|
+
tableName: 'broken',
|
|
1240
|
+
fields: [],
|
|
1241
|
+
},
|
|
1242
|
+
]),
|
|
1243
|
+
).toThrow('Invalid saved relation');
|
|
1244
|
+
|
|
1245
|
+
expect(ds.collectionManager.hasCollection('orders')).toBe(true);
|
|
1246
|
+
expect(ds.collectionManager.getCollection('orders')?.options.title).toBe('Original Orders');
|
|
1247
|
+
expect(ds.collectionManager.hasCollection('fresh_table')).toBe(false);
|
|
1248
|
+
});
|
|
1249
|
+
|
|
1250
|
+
it('queues tablesLoaded behind selectionChanged and does not resurrect deselected tables on HA peers', async () => {
|
|
1251
|
+
const { plugin, ds, dataSourcesRepo } = createPluginHarness();
|
|
1252
|
+
await plugin.load();
|
|
1253
|
+
ds.options = {
|
|
1254
|
+
...ds.options,
|
|
1255
|
+
addAllCollections: false,
|
|
1256
|
+
selectedCollections: ['orders'],
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
let releaseReconcile: (() => void) | undefined;
|
|
1260
|
+
const reconcileGate = new Promise<void>((resolve) => {
|
|
1261
|
+
releaseReconcile = resolve;
|
|
1262
|
+
});
|
|
1263
|
+
const order: string[] = [];
|
|
1264
|
+
|
|
1265
|
+
dataSourcesRepo.findOne.mockImplementation(async () => ({
|
|
1266
|
+
get: (field: string) =>
|
|
1267
|
+
field === 'options'
|
|
1268
|
+
? {
|
|
1269
|
+
host: '127.0.0.1',
|
|
1270
|
+
port: 5432,
|
|
1271
|
+
database: 'sales',
|
|
1272
|
+
username: 'postgres',
|
|
1273
|
+
password: 'secret-password',
|
|
1274
|
+
ssl: true,
|
|
1275
|
+
sslCa: '-----BEGIN CERTIFICATE-----',
|
|
1276
|
+
addAllCollections: false,
|
|
1277
|
+
selectedCollections: [],
|
|
1278
|
+
}
|
|
1279
|
+
: undefined,
|
|
1280
|
+
loadLocalData: vi.fn().mockResolvedValue({}),
|
|
1281
|
+
}));
|
|
1282
|
+
vi.spyOn(ds.introspector, 'getTables').mockImplementation(async () => {
|
|
1283
|
+
order.push('getTables');
|
|
1284
|
+
await reconcileGate;
|
|
1285
|
+
return ['orders'];
|
|
1286
|
+
});
|
|
1287
|
+
const prepareSpy = vi.spyOn(ds, 'prepareTables').mockImplementation(async (tables) => {
|
|
1288
|
+
order.push(`prepare:${tables.join(',')}`);
|
|
1289
|
+
return tables.map((name) => ({
|
|
1290
|
+
name,
|
|
1291
|
+
tableName: name,
|
|
1292
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
1293
|
+
}));
|
|
1294
|
+
});
|
|
1295
|
+
|
|
1296
|
+
const selectionPromise = plugin.handleSyncMessage({
|
|
1297
|
+
type: 'selectionChanged',
|
|
1298
|
+
dataSourceKey: 'pg-ext',
|
|
1299
|
+
});
|
|
1300
|
+
const loadedPromise = plugin.handleSyncMessage({
|
|
1301
|
+
type: 'tablesLoaded',
|
|
1302
|
+
dataSourceKey: 'pg-ext',
|
|
1303
|
+
tableNames: ['orders'],
|
|
1304
|
+
});
|
|
1305
|
+
|
|
1306
|
+
await Promise.resolve();
|
|
1307
|
+
releaseReconcile?.();
|
|
1308
|
+
await Promise.all([selectionPromise, loadedPromise]);
|
|
1309
|
+
|
|
1310
|
+
expect(ds.collectionManager.hasCollection('orders')).toBe(false);
|
|
1311
|
+
expect(prepareSpy).toHaveBeenCalledWith([], {});
|
|
1312
|
+
expect(order).toEqual(['getTables', 'prepare:']);
|
|
1313
|
+
});
|
|
1314
|
+
|
|
1315
|
+
it('preserves selectedCollections on v1 edit when __postgresPreserveSelection is set while allowing v2 clear-all', async () => {
|
|
1316
|
+
const ds = createDataSource({ name: 'pg-v1-preserve', addAllCollections: false, selectedCollections: ['orders'] });
|
|
1317
|
+
vi.spyOn(ds, 'prepareTables').mockResolvedValue([]);
|
|
1318
|
+
vi.spyOn(ds, 'close').mockResolvedValue(undefined);
|
|
1319
|
+
|
|
1320
|
+
const v1Params = {
|
|
1321
|
+
values: {
|
|
1322
|
+
__postgresPreserveSelection: true,
|
|
1323
|
+
collections: [],
|
|
1324
|
+
options: {
|
|
1325
|
+
addAllCollections: false,
|
|
1326
|
+
selectedCollections: ['orders'],
|
|
1327
|
+
},
|
|
1328
|
+
},
|
|
1329
|
+
};
|
|
1330
|
+
await ds.loadTables(
|
|
1331
|
+
{ action: { resourceName: 'dataSources', actionName: 'update', params: v1Params } } as never,
|
|
1332
|
+
[],
|
|
1333
|
+
);
|
|
1334
|
+
expect('__postgresPreserveSelection' in v1Params.values).toBe(false);
|
|
1335
|
+
expect(v1Params.values.options.selectedCollections).toEqual(['orders']);
|
|
1336
|
+
|
|
1337
|
+
const v2Params = {
|
|
1338
|
+
values: {
|
|
1339
|
+
collections: [],
|
|
1340
|
+
options: {
|
|
1341
|
+
addAllCollections: false,
|
|
1342
|
+
selectedCollections: ['orders'],
|
|
1343
|
+
},
|
|
1344
|
+
},
|
|
1345
|
+
};
|
|
1346
|
+
await ds.loadTables(
|
|
1347
|
+
{ action: { resourceName: 'dataSources', actionName: 'update', params: v2Params } } as never,
|
|
1348
|
+
[],
|
|
1349
|
+
);
|
|
1350
|
+
expect(v2Params.values.options.selectedCollections).toEqual([]);
|
|
1351
|
+
});
|
|
1352
|
+
|
|
1353
|
+
it('registers and persists companion array fields for m2m_array, validates view/join-table DDL, and isolates destroy cleanup & pool lifecycle', async () => {
|
|
1354
|
+
const { plugin, ds, app, middlewares, fieldsRepo, dataSourcesRepo, dbEvents } = createPluginHarness();
|
|
1355
|
+
const createFieldSpy = vi.fn().mockResolvedValue(undefined);
|
|
1356
|
+
(fieldsRepo as Record<string, unknown>).create = createFieldSpy;
|
|
1357
|
+
ds.collectionManager.defineCollection({
|
|
1358
|
+
name: 'tags',
|
|
1359
|
+
tableName: 'tags',
|
|
1360
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1361
|
+
});
|
|
1362
|
+
|
|
1363
|
+
await plugin.beforeLoad();
|
|
1364
|
+
await plugin.load();
|
|
1365
|
+
const schemaMiddleware = middlewares[1];
|
|
1366
|
+
|
|
1367
|
+
// 1. m2m_array creates & binds companion foreignKey field in memory and persists it to dataSourcesFields.
|
|
1368
|
+
vi.spyOn(ds.collectionManager, 'ensureForeignKeyArray').mockResolvedValue(undefined);
|
|
1369
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
1370
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
1371
|
+
) => cb({})) as never);
|
|
1372
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
1373
|
+
|
|
1374
|
+
const arrayInput: Record<string, unknown> = {
|
|
1375
|
+
name: 'tagRefs',
|
|
1376
|
+
interface: 'm2m_array',
|
|
1377
|
+
target: 'tags',
|
|
1378
|
+
};
|
|
1379
|
+
await schemaMiddleware(
|
|
1380
|
+
{
|
|
1381
|
+
action: {
|
|
1382
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
1383
|
+
actionName: 'create',
|
|
1384
|
+
params: { associatedIndex: 'pg-ext.orders', values: arrayInput },
|
|
1385
|
+
},
|
|
1386
|
+
db: app.db,
|
|
1387
|
+
},
|
|
1388
|
+
vi.fn().mockResolvedValue(undefined),
|
|
1389
|
+
);
|
|
1390
|
+
expect(ds.collectionManager.getCollection('orders')?.getField('tagRefId')?.options).toMatchObject({
|
|
1391
|
+
name: 'tagRefId',
|
|
1392
|
+
type: 'set',
|
|
1393
|
+
dataType: 'array',
|
|
1394
|
+
elementType: 'bigInt',
|
|
1395
|
+
isForeignKey: true,
|
|
1396
|
+
});
|
|
1397
|
+
expect(createFieldSpy).toHaveBeenCalledWith({
|
|
1398
|
+
values: expect.objectContaining({
|
|
1399
|
+
name: 'tagRefId',
|
|
1400
|
+
collectionName: 'orders',
|
|
1401
|
+
dataSourceKey: 'pg-ext',
|
|
1402
|
+
type: 'set',
|
|
1403
|
+
dataType: 'array',
|
|
1404
|
+
elementType: 'bigInt',
|
|
1405
|
+
}),
|
|
1406
|
+
});
|
|
1407
|
+
|
|
1408
|
+
// 2. DDL validations: ensureForeignKey rejects view target before ADD COLUMN; ensureJoinTable rejects SET NULL & tableName collision; ensureForeignKeyArray rejects incompatible scalar column.
|
|
1409
|
+
const ddlDs = createDataSource({ name: 'pg-ddl-guards' });
|
|
1410
|
+
ddlDs.collectionManager.defineCollection({
|
|
1411
|
+
name: 'orders',
|
|
1412
|
+
tableName: 'pg_orders',
|
|
1413
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1414
|
+
});
|
|
1415
|
+
ddlDs.collectionManager.defineCollection({
|
|
1416
|
+
name: 'tags',
|
|
1417
|
+
tableName: 'tags',
|
|
1418
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
1419
|
+
});
|
|
1420
|
+
const ddlExecuted: string[] = [];
|
|
1421
|
+
vi.spyOn(ddlDs.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, opts) => {
|
|
1422
|
+
const text = String(sql);
|
|
1423
|
+
ddlExecuted.push(text);
|
|
1424
|
+
const replacements = (opts as { replacements?: { tableName?: string; columnName?: string } } | undefined)
|
|
1425
|
+
?.replacements;
|
|
1426
|
+
if (text.includes('SELECT c.relkind AS kind')) {
|
|
1427
|
+
if (replacements?.tableName === 'order_view') return [{ kind: 'v' }] as never;
|
|
1428
|
+
if (replacements?.tableName === 'orders_tags_new') return [] as never;
|
|
1429
|
+
return [{ kind: 'r' }] as never;
|
|
1430
|
+
}
|
|
1431
|
+
if (text.includes('pg_catalog.format_type')) {
|
|
1432
|
+
if (replacements?.columnName === 'badScalar') return [{ dataType: 'character varying(255)' }] as never;
|
|
1433
|
+
return [{ dataType: 'bigint' }] as never;
|
|
1434
|
+
}
|
|
1435
|
+
return [] as never;
|
|
1436
|
+
});
|
|
1437
|
+
|
|
1438
|
+
await expect(
|
|
1439
|
+
ddlDs.collectionManager.ensureForeignKey(
|
|
1440
|
+
'orders',
|
|
1441
|
+
{ foreignKey: 'viewId', targetKey: 'id', target: 'order_view' },
|
|
1442
|
+
{} as never,
|
|
1443
|
+
),
|
|
1444
|
+
).rejects.toThrow('This collection is read-only');
|
|
1445
|
+
expect(ddlExecuted.some((q) => q.includes('ADD COLUMN'))).toBe(false);
|
|
1446
|
+
|
|
1447
|
+
await expect(
|
|
1448
|
+
ddlDs.collectionManager.ensureJoinTable(
|
|
1449
|
+
'orders',
|
|
1450
|
+
{
|
|
1451
|
+
through: 'pg_orders',
|
|
1452
|
+
foreignKey: 'orderId',
|
|
1453
|
+
otherKey: 'tagId',
|
|
1454
|
+
sourceKey: 'id',
|
|
1455
|
+
targetKey: 'id',
|
|
1456
|
+
target: 'tags',
|
|
1457
|
+
},
|
|
1458
|
+
{} as never,
|
|
1459
|
+
),
|
|
1460
|
+
).rejects.toThrow('Join table pg_orders cannot match source or target collection');
|
|
1461
|
+
|
|
1462
|
+
await expect(
|
|
1463
|
+
ddlDs.collectionManager.ensureJoinTable(
|
|
1464
|
+
'orders',
|
|
1465
|
+
{
|
|
1466
|
+
through: 'orders_tags_new',
|
|
1467
|
+
foreignKey: 'orderId',
|
|
1468
|
+
otherKey: 'tagId',
|
|
1469
|
+
sourceKey: 'id',
|
|
1470
|
+
targetKey: 'id',
|
|
1471
|
+
target: 'tags',
|
|
1472
|
+
onDelete: 'SET NULL',
|
|
1473
|
+
},
|
|
1474
|
+
{} as never,
|
|
1475
|
+
),
|
|
1476
|
+
).rejects.toThrow('Invalid PostgreSQL foreign key action');
|
|
1477
|
+
|
|
1478
|
+
await expect(
|
|
1479
|
+
ddlDs.collectionManager.ensureForeignKeyArray(
|
|
1480
|
+
'orders',
|
|
1481
|
+
{ foreignKey: 'badScalar', targetKey: 'id', target: 'tags' },
|
|
1482
|
+
{} as never,
|
|
1483
|
+
),
|
|
1484
|
+
).rejects.toThrow('Foreign key orders.badScalar has incompatible PostgreSQL type character varying(255)');
|
|
1485
|
+
|
|
1486
|
+
// 3. collections:destroy logs warning instead of rolling back DROP TABLE if fieldsRepo.destroy throws post-commit.
|
|
1487
|
+
vi.spyOn(ds.collectionManager, 'dropTable').mockResolvedValue(undefined);
|
|
1488
|
+
vi.spyOn(ds, 'removeSelectedTables').mockResolvedValue(false);
|
|
1489
|
+
fieldsRepo.destroy.mockRejectedValueOnce(new Error('transient main-db timeout'));
|
|
1490
|
+
await schemaMiddleware(
|
|
1491
|
+
{
|
|
1492
|
+
action: {
|
|
1493
|
+
resourceName: 'dataSources.collections',
|
|
1494
|
+
actionName: 'destroy',
|
|
1495
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'tags' },
|
|
1496
|
+
},
|
|
1497
|
+
},
|
|
1498
|
+
vi.fn().mockResolvedValue(undefined),
|
|
1499
|
+
);
|
|
1500
|
+
expect(ds.collectionManager.hasCollection('tags')).toBe(false);
|
|
1501
|
+
expect(app.log.warn).toHaveBeenCalled();
|
|
1502
|
+
|
|
1503
|
+
// 4. Pool lifecycle: failed reload keeps original source tracked; same-key replacement is not closed by stale afterCommit or late HA message; close errors in afterCommit are caught.
|
|
1504
|
+
const failingReload = createDataSource({ name: 'pg-ext' });
|
|
1505
|
+
vi.spyOn(failingReload, 'load').mockRejectedValueOnce(new Error('bad password'));
|
|
1506
|
+
await expect(app.dataSourceManager.add(failingReload, { reuseDB: true })).rejects.toThrow('bad password');
|
|
1507
|
+
|
|
1508
|
+
const originalCloseSpy = vi.spyOn(ds, 'close').mockRejectedValueOnce(new Error('socket already closed'));
|
|
1509
|
+
const destroyListeners = dbEvents.get('dataSources.afterDestroy') || [];
|
|
1510
|
+
app.dataSourceManager.dataSources.delete('pg-ext');
|
|
1511
|
+
|
|
1512
|
+
let commitCallback: (() => Promise<void> | void) | undefined;
|
|
1513
|
+
await destroyListeners[0](
|
|
1514
|
+
{ get: (field: string) => (field === 'type' ? DATA_SOURCE_TYPE : field === 'key' ? 'pg-ext' : undefined) },
|
|
1515
|
+
{
|
|
1516
|
+
transaction: {
|
|
1517
|
+
afterCommit: (fn: () => Promise<void> | void) => {
|
|
1518
|
+
commitCallback = fn;
|
|
1519
|
+
},
|
|
1520
|
+
},
|
|
1521
|
+
},
|
|
1522
|
+
);
|
|
1523
|
+
|
|
1524
|
+
const replacement = createDataSource({ name: 'pg-ext' });
|
|
1525
|
+
const replacementCloseSpy = vi.spyOn(replacement, 'close').mockResolvedValue(undefined);
|
|
1526
|
+
vi.spyOn(replacement, 'load').mockResolvedValueOnce(undefined);
|
|
1527
|
+
await app.dataSourceManager.add(replacement);
|
|
1528
|
+
|
|
1529
|
+
await expect(Promise.resolve(commitCallback?.())).resolves.toBeUndefined();
|
|
1530
|
+
expect(originalCloseSpy).toHaveBeenCalledOnce();
|
|
1531
|
+
expect(replacementCloseSpy).not.toHaveBeenCalled();
|
|
1532
|
+
expect(app.dataSourceManager.get('pg-ext')).toBe(replacement);
|
|
1533
|
+
|
|
1534
|
+
dataSourcesRepo.findOne.mockResolvedValueOnce({ key: 'pg-ext' });
|
|
1535
|
+
await plugin.handleSyncMessage({ type: 'dataSourceRemoved', dataSourceKey: 'pg-ext' });
|
|
1536
|
+
expect(replacementCloseSpy).not.toHaveBeenCalled();
|
|
1537
|
+
});
|
|
1538
|
+
});
|