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.
Files changed (63) hide show
  1. package/README.md +9 -3
  2. package/client-v2.js +1 -0
  3. package/client.js +1 -0
  4. package/dist/client/index.js +10 -0
  5. package/dist/client-v2/985.34da95acdf7743ab.js +10 -0
  6. package/dist/client-v2/index.js +10 -0
  7. package/dist/constants.js +45 -0
  8. package/dist/externalVersion.js +28 -0
  9. package/dist/locale/en-US.json +141 -0
  10. package/dist/locale/zh-CN.json +141 -0
  11. package/dist/server/collections/adjacency-list-repository.js +340 -0
  12. package/dist/server/collections/index.js +45 -0
  13. package/dist/server/collections/sql-collection.js +84 -0
  14. package/dist/server/collections/sql-model.js +147 -0
  15. package/dist/server/collections/tree-collection.js +118 -0
  16. package/dist/server/hooks/field-hooks.js +392 -0
  17. package/dist/server/index.js +38 -0
  18. package/dist/server/plugin.js +690 -0
  19. package/dist/server/postgres-collection-manager.js +701 -0
  20. package/dist/server/postgres-datasource.js +327 -0
  21. package/dist/server/utils/sql-validator.js +203 -0
  22. package/dist/server/utils/validation-error.js +59 -0
  23. package/package.json +51 -4
  24. package/server.js +1 -0
  25. package/src/client/AddCollectionAction.tsx +307 -0
  26. package/src/client/ConfigurationForm.tsx +203 -0
  27. package/src/client/PostgresCollectionTemplate.tsx +109 -0
  28. package/src/client/__tests__/client-v1.test.tsx +265 -0
  29. package/src/client/collection-templates/CalendarCollectionTemplate.tsx +141 -0
  30. package/src/client/collection-templates/FileCollectionTemplate.tsx +154 -0
  31. package/src/client/collection-templates/SQLCollectionTemplate.tsx +184 -0
  32. package/src/client/collection-templates/TreeCollectionTemplate.tsx +136 -0
  33. package/src/client/collection-templates/base-template-helper.ts +62 -0
  34. package/src/client/collection-templates/field-interfaces-config.ts +73 -0
  35. package/src/client/collection-templates/index.ts +19 -0
  36. package/src/client/index.tsx +69 -0
  37. package/src/client-v2/PostgresAddCollection.tsx +422 -0
  38. package/src/client-v2/PostgresConfigForm.tsx +178 -0
  39. package/src/client-v2/PostgresDeleteCollection.tsx +83 -0
  40. package/src/client-v2/__tests__/plugin.test.tsx +372 -0
  41. package/src/client-v2/collection-options.ts +22 -0
  42. package/src/client-v2/index.tsx +10 -0
  43. package/src/client-v2/plugin.tsx +71 -0
  44. package/src/constants.ts +20 -0
  45. package/src/locale/en-US.json +141 -0
  46. package/src/locale/zh-CN.json +141 -0
  47. package/src/server/__tests__/field-hooks.test.ts +357 -0
  48. package/src/server/__tests__/postgres-data-source.integration.test.ts +543 -0
  49. package/src/server/__tests__/postgres-datasource.unit.test.ts +1538 -0
  50. package/src/server/__tests__/sql-model.test.ts +115 -0
  51. package/src/server/__tests__/sql-validator.test.ts +119 -0
  52. package/src/server/collections/adjacency-list-repository.ts +378 -0
  53. package/src/server/collections/index.ts +19 -0
  54. package/src/server/collections/sql-collection.ts +66 -0
  55. package/src/server/collections/sql-model.ts +158 -0
  56. package/src/server/collections/tree-collection.ts +102 -0
  57. package/src/server/hooks/field-hooks.ts +514 -0
  58. package/src/server/index.ts +13 -0
  59. package/src/server/plugin.ts +764 -0
  60. package/src/server/postgres-collection-manager.ts +827 -0
  61. package/src/server/postgres-datasource.ts +365 -0
  62. package/src/server/utils/sql-validator.ts +203 -0
  63. package/src/server/utils/validation-error.ts +38 -0
