@saltcorn/sql 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/action.js ADDED
@@ -0,0 +1,55 @@
1
+ const db = require("@saltcorn/data/db");
2
+ const { eval_expression } = require("@saltcorn/data/models/expression");
3
+
4
+ module.exports = {
5
+ run_sql_code: {
6
+ configFields: [
7
+ {
8
+ name: "sql",
9
+ label: "SQL",
10
+ input_type: "code",
11
+ attributes: { mode: "text/x-sql" },
12
+ sublabel:
13
+ "Refer to row parameters in the order below with <code>$1</code>, <code>$2</code> etc",
14
+ },
15
+ {
16
+ name: "row_parameters",
17
+ label: "Row parameters",
18
+ sublabel:
19
+ "Comma separated list of row variables to use as SQL query parameters. User variables can be used as <code>user.id</code> etc",
20
+ type: "String",
21
+ },
22
+ ],
23
+ run: async ({ row, configuration: { sql, row_parameters }, user }) => {
24
+ const is_sqlite = db.isSQLite;
25
+
26
+ const phValues = [];
27
+ (row_parameters || "")
28
+ .split(",")
29
+ .filter((s) => s)
30
+ .forEach((sp0) => {
31
+ const sp = sp0.trim();
32
+ if (sp.startsWith("user.")) {
33
+ phValues.push(eval_expression(sp, {}, user));
34
+ } else if (typeof row[sp] === "undefined") phValues.push(null);
35
+ else phValues.push(row[sp]);
36
+ });
37
+
38
+ const client = is_sqlite ? db : await db.getClient();
39
+ await client.query(`BEGIN;`);
40
+ if (!is_sqlite) {
41
+ await client.query(
42
+ `SET LOCAL search_path TO "${db.getTenantSchema()}";`
43
+ );
44
+ await client.query(
45
+ `SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;`
46
+ );
47
+ }
48
+ const qres = await client.query(sql, phValues);
49
+
50
+ await client.query(`COMMIT;`);
51
+
52
+ if (!is_sqlite) client.release(true);
53
+ },
54
+ },
55
+ };
package/index.js CHANGED
@@ -35,6 +35,8 @@ const configuration_workflow = () =>
35
35
  label: "SQL",
36
36
  input_type: "code",
37
37
  attributes: { mode: "text/x-sql" },
38
+ sublabel:
39
+ "Refer to state parameters in the order below with <code>$1</code>, <code>$2</code> etc",
38
40
  },
