plugin-data-source-postgres 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/constants.js +3 -0
- package/dist/externalVersion.js +10 -8
- package/dist/locale/en-US.json +8 -1
- package/dist/locale/zh-CN.json +8 -1
- package/dist/server/collections/sql-collection.js +2 -2
- package/dist/server/collections/sql-model.js +4 -2
- package/dist/server/hooks/field-hooks.js +20 -0
- package/dist/server/plugin.js +727 -23
- package/dist/server/postgres-collection-manager.js +192 -25
- package/dist/server/postgres-datasource.js +47 -13
- package/dist/server/utils/sql-validator.js +119 -69
- package/package.json +2 -2
- package/src/client/ConfigurationForm.tsx +312 -133
- package/src/client/__tests__/client-v1.test.tsx +80 -0
- package/src/client-v2/PostgresConfigForm.tsx +133 -6
- package/src/client-v2/__tests__/plugin.test.tsx +69 -0
- package/src/client-v2/plugin.tsx +2 -2
- package/src/constants.ts +15 -0
- package/src/locale/en-US.json +8 -1
- package/src/locale/zh-CN.json +8 -1
- package/src/server/__tests__/postgres-datasource.unit.test.ts +1038 -0
- package/src/server/__tests__/sql-model.test.ts +47 -3
- package/src/server/__tests__/sql-validator.test.ts +8 -1
- package/src/server/collections/sql-collection.ts +2 -2
- package/src/server/collections/sql-model.ts +2 -2
- package/src/server/hooks/field-hooks.ts +36 -2
- package/src/server/plugin.ts +912 -18
- package/src/server/postgres-collection-manager.ts +228 -28
- package/src/server/postgres-datasource.ts +57 -12
- package/src/server/utils/sql-validator.ts +123 -68
- package/dist/client-v2/985.34da95acdf7743ab.js +0 -10
|
@@ -51,6 +51,58 @@ describe('PostgresDataSource unit behavior', () => {
|
|
|
51
51
|
expect(ds.publicOptions()).toBeNull();
|
|
52
52
|
});
|
|
53
53
|
|
|
54
|
+
it('supports direct loadTables calls without ctx.action or params and preserves reusedDatabase', async () => {
|
|
55
|
+
const ds = createDataSource({ selectedCollections: [], autoDiscover: false });
|
|
56
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'authenticate').mockResolvedValue(undefined);
|
|
57
|
+
vi.spyOn(ds.introspector, 'getTables').mockResolvedValue(['orders']);
|
|
58
|
+
vi.spyOn(ds, 'prepareTables').mockImplementation(async (tables) =>
|
|
59
|
+
tables.map((name) => ({
|
|
60
|
+
name,
|
|
61
|
+
tableName: name,
|
|
62
|
+
introspected: true,
|
|
63
|
+
fields: [{ name: 'id', type: 'bigInt', primaryKey: true }],
|
|
64
|
+
})),
|
|
65
|
+
);
|
|
66
|
+
const closeSpy = vi.spyOn(ds, 'close');
|
|
67
|
+
|
|
68
|
+
await ds.load();
|
|
69
|
+
expect(ds.collectionManager.getCollections()).toHaveLength(0);
|
|
70
|
+
|
|
71
|
+
await ds.loadTables({} as never, ['orders']);
|
|
72
|
+
expect(ds.collectionManager.getCollections().map((c) => c.name)).toEqual(['orders']);
|
|
73
|
+
expect(closeSpy).not.toHaveBeenCalled();
|
|
74
|
+
|
|
75
|
+
await ds.loadTables({ action: {} } as never, ['orders']);
|
|
76
|
+
expect(ds.collectionManager.getCollections().map((c) => c.name)).toEqual(['orders']);
|
|
77
|
+
|
|
78
|
+
const sharedDb = new Database({
|
|
79
|
+
dialect: 'postgres',
|
|
80
|
+
host: '127.0.0.1',
|
|
81
|
+
port: 5432,
|
|
82
|
+
database: 'sales',
|
|
83
|
+
username: 'postgres',
|
|
84
|
+
logging: false,
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
const reused = new PostgresDataSource({
|
|
88
|
+
name: 'pg-reused',
|
|
89
|
+
databaseInstance: sharedDb,
|
|
90
|
+
addAllCollections: false,
|
|
91
|
+
autoDiscover: false,
|
|
92
|
+
});
|
|
93
|
+
vi.spyOn(reused, 'prepareTables').mockResolvedValue([
|
|
94
|
+
{ name: 'orders', tableName: 'orders', introspected: true, fields: [] },
|
|
95
|
+
]);
|
|
96
|
+
const sharedCloseSpy = vi.spyOn(sharedDb, 'close');
|
|
97
|
+
|
|
98
|
+
await reused.loadTables(undefined as never, ['orders']);
|
|
99
|
+
expect(reused.collectionManager.getCollections().map((c) => c.name)).toEqual(['orders']);
|
|
100
|
+
expect(sharedCloseSpy).not.toHaveBeenCalled();
|
|
101
|
+
} finally {
|
|
102
|
+
await sharedDb.close();
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
54
106
|
it('batches identity and relkind queries in prepareTables instead of running N+1 queries', async () => {
|
|
55
107
|
const ds = createDataSource();
|
|
56
108
|
const querySpy = vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql) => {
|
|
@@ -390,6 +442,8 @@ describe('PostgresTreeCollection and PostgresAdjacencyListRepository', () => {
|
|
|
390
442
|
describe('PluginDataSourcePostgresServer middleware and sync', () => {
|
|
391
443
|
function createPluginHarness() {
|
|
392
444
|
const preHandlers = new Map<string, (ctx: unknown, next: () => Promise<void>) => Promise<void>>();
|
|
445
|
+
const actionHandlers = new Map<string, (ctx: unknown, next: () => Promise<void>) => Promise<void>>();
|
|
446
|
+
const resourceActions = new Map<string, (ctx: unknown, next: () => Promise<void>) => Promise<void>>();
|
|
393
447
|
const middlewares: Array<(ctx: unknown, next: () => Promise<void>) => Promise<void>> = [];
|
|
394
448
|
const dataSourceManager = new DataSourceManager();
|
|
395
449
|
dataSourceManager.registerDataSourceType(DATA_SOURCE_TYPE, PostgresDataSource);
|
|
@@ -440,6 +494,23 @@ describe('PluginDataSourcePostgresServer middleware and sync', () => {
|
|
|
440
494
|
},
|
|
441
495
|
},
|
|
442
496
|
resourceManager: {
|
|
497
|
+
registerActionHandlers: (
|
|
498
|
+
handlers: Record<string, (ctx: unknown, next: () => Promise<void>) => Promise<void>>,
|
|
499
|
+
) => {
|
|
500
|
+
for (const [name, fn] of Object.entries(handlers)) {
|
|
501
|
+
actionHandlers.set(name, fn);
|
|
502
|
+
}
|
|
503
|
+
},
|
|
504
|
+
isDefined: (name: string) => name === 'dataSources',
|
|
505
|
+
getResource: (name: string) =>
|
|
506
|
+
name === 'dataSources'
|
|
507
|
+
? {
|
|
508
|
+
actions: resourceActions,
|
|
509
|
+
addAction: (actionName: string, fn: (ctx: unknown, next: () => Promise<void>) => Promise<void>) => {
|
|
510
|
+
resourceActions.set(actionName, fn);
|
|
511
|
+
},
|
|
512
|
+
}
|
|
513
|
+
: undefined,
|
|
443
514
|
registerPreActionHandler: (name: string, fn: (ctx: unknown, next: () => Promise<void>) => Promise<void>) => {
|
|
444
515
|
preHandlers.set(name, fn);
|
|
445
516
|
},
|
|
@@ -453,6 +524,8 @@ describe('PluginDataSourcePostgresServer middleware and sync', () => {
|
|
|
453
524
|
return {
|
|
454
525
|
plugin,
|
|
455
526
|
ds,
|
|
527
|
+
actionHandlers,
|
|
528
|
+
resourceActions,
|
|
456
529
|
preHandlers,
|
|
457
530
|
middlewares,
|
|
458
531
|
fieldsRepo,
|
|
@@ -1535,4 +1608,969 @@ describe('PluginDataSourcePostgresServer middleware and sync', () => {
|
|
|
1535
1608
|
await plugin.handleSyncMessage({ type: 'dataSourceRemoved', dataSourceKey: 'pg-ext' });
|
|
1536
1609
|
expect(replacementCloseSpy).not.toHaveBeenCalled();
|
|
1537
1610
|
});
|
|
1611
|
+
|
|
1612
|
+
it('filters collections consistently across DROP TABLE and metadata destroy for filterByTk, filter, and ACL scope', async () => {
|
|
1613
|
+
const { plugin, ds, middlewares, fieldsRepo, collectionsRepo, sendSyncMessage } = createPluginHarness();
|
|
1614
|
+
ds.collectionManager.defineCollection({
|
|
1615
|
+
name: 'invoices',
|
|
1616
|
+
tableName: 'invoices',
|
|
1617
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
1618
|
+
});
|
|
1619
|
+
await plugin.load();
|
|
1620
|
+
const schemaMiddleware = middlewares[1];
|
|
1621
|
+
|
|
1622
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
1623
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
1624
|
+
) => cb({})) as never);
|
|
1625
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
1626
|
+
const dropSpy = vi.spyOn(ds.collectionManager, 'dropTable').mockResolvedValue(undefined);
|
|
1627
|
+
vi.spyOn(ds, 'removeSelectedTables').mockResolvedValue(false);
|
|
1628
|
+
|
|
1629
|
+
// 1. Non-matching filter with filterByTk must drop nothing and skip next().
|
|
1630
|
+
const nextUnmatched = vi.fn().mockResolvedValue(undefined);
|
|
1631
|
+
const unmatchedCtx: Record<string, unknown> = {
|
|
1632
|
+
action: {
|
|
1633
|
+
resourceName: 'dataSources.collections',
|
|
1634
|
+
actionName: 'destroy',
|
|
1635
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'orders', filter: { name: 'invoices' } },
|
|
1636
|
+
},
|
|
1637
|
+
};
|
|
1638
|
+
await schemaMiddleware(unmatchedCtx, nextUnmatched);
|
|
1639
|
+
expect(dropSpy).not.toHaveBeenCalled();
|
|
1640
|
+
expect(nextUnmatched).not.toHaveBeenCalled();
|
|
1641
|
+
expect(ds.collectionManager.hasCollection('orders')).toBe(true);
|
|
1642
|
+
expect(unmatchedCtx.body).toBe(true);
|
|
1643
|
+
|
|
1644
|
+
// 2. Partial match via persisted collectionsRepo.find + ACL scope filter drops only the matched table
|
|
1645
|
+
// and passes the exact matched names (without filter) to next().
|
|
1646
|
+
(collectionsRepo as Record<string, unknown>).find = vi
|
|
1647
|
+
.fn()
|
|
1648
|
+
.mockResolvedValueOnce([{ get: () => 'orders' }, { get: () => 'invoices' }])
|
|
1649
|
+
.mockResolvedValueOnce([{ get: () => 'orders' }]);
|
|
1650
|
+
const partialParams: Record<string, unknown> = {
|
|
1651
|
+
associatedIndex: 'pg-ext',
|
|
1652
|
+
filterByTk: ['orders', 'invoices'],
|
|
1653
|
+
filter: { name: { $in: ['orders', 'invoices'] } },
|
|
1654
|
+
};
|
|
1655
|
+
const nextPartial = vi.fn().mockImplementation(async () => {
|
|
1656
|
+
expect(partialParams.filterByTk).toEqual(['orders']);
|
|
1657
|
+
expect(partialParams.filter).toBeUndefined();
|
|
1658
|
+
});
|
|
1659
|
+
await schemaMiddleware(
|
|
1660
|
+
{
|
|
1661
|
+
action: {
|
|
1662
|
+
resourceName: 'dataSources.collections',
|
|
1663
|
+
actionName: 'destroy',
|
|
1664
|
+
params: partialParams,
|
|
1665
|
+
},
|
|
1666
|
+
permission: {
|
|
1667
|
+
can: { params: { filter: { name: 'orders' } } },
|
|
1668
|
+
},
|
|
1669
|
+
},
|
|
1670
|
+
nextPartial,
|
|
1671
|
+
);
|
|
1672
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1673
|
+
expect(dropSpy).toHaveBeenCalledWith('orders', false, expect.anything());
|
|
1674
|
+
expect(nextPartial).toHaveBeenCalledOnce();
|
|
1675
|
+
expect(fieldsRepo.destroy).toHaveBeenCalledWith({
|
|
1676
|
+
filter: { dataSourceKey: 'pg-ext', collectionName: { $in: ['orders'] } },
|
|
1677
|
+
individualHooks: false,
|
|
1678
|
+
hooks: false,
|
|
1679
|
+
});
|
|
1680
|
+
expect(ds.collectionManager.hasCollection('orders')).toBe(false);
|
|
1681
|
+
expect(ds.collectionManager.hasCollection('invoices')).toBe(true);
|
|
1682
|
+
expect(sendSyncMessage).toHaveBeenLastCalledWith({
|
|
1683
|
+
type: 'collectionRemoved',
|
|
1684
|
+
dataSourceKey: 'pg-ext',
|
|
1685
|
+
collectionNames: ['orders'],
|
|
1686
|
+
});
|
|
1687
|
+
|
|
1688
|
+
// 3. Filter-only destroy (without filterByTk) resolves matched collections via filter.
|
|
1689
|
+
dropSpy.mockClear();
|
|
1690
|
+
(collectionsRepo as Record<string, unknown>).find = vi
|
|
1691
|
+
.fn()
|
|
1692
|
+
.mockResolvedValueOnce([{ get: () => 'invoices' }])
|
|
1693
|
+
.mockResolvedValueOnce([{ get: () => 'invoices' }]);
|
|
1694
|
+
const nextFilterOnly = vi.fn().mockResolvedValue(undefined);
|
|
1695
|
+
await schemaMiddleware(
|
|
1696
|
+
{
|
|
1697
|
+
action: {
|
|
1698
|
+
resourceName: 'dataSources.collections',
|
|
1699
|
+
actionName: 'destroy',
|
|
1700
|
+
params: { associatedIndex: 'pg-ext', filter: { name: 'invoices' } },
|
|
1701
|
+
},
|
|
1702
|
+
},
|
|
1703
|
+
nextFilterOnly,
|
|
1704
|
+
);
|
|
1705
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1706
|
+
expect(dropSpy).toHaveBeenCalledWith('invoices', false, expect.anything());
|
|
1707
|
+
expect(nextFilterOnly).toHaveBeenCalledOnce();
|
|
1708
|
+
expect(ds.collectionManager.hasCollection('invoices')).toBe(false);
|
|
1709
|
+
|
|
1710
|
+
// 4. Runtime-only collections (not yet persisted in dataSourcesCollections) must bind nested field
|
|
1711
|
+
// filters to the SAME field element instead of matching across different fields.
|
|
1712
|
+
ds.collectionManager.defineCollection({
|
|
1713
|
+
name: 'runtime_audit',
|
|
1714
|
+
tableName: 'runtime_audit',
|
|
1715
|
+
fields: [
|
|
1716
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
1717
|
+
{ name: 'code', type: 'string' },
|
|
1718
|
+
],
|
|
1719
|
+
});
|
|
1720
|
+
|
|
1721
|
+
for (const crossFieldFilter of [
|
|
1722
|
+
{ 'fields.name': 'code', 'fields.type': 'integer' },
|
|
1723
|
+
{ $and: [{ 'fields.name': 'code' }, { 'fields.type': 'integer' }] },
|
|
1724
|
+
{ $and: [{ fields: { name: 'code' } }, { fields: { type: 'integer' } }] },
|
|
1725
|
+
{ 'fields.name': { $startsWith: 'co', $endWith: 'id' } },
|
|
1726
|
+
]) {
|
|
1727
|
+
dropSpy.mockClear();
|
|
1728
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1729
|
+
const crossCtx: Record<string, unknown> = {
|
|
1730
|
+
action: {
|
|
1731
|
+
resourceName: 'dataSources.collections',
|
|
1732
|
+
actionName: 'destroy',
|
|
1733
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'runtime_audit', filter: crossFieldFilter },
|
|
1734
|
+
},
|
|
1735
|
+
};
|
|
1736
|
+
const crossNext = vi.fn().mockResolvedValue(undefined);
|
|
1737
|
+
await schemaMiddleware(crossCtx, crossNext);
|
|
1738
|
+
expect(dropSpy).not.toHaveBeenCalled();
|
|
1739
|
+
expect(crossNext).not.toHaveBeenCalled();
|
|
1740
|
+
expect(crossCtx.body).toBe(true);
|
|
1741
|
+
expect(ds.collectionManager.hasCollection('runtime_audit')).toBe(true);
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
// Separate filter vs ACL scope across different fields on runtime_audit must also fail to match,
|
|
1745
|
+
// including when both sides contain $or groups or nested fields.$or conditions, and $ne array
|
|
1746
|
+
// operands must follow core notIn semantics.
|
|
1747
|
+
for (const { filter, scope } of [
|
|
1748
|
+
{
|
|
1749
|
+
filter: { 'fields.name': 'code' },
|
|
1750
|
+
scope: { 'fields.type': 'integer' },
|
|
1751
|
+
},
|
|
1752
|
+
{
|
|
1753
|
+
filter: { $or: [{ 'fields.name': 'code' }, { 'fields.name': 'slug' }] },
|
|
1754
|
+
scope: { $or: [{ 'fields.type': 'integer' }, { 'fields.type': 'bigInt' }] },
|
|
1755
|
+
},
|
|
1756
|
+
{
|
|
1757
|
+
filter: { fields: { $or: [{ name: 'code' }, { name: 'slug' }] } },
|
|
1758
|
+
scope: { fields: { $or: [{ type: 'integer' }, { type: 'bigInt' }] } },
|
|
1759
|
+
},
|
|
1760
|
+
{
|
|
1761
|
+
filter: { name: { $ne: ['runtime_audit', 'orders'] } },
|
|
1762
|
+
scope: undefined,
|
|
1763
|
+
},
|
|
1764
|
+
{
|
|
1765
|
+
filter: { 'fields.name': { $ne: ['id', 'code'] } },
|
|
1766
|
+
scope: undefined,
|
|
1767
|
+
},
|
|
1768
|
+
]) {
|
|
1769
|
+
dropSpy.mockClear();
|
|
1770
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1771
|
+
const scopedCrossNext = vi.fn().mockResolvedValue(undefined);
|
|
1772
|
+
await schemaMiddleware(
|
|
1773
|
+
{
|
|
1774
|
+
action: {
|
|
1775
|
+
resourceName: 'dataSources.collections',
|
|
1776
|
+
actionName: 'destroy',
|
|
1777
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'runtime_audit', filter },
|
|
1778
|
+
},
|
|
1779
|
+
...(scope ? { permission: { can: { params: { filter: scope } } } } : {}),
|
|
1780
|
+
},
|
|
1781
|
+
scopedCrossNext,
|
|
1782
|
+
);
|
|
1783
|
+
expect(dropSpy).not.toHaveBeenCalled();
|
|
1784
|
+
expect(scopedCrossNext).not.toHaveBeenCalled();
|
|
1785
|
+
expect(ds.collectionManager.hasCollection('runtime_audit')).toBe(true);
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
// Same-field filter + ACL $or groups and $ne exclusion list mismatch DO match runtime_audit and drop it.
|
|
1789
|
+
dropSpy.mockClear();
|
|
1790
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1791
|
+
const matchedOrAndNeNext = vi.fn().mockResolvedValue(undefined);
|
|
1792
|
+
await schemaMiddleware(
|
|
1793
|
+
{
|
|
1794
|
+
action: {
|
|
1795
|
+
resourceName: 'dataSources.collections',
|
|
1796
|
+
actionName: 'destroy',
|
|
1797
|
+
params: {
|
|
1798
|
+
associatedIndex: 'pg-ext',
|
|
1799
|
+
filterByTk: 'runtime_audit',
|
|
1800
|
+
filter: {
|
|
1801
|
+
$and: [
|
|
1802
|
+
{ name: { $ne: ['other_table'] } },
|
|
1803
|
+
{ $or: [{ 'fields.name': 'code' }, { 'fields.name': 'slug' }] },
|
|
1804
|
+
],
|
|
1805
|
+
},
|
|
1806
|
+
},
|
|
1807
|
+
},
|
|
1808
|
+
permission: {
|
|
1809
|
+
can: { params: { filter: { $or: [{ 'fields.type': 'string' }, { 'fields.type': 'text' }] } } },
|
|
1810
|
+
},
|
|
1811
|
+
},
|
|
1812
|
+
matchedOrAndNeNext,
|
|
1813
|
+
);
|
|
1814
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1815
|
+
expect(dropSpy).toHaveBeenCalledWith('runtime_audit', false, expect.anything());
|
|
1816
|
+
expect(matchedOrAndNeNext).toHaveBeenCalledOnce();
|
|
1817
|
+
expect(ds.collectionManager.hasCollection('runtime_audit')).toBe(false);
|
|
1818
|
+
|
|
1819
|
+
// Same-field direct property filter ({ name: 'code', type: 'string' }) also matches and drops runtime_audit.
|
|
1820
|
+
ds.collectionManager.defineCollection({
|
|
1821
|
+
name: 'runtime_audit',
|
|
1822
|
+
tableName: 'runtime_audit',
|
|
1823
|
+
fields: [
|
|
1824
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
1825
|
+
{ name: 'code', type: 'string' },
|
|
1826
|
+
],
|
|
1827
|
+
});
|
|
1828
|
+
dropSpy.mockClear();
|
|
1829
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1830
|
+
const matchedRuntimeNext = vi.fn().mockResolvedValue(undefined);
|
|
1831
|
+
await schemaMiddleware(
|
|
1832
|
+
{
|
|
1833
|
+
action: {
|
|
1834
|
+
resourceName: 'dataSources.collections',
|
|
1835
|
+
actionName: 'destroy',
|
|
1836
|
+
params: {
|
|
1837
|
+
associatedIndex: 'pg-ext',
|
|
1838
|
+
filterByTk: 'runtime_audit',
|
|
1839
|
+
filter: { 'fields.name': 'code', 'fields.type': 'string' },
|
|
1840
|
+
},
|
|
1841
|
+
},
|
|
1842
|
+
},
|
|
1843
|
+
matchedRuntimeNext,
|
|
1844
|
+
);
|
|
1845
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1846
|
+
expect(dropSpy).toHaveBeenCalledWith('runtime_audit', false, expect.anything());
|
|
1847
|
+
expect(matchedRuntimeNext).toHaveBeenCalledOnce();
|
|
1848
|
+
expect(ds.collectionManager.hasCollection('runtime_audit')).toBe(false);
|
|
1849
|
+
|
|
1850
|
+
// Case-insensitive $notIncludes / $includes / $startsWith / $notStartsWith / $endWith / $notEndWith
|
|
1851
|
+
// must match PostgreSQL metadata DB ILIKE/NOT ILIKE semantics so mixed-case runtime tables are never dropped
|
|
1852
|
+
// by lowercase exclusion filters while non-matching tables ARE dropped.
|
|
1853
|
+
ds.collectionManager.defineCollection({
|
|
1854
|
+
name: 'Runtime_Audit',
|
|
1855
|
+
tableName: 'Runtime_Audit',
|
|
1856
|
+
fields: [
|
|
1857
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
1858
|
+
{ name: 'secretCode', type: 'string' },
|
|
1859
|
+
],
|
|
1860
|
+
});
|
|
1861
|
+
ds.collectionManager.defineCollection({
|
|
1862
|
+
name: 'public_items',
|
|
1863
|
+
tableName: 'public_items',
|
|
1864
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
1865
|
+
});
|
|
1866
|
+
|
|
1867
|
+
for (const exclusionCase of [
|
|
1868
|
+
{ filter: { name: { $notIncludes: 'audit' } }, scope: undefined },
|
|
1869
|
+
{ filter: { name: { $notIncludes: ['audit', 'temp'] } }, scope: undefined },
|
|
1870
|
+
{ filter: { name: { $notStartsWith: ['runtime_', 'internal_'] } }, scope: undefined },
|
|
1871
|
+
{ filter: { name: { $notEndWith: ['_AUDIT', '_LOG'] } }, scope: undefined },
|
|
1872
|
+
{
|
|
1873
|
+
filter: { name: { $notIncludes: 'temp' } },
|
|
1874
|
+
scope: { 'fields.name': { $notIncludes: ['id', 'secret'] } },
|
|
1875
|
+
},
|
|
1876
|
+
{ filter: { 'fields.name': { $notIncludes: null } }, scope: { description: { $notIncludes: 'audit' } } },
|
|
1877
|
+
]) {
|
|
1878
|
+
dropSpy.mockClear();
|
|
1879
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1880
|
+
const nextExclusion = vi.fn().mockResolvedValue(undefined);
|
|
1881
|
+
await schemaMiddleware(
|
|
1882
|
+
{
|
|
1883
|
+
action: {
|
|
1884
|
+
resourceName: 'dataSources.collections',
|
|
1885
|
+
actionName: 'destroy',
|
|
1886
|
+
params: { associatedIndex: 'pg-ext', filterByTk: 'Runtime_Audit', filter: exclusionCase.filter },
|
|
1887
|
+
},
|
|
1888
|
+
...(exclusionCase.scope ? { permission: { can: { params: { filter: exclusionCase.scope } } } } : {}),
|
|
1889
|
+
},
|
|
1890
|
+
nextExclusion,
|
|
1891
|
+
);
|
|
1892
|
+
expect(dropSpy).not.toHaveBeenCalled();
|
|
1893
|
+
expect(nextExclusion).not.toHaveBeenCalled();
|
|
1894
|
+
expect(ds.collectionManager.hasCollection('Runtime_Audit')).toBe(true);
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
// Conversely, mixed-case exclusion on filter-only destroy drops only public_items and retains Runtime_Audit,
|
|
1898
|
+
// and positive case-insensitive $includes matches Runtime_Audit.
|
|
1899
|
+
dropSpy.mockClear();
|
|
1900
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1901
|
+
const nextNonAuditOnly = vi.fn().mockResolvedValue(undefined);
|
|
1902
|
+
await schemaMiddleware(
|
|
1903
|
+
{
|
|
1904
|
+
action: {
|
|
1905
|
+
resourceName: 'dataSources.collections',
|
|
1906
|
+
actionName: 'destroy',
|
|
1907
|
+
params: {
|
|
1908
|
+
associatedIndex: 'pg-ext',
|
|
1909
|
+
filterByTk: ['Runtime_Audit', 'public_items'],
|
|
1910
|
+
filter: { name: { $notIncludes: 'audit' } },
|
|
1911
|
+
},
|
|
1912
|
+
},
|
|
1913
|
+
},
|
|
1914
|
+
nextNonAuditOnly,
|
|
1915
|
+
);
|
|
1916
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1917
|
+
expect(dropSpy).toHaveBeenCalledWith('public_items', false, expect.anything());
|
|
1918
|
+
expect(nextNonAuditOnly).toHaveBeenCalledOnce();
|
|
1919
|
+
expect(ds.collectionManager.hasCollection('public_items')).toBe(false);
|
|
1920
|
+
expect(ds.collectionManager.hasCollection('Runtime_Audit')).toBe(true);
|
|
1921
|
+
|
|
1922
|
+
dropSpy.mockClear();
|
|
1923
|
+
(collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
1924
|
+
const nextCaseMatched = vi.fn().mockResolvedValue(undefined);
|
|
1925
|
+
await schemaMiddleware(
|
|
1926
|
+
{
|
|
1927
|
+
action: {
|
|
1928
|
+
resourceName: 'dataSources.collections',
|
|
1929
|
+
actionName: 'destroy',
|
|
1930
|
+
params: {
|
|
1931
|
+
associatedIndex: 'pg-ext',
|
|
1932
|
+
filterByTk: 'Runtime_Audit',
|
|
1933
|
+
filter: { name: { $includes: 'audit' }, 'fields.name': { $startsWith: ['SECRET', 'OTHER'] } },
|
|
1934
|
+
},
|
|
1935
|
+
},
|
|
1936
|
+
},
|
|
1937
|
+
nextCaseMatched,
|
|
1938
|
+
);
|
|
1939
|
+
expect(dropSpy).toHaveBeenCalledTimes(1);
|
|
1940
|
+
expect(dropSpy).toHaveBeenCalledWith('Runtime_Audit', false, expect.anything());
|
|
1941
|
+
expect(nextCaseMatched).toHaveBeenCalledOnce();
|
|
1942
|
+
expect(ds.collectionManager.hasCollection('Runtime_Audit')).toBe(false);
|
|
1943
|
+
});
|
|
1944
|
+
|
|
1945
|
+
it('matches core SQLite metadata LIKE semantics for _ and % so runtime-only tables match persisted results', async () => {
|
|
1946
|
+
const sqliteMetaDb = new Database({
|
|
1947
|
+
dialect: 'sqlite',
|
|
1948
|
+
storage: ':memory:',
|
|
1949
|
+
logging: false,
|
|
1950
|
+
});
|
|
1951
|
+
try {
|
|
1952
|
+
sqliteMetaDb.collection({
|
|
1953
|
+
name: 'dataSourcesCollections',
|
|
1954
|
+
autoGenId: false,
|
|
1955
|
+
fields: [
|
|
1956
|
+
{ name: 'name', type: 'string', primaryKey: true },
|
|
1957
|
+
{ name: 'dataSourceKey', type: 'string', primaryKey: true },
|
|
1958
|
+
],
|
|
1959
|
+
});
|
|
1960
|
+
await sqliteMetaDb.sync();
|
|
1961
|
+
const sqliteCollectionsRepo = sqliteMetaDb.getRepository('dataSourcesCollections');
|
|
1962
|
+
|
|
1963
|
+
const candidateNames = ['order_items', 'order\\xitems', 'foo%bar', 'foo\\abcbar', 'Plain_Table'];
|
|
1964
|
+
for (const name of candidateNames) {
|
|
1965
|
+
await sqliteCollectionsRepo.create({ values: { name, dataSourceKey: 'pg-sqlite-meta' } });
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
const filtersToVerify = [
|
|
1969
|
+
{ name: { $includes: 'order_' } },
|
|
1970
|
+
{ name: { $notIncludes: 'order_' } },
|
|
1971
|
+
{ name: { $startsWith: 'order_' } },
|
|
1972
|
+
{ name: { $notStartsWith: 'order_' } },
|
|
1973
|
+
{ name: { $endWith: '_items' } },
|
|
1974
|
+
{ name: { $notEndWith: '_items' } },
|
|
1975
|
+
{ name: { $includes: 'foo%bar' } },
|
|
1976
|
+
{ name: { $notIncludes: 'foo%bar' } },
|
|
1977
|
+
{ name: { $includes: ['order_', 'foo%bar'] } },
|
|
1978
|
+
];
|
|
1979
|
+
|
|
1980
|
+
for (const filter of filtersToVerify) {
|
|
1981
|
+
// 1. Query real SQLite metadata repository directly via core operators.
|
|
1982
|
+
const coreMatchedRows = await sqliteCollectionsRepo.find({
|
|
1983
|
+
filter: { $and: [{ dataSourceKey: 'pg-sqlite-meta' }, filter] },
|
|
1984
|
+
});
|
|
1985
|
+
const coreMatchedNames = coreMatchedRows.map((row) => String(row.get('name'))).sort();
|
|
1986
|
+
|
|
1987
|
+
// 2. Run pre-DROP resolution when all candidate collections exist ONLY at runtime (zero persisted rows).
|
|
1988
|
+
const harness = createPluginHarness();
|
|
1989
|
+
(harness.app as { db: unknown }).db = {
|
|
1990
|
+
sequelize: sqliteMetaDb.sequelize,
|
|
1991
|
+
getRepository: (repoName: string) => {
|
|
1992
|
+
if (repoName === 'dataSourcesCollections') {
|
|
1993
|
+
return { find: vi.fn().mockResolvedValue([]) };
|
|
1994
|
+
}
|
|
1995
|
+
if (repoName === 'dataSourcesFields') return harness.fieldsRepo;
|
|
1996
|
+
return harness.dataSourcesRepo;
|
|
1997
|
+
},
|
|
1998
|
+
on: () => undefined,
|
|
1999
|
+
};
|
|
2000
|
+
for (const existing of [...harness.ds.collectionManager.getCollections()]) {
|
|
2001
|
+
harness.ds.collectionManager.removeCollection(existing.name);
|
|
2002
|
+
}
|
|
2003
|
+
for (const name of candidateNames) {
|
|
2004
|
+
harness.ds.collectionManager.defineCollection({
|
|
2005
|
+
name,
|
|
2006
|
+
tableName: name,
|
|
2007
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
2008
|
+
});
|
|
2009
|
+
}
|
|
2010
|
+
vi.spyOn(harness.ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
2011
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
2012
|
+
) => cb({})) as never);
|
|
2013
|
+
vi.spyOn(harness.ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
2014
|
+
const droppedRuntime: string[] = [];
|
|
2015
|
+
vi.spyOn(harness.ds.collectionManager, 'dropTable').mockImplementation(async (name) => {
|
|
2016
|
+
droppedRuntime.push(name);
|
|
2017
|
+
});
|
|
2018
|
+
vi.spyOn(harness.ds, 'removeSelectedTables').mockResolvedValue(false);
|
|
2019
|
+
|
|
2020
|
+
await harness.plugin.load();
|
|
2021
|
+
const destroyMiddleware = harness.middlewares[1];
|
|
2022
|
+
await destroyMiddleware(
|
|
2023
|
+
{
|
|
2024
|
+
action: {
|
|
2025
|
+
resourceName: 'dataSources.collections',
|
|
2026
|
+
actionName: 'destroy',
|
|
2027
|
+
params: { associatedIndex: 'pg-ext', filter },
|
|
2028
|
+
},
|
|
2029
|
+
},
|
|
2030
|
+
vi.fn().mockResolvedValue(undefined),
|
|
2031
|
+
);
|
|
2032
|
+
|
|
2033
|
+
expect(droppedRuntime.sort(), `SQLite parity mismatch for filter ${JSON.stringify(filter)}`).toEqual(
|
|
2034
|
+
coreMatchedNames,
|
|
2035
|
+
);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// Specifically confirm `order_items` is NOT matched by `{ name: { $includes: 'order_' } }` on SQLite,
|
|
2039
|
+
// whereas on PostgreSQL metadata DB (`ILIKE` with default `\` escape) `order_items` IS matched.
|
|
2040
|
+
const pgHarness = createPluginHarness();
|
|
2041
|
+
(pgHarness.app.db as Record<string, unknown>).sequelize = { getDialect: () => 'postgres' };
|
|
2042
|
+
(pgHarness.collectionsRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([]);
|
|
2043
|
+
pgHarness.ds.collectionManager.defineCollection({
|
|
2044
|
+
name: 'order_items',
|
|
2045
|
+
tableName: 'order_items',
|
|
2046
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
2047
|
+
});
|
|
2048
|
+
pgHarness.ds.collectionManager.defineCollection({
|
|
2049
|
+
name: 'orderxitems',
|
|
2050
|
+
tableName: 'orderxitems',
|
|
2051
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
2052
|
+
});
|
|
2053
|
+
vi.spyOn(pgHarness.ds.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
2054
|
+
cb: (tx: unknown) => Promise<unknown>,
|
|
2055
|
+
) => cb({})) as never);
|
|
2056
|
+
vi.spyOn(pgHarness.ds.collectionManager.db.sequelize, 'query').mockResolvedValue([] as never);
|
|
2057
|
+
const pgDropped: string[] = [];
|
|
2058
|
+
vi.spyOn(pgHarness.ds.collectionManager, 'dropTable').mockImplementation(async (name) => {
|
|
2059
|
+
pgDropped.push(name);
|
|
2060
|
+
});
|
|
2061
|
+
vi.spyOn(pgHarness.ds, 'removeSelectedTables').mockResolvedValue(false);
|
|
2062
|
+
await pgHarness.plugin.load();
|
|
2063
|
+
await pgHarness.middlewares[1](
|
|
2064
|
+
{
|
|
2065
|
+
action: {
|
|
2066
|
+
resourceName: 'dataSources.collections',
|
|
2067
|
+
actionName: 'destroy',
|
|
2068
|
+
params: { associatedIndex: 'pg-ext', filter: { name: { $includes: 'order_' } } },
|
|
2069
|
+
},
|
|
2070
|
+
},
|
|
2071
|
+
vi.fn().mockResolvedValue(undefined),
|
|
2072
|
+
);
|
|
2073
|
+
expect(pgDropped).toEqual(['order_items']);
|
|
2074
|
+
} finally {
|
|
2075
|
+
await sqliteMetaDb.close();
|
|
2076
|
+
}
|
|
2077
|
+
});
|
|
2078
|
+
|
|
2079
|
+
it('emits valid PostgreSQL ARRAY literals for ARRAY columns while keeping JSON encoding for JSON/JSONB', async () => {
|
|
2080
|
+
const ds = createDataSource({ name: 'pg-array-defaults' });
|
|
2081
|
+
ds.collectionManager.defineCollection({
|
|
2082
|
+
name: 'items',
|
|
2083
|
+
tableName: 'items',
|
|
2084
|
+
fields: [
|
|
2085
|
+
{ name: 'id', type: 'bigInt', primaryKey: true },
|
|
2086
|
+
{ name: 'tags', type: 'array', dataType: 'array', elementType: 'integer' },
|
|
2087
|
+
{ name: 'flags', type: 'array', dataType: 'array', elementType: 'boolean' },
|
|
2088
|
+
{ name: 'meta', type: 'jsonb' },
|
|
2089
|
+
],
|
|
2090
|
+
});
|
|
2091
|
+
|
|
2092
|
+
const executed: string[] = [];
|
|
2093
|
+
vi.spyOn(ds.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, opts) => {
|
|
2094
|
+
const text = String(sql);
|
|
2095
|
+
executed.push(text);
|
|
2096
|
+
const colName = (opts as { replacements?: { columnName?: string } } | undefined)?.replacements?.columnName;
|
|
2097
|
+
if (text.includes('pg_catalog.format_type')) {
|
|
2098
|
+
if (colName === 'tags') return [{ dataType: 'integer[]' }] as never;
|
|
2099
|
+
if (colName === 'flags') return [{ dataType: 'boolean[]' }] as never;
|
|
2100
|
+
if (colName === 'meta') return [{ dataType: 'jsonb' }] as never;
|
|
2101
|
+
}
|
|
2102
|
+
return [] as never;
|
|
2103
|
+
});
|
|
2104
|
+
|
|
2105
|
+
await ds.collectionManager.addField(
|
|
2106
|
+
'items',
|
|
2107
|
+
{ name: 'scores', type: 'array', elementType: 'integer', defaultValue: [1, 2] },
|
|
2108
|
+
{} as never,
|
|
2109
|
+
);
|
|
2110
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2111
|
+
'ALTER TABLE "public"."items" ADD COLUMN "scores" INTEGER[] DEFAULT ARRAY[1, 2]::INTEGER[]',
|
|
2112
|
+
);
|
|
2113
|
+
|
|
2114
|
+
await ds.collectionManager.addField(
|
|
2115
|
+
'items',
|
|
2116
|
+
{ name: 'labels', type: 'array', dataType: 'array', elementType: 'text', defaultValue: [] },
|
|
2117
|
+
{} as never,
|
|
2118
|
+
);
|
|
2119
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2120
|
+
'ALTER TABLE "public"."items" ADD COLUMN "labels" TEXT[] DEFAULT ARRAY[]::TEXT[]',
|
|
2121
|
+
);
|
|
2122
|
+
|
|
2123
|
+
await ds.collectionManager.addField(
|
|
2124
|
+
'items',
|
|
2125
|
+
{ name: 'json_arr', type: 'array', defaultValue: [1, 2] },
|
|
2126
|
+
{} as never,
|
|
2127
|
+
);
|
|
2128
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2129
|
+
`ALTER TABLE "public"."items" ADD COLUMN "json_arr" JSONB DEFAULT '[1,2]'`,
|
|
2130
|
+
);
|
|
2131
|
+
|
|
2132
|
+
await ds.collectionManager.updateField('items', 'tags', { defaultValue: [3, 4] }, {} as never);
|
|
2133
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2134
|
+
'ALTER TABLE "public"."items" ALTER COLUMN "tags" SET DEFAULT ARRAY[3, 4]::integer[]',
|
|
2135
|
+
);
|
|
2136
|
+
|
|
2137
|
+
await ds.collectionManager.updateField('items', 'flags', { defaultValue: [true, false] }, {} as never);
|
|
2138
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2139
|
+
'ALTER TABLE "public"."items" ALTER COLUMN "flags" SET DEFAULT ARRAY[TRUE, FALSE]::boolean[]',
|
|
2140
|
+
);
|
|
2141
|
+
|
|
2142
|
+
await ds.collectionManager.updateField('items', 'meta', { defaultValue: { a: 1 } }, {} as never);
|
|
2143
|
+
expect(executed[executed.length - 1]).toBe(
|
|
2144
|
+
`ALTER TABLE "public"."items" ALTER COLUMN "meta" SET DEFAULT '{"a":1}'`,
|
|
2145
|
+
);
|
|
2146
|
+
|
|
2147
|
+
await expect(
|
|
2148
|
+
ds.collectionManager.updateField('items', 'tags', { defaultValue: ['not-an-int'] }, {} as never),
|
|
2149
|
+
).rejects.toThrow('Unsupported PostgreSQL default value');
|
|
2150
|
+
});
|
|
2151
|
+
|
|
2152
|
+
it('persists dataType: array when elementType is given and keeps model ARRAY typing across write, reload, and read', async () => {
|
|
2153
|
+
const { plugin, ds, middlewares } = createPluginHarness();
|
|
2154
|
+
await plugin.load();
|
|
2155
|
+
const schemaMiddleware = middlewares[1];
|
|
2156
|
+
const itemsCollection = ds.collectionManager.defineCollection({
|
|
2157
|
+
name: 'items',
|
|
2158
|
+
tableName: 'items',
|
|
2159
|
+
autoGenId: false,
|
|
2160
|
+
timestamps: false,
|
|
2161
|
+
fields: [{ name: 'id', type: 'integer', primaryKey: true }],
|
|
2162
|
+
});
|
|
2163
|
+
|
|
2164
|
+
const capturedInserts: Array<{ sql: string; bind?: unknown[] }> = [];
|
|
2165
|
+
const storedRows = new Map<number, { id: number; scores: number[] }>();
|
|
2166
|
+
const bindMockQuery = (targetDs: PostgresDataSource) => {
|
|
2167
|
+
const fakeTx = {
|
|
2168
|
+
commit: async () => undefined,
|
|
2169
|
+
rollback: async () => undefined,
|
|
2170
|
+
afterCommit: () => undefined,
|
|
2171
|
+
};
|
|
2172
|
+
vi.spyOn(targetDs.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
2173
|
+
cbOrOpts?: unknown,
|
|
2174
|
+
maybeCb?: unknown,
|
|
2175
|
+
) => {
|
|
2176
|
+
const cb = typeof cbOrOpts === 'function' ? cbOrOpts : typeof maybeCb === 'function' ? maybeCb : null;
|
|
2177
|
+
return cb ? await (cb as (tx: unknown) => Promise<unknown>)(fakeTx) : fakeTx;
|
|
2178
|
+
}) as never);
|
|
2179
|
+
vi.spyOn(targetDs.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, opts) => {
|
|
2180
|
+
const sqlObj = typeof sql === 'object' && sql !== null ? (sql as { query?: unknown; bind?: unknown[] }) : null;
|
|
2181
|
+
const text = sqlObj ? String(sqlObj.query ?? '') : String(sql);
|
|
2182
|
+
const queryOpts = (opts || {}) as {
|
|
2183
|
+
type?: string;
|
|
2184
|
+
bind?: unknown[];
|
|
2185
|
+
instance?: { isNewRecord?: boolean; dataValues?: Record<string, unknown> };
|
|
2186
|
+
model?: { bulkBuild: (rows: unknown[], buildOpts: Record<string, unknown>) => unknown[] };
|
|
2187
|
+
raw?: boolean;
|
|
2188
|
+
attributes?: unknown[];
|
|
2189
|
+
originalAttributes?: unknown[];
|
|
2190
|
+
};
|
|
2191
|
+
const bind = sqlObj?.bind ?? queryOpts.bind;
|
|
2192
|
+
if (text.startsWith('INSERT INTO') || queryOpts.type === 'INSERT') {
|
|
2193
|
+
capturedInserts.push({ sql: text, bind });
|
|
2194
|
+
// Reject JSONB-encoded array strings on an INTEGER[] column just like PostgreSQL does.
|
|
2195
|
+
if (
|
|
2196
|
+
text.includes(`'[`) ||
|
|
2197
|
+
(Array.isArray(bind) && bind.some((item) => typeof item === 'string' && item.startsWith('[')))
|
|
2198
|
+
) {
|
|
2199
|
+
throw new Error('malformed array literal: JSON string passed to integer[]');
|
|
2200
|
+
}
|
|
2201
|
+
if (Array.isArray(bind) && bind.length >= 2 && Array.isArray(bind[1])) {
|
|
2202
|
+
const id = Number(bind[0]);
|
|
2203
|
+
const nums = bind[1].map((item) => Number(item));
|
|
2204
|
+
storedRows.set(id, { id, scores: nums });
|
|
2205
|
+
} else {
|
|
2206
|
+
const arrayMatch = text.match(/VALUES\s*\((\d+),\s*ARRAY\[([^\]]+)\]/);
|
|
2207
|
+
if (arrayMatch) {
|
|
2208
|
+
const id = Number(arrayMatch[1]);
|
|
2209
|
+
const nums = arrayMatch[2].split(',').map((part) => Number(part.trim()));
|
|
2210
|
+
storedRows.set(id, { id, scores: nums });
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
return [queryOpts.instance, 1] as never;
|
|
2214
|
+
}
|
|
2215
|
+
if (text.startsWith('SELECT') && text.includes('FROM "public"."items"')) {
|
|
2216
|
+
const latest = [...storedRows.values()][storedRows.size - 1];
|
|
2217
|
+
const rawRows = latest ? [latest] : [];
|
|
2218
|
+
if (queryOpts.model && !queryOpts.raw) {
|
|
2219
|
+
return queryOpts.model.bulkBuild(rawRows, {
|
|
2220
|
+
isNewRecord: false,
|
|
2221
|
+
raw: true,
|
|
2222
|
+
attributes: queryOpts.originalAttributes || queryOpts.attributes,
|
|
2223
|
+
}) as never;
|
|
2224
|
+
}
|
|
2225
|
+
return rawRows as never;
|
|
2226
|
+
}
|
|
2227
|
+
return [] as never;
|
|
2228
|
+
});
|
|
2229
|
+
};
|
|
2230
|
+
bindMockQuery(ds);
|
|
2231
|
+
|
|
2232
|
+
// 1. Add array field via schema action without explicit dataType.
|
|
2233
|
+
const fieldValues: Record<string, unknown> = {
|
|
2234
|
+
name: 'scores',
|
|
2235
|
+
type: 'array',
|
|
2236
|
+
elementType: 'integer',
|
|
2237
|
+
defaultValue: [1, 2],
|
|
2238
|
+
};
|
|
2239
|
+
await schemaMiddleware(
|
|
2240
|
+
{
|
|
2241
|
+
action: {
|
|
2242
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
2243
|
+
actionName: 'create',
|
|
2244
|
+
params: { associatedIndex: 'pg-ext.items', values: fieldValues },
|
|
2245
|
+
},
|
|
2246
|
+
},
|
|
2247
|
+
async () => {
|
|
2248
|
+
itemsCollection.setField('scores', fieldValues);
|
|
2249
|
+
},
|
|
2250
|
+
);
|
|
2251
|
+
|
|
2252
|
+
expect(fieldValues.dataType).toBe('array');
|
|
2253
|
+
expect(itemsCollection.getField('scores')?.options.dataType).toBe('array');
|
|
2254
|
+
expect((itemsCollection.model.rawAttributes.scores.type as { key?: string }).key).toBe('ARRAY');
|
|
2255
|
+
|
|
2256
|
+
// 2. Writing via Sequelize repository must serialize ARRAY column cleanly, not JSONB string '[3,9]'.
|
|
2257
|
+
await itemsCollection.repository.create({ values: { id: 1, scores: [9, 3] } });
|
|
2258
|
+
const firstInsert = capturedInserts[capturedInserts.length - 1];
|
|
2259
|
+
expect(
|
|
2260
|
+
firstInsert.sql.includes('ARRAY[3,9]') ||
|
|
2261
|
+
(Array.isArray(firstInsert.bind?.[1]) && firstInsert.bind?.[1].join(',') === '3,9'),
|
|
2262
|
+
).toBe(true);
|
|
2263
|
+
expect(storedRows.get(1)?.scores).toEqual([3, 9]);
|
|
2264
|
+
|
|
2265
|
+
// 3. Reload into a fresh PostgresDataSource using persisted metadata (even if dataType were omitted in legacy JSON).
|
|
2266
|
+
const persistedLocalData = {
|
|
2267
|
+
items: {
|
|
2268
|
+
name: 'items',
|
|
2269
|
+
tableName: 'items',
|
|
2270
|
+
autoGenId: false,
|
|
2271
|
+
timestamps: false,
|
|
2272
|
+
fields: [
|
|
2273
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
2274
|
+
{ name: 'scores', type: 'array', dataType: fieldValues.dataType, elementType: 'integer' },
|
|
2275
|
+
],
|
|
2276
|
+
},
|
|
2277
|
+
};
|
|
2278
|
+
const reloaded = createDataSource({ name: 'pg-ext-reloaded' });
|
|
2279
|
+
vi.spyOn(reloaded.collectionManager.db.sequelize, 'authenticate').mockResolvedValue(undefined);
|
|
2280
|
+
vi.spyOn(reloaded.introspector, 'getTables').mockResolvedValue(['items']);
|
|
2281
|
+
vi.spyOn(reloaded, 'prepareTables').mockImplementation(async () => [
|
|
2282
|
+
{
|
|
2283
|
+
name: 'items',
|
|
2284
|
+
tableName: 'items',
|
|
2285
|
+
autoGenId: false,
|
|
2286
|
+
timestamps: false,
|
|
2287
|
+
introspected: true,
|
|
2288
|
+
fields: persistedLocalData.items.fields.map((f) => ({ ...f })),
|
|
2289
|
+
},
|
|
2290
|
+
]);
|
|
2291
|
+
await reloaded.load({ localData: persistedLocalData });
|
|
2292
|
+
bindMockQuery(reloaded);
|
|
2293
|
+
|
|
2294
|
+
const reloadedItems = reloaded.collectionManager.getCollection('items');
|
|
2295
|
+
expect(reloadedItems.getField('scores')?.options.dataType).toBe('array');
|
|
2296
|
+
expect((reloadedItems.model.rawAttributes.scores.type as { key?: string }).key).toBe('ARRAY');
|
|
2297
|
+
|
|
2298
|
+
await reloadedItems.repository.create({ values: { id: 2, scores: [7, 1] } });
|
|
2299
|
+
const secondInsert = capturedInserts[capturedInserts.length - 1];
|
|
2300
|
+
expect(
|
|
2301
|
+
secondInsert.sql.includes('ARRAY[1,7]') ||
|
|
2302
|
+
(Array.isArray(secondInsert.bind?.[1]) && secondInsert.bind?.[1].join(',') === '1,7'),
|
|
2303
|
+
).toBe(true);
|
|
2304
|
+
expect(storedRows.get(2)?.scores).toEqual([1, 7]);
|
|
2305
|
+
|
|
2306
|
+
const loadedRecord = await reloadedItems.repository.findOne({ filterByTk: 2 });
|
|
2307
|
+
expect(loadedRecord?.get('scores')).toEqual([1, 7]);
|
|
2308
|
+
|
|
2309
|
+
// Also verify buildField normalizes legacy field metadata defined without dataType when not backed by JSON/JSONB.
|
|
2310
|
+
const legacyCollection = reloaded.collectionManager.defineCollection({
|
|
2311
|
+
name: 'legacy_items',
|
|
2312
|
+
tableName: 'legacy_items',
|
|
2313
|
+
fields: [{ name: 'nums', type: 'array', elementType: 'integer' }],
|
|
2314
|
+
});
|
|
2315
|
+
expect(legacyCollection.getField('nums')?.options.dataType).toBe('array');
|
|
2316
|
+
expect((legacyCollection.model.rawAttributes.nums.type as { key?: string }).key).toBe('ARRAY');
|
|
2317
|
+
|
|
2318
|
+
// Legacy field metadata saved as { type: 'array', elementType: 'string' } without dataType over an
|
|
2319
|
+
// existing PostgreSQL JSONB column must keep JSONB typing through real prepareTables() reload & writes,
|
|
2320
|
+
// while a sibling physical ARRAY column in the same table resolves to ARRAY.
|
|
2321
|
+
const legacyHarness = createPluginHarness();
|
|
2322
|
+
await legacyHarness.plugin.load();
|
|
2323
|
+
const legacyMiddleware = legacyHarness.middlewares[1];
|
|
2324
|
+
const legacyDs = legacyHarness.ds;
|
|
2325
|
+
vi.spyOn(legacyDs.collectionManager.db.sequelize.getQueryInterface(), 'describeTable').mockResolvedValue({
|
|
2326
|
+
id: { type: 'INTEGER', allowNull: false, defaultValue: '', primaryKey: true },
|
|
2327
|
+
tags: { type: 'JSONB', allowNull: true, defaultValue: null, primaryKey: false },
|
|
2328
|
+
scores: { type: 'ARRAY', allowNull: true, defaultValue: null, primaryKey: false },
|
|
2329
|
+
} as never);
|
|
2330
|
+
vi.spyOn(legacyDs.introspector, 'getTableConstraints').mockResolvedValue([]);
|
|
2331
|
+
vi.spyOn(legacyDs.collectionManager, 'getTableKinds').mockResolvedValue(new Map([['legacy_orders', 'r']]));
|
|
2332
|
+
const executedDefaults: string[] = [];
|
|
2333
|
+
const legacyInserts: Array<{ sql: string; bind?: unknown[] }> = [];
|
|
2334
|
+
const legacyRows = new Map<number, { id: number; tags: unknown; scores: number[] }>();
|
|
2335
|
+
const legacyTx = {
|
|
2336
|
+
commit: async () => undefined,
|
|
2337
|
+
rollback: async () => undefined,
|
|
2338
|
+
afterCommit: () => undefined,
|
|
2339
|
+
};
|
|
2340
|
+
vi.spyOn(legacyDs.collectionManager.db.sequelize, 'transaction').mockImplementation((async (
|
|
2341
|
+
cbOrOpts?: unknown,
|
|
2342
|
+
maybeCb?: unknown,
|
|
2343
|
+
) => {
|
|
2344
|
+
const cb = typeof cbOrOpts === 'function' ? cbOrOpts : typeof maybeCb === 'function' ? maybeCb : null;
|
|
2345
|
+
return cb ? await (cb as (tx: unknown) => Promise<unknown>)(legacyTx) : legacyTx;
|
|
2346
|
+
}) as never);
|
|
2347
|
+
vi.spyOn(legacyDs.collectionManager.db.sequelize, 'query').mockImplementation(async (sql, opts) => {
|
|
2348
|
+
const sqlObj = typeof sql === 'object' && sql !== null ? (sql as { query?: unknown; bind?: unknown[] }) : null;
|
|
2349
|
+
const text = sqlObj ? String(sqlObj.query ?? '') : String(sql);
|
|
2350
|
+
const queryOpts = (opts || {}) as {
|
|
2351
|
+
type?: string;
|
|
2352
|
+
bind?: unknown[];
|
|
2353
|
+
replacements?: { columnName?: string };
|
|
2354
|
+
instance?: unknown;
|
|
2355
|
+
model?: { bulkBuild: (rows: unknown[], buildOpts: Record<string, unknown>) => unknown[] };
|
|
2356
|
+
raw?: boolean;
|
|
2357
|
+
attributes?: unknown[];
|
|
2358
|
+
originalAttributes?: unknown[];
|
|
2359
|
+
};
|
|
2360
|
+
if (text.includes('information_schema.element_types')) {
|
|
2361
|
+
return [{ column_name: 'scores', element_type: 'integer' }] as never;
|
|
2362
|
+
}
|
|
2363
|
+
if (text.includes('pg_catalog.format_type')) {
|
|
2364
|
+
if (queryOpts.replacements?.columnName === 'tags') return [{ dataType: 'jsonb' }] as never;
|
|
2365
|
+
if (queryOpts.replacements?.columnName === 'scores') return [{ dataType: 'integer[]' }] as never;
|
|
2366
|
+
}
|
|
2367
|
+
if (text.startsWith('ALTER TABLE')) {
|
|
2368
|
+
executedDefaults.push(text);
|
|
2369
|
+
return [] as never;
|
|
2370
|
+
}
|
|
2371
|
+
if (text.startsWith('INSERT INTO') || queryOpts.type === 'INSERT') {
|
|
2372
|
+
const bind = sqlObj?.bind ?? queryOpts.bind;
|
|
2373
|
+
legacyInserts.push({ sql: text, bind });
|
|
2374
|
+
if (!Array.isArray(bind) || typeof bind[1] !== 'string' || !Array.isArray(bind[2])) {
|
|
2375
|
+
throw new Error(`Expected JSONB string bind[1] and ARRAY bind[2], got: ${JSON.stringify(bind)}`);
|
|
2376
|
+
}
|
|
2377
|
+
legacyRows.set(Number(bind[0]), {
|
|
2378
|
+
id: Number(bind[0]),
|
|
2379
|
+
tags: JSON.parse(bind[1]),
|
|
2380
|
+
scores: bind[2].map((v) => Number(v)),
|
|
2381
|
+
});
|
|
2382
|
+
return [queryOpts.instance, 1] as never;
|
|
2383
|
+
}
|
|
2384
|
+
if (text.startsWith('SELECT') && text.includes('FROM "public"."legacy_orders"')) {
|
|
2385
|
+
const row = legacyRows.get(1);
|
|
2386
|
+
const rawRows = row ? [row] : [];
|
|
2387
|
+
if (queryOpts.model && !queryOpts.raw) {
|
|
2388
|
+
return queryOpts.model.bulkBuild(rawRows, {
|
|
2389
|
+
isNewRecord: false,
|
|
2390
|
+
raw: true,
|
|
2391
|
+
attributes: queryOpts.originalAttributes || queryOpts.attributes,
|
|
2392
|
+
}) as never;
|
|
2393
|
+
}
|
|
2394
|
+
return rawRows as never;
|
|
2395
|
+
}
|
|
2396
|
+
return [] as never;
|
|
2397
|
+
});
|
|
2398
|
+
|
|
2399
|
+
const prepared = await legacyDs.prepareTables(['legacy_orders'], {
|
|
2400
|
+
legacy_orders: {
|
|
2401
|
+
name: 'legacy_orders',
|
|
2402
|
+
tableName: 'legacy_orders',
|
|
2403
|
+
autoGenId: false,
|
|
2404
|
+
timestamps: false,
|
|
2405
|
+
fields: [
|
|
2406
|
+
{ name: 'id', type: 'integer', primaryKey: true },
|
|
2407
|
+
{ name: 'tags', type: 'array', elementType: 'string' },
|
|
2408
|
+
{ name: 'scores', type: 'array', elementType: 'integer' },
|
|
2409
|
+
],
|
|
2410
|
+
},
|
|
2411
|
+
});
|
|
2412
|
+
legacyDs.collectionManager.replaceCollections(prepared);
|
|
2413
|
+
|
|
2414
|
+
const legacyOrders = legacyDs.collectionManager.getCollection('legacy_orders');
|
|
2415
|
+
expect(legacyOrders.getField('tags')?.options.dataType).toBe('json');
|
|
2416
|
+
expect(legacyOrders.getField('tags')?.options.rawType).toBe('JSONB');
|
|
2417
|
+
expect((legacyOrders.model.rawAttributes.tags.type as { key?: string }).key).toBe('JSONB');
|
|
2418
|
+
expect(legacyOrders.getField('scores')?.options.dataType).toBe('array');
|
|
2419
|
+
expect((legacyOrders.model.rawAttributes.scores.type as { key?: string }).key).toBe('ARRAY');
|
|
2420
|
+
|
|
2421
|
+
await legacyOrders.repository.create({ values: { id: 1, tags: ['b', 'a'], scores: [7, 1] } });
|
|
2422
|
+
expect(legacyInserts).toHaveLength(1);
|
|
2423
|
+
const reloadedLegacy = await legacyOrders.repository.findOne({ filterByTk: 1 });
|
|
2424
|
+
expect(reloadedLegacy?.get('tags')).toEqual(['a', 'b']);
|
|
2425
|
+
expect(reloadedLegacy?.get('scores')).toEqual([1, 7]);
|
|
2426
|
+
|
|
2427
|
+
// Updating the legacy JSONB-backed field must emit JSON default instead of promoting to ARRAY.
|
|
2428
|
+
const updateValues: Record<string, unknown> = { type: 'array', elementType: 'string', defaultValue: ['x', 'y'] };
|
|
2429
|
+
await legacyMiddleware(
|
|
2430
|
+
{
|
|
2431
|
+
action: {
|
|
2432
|
+
resourceName: 'dataSourcesCollections.fields',
|
|
2433
|
+
actionName: 'update',
|
|
2434
|
+
params: { associatedIndex: 'pg-ext.legacy_orders', filterByTk: 'tags', values: updateValues },
|
|
2435
|
+
},
|
|
2436
|
+
},
|
|
2437
|
+
vi.fn().mockResolvedValue(undefined),
|
|
2438
|
+
);
|
|
2439
|
+
expect(updateValues.dataType).toBeUndefined();
|
|
2440
|
+
expect(executedDefaults[executedDefaults.length - 1]).toBe(
|
|
2441
|
+
`ALTER TABLE "public"."legacy_orders" ALTER COLUMN "tags" SET DEFAULT '["x","y"]'`,
|
|
2442
|
+
);
|
|
2443
|
+
});
|
|
2444
|
+
|
|
2445
|
+
it('lists saved PostgreSQL connections without secrets and hydrates matching host/port/user credentials on reuse', async () => {
|
|
2446
|
+
const { plugin, actionHandlers, resourceActions, middlewares, dataSourcesRepo, app } = createPluginHarness();
|
|
2447
|
+
await plugin.load();
|
|
2448
|
+
expect(resourceActions.has('listPostgresConnections')).toBe(true);
|
|
2449
|
+
|
|
2450
|
+
const savedRecord = {
|
|
2451
|
+
get: (key: string) => {
|
|
2452
|
+
if (key === 'key') return 'pg_saved';
|
|
2453
|
+
if (key === 'displayName') return 'Primary PG';
|
|
2454
|
+
if (key === 'type') return DATA_SOURCE_TYPE;
|
|
2455
|
+
if (key === 'options') {
|
|
2456
|
+
return {
|
|
2457
|
+
host: 'pg.internal',
|
|
2458
|
+
port: 5433,
|
|
2459
|
+
database: 'sales',
|
|
2460
|
+
schema: 'billing',
|
|
2461
|
+
username: 'pg_admin',
|
|
2462
|
+
password: 'super-secret-password',
|
|
2463
|
+
ssl: true,
|
|
2464
|
+
sslCa: '-----BEGIN CERTIFICATE-----\nTEST\n-----END CERTIFICATE-----',
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
return undefined;
|
|
2468
|
+
},
|
|
2469
|
+
};
|
|
2470
|
+
(dataSourcesRepo as Record<string, unknown>).find = vi.fn().mockResolvedValue([savedRecord]);
|
|
2471
|
+
dataSourcesRepo.findOne.mockImplementation(async (query?: { filter?: { key?: string } }) =>
|
|
2472
|
+
query?.filter?.key === 'pg_saved' ? savedRecord : null,
|
|
2473
|
+
);
|
|
2474
|
+
|
|
2475
|
+
const listHandler =
|
|
2476
|
+
resourceActions.get('listPostgresConnections') || actionHandlers.get('dataSources:listPostgresConnections');
|
|
2477
|
+
expect(listHandler).toBeDefined();
|
|
2478
|
+
expect(actionHandlers.has('dataSources:listPostgresConnections')).toBe(false);
|
|
2479
|
+
const listCtx: { db: typeof app.db; body?: unknown } = { db: app.db };
|
|
2480
|
+
await listHandler?.(listCtx, vi.fn().mockResolvedValue(undefined));
|
|
2481
|
+
expect(listCtx.body).toEqual([
|
|
2482
|
+
{
|
|
2483
|
+
key: 'pg_saved',
|
|
2484
|
+
displayName: 'Primary PG',
|
|
2485
|
+
host: 'pg.internal',
|
|
2486
|
+
port: 5433,
|
|
2487
|
+
database: 'sales',
|
|
2488
|
+
schema: 'billing',
|
|
2489
|
+
username: 'pg_admin',
|
|
2490
|
+
ssl: true,
|
|
2491
|
+
hasPassword: true,
|
|
2492
|
+
hasSslCa: true,
|
|
2493
|
+
},
|
|
2494
|
+
]);
|
|
2495
|
+
expect(JSON.stringify(listCtx.body)).not.toContain('super-secret-password');
|
|
2496
|
+
expect(JSON.stringify(listCtx.body)).not.toContain('BEGIN CERTIFICATE');
|
|
2497
|
+
|
|
2498
|
+
const savedConnectionMiddleware = middlewares[2];
|
|
2499
|
+
expect(savedConnectionMiddleware).toBeDefined();
|
|
2500
|
+
|
|
2501
|
+
// Same host/port/username with a different database & schema inherits password and sslCa, and strips sourceConnectionKey.
|
|
2502
|
+
const createOptions: Record<string, unknown> = {
|
|
2503
|
+
sourceConnectionKey: 'pg_saved',
|
|
2504
|
+
host: 'pg.internal',
|
|
2505
|
+
port: 5433,
|
|
2506
|
+
database: 'analytics',
|
|
2507
|
+
schema: 'reporting',
|
|
2508
|
+
username: 'pg_admin',
|
|
2509
|
+
password: '',
|
|
2510
|
+
ssl: true,
|
|
2511
|
+
sslCa: '',
|
|
2512
|
+
};
|
|
2513
|
+
await savedConnectionMiddleware(
|
|
2514
|
+
{
|
|
2515
|
+
db: app.db,
|
|
2516
|
+
action: {
|
|
2517
|
+
resourceName: 'dataSources',
|
|
2518
|
+
actionName: 'create',
|
|
2519
|
+
params: { values: { type: DATA_SOURCE_TYPE, options: createOptions } },
|
|
2520
|
+
},
|
|
2521
|
+
},
|
|
2522
|
+
vi.fn().mockResolvedValue(undefined),
|
|
2523
|
+
);
|
|
2524
|
+
expect(createOptions.sourceConnectionKey).toBeUndefined();
|
|
2525
|
+
expect(createOptions.password).toBe('super-secret-password');
|
|
2526
|
+
expect(createOptions.sslCa).toContain('BEGIN CERTIFICATE');
|
|
2527
|
+
expect(createOptions.database).toBe('analytics');
|
|
2528
|
+
expect(createOptions.schema).toBe('reporting');
|
|
2529
|
+
|
|
2530
|
+
// Different host must NOT inherit saved secrets (prevents credential exfiltration).
|
|
2531
|
+
const differentHostOptions: Record<string, unknown> = {
|
|
2532
|
+
sourceConnectionKey: 'pg_saved',
|
|
2533
|
+
host: 'other.example.com',
|
|
2534
|
+
port: 5433,
|
|
2535
|
+
database: 'analytics',
|
|
2536
|
+
username: 'pg_admin',
|
|
2537
|
+
password: '',
|
|
2538
|
+
ssl: true,
|
|
2539
|
+
sslCa: '',
|
|
2540
|
+
};
|
|
2541
|
+
await savedConnectionMiddleware(
|
|
2542
|
+
{
|
|
2543
|
+
db: app.db,
|
|
2544
|
+
action: {
|
|
2545
|
+
resourceName: 'dataSources',
|
|
2546
|
+
actionName: 'testConnection',
|
|
2547
|
+
params: { values: { type: DATA_SOURCE_TYPE, options: differentHostOptions } },
|
|
2548
|
+
},
|
|
2549
|
+
},
|
|
2550
|
+
vi.fn().mockResolvedValue(undefined),
|
|
2551
|
+
);
|
|
2552
|
+
expect(differentHostOptions.sourceConnectionKey).toBeUndefined();
|
|
2553
|
+
expect(differentHostOptions.password).toBe('');
|
|
2554
|
+
expect(differentHostOptions.sslCa).toBe('');
|
|
2555
|
+
|
|
2556
|
+
// Missing saved connection key fails with a validation error.
|
|
2557
|
+
await expect(
|
|
2558
|
+
savedConnectionMiddleware(
|
|
2559
|
+
{
|
|
2560
|
+
db: app.db,
|
|
2561
|
+
action: {
|
|
2562
|
+
resourceName: 'dataSources',
|
|
2563
|
+
actionName: 'create',
|
|
2564
|
+
params: {
|
|
2565
|
+
values: {
|
|
2566
|
+
type: DATA_SOURCE_TYPE,
|
|
2567
|
+
options: { sourceConnectionKey: 'missing_pg', host: 'pg.internal' },
|
|
2568
|
+
},
|
|
2569
|
+
},
|
|
2570
|
+
},
|
|
2571
|
+
},
|
|
2572
|
+
vi.fn(),
|
|
2573
|
+
),
|
|
2574
|
+
).rejects.toThrow('Saved PostgreSQL connection missing_pg does not exist');
|
|
2575
|
+
});
|
|
1538
2576
|
});
|