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,66 @@
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 { Collection, CollectionContext, CollectionOptions } from '@nocobase/database';
11
+ import { ModelStatic, QueryInterfaceDropTableOptions } from 'sequelize';
12
+ import type { Model } from '@nocobase/database';
13
+ import { SQLModel } from './sql-model';
14
+
15
+ export class PostgresSQLCollection extends Collection {
16
+ constructor(options: CollectionOptions, context: CollectionContext) {
17
+ options.autoGenId = false;
18
+ options.timestamps = false;
19
+ options.underscored = false;
20
+ super(options, context);
21
+ }
22
+
23
+ get filterTargetKey() {
24
+ const targetKey = this.options.filterTargetKey || 'id';
25
+ if (Array.isArray(targetKey)) return targetKey;
26
+ if (targetKey && this.model.getAttributes()[targetKey]) return targetKey;
27
+ return this.model.primaryKeyAttributes.length > 1 ? null : this.model.primaryKeyAttribute;
28
+ }
29
+
30
+ isSql() {
31
+ return true;
32
+ }
33
+
34
+ unavailableActions(): string[] {
35
+ return ['create', 'update', 'destroy', 'importXlsx', 'destroyMany', 'updateMany'];
36
+ }
37
+
38
+ collectionSchema() {
39
+ return undefined;
40
+ }
41
+
42
+ modelInit() {
43
+ const sql = String(this.options.sql || '').trim();
44
+ const normalizedSql = sql.endsWith(';') ? sql.slice(0, -1) : sql;
45
+ if (this.model) {
46
+ (this.model as unknown as typeof SQLModel).sql = normalizedSql;
47
+ return;
48
+ }
49
+ const model = class extends SQLModel {};
50
+ const registeredModel = model as unknown as ModelStatic<Model>;
51
+ registeredModel.init(null, { ...this.sequelizeModelOptions(), schema: undefined });
52
+ registeredModel.removeAttribute('id');
53
+ model.sql = normalizedSql;
54
+ model.database = this.context.database;
55
+ model.collection = this;
56
+ this.model = new Proxy(registeredModel, {
57
+ get(target, key, receiver) {
58
+ return key === '_schema' ? undefined : Reflect.get(target, key, receiver);
59
+ },
60
+ });
61
+ }
62
+
63
+ async removeFromDb(options?: QueryInterfaceDropTableOptions & { dropCollection?: boolean }) {
64
+ if (options?.dropCollection !== false) return this.remove();
65
+ }
66
+ }
@@ -0,0 +1,158 @@
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 { Model } from '@nocobase/database';
11
+ import { isEmpty } from 'lodash';
12
+ import { QueryTypes, Transaction } from 'sequelize';
13
+ import type { GroupOption, Order, ProjectionAlias, WhereOptions } from 'sequelize';
14
+ import { PostgresValidationError } from '../utils/validation-error';
15
+
16
+ type SelectOptions = {
17
+ attributes?: (string | ProjectionAlias)[];
18
+ where?: WhereOptions | string;
19
+ order?: Order;
20
+ group?: GroupOption | string;
21
+ limit?: number;
22
+ offset?: number;
23
+ transaction?: Transaction | null;
24
+ [key: string]: unknown;
25
+ };
26
+
27
+ type SqlGenerator = {
28
+ escapeAttributes(attributes: SelectOptions['attributes'], options: { model: typeof SQLModel }): string[] | undefined;
29
+ getWhereConditions(
30
+ where: SelectOptions['where'],
31
+ name: string,
32
+ model: typeof SQLModel,
33
+ options: SelectOptions,
34
+ ): string;
35
+ aliasGrouping(value: unknown, model: typeof SQLModel, name: string, options: SelectOptions): string;
36
+ getQueryOrders(options: SelectOptions, model: typeof SQLModel, subQuery: boolean): { mainQueryOrder: string[] };
37
+ addLimitAndOffset(options: SelectOptions, model: typeof SQLModel): string;
38
+ getAliasToken(): string;
39
+ quoteIdentifier(value: string): string;
40
+ };
41
+
42
+ // Mirrors the host SQL collection's query generator, retaining its filter, order and pagination options.
43
+ function selectQuery(this: SqlGenerator, _tableName: string, options: SelectOptions, model: typeof SQLModel): string {
44
+ const queryOptions = options || {};
45
+ if (isEmpty(queryOptions)) return `${model.sql};`;
46
+
47
+ let attributes = queryOptions.attributes?.slice();
48
+ if (attributes) {
49
+ const fields = Array.from(model.collection.fields.keys());
50
+ attributes = attributes.filter(
51
+ (attribute) => attribute === '*' || typeof attribute !== 'string' || fields.includes(attribute),
52
+ );
53
+ }
54
+ const escaped = this.escapeAttributes(attributes, { model });
55
+ const selected = escaped && escaped.length > 0 ? escaped : ['*'];
56
+ const clauses: string[] = [];
57
+ if (Object.prototype.hasOwnProperty.call(queryOptions, 'where')) {
58
+ const where = this.getWhereConditions(queryOptions.where, model.name, model, queryOptions);
59
+ if (where) clauses.push(` WHERE ${where}`);
60
+ }
61
+ if (queryOptions.group) {
62
+ const groups = Array.isArray(queryOptions.group) ? queryOptions.group : [queryOptions.group];
63
+ clauses.push(
64
+ ` GROUP BY ${groups.map((value) => this.aliasGrouping(value, model, model.name, queryOptions)).join(', ')}`,
65
+ );
66
+ }
67
+ if (queryOptions.order) {
68
+ const orders = this.getQueryOrders(queryOptions, model, false).mainQueryOrder;
69
+ if (orders.length) clauses.push(` ORDER BY ${orders.join(', ')}`);
70
+ }
71
+ const limit = this.addLimitAndOffset(queryOptions, model);
72
+ if (limit) clauses.push(limit);
73
+ return `SELECT ${selected.join(', ')} FROM (${model.sql}) ${this.getAliasToken()} ${this.quoteIdentifier(
74
+ model.name,
75
+ )}${clauses.join('')};`;
76
+ }
77
+
78
+ export class SQLModel extends Model {
79
+ static sql: string;
80
+
81
+ static get queryInterface() {
82
+ const queryInterface = this.sequelize.getQueryInterface();
83
+ const nativeGenerator = (
84
+ queryInterface as unknown as { queryGenerator: { quoteIdentifier(value: string): string } }
85
+ ).queryGenerator;
86
+ const generator = new Proxy(nativeGenerator, {
87
+ get(target, key, receiver) {
88
+ return key === 'selectQuery' ? selectQuery : Reflect.get(target, key, receiver);
89
+ },
90
+ });
91
+
92
+ return new Proxy(queryInterface, {
93
+ get: (target, key, receiver) => {
94
+ if (key === 'queryGenerator') return generator;
95
+ if (key !== 'select' && key !== 'rawSelect') return Reflect.get(target, key, receiver);
96
+
97
+ return async (...args: unknown[]) => {
98
+ const optionsIndex = key === 'select' ? 2 : 1;
99
+ const options = (args[optionsIndex] || {}) as SelectOptions;
100
+ const schema = this.database.options.schema || 'public';
101
+ const quotedSchema = nativeGenerator.quoteIdentifier(schema);
102
+ if (options.transaction) {
103
+ const transaction = options.transaction;
104
+ const [settings] = await this.sequelize.query<{ readOnly: string; searchPath: string; scs: string }>(
105
+ `SELECT current_setting('transaction_read_only') AS "readOnly", current_setting('search_path') AS "searchPath", current_setting('standard_conforming_strings') AS scs`,
106
+ { type: QueryTypes.SELECT, transaction },
107
+ );
108
+ if (settings.readOnly !== 'on')
109
+ throw new PostgresValidationError('SQL collection queries require a read-only transaction');
110
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', 'on', true)`, { transaction });
111
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
112
+ replacements: { path: quotedSchema },
113
+ transaction,
114
+ });
115
+ let result: unknown;
116
+ try {
117
+ result = await Reflect.apply(Reflect.get(target, key), receiver, args);
118
+ } catch (error) {
119
+ try {
120
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
121
+ replacements: { path: settings.searchPath },
122
+ transaction,
123
+ });
124
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', :scs, true)`, {
125
+ replacements: { scs: settings.scs },
126
+ transaction,
127
+ });
128
+ } catch {
129
+ // A failed SQL statement can abort the transaction before session settings can be restored.
130
+ }
131
+ throw error;
132
+ }
133
+ await this.sequelize.query(`SELECT set_config('search_path', :path, true)`, {
134
+ replacements: { path: settings.searchPath },
135
+ transaction,
136
+ });
137
+ await this.sequelize.query(`SELECT set_config('standard_conforming_strings', :scs, true)`, {
138
+ replacements: { scs: settings.scs },
139
+ transaction,
140
+ });
141
+ return result;
142
+ }
143
+ return this.sequelize.transaction(async (transaction) => {
144
+ await this.sequelize.query('SET TRANSACTION READ ONLY', { transaction });
145
+ await this.sequelize.query('SET LOCAL standard_conforming_strings = on', { transaction });
146
+ await this.sequelize.query(`SET LOCAL search_path TO ${quotedSchema}`, { transaction });
147
+ args[optionsIndex] = { ...options, transaction };
148
+ return Reflect.apply(Reflect.get(target, key), receiver, args);
149
+ });
150
+ };
151
+ },
152
+ });
153
+ }
154
+
155
+ static async sync<M extends Model>(): Promise<M> {
156
+ return this as unknown as M;
157
+ }
158
+ }
@@ -0,0 +1,102 @@
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 { Collection, CollectionContext, CollectionOptions, Model } from '@nocobase/database';
11
+ import { QueryTypes, Transaction } from 'sequelize';
12
+ import { PostgresAdjacencyListRepository } from './adjacency-list-repository';
13
+ import { PostgresValidationError } from '../utils/validation-error';
14
+
15
+ type TreeCollectionOptions = CollectionOptions & { postgresTree?: boolean | string; tree?: boolean | string };
16
+
17
+ function quoteIdentifier(value: string): string {
18
+ return `"${value.replace(/"/g, '""')}"`;
19
+ }
20
+
21
+ function normalizeTree(options: TreeCollectionOptions): TreeCollectionOptions {
22
+ const result = { ...options, postgresTree: options.postgresTree || options.tree || true };
23
+ delete result.tree;
24
+ return result;
25
+ }
26
+
27
+ export class PostgresTreeCollection extends Collection {
28
+ constructor(options: TreeCollectionOptions, context: CollectionContext) {
29
+ super(normalizeTree(options), context);
30
+ this.model.addHook('beforeSave', async (node: Model, hookOptions: { transaction?: Transaction }) => {
31
+ if (!node.isNewRecord && !node.changed(this.treeForeignKey)) return;
32
+ const primaryKey = this.model.primaryKeyAttribute;
33
+ const nodeKey = node.get(primaryKey);
34
+ const parent = node.get(this.treeForeignKey);
35
+ if (parent === null || parent === undefined) return;
36
+ if (!hookOptions.transaction) throw new PostgresValidationError('Tree parent changes require a transaction');
37
+ if (nodeKey !== null && nodeKey !== undefined && String(parent) === String(nodeKey)) {
38
+ throw new PostgresValidationError('Cycle detected in tree collection {{name}}', { name: this.name });
39
+ }
40
+ const modelTable = this.model.getTableName();
41
+ const schema =
42
+ typeof modelTable === 'object' && modelTable
43
+ ? modelTable.schema || this.db.options.schema || 'public'
44
+ : this.db.options.schema || 'public';
45
+ const tableName =
46
+ typeof modelTable === 'object' && modelTable ? modelTable.tableName : String(modelTable || this.name);
47
+ await this.db.sequelize.query('SELECT pg_advisory_xact_lock(hashtextextended(:tree, 0))', {
48
+ replacements: { tree: `${schema}.${tableName}` },
49
+ transaction: hookOptions.transaction,
50
+ });
51
+ const pk = quoteIdentifier(this.getField(primaryKey)?.columnName() || primaryKey);
52
+ const fk = quoteIdentifier(this.getField(this.treeForeignKey)?.columnName() || this.treeForeignKey);
53
+ const tableSql = `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}`;
54
+ const hasNodeKey = nodeKey !== null && nodeKey !== undefined;
55
+ const rows = await this.db.sequelize.query<{ hasCycle: boolean }>(
56
+ `WITH RECURSIVE ancestors AS (
57
+ SELECT t.${pk} AS id, t.${fk} AS "parentId", ARRAY[t.${pk}] AS path, FALSE AS is_cycle
58
+ FROM ${tableSql} t
59
+ WHERE t.${pk} = :parent
60
+ UNION ALL
61
+ SELECT p.${pk} AS id, p.${fk} AS "parentId", ancestors.path || p.${pk}, p.${pk} = ANY(ancestors.path) AS is_cycle
62
+ FROM ${tableSql} p
63
+ JOIN ancestors ON p.${pk} = ancestors."parentId"
64
+ WHERE NOT ancestors.is_cycle
65
+ )
66
+ SELECT COALESCE(BOOL_OR(is_cycle${hasNodeKey ? ' OR id = :nodeKey' : ''}), FALSE) AS "hasCycle"
67
+ FROM ancestors`,
68
+ {
69
+ replacements: hasNodeKey ? { parent, nodeKey } : { parent },
70
+ type: QueryTypes.SELECT,
71
+ transaction: hookOptions.transaction,
72
+ },
73
+ );
74
+ if (rows[0]?.hasCycle) {
75
+ throw new PostgresValidationError('Cycle detected in tree collection {{name}}', { name: this.name });
76
+ }
77
+ });
78
+ this.model.addHook('beforeBulkCreate', (_nodes, hookOptions) => {
79
+ hookOptions.individualHooks = true;
80
+ });
81
+ this.model.addHook('beforeBulkUpdate', (hookOptions) => {
82
+ const { attributes } = hookOptions as typeof hookOptions & { attributes?: Record<string, unknown> };
83
+ if (!hookOptions.individualHooks && Object.prototype.hasOwnProperty.call(attributes || {}, this.treeForeignKey)) {
84
+ throw new PostgresValidationError('Bulk changes to a tree parent require individual hooks');
85
+ }
86
+ });
87
+ }
88
+
89
+ updateOptions(options: TreeCollectionOptions, mergeOptions?: unknown) {
90
+ return super.updateOptions(normalizeTree(options), mergeOptions);
91
+ }
92
+
93
+ setRepository() {
94
+ this.repository = new PostgresAdjacencyListRepository(this);
95
+ }
96
+
97
+ get treeForeignKey(): string {
98
+ const foreignKey = this.treeParentField?.options.foreignKey;
99
+ if (typeof foreignKey === 'string') return foreignKey;
100
+ return typeof this.options.postgresTree === 'string' ? this.options.postgresTree : 'parentId';
101
+ }
102
+ }