39
41
  {
40
42
  name: "state_parameters",
@@ -103,7 +105,7 @@ const run = async (
103
105
  }
104
106
  const qres = await client.query(sql, phValues);
105
107
 
106
- await client.query(`ROLLBACK`);
108
+ await client.query(`ROLLBACK;`);
107
109
 
108
110
  if (!is_sqlite) client.release(true);
109
111
  switch (output_type) {
@@ -129,6 +131,8 @@ const run = async (
129
131
  module.exports = {
130
132
  sc_plugin_api_version: 1,
131
133
  plugin_name: "sql",
134
+ actions: require("./action.js"),
135
+ table_providers: require("./table-provider.js"),
132
136
  viewtemplates: [
133
137
  {
134
138
  name: "SQLView",
package/package.json CHANGED
@@ -1,12 +1,14 @@
1
1
  {
2
2
  "name": "@saltcorn/sql",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Actions and views based on SQL",
5
5
  "main": "index.js",
6
6
  "dependencies": {
7
7
  "@saltcorn/markup": "^0.6.0",
8
8
  "@saltcorn/data": "^0.6.0",
9
- "underscore": "1.13.6"
9
+ "underscore": "1.13.6",
10
+ "node-sql-parser": "4.0.8",
11
+ "sqlstring": "^2.3.3"
10
12
  },
11
13
  "author": "Tom Nielsen",
12
14
  "license": "MIT",
@@ -0,0 +1,228 @@
1
+ const db = require("@saltcorn/data/db");
2
+ const { eval_expression } = require("@saltcorn/data/models/expression");
3
+ const Workflow = require("@saltcorn/data/models/workflow");
4
+ const Form = require("@saltcorn/data/models/form");
5
+ const FieldRepeat = require("@saltcorn/data/models/fieldrepeat");
6
+ const Field = require("@saltcorn/data/models/field");
7
+ const { getState } = require("@saltcorn/data/db/state");
8
+ const SqlString = require("sqlstring");
9
+ const { Parser } = require("node-sql-parser");
10
+ const { mkTable } = require("@saltcorn/markup");
11
+ const { pre, code } = require("@saltcorn/markup/tags");
12
+ const parser = new Parser();
13
+ const _ = require("underscore");
14
+
15
+ const configuration_workflow = (req) =>
16
+ new Workflow({
17
+ steps: [
18
+ {
19
+ name: "query",
20
+ form: async () => {
21
+ return new Form({
22
+ fields: [
23
+ {
24
+ name: "sql",
25
+ label: "SQL",
26
+ input_type: "code",
27
+ attributes: { mode: "text/x-sql" },
28
+ validator(sql) {
29
+ try {
30
+ const is_sqlite = db.isSQLite;
31
+ const opt = {
32
+ database: is_sqlite ? "SQLite" : "PostgreSQL",
33
+ };
34
+ const template = _.template(sql || "", {
35
+ evaluate: /\{\{#(.+?)\}\}/g,
36
+ interpolate: /\{\{([^#].+?)\}\}/g,
37
+ });
38
+ const sql1 = template({ user: req.user });
39
+
40
+ const pres = parser.parse(sql1, opt);
41
+ if (!Array.isArray(pres.ast))
42
+ return "Not terminated by semicolon?";
43
+ } catch (e) {
44
+ return e.message;
45
+ }
46
+ },
47
+ },
48
+ ],
49
+ });
50
+ },
51
+ },
52
+ {
53
+ name: "columns",
54
+ form: async (context) => {
55
+ const qres = await runQuery(context, { forUser: req.user });
56
+ const tbl = mkTable(
57
+ qres.fields.map((field) => ({
58
+ label: field.name,
59
+ key: field.name,
60
+ })),
61
+ qres.rows?.slice?.(0, 5)
62
+ );
63
+ const theForm = new Form({
64
+ blurb: pre(code(qres.query)) + tbl,
65
+ fields: [
66
+ {
67
+ input_type: "section_header",
68
+ label: "Column types",
69
+ },
70
+ new FieldRepeat({
71
+ name: "columns",
72
+ fields: [
73
+ {
74
+ name: "name",
75
+ label: "Name",
76
+ type: "String",
77
+ required: true,
78
+ },
79
+ {
80
+ name: "label",
81
+ label: "Label",
82
+ type: "String",
83
+ required: true,
84
+ },
85
+ {
86
+ name: "type",
87
+ label: "Type",
88
+ type: "String",
89
+ required: true,
90
+ attributes: { options: getState().type_names },
91
+ },
92
+ ],
93
+ }),
94
+ ],
95
+ });
96
+ if (!context.columns || !context.columns.length) {
97
+ if (!theForm.values) theForm.values = {};
98
+ theForm.values.columns = qres.fields.map((f) => ({
99
+ name: f.name,
100
+ label: Field.nameToLabel(f.name),
101
+ type: dataTypeIdToTypeGuess(f.dataTypeID),
102
+ }));
103
+ }
104
+ return theForm;
105
+ },
106
+ },
107
+ ],
108
+ });
109
+
110
+ const dataTypeIdToTypeGuess = (typeid) => {
111
+ switch (typeid) {
112
+ case 23:
113
+ return "Integer";
114
+ case 25:
115
+ return "String";
116
+ case 1184:
117
+ return "Date";
118
+ case 16:
119
+ return "Bool";
120
+ case 701:
121
+ return "Float";
122
+ case 3802:
123
+ return "JSON";
124
+ default:
125
+ return "String";
126
+ }
127
+ };
128
+
129
+ const sqlEscapeObject = (o) => {
130
+ if (typeof o !== "object" || o === null) return SqlString.escape(o);
131
+ const r = {};
132
+ Object.entries(o).forEach(([k, v]) => {
133
+ if (typeof v === "object") r[k] = sqlEscapeObject(v);
134
+ else r[k] = SqlString.escape(v);
135
+ });
136
+ return r;
137
+ };
138
+
139
+ const runQuery = async (cfg, where) => {
140
+ const sqlTmpl = cfg?.sql || "";
141
+ const template = _.template(sqlTmpl || "", {
142
+ evaluate: /\{\{#(.+?)\}\}/g,
143
+ interpolate: /\{\{([^#].+?)\}\}/g,
144
+ });
145
+
146
+ const qctx = {};
147
+
148
+ if (where.forUser) qctx.user = sqlEscapeObject(where.forUser);
149
+ else qctx.user = null;
150
+
151
+ const sql = template(qctx);
152
+
153
+ const is_sqlite = db.isSQLite;
154
+ const opt = {
155
+ database: is_sqlite ? "SQLite" : "PostgreSQL",
156
+ };
157
+
158
+ const { ast } = parser.parse(sql, opt);
159
+
160
+ const colNames = new Set((cfg?.columns || []).map((c) => c.name));
161
+
162
+ let phIndex = 1;
163
+ const phValues = [];
164
+ for (const k of Object.keys(where)) {
165
+ if (!colNames.has(k)) continue;
166
+ const newClause = {
167
+ type: "binary_expr",
168
+ operator: "=",
169
+ left: { type: "column_ref", table: null, column: db.sqlsanitize(k) },
170
+ right: { type: "number", value: "$" + phIndex },
171
+ };
172
+ phIndex += 1;
173
+ phValues.push(where[k]);
174
+ if (!ast[0].where) ast[0].where = newClause;
175
+ else {
176
+ ast[0].where = {
177
+ type: "binary_expr",
178
+ operator: "AND",
179
+ left: ast[0].where,
180
+ right: newClause,
181
+ };
182
+ }
183
+ }
184
+ if (where?.limit && where?.offset) {
185
+ ast[0].limit = {
186
+ seperator: "offset",
187
+ value: [
188
+ { type: "number", value: where.limit },
189
+ { type: "number", value: where.offset },
190
+ ],
191
+ };
192
+ } else if (where?.limit) {
193
+ ast[0].limit = {
194
+ seperator: "",
195
+ value: [{ type: "number", value: where.limit }],
196
+ };
197
+ }
198
+
199
+ const client = is_sqlite ? db : await db.getClient();
200
+ await client.query(`BEGIN;`);
201
+ if (!is_sqlite) {
202
+ await client.query(`SET LOCAL search_path TO "${db.getTenantSchema()}";`);
203
+ await client.query(`SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;`);
204
+ }
205
+
206
+ const sqlQ = parser.sqlify(ast, opt);
207
+ const qres = await client.query(sqlQ, phValues);
208
+ qres.query = sqlQ;
209
+ await client.query(`ROLLBACK;`);
210
+
211
+ if (!is_sqlite) client.release(true);
212
+ return qres;
213
+ };
214
+
215
+ module.exports = {
216
+ "SQL query": {
217
+ configuration_workflow,
218
+ fields: (cfg) => cfg?.columns || [],
219
+ get_table: (cfg) => {
220
+ return {
221
+ getRows: async (where) => {
222
+ const qres = await runQuery(cfg, where);
223
+ return qres.rows;
224
+ },
225
+ };
226
+ },
227
+ },
228
+ };