@@ -0,0 +1,141 @@
1
+ {
2
+ "External PostgreSQL Database": "外部PostgreSQL数据库",
3
+ "Display Name": "显示名称",
4
+ "Host": "主机",
5
+ "Port": "端口",
6
+ "Database": "数据库",
7
+ "Username": "用户名",
8
+ "Password": "密码",
9
+ "Schema": "模式",
10
+ "PostgreSQL schema name, defaults to public": "PostgreSQL模式名称,默认为public",
11
+ "Use SSL": "使用SSL",
12
+ "Enable SSL/TLS connection": "启用SSL/TLS连接",
13
+ "Connection Settings": "连接设置",
14
+ "Advanced Settings": "高级设置",
15
+ "Auto Discover Tables": "自动发现表",
16
+ "Automatically discover tables from the database": "自动从数据库中发现表",
17
+ "The connection name to display in NocoBase": "在NocoBase中显示的连接名称",
18
+ "PostgreSQL server hostname or IP address": "PostgreSQL服务器主机名或IP地址",
19
+ "PostgreSQL server port number": "PostgreSQL服务器端口号",
20
+ "Name of the PostgreSQL database": "PostgreSQL数据库名称",
21
+ "Database username for authentication": "用于身份验证的数据库用户名",
22
+ "Database password for authentication": "用于身份验证的数据库密码",
23
+ "CA certificate (PEM)": "CA 证书(PEM)",
24
+ "Load all collections": "加载所有数据表",
25
+ "Collections": "数据表",
26
+ "Unable to load collections": "无法加载数据表",
27
+ "Create collection": "创建数据表",
28
+ "Load existing tables and views": "加载已有数据表和视图",
29
+ "Add collection": "添加数据表",
30
+ "Collection name": "数据表名称",
31
+ "Collection display name": "数据表显示名称",
32
+ "Collection template": "数据表模板",
33
+ "General collection": "普通数据表",
34
+ "Calendar collection": "日历数据表",
35
+ "File collection": "文件数据表",
36
+ "Tree collection": "树形数据表",
37
+ "SQL collection": "SQL 数据表",
38
+ "SQL query": "SQL 查询",
39
+ "Use a SELECT query. SQL collections are read-only.": "使用 SELECT 查询。SQL 数据表为只读。",
40
+ "Add at least one query column": "至少添加一个查询列",
41
+ "Column names must be unique": "列名必须唯一",
42
+ "Column name {{number}}": "第 {{number}} 列名称",
43
+ "Column type {{number}}": "第 {{number}} 列类型",
44
+ "Remove query column {{number}}": "删除第 {{number}} 个查询列",
45
+ "Add query column": "添加查询列",
46
+ "Text": "文本",
47
+ "Long text": "长文本",
48
+ "Integer": "整数",
49
+ "Big integer": "大整数",
50
+ "Decimal": "小数",
51
+ "Boolean": "布尔值",
52
+ "Date and time": "日期和时间",
53
+ "JSON": "JSON",
54
+ "UUID": "UUID",
55
+ "Name": "名称",
56
+ "Title": "标题",
57
+ "Start date": "开始日期",
58
+ "End date": "结束日期",
59
+ "Filename": "文件名",
60
+ "URL": "网址",
61
+ "MIME type": "MIME 类型",
62
+ "File size": "文件大小",
63
+ "Create timestamp fields": "创建时间戳字段",
64
+ "Create": "创建",
65
+ "Load": "加载",
66
+ "Delete": "删除",
67
+ "Delete collection": "删除数据表",
68
+ "Delete the selected collection and its PostgreSQL table or view?": "确定删除所选数据表及其 PostgreSQL 表或视图吗?",
69
+ "Also drop dependent PostgreSQL objects": "同时删除依赖的 PostgreSQL 对象",
70
+ "Failed to create collection": "创建数据表失败",
71
+ "Failed to delete collection": "删除数据表失败",
72
+ "A collection name is required": "请输入数据表名称",
73
+ "Collection name is required": "请输入数据表名称",
74
+ "Unknown preset field {{name}}": "未知的预设字段 {{name}}",
75
+ "This collection is read-only": "此数据表为只读",
76
+ "Collection {{name}} does not exist": "数据表 {{name}} 不存在",
77
+ "Collection {{name}} already exists": "数据表 {{name}} 已存在",
78
+ "Table {{name}} already exists": "表 {{name}} 已存在",
79
+ "Use Load tables to import an existing view": "请使用加载数据表功能导入现有视图",
80
+ "Delete one field at a time": "请一次删除一个字段",
81
+ "Field {{name}} is referenced by another field": "字段 {{name}} 被其他字段引用",
82
+ "Field name is required": "请输入字段名称",
83
+ "Field name and type are required": "请输入字段名称和类型",
84
+ "A generated field cannot also have a default value": "自动生成字段不能同时设置默认值",
85
+ "Field {{name}} cannot change generated-id or primary-key settings": "不能更改字段 {{name}} 的自动生成或主键设置",
86
+ "Field {{name}} does not exist": "字段 {{name}} 不存在",
87
+ "Field {{name}} already exists": "字段 {{name}} 已存在",
88
+ "Field {{name}} is referenced by {{collection}}.{{field}}": "字段 {{name}} 被 {{collection}}.{{field}} 引用",
89
+ "Field {{name}} cannot be changed between a relation and a physical column": "字段 {{name}} 不能在关系字段和物理列之间转换",
90
+ "Relation field {{name}} requires a target": "关系字段 {{name}} 需要指定目标数据表",
91
+ "Field type {{type}} does not represent a PostgreSQL column": "字段类型 {{type}} 不是 PostgreSQL 列类型",
92
+ "Cannot determine PostgreSQL type for field {{name}}": "无法确定字段 {{name}} 的 PostgreSQL 类型",
93
+ "Unsupported PostgreSQL default value": "不支持此 PostgreSQL 默认值",
94
+ "Invalid PostgreSQL foreign key action": "PostgreSQL 外键操作无效",
95
+ "Target column {{collection}}.{{field}} does not exist": "目标列 {{collection}}.{{field}} 不存在",
96
+ "Conflicting foreign key exists for {{collection}}.{{field}}": "{{collection}}.{{field}} 存在冲突的外键",
97
+ "Invalid PostgreSQL port": "PostgreSQL 端口无效",
98
+ "Test connection failed: {{reason}}": "连接测试失败:{{reason}}",
99
+ "Data source {{name}} does not exist": "数据源 {{name}} 不存在",
100
+ "A tree collection requires one primary key": "树形数据表需要一个主键",
101
+ "Cycle detected in tree collection {{name}}": "树形数据表 {{name}} 存在循环引用",
102
+ "Tree parent changes require a transaction": "更改树节点的父级需要事务",
103
+ "Bulk changes to a tree parent require individual hooks": "批量更改树节点父级需要逐条执行钩子",
104
+ "SQL collection queries require a read-only transaction": "SQL 数据表查询需要只读事务",
105
+ "SQL query is required": "请输入 SQL 查询",
106
+ "SQL query cannot be empty": "SQL 查询不能为空",
107
+ "Invalid or unsupported SQL syntax": "SQL 语法无效或不受支持",
108
+ "Only SELECT statements or WITH clauses are supported": "仅支持 SELECT 语句或 WITH 子句",
109
+ "SQL statement contains dangerous keyword: {{keyword}}": "SQL 语句包含危险关键字:{{keyword}}",
110
+ "Multiple SQL statements are not allowed": "不允许执行多条 SQL 语句",
111
+ "Only SQL collections can update SQL queries": "仅 SQL 数据表支持更新 SQL 查询",
112
+ "Join table {{name}} cannot match source or target collection": "中间表 {{name}} 不能与源数据表或目标数据表相同",
113
+ "Many-to-many foreign key and other key must be different": "多对多关系的外键和另一外键必须不同",
114
+ "Cancel": "取消",
115
+ "Submit": "提交",
116
+ "ID": "ID",
117
+ "Description": "描述",
118
+ "Please input collection name": "请输入数据表名称",
119
+ "Must start with a letter and can only contain letters, numbers, and underscores": "必须以字母开头,且只能包含字母、数字和下划线",
120
+ "Use letters, numbers and underscores, must start with a letter. Example: users, products, orders": "使用字母、数字和下划线,必须以字母开头。示例:users、products、orders",
121
+ "Use letters, numbers and underscores, must start with a letter. Example: events, meetings, tasks": "使用字母、数字和下划线,必须以字母开头。示例:events、meetings、tasks",
122
+ "Use letters, numbers and underscores, must start with a letter. Example: documents, images, attachments": "使用字母、数字和下划线,必须以字母开头。示例:documents、images、attachments",
123
+ "Use letters, numbers and underscores, must start with a letter. Example: analytics, reports, queries": "使用字母、数字和下划线,必须以字母开头。示例:analytics、reports、queries",
124
+ "Use letters, numbers and underscores, must start with a letter. Example: categories, departments": "使用字母、数字和下划线,必须以字母开头。示例:categories、departments",
125
+ "Preset fields": "预设字段",
126
+ "Select default fields to include in this collection": "选择此数据表包含的默认字段",
127
+ "ID - Primary key (auto-increment)": "ID - 主键(自增)",
128
+ "Created At - Timestamp when record is created": "创建时间 - 记录创建时的时间戳",
129
+ "Updated At - Timestamp when record is updated": "更新时间 - 记录更新时的时间戳",
130
+ "Collections used for calendar events, with start and end date fields": "用于日历事件的数据表,包含开始和结束日期字段",
131
+ "Collections for storing file metadata and attachments": "用于存储文件元数据和附件的数据表",
132
+ "Collections created from custom SQL queries, read-only by default": "基于自定义 SQL 查询创建的数据表,默认为只读",
133
+ "Collections organized in parent-child tree structure, like categories, departments, etc": "按父子层级树形结构组织的数据表,如分类、部门等",
134
+ "SELECT * FROM your_table WHERE ...": "SELECT * FROM your_table WHERE ...",
135
+ "Custom SQL query to retrieve data. Must be a SELECT statement. The collection will be read-only.": "用于检索数据的自定义 SQL 查询。必须是 SELECT 语句。该数据表为只读。",
136
+ "Query columns": "查询列",
137
+ "Column name": "列名",
138
+ "Column name is required": "请输入列名",
139
+ "Foreign key {{foreignKey}} cannot have the same name as relation field {{name}}": "外键 {{foreignKey}} 不能与关系字段 {{name}} 同名",
140
+ "Foreign key {{collection}}.{{field}} has incompatible PostgreSQL type {{type}}": "外键 {{collection}}.{{field}} 的 PostgreSQL 类型 {{type}} 不兼容"
141
+ }
@@ -0,0 +1,357 @@
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 type { Collection } from '@nocobase/database';
11
+ import type { Transaction } from 'sequelize';
12
+ import { describe, expect, it, vi } from 'vitest';
13
+ import {
14
+ buildArrayForeignKeyField,
15
+ fieldReferencesColumn,
16
+ getRelationLockTables,
17
+ syncFieldAction,
18
+ } from '../hooks/field-hooks';
19
+ import type { PostgresCollectionManager } from '../postgres-collection-manager';
20
+
21
+ describe('field-hooks', () => {
22
+ it('detects references by either logical field name or physical column name', () => {
23
+ const relation = {
24
+ type: 'belongsTo',
25
+ target: 'orders',
26
+ foreignKey: 'order_code',
27
+ targetKey: 'order_code',
28
+ };
29
+
30
+ expect(fieldReferencesColumn(relation, 'order_items', 'orders', ['orderCode', 'order_code'])).toBe(true);
31
+ expect(fieldReferencesColumn(relation, 'order_items', 'orders', ['orderCode'])).toBe(false);
32
+ });
33
+
34
+ it('writes derived belongsTo defaults back onto input so downstream beforeCreate succeeds', async () => {
35
+ const ensureForeignKey = vi.fn().mockResolvedValue(undefined);
36
+ const manager = {
37
+ getCollection: vi.fn().mockReturnValue({
38
+ name: 'order_items',
39
+ getField: vi.fn().mockReturnValue(undefined),
40
+ } as unknown as Collection),
41
+ ensureForeignKey,
42
+ } as unknown as PostgresCollectionManager;
43
+ const input: Record<string, unknown> = {
44
+ name: 'order',
45
+ interface: 'm2o',
46
+ target: 'orders',
47
+ };
48
+
49
+ await syncFieldAction(manager, 'create', 'order_items', undefined, input, {} as Transaction);
50
+
51
+ expect(ensureForeignKey).toHaveBeenCalledWith(
52
+ 'order_items',
53
+ expect.objectContaining({
54
+ target: 'orders',
55
+ targetKey: 'id',
56
+ foreignKey: 'orderId',
57
+ }),
58
+ expect.anything(),
59
+ );
60
+ expect(input).toMatchObject({
61
+ type: 'belongsTo',
62
+ target: 'orders',
63
+ targetKey: 'id',
64
+ foreignKey: 'orderId',
65
+ });
66
+ });
67
+
68
+ it('rejects primary-key/auto-increment changes and relation-to-column type flips', async () => {
69
+ const existingField = {
70
+ name: 'code',
71
+ options: { name: 'code', type: 'string', primaryKey: false, autoIncrement: false },
72
+ isRelationField: () => false,
73
+ columnName: () => 'code',
74
+ };
75
+ const manager = {
76
+ getCollection: vi.fn().mockReturnValue({
77
+ name: 'orders',
78
+ getField: vi.fn().mockReturnValue(existingField),
79
+ } as unknown as Collection),
80
+ } as unknown as PostgresCollectionManager;
81
+
82
+ await expect(
83
+ syncFieldAction(manager, 'update', 'orders', 'code', { primaryKey: true }, {} as Transaction),
84
+ ).rejects.toThrow('Field code cannot change generated-id or primary-key settings');
85
+
86
+ await expect(
87
+ syncFieldAction(manager, 'update', 'orders', 'code', { type: 'belongsTo' }, {} as Transaction),
88
+ ).rejects.toThrow('Field code cannot be changed between a relation and a physical column');
89
+ });
90
+
91
+ it('ensures physical foreign keys for hasMany/hasOne, join tables for belongsToMany, and array columns for belongsToArray', async () => {
92
+ const ensureForeignKey = vi.fn().mockResolvedValue(undefined);
93
+ const ensureJoinTable = vi.fn().mockResolvedValue(undefined);
94
+ const ensureForeignKeyArray = vi.fn().mockResolvedValue(undefined);
95
+ const collections: Record<string, Collection> = {
96
+ orders: {
97
+ name: 'orders',
98
+ options: { tableName: 'orders' },
99
+ model: { primaryKeyAttribute: 'id' },
100
+ getField: vi.fn().mockReturnValue(undefined),
101
+ } as unknown as Collection,
102
+ order_items: {
103
+ name: 'order_items',
104
+ options: { tableName: 'order_items' },
105
+ model: { primaryKeyAttribute: 'id' },
106
+ getField: vi.fn().mockReturnValue(undefined),
107
+ } as unknown as Collection,
108
+ tags: {
109
+ name: 'tags',
110
+ options: { tableName: 'tags' },
111
+ model: { primaryKeyAttribute: 'id' },
112
+ getField: vi.fn().mockReturnValue(undefined),
113
+ } as unknown as Collection,
114
+ order_view: {
115
+ name: 'order_view',
116
+ options: { tableName: 'order_view', view: true },
117
+ model: { primaryKeyAttribute: 'id' },
118
+ getField: vi.fn().mockReturnValue(undefined),
119
+ } as unknown as Collection,
120
+ };
121
+ const manager = {
122
+ db: { options: { schema: 'public' } },
123
+ getCollection: vi.fn((name: string) => collections[name]),
124
+ ensureForeignKey,
125
+ ensureJoinTable,
126
+ ensureForeignKeyArray,
127
+ } as unknown as PostgresCollectionManager;
128
+
129
+ const hasManyInput: Record<string, unknown> = { name: 'items', interface: 'o2m', target: 'order_items' };
130
+ await syncFieldAction(manager, 'create', 'orders', undefined, hasManyInput, {} as Transaction);
131
+ expect(ensureForeignKey).toHaveBeenCalledWith(
132
+ 'order_items',
133
+ expect.objectContaining({ target: 'orders', targetKey: 'id', foreignKey: 'orderId' }),
134
+ expect.anything(),
135
+ );
136
+ expect(hasManyInput).toMatchObject({
137
+ type: 'hasMany',
138
+ target: 'order_items',
139
+ sourceKey: 'id',
140
+ foreignKey: 'orderId',
141
+ });
142
+
143
+ const m2mInput: Record<string, unknown> = { name: 'tags', interface: 'm2m', target: 'tags' };
144
+ await syncFieldAction(manager, 'create', 'orders', undefined, m2mInput, {} as Transaction);
145
+ expect(ensureJoinTable).toHaveBeenCalledWith(
146
+ 'orders',
147
+ expect.objectContaining({
148
+ target: 'tags',
149
+ through: 'ordersTags',
150
+ foreignKey: 'orderId',
151
+ otherKey: 'tagId',
152
+ sourceKey: 'id',
153
+ targetKey: 'id',
154
+ }),
155
+ expect.anything(),
156
+ );
157
+ expect(m2mInput).toMatchObject({
158
+ type: 'belongsToMany',
159
+ through: 'ordersTags',
160
+ foreignKey: 'orderId',
161
+ otherKey: 'tagId',
162
+ });
163
+
164
+ const arrayInput: Record<string, unknown> = { name: 'tagRefs', interface: 'm2m_array', target: 'tags' };
165
+ await syncFieldAction(manager, 'create', 'orders', undefined, arrayInput, {} as Transaction);
166
+ expect(ensureForeignKeyArray).toHaveBeenCalledWith(
167
+ 'orders',
168
+ expect.objectContaining({ target: 'tags', targetKey: 'id', foreignKey: 'tagRefId' }),
169
+ expect.anything(),
170
+ );
171
+ expect(arrayInput).toMatchObject({ type: 'belongsToArray', foreignKey: 'tagRefId', targetKey: 'id' });
172
+
173
+ await expect(
174
+ syncFieldAction(
175
+ manager,
176
+ 'create',
177
+ 'orders',
178
+ undefined,
179
+ { name: 'v', interface: 'o2m', target: 'order_view' },
180
+ {} as Transaction,
181
+ ),
182
+ ).rejects.toThrow('This collection is read-only');
183
+
184
+ expect(getRelationLockTables(manager, 'orders', m2mInput)).toEqual([
185
+ 'public.orders',
186
+ 'public.ordersTags',
187
+ 'public.tags',
188
+ ]);
189
+ });
190
+
191
+ it('passes replaceActions on relation updates and locks existing/new target and join tables on partial updates', async () => {
192
+ const ensureForeignKey = vi.fn().mockResolvedValue(undefined);
193
+ const ensureJoinTable = vi.fn().mockResolvedValue(undefined);
194
+ const existingFields: Record<string, { name: string; options: Record<string, unknown> }> = {
195
+ items: {
196
+ name: 'items',
197
+ options: { name: 'items', type: 'hasMany', target: 'order_items', foreignKey: 'orderId', sourceKey: 'id' },
198
+ },
199
+ tags: {
200
+ name: 'tags',
201
+ options: {
202
+ name: 'tags',
203
+ type: 'belongsToMany',
204
+ target: 'tags',
205
+ through: 'orders_tags',
206
+ foreignKey: 'orderId',
207
+ otherKey: 'tagId',
208
+ sourceKey: 'id',
209
+ targetKey: 'id',
210
+ },
211
+ },
212
+ };
213
+ const collections: Record<string, Collection> = {
214
+ orders: {
215
+ name: 'orders',
216
+ options: { tableName: 'orders' },
217
+ model: { primaryKeyAttribute: 'id' },
218
+ getField: vi.fn((name: string) => existingFields[name]),
219
+ } as unknown as Collection,
220
+ order_items: {
221
+ name: 'order_items',
222
+ options: { tableName: 'order_items' },
223
+ model: { primaryKeyAttribute: 'id' },
224
+ getField: vi.fn().mockReturnValue(undefined),
225
+ } as unknown as Collection,
226
+ tags: {
227
+ name: 'tags',
228
+ options: { tableName: 'tags' },
229
+ model: { primaryKeyAttribute: 'id' },
230
+ getField: vi.fn().mockReturnValue(undefined),
231
+ } as unknown as Collection,
232
+ };
233
+ const manager = {
234
+ db: { options: { schema: 'public' } },
235
+ getCollection: vi.fn((name: string) => collections[name]),
236
+ ensureForeignKey,
237
+ ensureJoinTable,
238
+ } as unknown as PostgresCollectionManager;
239
+
240
+ expect(getRelationLockTables(manager, 'orders', { onDelete: 'CASCADE' }, 'items')).toEqual([
241
+ 'public.order_items',
242
+ 'public.orders',
243
+ ]);
244
+ expect(getRelationLockTables(manager, 'orders', { name: 'tags', through: 'orders_tags_v2' })).toEqual([
245
+ 'public.orders',
246
+ 'public.orders_tags',
247
+ 'public.orders_tags_v2',
248
+ 'public.tags',
249
+ ]);
250
+
251
+ await syncFieldAction(manager, 'update', 'orders', 'items', { onDelete: 'CASCADE' }, {} as Transaction);
252
+ expect(ensureForeignKey).toHaveBeenCalledWith(
253
+ 'order_items',
254
+ expect.objectContaining({
255
+ target: 'orders',
256
+ foreignKey: 'orderId',
257
+ targetKey: 'id',
258
+ onDelete: 'CASCADE',
259
+ replaceActions: true,
260
+ }),
261
+ expect.anything(),
262
+ );
263
+
264
+ await syncFieldAction(manager, 'update', 'orders', 'tags', { onDelete: 'RESTRICT' }, {} as Transaction);
265
+ expect(ensureJoinTable).toHaveBeenCalledWith(
266
+ 'orders',
267
+ expect.objectContaining({
268
+ target: 'tags',
269
+ through: 'orders_tags',
270
+ onDelete: 'RESTRICT',
271
+ replaceActions: true,
272
+ }),
273
+ expect.anything(),
274
+ );
275
+ });
276
+
277
+ it('guards belongsToArray column references, blocks belongsTo targeting views, and builds companion array fields', async () => {
278
+ const arrayRelation = {
279
+ type: 'belongsToArray',
280
+ target: 'tags',
281
+ foreignKey: 'tagRefId',
282
+ targetKey: 'code',
283
+ };
284
+ expect(fieldReferencesColumn(arrayRelation, 'orders', 'orders', ['tagRefId'])).toBe(true);
285
+ expect(fieldReferencesColumn(arrayRelation, 'orders', 'tags', ['code'])).toBe(true);
286
+ expect(fieldReferencesColumn(arrayRelation, 'orders', 'tags', ['id'])).toBe(false);
287
+
288
+ const collections: Record<string, Collection> = {
289
+ orders: {
290
+ name: 'orders',
291
+ options: { tableName: 'orders' },
292
+ model: { primaryKeyAttribute: 'id' },
293
+ getField: vi.fn().mockReturnValue(undefined),
294
+ } as unknown as Collection,
295
+ tags: {
296
+ name: 'tags',
297
+ options: { tableName: 'tags' },
298
+ model: { primaryKeyAttribute: 'code' },
299
+ getField: vi.fn((name: string) =>
300
+ name === 'code' ? { name: 'code', options: { name: 'code', type: 'nanoid' } } : undefined,
301
+ ),
302
+ } as unknown as Collection,
303
+ order_view: {
304
+ name: 'order_view',
305
+ options: { tableName: 'order_view', view: true },
306
+ model: { primaryKeyAttribute: 'id' },
307
+ getField: vi.fn().mockReturnValue(undefined),
308
+ } as unknown as Collection,
309
+ };
310
+ const manager = {
311
+ db: { options: { schema: 'public' } },
312
+ getCollection: vi.fn((name: string) => collections[name]),
313
+ ensureForeignKey: vi.fn().mockResolvedValue(undefined),
314
+ ensureForeignKeyArray: vi.fn().mockResolvedValue(undefined),
315
+ } as unknown as PostgresCollectionManager;
316
+
317
+ await expect(
318
+ syncFieldAction(
319
+ manager,
320
+ 'create',
321
+ 'orders',
322
+ undefined,
323
+ { name: 'viewRef', interface: 'm2o', target: 'order_view' },
324
+ {} as Transaction,
325
+ ),
326
+ ).rejects.toThrow('This collection is read-only');
327
+
328
+ await expect(
329
+ syncFieldAction(
330
+ manager,
331
+ 'create',
332
+ 'orders',
333
+ undefined,
334
+ { name: 'tagRefId', interface: 'm2m_array', target: 'tags', foreignKey: 'tagRefId' },
335
+ {} as Transaction,
336
+ ),
337
+ ).rejects.toThrow('Foreign key tagRefId cannot have the same name as relation field tagRefId');
338
+
339
+ expect(
340
+ buildArrayForeignKeyField(manager, 'orders', {
341
+ name: 'tagRefs',
342
+ type: 'belongsToArray',
343
+ target: 'tags',
344
+ targetKey: 'code',
345
+ foreignKey: 'tagRefId',
346
+ }),
347
+ ).toMatchObject({
348
+ name: 'tagRefId',
349
+ field: 'tagRefId',
350
+ type: 'set',
351
+ dataType: 'array',
352
+ elementType: 'string',
353
+ interface: 'json',
354
+ isForeignKey: true,
355
+ });
356
+ });
357
+ });