@nocobase/plugin-collection-sql 1.0.0-alpha.15

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/LICENSE.txt ADDED
@@ -0,0 +1,122 @@
1
+ Updated Date: March 30, 2024
2
+
3
+ NocoBase License Agreement
4
+
5
+ NocoBase Co., Ltd. ("The Company") https://www.nocobase.com/ issues this License Agreement ("Agreement") to you. You, as an individual or a company ("User"), will be deemed to voluntarily accept all terms of this Agreement by using NocoBase (including but not limited to obtaining NocoBase source code or installation package in any form, installing and using NocoBase, purchasing NocoBase commercial license and services, purchasing NocoBase commercial plugins). If the User does not agree to any term of this Agreement, or cannot accurately understand our interpretation of the relevant terms, please stop using it immediately.
6
+
7
+ This Agreement applies to any use, quotation, contract, invoice, and all software delivered by the Company. The User and the Company or NocoBase's agents can no longer sign a separate license agreement for the sale and delivery of the software.
8
+
9
+ The Company reserves the right to formulate and modify this Agreement from time to time as needed. If there are changes, the Company will announce them in the form of website announcements, without further individual notification. The changed Agreement will automatically take effect once it is announced, becoming part of this Agreement.
10
+
11
+ ==============
12
+ 1. Definitions
13
+ ==============
14
+ 1.1 "Software" refers to the NocoBase kernel and plugins placed in the same code repository as the kernel, including their source code, installation packages, images, and all their modifications, updates, and upgrades.
15
+
16
+ 1.2 "Plugin Market" refers to the market provided by the Company for selling Software plugins and solutions.
17
+
18
+ 1.3 "Commercial Plugin" refers to the paid plugins provided by the Plugin Market.
19
+
20
+ 1.4 "Root Version" refers to the major version number before the first point in the version number. For example, from 1.0 to 1.x are all the same Root Version 1.
21
+
22
+ 1.5 "Plugin Package" is the unit for batch licensing Commercial Plugins. P5, P10, and P20 Plugin Packages include installation packages for 5, 10, and 20 Commercial Plugins respectively. P5+, P10+, P20+ provide the source code of the Plugins in addition to the installation packages.
23
+
24
+ 1.6 "Upper Layer Application" refers to a specific business use case application serving internal or external customers of the User, developed based on Software and Commercial Plugins, such as ERP/CRM.
25
+
26
+ 1.7 "Third-Party Open Source Software" refers to open source software provided with Software and Commercial Plugins. They are licensed through various published open source software licenses or copyright notices accompanying such software.
27
+
28
+ ===================================
29
+ 2. Intellectual Property Protection
30
+ ===================================
31
+
32
+ Except for Third-Party Open Source Software, the Company owns all copyrights, trademark rights, patent rights, trade secrets, and other intellectual property rights of the Software and Commercial Plugins, and has registered and protected them in relevant countries and regions according to the "Paris Convention" or "TRIPS Agreement", ensuring that the intellectual property rights of the Software and Commercial Plugins are internationally recognized and protected.
33
+
34
+ =============
35
+ 3. Disclaimer
36
+ =============
37
+
38
+ 3.1 Users shall not use the Software and Commercial Plugins to engage in activities that violate local laws and regulations, religious beliefs. All legal responsibilities and legal consequences arising from the use of Software and Commercial Plugins shall be borne by the User.
39
+
40
+ 3.2 The Company shall not be liable for any direct, indirect, special, incidental, or consequential damages (including but not limited to loss of profits, business interruption, data loss, or business information disclosure) caused by the User's use of the Software and Commercial Plugins, even if it has been previously informed of the possibility of such damages.
41
+
42
+ ===============
43
+ 4. License Type
44
+ ===============
45
+
46
+ 4.1 The Software uses a dual license type of AGPL-3.0 Open Source License https://www.gnu.org/licenses/agpl-3..en.htm and Commercial License.
47
+
48
+ 4.2 Commercial Plugins use Commercial License.
49
+
50
+ ================================================
51
+ 5. Rights and Obligations of Open Source License
52
+ ================================================
53
+
54
+ 5.1 The Software can be used for commercial purposes, such as developing applications for internal use within a company or for clients.
55
+
56
+ 5.2 User can sell plugins developed for the Software in the Plugin Market.
57
+
58
+ 5.3 Outside the Plugin Market, changes and plugins to the Software developed by User or third parties, and third-party software integrated with the Software must all be open sourced under the AGPL-3.0 license.
59
+
60
+ 5.4 It is not allowed to remove or change the brand, name, link, version number, license, and other information about NocoBase on the Software interface, except for the main LOGO in the upper left corner of the page.
61
+
62
+ 5.5 It is not allowed to remove or change all intellectual property statements about NocoBase in the code.
63
+
64
+ 5.6 It is not allowed to provide any form of no-code, zero-code, low-code platform SaaS products to the public using the original or modified Software.
65
+
66
+ 5.7 Comply with all requirements of the AGPL-3.0 agreement.
67
+
68
+ ===============================
69
+ 6. Rights of Commercial License
70
+ ===============================
71
+
72
+ 6.1 Obtain a permanent commercial license for a Root Version of the Software or Commercial Plugin.
73
+
74
+ 6.2 Get 6 months of exclusive technical support.
75
+
76
+ 6.3 Upgrade to the next Root Version at 50% of the contract price.
77
+
78
+ 6.4 The licensed Software and Commercial Plugins can be used for commercial purposes, such as developing applications for internal use within a company or for clients, with no restrictions on the number of applications and users.
79
+
80
+ 6.5 Changes and plugins to the Software, and applications integrated with the Software do not need to be open sourced.
81
+
82
+ 6.6 Can remove or change the brand, name, link, version number, license, and other information about NocoBase on the Software interface.
83
+
84
+ 6.7 Can sell plugins developed for Software in the Plugin Market or on User’s own website.
85
+
86
+ 6.8 Can sell or provide Upper Layer Applications developed based on Software in the form of SaaS to the public.
87
+
88
+ 6.9 Not restricted by the AGPL-3.0 agreement.
89
+
90
+ 6.10 If there are other agreements in the contract for the above rights, the contract agreement shall prevail.
91
+
92
+ ====================================
93
+ 7. Obligations of Commercial License
94
+ ====================================
95
+
96
+ 7.1 It is not allowed to remove or change all intellectual property statements about NocoBase in the code.
97
+
98
+ 7.2 It is not allowed to sell, transfer, lease, share, or give away the Commercial License.
99
+
100
+ 7.3 It is not allowed to sell, transfer, lease, share, or give away any form of no-code, zero-code, low-code platform, or developer tools developed based on Software.
101
+
102
+ 7.4 It is not allowed to provide any form of no-code, zero-code, low-code platform SaaS products to the public using the original or modified Software.
103
+
104
+ 7.5 It is not allowed to use reverse engineering, decompilation, and other means to try to discover the source code of Commercial Plugins that have not obtained source code license.
105
+
106
+ 7.6 It is not allowed to disclose the source code of Commercial Plugins to any third party.
107
+
108
+ 7.7 If there is a violation of the above obligations or the terms of this Agreement, the rights owned by the User will be immediately terminated, the paid fees will not be refunded, and the Company reserves the right to pursue the User's legal responsibility.
109
+
110
+ 7.8 If there are other agreements in the contract for the above obligations, the contract agreement shall prevail.
111
+
112
+ =============================================================
113
+ 8. Legal Jurisdiction, Interpretation, and Dispute Resolution
114
+ =============================================================
115
+
116
+ 8.1 Except for Mainland China, the interpretation, application, and all matters related to this agreement are subject to the jurisdiction of Singapore law.
117
+
118
+ 8.2 Any dispute related to this Agreement should first be resolved through friendly negotiation. If the negotiation fails to resolve the dispute, the dispute should be submitted to the International Chamber of Commerce (ICC) for arbitration. The arbitration venue should be Singapore, conducted in English.
119
+
120
+ 8.3 All terms and conditions of this Agreement shall be deemed enforceable to the maximum extent permitted by applicable law. If any term of this Agreement is deemed invalid by any applicable law, the invalidity of that term does not affect the validity of any other term of this Agreement, and it should be deemed that the invalid term has been modified as much as possible to make it valid and enforceable, or if the term cannot be modified, it should be deemed to have been deleted from this Agreement.
121
+
122
+ 8.4 The arbitration award is final, binding on both parties, and can be enforced in any court with jurisdiction.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # @nocobase/plugin-collection-sql
package/client.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './dist/client';
2
+ export { default } from './dist/client';
package/client.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/client/index.js');
@@ -0,0 +1,7 @@
1
+ import { Plugin } from '@nocobase/client';
2
+ export declare class PluginCollectionSqlClient extends Plugin {
3
+ afterAdd(): Promise<void>;
4
+ beforeLoad(): Promise<void>;
5
+ load(): Promise<void>;
6
+ }
7
+ export default PluginCollectionSqlClient;
@@ -0,0 +1,10 @@
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
+ (function(e,n){typeof exports=="object"&&typeof module!="undefined"?n(exports,require("@nocobase/client")):typeof define=="function"&&define.amd?define(["exports","@nocobase/client"],n):(e=typeof globalThis!="undefined"?globalThis:e||self,n(e["@nocobase/plugin-collection-sql"]={},e["@nocobase/client"]))})(this,function(e,n){"use strict";var l=(e,n,o)=>new Promise((c,d)=>{var u=i=>{try{t(o.next(i))}catch(s){d(s)}},f=i=>{try{t(o.throw(i))}catch(s){d(s)}},t=i=>i.done?c(i.value):Promise.resolve(i.value).then(u,f);t((o=o.apply(e,n)).next())});class o extends n.Plugin{afterAdd(){return l(this,null,function*(){})}beforeLoad(){return l(this,null,function*(){})}load(){return l(this,null,function*(){console.log(this.app)})}}e.PluginCollectionSqlClient=o,e.default=o,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
@@ -0,0 +1,17 @@
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
+ module.exports = {
11
+ "@nocobase/client": "1.0.0-alpha.15",
12
+ "@nocobase/server": "1.0.0-alpha.15",
13
+ "@nocobase/database": "1.0.0-alpha.15",
14
+ "@nocobase/actions": "1.0.0-alpha.15",
15
+ "sequelize": "6.35.2",
16
+ "@nocobase/utils": "1.0.0-alpha.15"
17
+ };
@@ -0,0 +1,2 @@
1
+ export * from './server';
2
+ export { default } from './server';
package/dist/index.js ADDED
@@ -0,0 +1,48 @@
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
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
+ // If the importer is in node compatibility mode or this is not an ESM
31
+ // file that has been converted to a CommonJS file using a Babel-
32
+ // compatible transform (i.e. "__esModule" has not been set), then set
33
+ // "default" to the CommonJS "module.exports" for node compatibility.
34
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
+ mod
36
+ ));
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+ var src_exports = {};
39
+ __export(src_exports, {
40
+ default: () => import_server.default
41
+ });
42
+ module.exports = __toCommonJS(src_exports);
43
+ __reExport(src_exports, require("./server"), module.exports);
44
+ var import_server = __toESM(require("./server"));
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ ...require("./server")
48
+ });
@@ -0,0 +1 @@
1
+ export { default } from './plugin';
@@ -0,0 +1,42 @@
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
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var server_exports = {};
38
+ __export(server_exports, {
39
+ default: () => import_plugin.default
40
+ });
41
+ module.exports = __toCommonJS(server_exports);
42
+ var import_plugin = __toESM(require("./plugin"));
@@ -0,0 +1,13 @@
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
+ import { Plugin } from '@nocobase/server';
10
+ export declare class PluginCollectionSQLServer extends Plugin {
11
+ beforeLoad(): Promise<void>;
12
+ }
13
+ export default PluginCollectionSQLServer;
@@ -0,0 +1,70 @@
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
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var plugin_exports = {};
38
+ __export(plugin_exports, {
39
+ PluginCollectionSQLServer: () => PluginCollectionSQLServer,
40
+ default: () => plugin_default
41
+ });
42
+ module.exports = __toCommonJS(plugin_exports);
43
+ var import_server = require("@nocobase/server");
44
+ var import_sql_collection = require("./sql-collection");
45
+ var import_sql = __toESM(require("./resources/sql"));
46
+ class PluginCollectionSQLServer extends import_server.Plugin {
47
+ async beforeLoad() {
48
+ this.app.db.collectionFactory.registerCollectionType(import_sql_collection.SQLCollection, {
49
+ condition: (options) => {
50
+ return options.sql;
51
+ },
52
+ async onSync() {
53
+ return;
54
+ },
55
+ async onDump(dumper, collection) {
56
+ return;
57
+ }
58
+ });
59
+ this.app.resourceManager.define(import_sql.default);
60
+ this.app.acl.registerSnippet({
61
+ name: `pm.data-source-manager.collection-sql `,
62
+ actions: ["sqlCollection:*"]
63
+ });
64
+ }
65
+ }
66
+ var plugin_default = PluginCollectionSQLServer;
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ PluginCollectionSQLServer
70
+ });
@@ -0,0 +1,18 @@
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
+ import { Context, Next } from '@nocobase/actions';
10
+ declare const _default: {
11
+ name: string;
12
+ actions: {
13
+ execute: (ctx: Context, next: Next) => Promise<void>;
14
+ setFields: (ctx: Context, next: Next) => Promise<void>;
15
+ update: (ctx: Context, next: Next) => Promise<void>;
16
+ };
17
+ };
18
+ export default _default;
@@ -0,0 +1,119 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var sql_exports = {};
28
+ __export(sql_exports, {
29
+ default: () => sql_default
30
+ });
31
+ module.exports = __toCommonJS(sql_exports);
32
+ var import_sql_collection = require("../sql-collection");
33
+ const updateCollection = async (ctx, transaction) => {
34
+ const { filterByTk, values } = ctx.action.params;
35
+ const repo = ctx.db.getRepository("collections");
36
+ const collection = await repo.findOne({
37
+ filter: {
38
+ name: filterByTk
39
+ },
40
+ transaction
41
+ });
42
+ const existFields = await collection.getFields({ transaction });
43
+ const deletedFields = existFields.filter((field) => {
44
+ var _a;
45
+ return !((_a = values.fields) == null ? void 0 : _a.find((f) => f.name === field.name));
46
+ });
47
+ for (const field of deletedFields) {
48
+ await field.destroy({ transaction });
49
+ }
50
+ const upRes = await repo.update({
51
+ filterByTk,
52
+ values,
53
+ updateAssociationValues: ["fields"],
54
+ transaction
55
+ });
56
+ return { collection, upRes };
57
+ };
58
+ var sql_default = {
59
+ name: "sqlCollection",
60
+ actions: {
61
+ execute: async (ctx, next) => {
62
+ let { sql } = ctx.action.params.values || {};
63
+ if (!sql) {
64
+ ctx.throw(400, ctx.t("Please enter a SQL statement"));
65
+ }
66
+ sql = sql.trim().split(";").shift();
67
+ if (!/^select/i.test(sql) && !/^with([\s\S]+)select([\s\S]+)/i.test(sql)) {
68
+ ctx.throw(400, ctx.t("Only supports SELECT statements or WITH clauses"));
69
+ }
70
+ const tmpCollection = new import_sql_collection.SQLCollection({ name: "tmp", sql }, { database: ctx.db });
71
+ const model = tmpCollection.model;
72
+ const data = await model.findAll({ attributes: ["*"], limit: 5, raw: true });
73
+ let fields = {};
74
+ try {
75
+ fields = model.inferFields();
76
+ } catch (err) {
77
+ ctx.logger.warn(`resource: sql-collection, action: execute, error: ${err}`);
78
+ fields = {};
79
+ }
80
+ const sources = Array.from(
81
+ new Set(
82
+ Object.values(fields).map((field) => field.collection).filter((c) => c)
83
+ )
84
+ );
85
+ ctx.body = { data, fields, sources };
86
+ await next();
87
+ },
88
+ setFields: async (ctx, next) => {
89
+ const transaction = await ctx.app.db.sequelize.transaction();
90
+ try {
91
+ const {
92
+ upRes: [collection]
93
+ } = await updateCollection(ctx, transaction);
94
+ await collection.loadFields({
95
+ transaction
96
+ });
97
+ await transaction.commit();
98
+ } catch (e) {
99
+ await transaction.rollback();
100
+ throw e;
101
+ }
102
+ await next();
103
+ },
104
+ update: async (ctx, next) => {
105
+ const transaction = await ctx.app.db.sequelize.transaction();
106
+ try {
107
+ const { upRes } = await updateCollection(ctx, transaction);
108
+ const [collection] = upRes;
109
+ await collection.load({ transaction, resetFields: true });
110
+ await transaction.commit();
111
+ ctx.body = upRes;
112
+ } catch (e) {
113
+ await transaction.rollback();
114
+ throw e;
115
+ }
116
+ await next();
117
+ }
118
+ }
119
+ };
@@ -0,0 +1,10 @@
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
+ export * from './sql-model';
10
+ export * from './sql-collection';
@@ -0,0 +1,32 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+ var sql_collection_exports = {};
25
+ module.exports = __toCommonJS(sql_collection_exports);
26
+ __reExport(sql_collection_exports, require("./sql-model"), module.exports);
27
+ __reExport(sql_collection_exports, require("./sql-collection"), module.exports);
28
+ // Annotate the CommonJS export names for ESM import in node:
29
+ 0 && (module.exports = {
30
+ ...require("./sql-model"),
31
+ ...require("./sql-collection")
32
+ });
@@ -0,0 +1,18 @@
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
+ import { GroupOption, Order, ProjectionAlias, WhereOptions } from 'sequelize';
10
+ import { SQLModel } from './sql-model';
11
+ export declare function selectQuery(tableName: string, options: {
12
+ attributes?: (string | ProjectionAlias)[];
13
+ where?: WhereOptions;
14
+ order?: Order;
15
+ group?: GroupOption;
16
+ limit?: number;
17
+ offset?: number;
18
+ }, model: SQLModel): string;
@@ -0,0 +1,77 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var query_generator_exports = {};
28
+ __export(query_generator_exports, {
29
+ selectQuery: () => selectQuery
30
+ });
31
+ module.exports = __toCommonJS(query_generator_exports);
32
+ var import_utils = require("@nocobase/utils");
33
+ function selectQuery(tableName, options, model) {
34
+ var _a;
35
+ options = options || {};
36
+ if (import_utils.lodash.isEmpty(options)) {
37
+ return `${model.sql};`;
38
+ }
39
+ const queryItems = [];
40
+ let attributes = options.attributes && options.attributes.slice();
41
+ if (attributes) {
42
+ const fields = Array.from(((_a = model.collection) == null ? void 0 : _a.fields.keys()) || []);
43
+ attributes = attributes.filter((attr) => attr === "*" || typeof attr !== "string" || fields.includes(attr));
44
+ }
45
+ attributes = this.escapeAttributes(attributes, { model });
46
+ attributes = attributes || ["*"];
47
+ if (Object.prototype.hasOwnProperty.call(options, "where")) {
48
+ options.where = this.getWhereConditions(options.where, tableName, model, options);
49
+ if (options.where) {
50
+ queryItems.push(` WHERE ${options.where}`);
51
+ }
52
+ }
53
+ if (options.group) {
54
+ options.group = Array.isArray(options.group) ? options.group.map((t) => this.aliasGrouping(t, model, tableName, options)).join(", ") : this.aliasGrouping(options.group, model, tableName, options);
55
+ if (options.group) {
56
+ queryItems.push(` GROUP BY ${options.group}`);
57
+ }
58
+ }
59
+ if (options.order) {
60
+ const orders = this.getQueryOrders(options, model, false);
61
+ if (orders.mainQueryOrder.length) {
62
+ queryItems.push(` ORDER BY ${orders.mainQueryOrder.join(", ")}`);
63
+ }
64
+ }
65
+ const limitOrder = this.addLimitAndOffset(options, model);
66
+ if (limitOrder) {
67
+ queryItems.push(limitOrder);
68
+ }
69
+ const query = `SELECT ${attributes.join(", ")} FROM (${model.sql}) ${this.getAliasToken()} ${this.quoteIdentifier(
70
+ model.name
71
+ )}${queryItems.join("")}`;
72
+ return `${query};`;
73
+ }
74
+ // Annotate the CommonJS export names for ESM import in node:
75
+ 0 && (module.exports = {
76
+ selectQuery
77
+ });
@@ -0,0 +1,20 @@
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
+ import { Collection, CollectionContext, CollectionOptions } from '@nocobase/database';
10
+ import { QueryInterfaceDropTableOptions } from 'sequelize';
11
+ export declare class SQLCollection extends Collection {
12
+ constructor(options: CollectionOptions, context: CollectionContext);
13
+ isSql(): boolean;
14
+ collectionSchema(): any;
15
+ get filterTargetKey(): string;
16
+ modelInit(): void;
17
+ removeFromDb(options?: QueryInterfaceDropTableOptions & {
18
+ dropCollection?: boolean;
19
+ }): Promise<Collection<any, any>>;
20
+ }
@@ -0,0 +1,91 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var sql_collection_exports = {};
28
+ __export(sql_collection_exports, {
29
+ SQLCollection: () => SQLCollection
30
+ });
31
+ module.exports = __toCommonJS(sql_collection_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_sql_model = require("./sql-model");
34
+ class SQLCollection extends import_database.Collection {
35
+ constructor(options, context) {
36
+ options.autoGenId = false;
37
+ options.timestamps = false;
38
+ options.underscored = false;
39
+ super(options, context);
40
+ }
41
+ isSql() {
42
+ return true;
43
+ }
44
+ collectionSchema() {
45
+ return void 0;
46
+ }
47
+ /* istanbul ignore next -- @preserve */
48
+ get filterTargetKey() {
49
+ var _a;
50
+ const targetKey = ((_a = this.options) == null ? void 0 : _a.filterTargetKey) || "id";
51
+ if (targetKey && this.model.getAttributes()[targetKey]) {
52
+ return targetKey;
53
+ }
54
+ if (this.model.primaryKeyAttributes.length > 1) {
55
+ return null;
56
+ }
57
+ return this.model.primaryKeyAttribute;
58
+ }
59
+ modelInit() {
60
+ const { autoGenId, sql } = this.options;
61
+ const model = class extends import_sql_model.SQLModel {
62
+ };
63
+ model.init(null, {
64
+ ...this.sequelizeModelOptions(),
65
+ schema: void 0
66
+ });
67
+ if (!autoGenId) {
68
+ model.removeAttribute("id");
69
+ }
70
+ model.sql = (sql == null ? void 0 : sql.endsWith(";")) ? sql.slice(0, -1) : sql;
71
+ model.database = this.context.database;
72
+ model.collection = this;
73
+ this.model = new Proxy(model, {
74
+ get(target, prop) {
75
+ if (prop === "_schema") {
76
+ return void 0;
77
+ }
78
+ return Reflect.get(target, prop);
79
+ }
80
+ });
81
+ }
82
+ async removeFromDb(options) {
83
+ if ((options == null ? void 0 : options.dropCollection) !== false) {
84
+ return this.remove();
85
+ }
86
+ }
87
+ }
88
+ // Annotate the CommonJS export names for ESM import in node:
89
+ 0 && (module.exports = {
90
+ SQLCollection
91
+ });
@@ -0,0 +1,25 @@
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
+ import { Model } from '@nocobase/database';
10
+ export declare class SQLModel extends Model {
11
+ static sql: string;
12
+ static get queryInterface(): import("sequelize").QueryInterface;
13
+ static sync(): Promise<any>;
14
+ private static getTableNameWithSchema;
15
+ private static parseSelectAST;
16
+ private static parseTablesAndColumns;
17
+ static inferFields(): {
18
+ [field: string]: {
19
+ type: string;
20
+ source: string;
21
+ collection: string;
22
+ interface: string;
23
+ };
24
+ };
25
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var sql_model_exports = {};
28
+ __export(sql_model_exports, {
29
+ SQLModel: () => SQLModel
30
+ });
31
+ module.exports = __toCommonJS(sql_model_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_query_generator = require("./query-generator");
34
+ class SQLModel extends import_database.Model {
35
+ static sql;
36
+ static get queryInterface() {
37
+ const queryInterface = this.sequelize.getQueryInterface();
38
+ const queryGenerator = queryInterface.queryGenerator;
39
+ const sqlGenerator = new Proxy(queryGenerator, {
40
+ get(target, prop) {
41
+ if (prop === "selectQuery") {
42
+ return import_query_generator.selectQuery.bind(target);
43
+ }
44
+ return Reflect.get(target, prop);
45
+ }
46
+ });
47
+ return new Proxy(queryInterface, {
48
+ get(target, prop) {
49
+ if (prop === "queryGenerator") {
50
+ return sqlGenerator;
51
+ }
52
+ return Reflect.get(target, prop);
53
+ }
54
+ });
55
+ }
56
+ static async sync() {
57
+ }
58
+ static getTableNameWithSchema(table) {
59
+ if (this.database.inDialect("postgres") && !table.includes(".")) {
60
+ const schema = process.env.DB_SCHEMA || "public";
61
+ return `${schema}.${table}`;
62
+ }
63
+ return table;
64
+ }
65
+ static parseSelectAST(ast) {
66
+ const tablesMap = {};
67
+ const tableAliases = {};
68
+ ast.from.forEach((fromItem) => {
69
+ tablesMap[fromItem.table] = [];
70
+ if (fromItem.as) {
71
+ tableAliases[fromItem.as] = fromItem.table;
72
+ }
73
+ });
74
+ ast.columns.forEach((column) => {
75
+ const expr = column.expr;
76
+ if (expr.type !== "column_ref") {
77
+ return;
78
+ }
79
+ const table = expr.table;
80
+ const name = tableAliases[table] || table;
81
+ const columnAttr = { name: expr.column, as: column.as };
82
+ if (!name) {
83
+ Object.keys(tablesMap).forEach((n) => {
84
+ tablesMap[n].push(columnAttr);
85
+ });
86
+ } else if (tablesMap[name]) {
87
+ tablesMap[name].push(columnAttr);
88
+ }
89
+ });
90
+ return tablesMap;
91
+ }
92
+ static parseTablesAndColumns() {
93
+ let { ast: _ast } = import_database.sqlParser.parse(this.sql);
94
+ if (Array.isArray(_ast)) {
95
+ _ast = _ast[0];
96
+ }
97
+ const ast = _ast;
98
+ ast.from = ast.from || [];
99
+ ast.columns = ast.columns || [];
100
+ if (ast.with) {
101
+ const withAST = ast.with;
102
+ withAST.forEach((withItem) => {
103
+ const as = withItem.name.value;
104
+ const withAst = withItem.stmt.ast;
105
+ ast.from.push(...withAst.from.map((f) => ({ ...f, as })));
106
+ ast.columns.push(
107
+ ...withAst.columns.map((c) => ({
108
+ ...c,
109
+ expr: {
110
+ ...c.expr,
111
+ table: as
112
+ }
113
+ }))
114
+ );
115
+ });
116
+ }
117
+ const tablesMap = this.parseSelectAST(ast);
118
+ return Object.entries(tablesMap).filter(([_, columns]) => columns).map(([table, columns]) => ({ table, columns }));
119
+ }
120
+ static inferFields() {
121
+ const tables = this.parseTablesAndColumns();
122
+ return tables.reduce((fields, { table, columns }) => {
123
+ const tableName = this.getTableNameWithSchema(table);
124
+ const collection = this.database.tableNameCollectionMap.get(tableName);
125
+ if (!collection) {
126
+ const originFields = {};
127
+ columns.forEach((column) => {
128
+ if (column.name === "*") {
129
+ return;
130
+ }
131
+ originFields[column.as || column.name] = {};
132
+ });
133
+ return { ...fields, ...originFields };
134
+ }
135
+ const all = columns.some((column) => column.name === "*");
136
+ const attributes = collection.model.getAttributes();
137
+ const sourceFields = {};
138
+ if (all) {
139
+ Object.values(attributes).forEach((attribute) => {
140
+ const field = collection.getField(attribute.fieldName);
141
+ if (!(field == null ? void 0 : field.options.interface)) {
142
+ return;
143
+ }
144
+ sourceFields[field.name] = {
145
+ collection: field.collection.name,
146
+ type: field.type,
147
+ source: `${field.collection.name}.${field.name}`,
148
+ interface: field.options.interface,
149
+ uiSchema: field.options.uiSchema
150
+ };
151
+ });
152
+ } else {
153
+ columns.forEach((column) => {
154
+ let options = {};
155
+ const modelField = Object.values(attributes).find((attribute) => attribute.field === column.name);
156
+ if (modelField) {
157
+ const field = collection.getField(modelField.fieldName);
158
+ if (field == null ? void 0 : field.options.interface) {
159
+ options = {
160
+ collection: field.collection.name,
161
+ type: field.type,
162
+ source: `${field.collection.name}.${field.name}`,
163
+ interface: field.options.interface,
164
+ uiSchema: field.options.uiSchema
165
+ };
166
+ }
167
+ }
168
+ sourceFields[column.as || column.name] = options;
169
+ });
170
+ }
171
+ return { ...fields, ...sourceFields };
172
+ }, {});
173
+ }
174
+ }
175
+ // Annotate the CommonJS export names for ESM import in node:
176
+ 0 && (module.exports = {
177
+ SQLModel
178
+ });
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@nocobase/plugin-collection-sql",
3
+ "displayName": "Collection: SQL",
4
+ "displayName.zh-CN": "数据表: SQL",
5
+ "description": "Provides SQL collection template",
6
+ "description.zh-CN": "提供 SQL 数据表模板",
7
+ "version": "1.0.0-alpha.15",
8
+ "homepage": "https://docs-cn.nocobase.com/handbook/collection-sql",
9
+ "homepage.zh-CN": "https://docs-cn.nocobase.com/handbook/collection-sql",
10
+ "main": "dist/server/index.js",
11
+ "license": "AGPL-3.0",
12
+ "peerDependencies": {
13
+ "@nocobase/client": "0.x",
14
+ "@nocobase/server": "0.x",
15
+ "@nocobase/test": "0.x"
16
+ },
17
+ "keywords": [
18
+ "Collections"
19
+ ],
20
+ "gitHead": "2793d371368e094ea2bba04cfbe9b9b73c44edba"
21
+ }
package/server.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './dist/server';
2
+ export { default } from './dist/server';
package/server.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/server/index.js');