@cerebruminc/yates 3.1.1 → 3.2.0-beta.dangerous.e67b943

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.0](https://github.com/cerebruminc/yates/compare/v3.1.1...v3.2.0) (2024-01-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * add support for the `in` operator with static scalar values ([7cf7903](https://github.com/cerebruminc/yates/commit/7cf7903df48865f18ea17b1e4f4e1e4e7683aaa8))
9
+
3
10
  ## [3.1.1](https://github.com/cerebruminc/yates/compare/v3.1.0...v3.1.1) (2024-01-15)
4
11
 
5
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cerebruminc/yates",
3
- "version": "3.1.1",
3
+ "version": "3.2.0-beta.dangerous.e67b943",
4
4
  "description": "Role based access control for Prisma Apps",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -8,6 +8,7 @@
8
8
  "build": "tsc",
9
9
  "test": "rome ci src test",
10
10
  "lint:fix": "rome check --apply src test",
11
+ "test:types": "tsc --noEmit",
11
12
  "test:integration": "jest --runInBand test/integration",
12
13
  "test:compose:integration": "docker compose -f docker-compose.yml --profile with-sut up db sut --exit-code-from sut",
13
14
  "setup": "prisma generate && prisma migrate dev",
@@ -30,11 +31,12 @@
30
31
  "uuid": "^9.0.0"
31
32
  },
32
33
  "dependencies": {
34
+ "lodash": "^4.17.21",
33
35
  "node-sql-parser": "^4.12.0",
34
- "lodash": "^4.17.21"
36
+ "type-fest": "^4.10.3"
35
37
  },
36
38
  "peerDependencies": {
37
39
  "@prisma/client": "^5.0.0",
38
40
  "prisma": "^5.0.0"
39
41
  }
40
- }
42
+ }
@@ -1,68 +0,0 @@
1
- /**
2
- * Generates an AST fragment that will check if a column value exists in a JSONB array stored in a `current_setting`
3
- * The AST fragment represents SQL that looks like this:
4
- * = ANY (SELECT jsonb_array_elements_text(current_setting('ctx.my_context_value')::jsonb))
5
- */
6
- export declare const jsonb_array_elements_text: (setting: string) => {
7
- type: string;
8
- name: string;
9
- args: {
10
- type: string;
11
- value: {
12
- ast: {
13
- with: null;
14
- type: string;
15
- options: null;
16
- distinct: {
17
- type: null;
18
- };
19
- columns: {
20
- type: string;
21
- expr: {
22
- type: string;
23
- name: string;
24
- args: {
25
- type: string;
26
- value: {
27
- type: string;
28
- keyword: string;
29
- expr: {
30
- type: string;
31
- name: string;
32
- args: {
33
- type: string;
34
- value: {
35
- type: string;
36
- value: string;
37
- }[];
38
- };
39
- };
40
- as: null;
41
- symbol: string;
42
- target: {
43
- dataType: string;
44
- };
45
- arrows: never[];
46
- properties: never[];
47
- }[];
48
- };
49
- };
50
- as: null;
51
- }[];
52
- into: {
53
- position: null;
54
- };
55
- from: null;
56
- where: null;
57
- groupby: null;
58
- having: null;
59
- orderby: null;
60
- limit: {
61
- seperator: string;
62
- value: never[];
63
- };
64
- window: null;
65
- };
66
- }[];
67
- };
68
- };
@@ -1,84 +0,0 @@
1
- "use strict";
2
- exports.__esModule = true;
3
- exports.jsonb_array_elements_text = void 0;
4
- var escape_1 = require("./escape");
5
- /**
6
- * Generates an AST fragment that will check if a column value exists in a JSONB array stored in a `current_setting`
7
- * The AST fragment represents SQL that looks like this:
8
- * = ANY (SELECT jsonb_array_elements_text(current_setting('ctx.my_context_value')::jsonb))
9
- */
10
- var jsonb_array_elements_text = function (setting) {
11
- return {
12
- type: "function",
13
- name: "ANY",
14
- args: {
15
- type: "expr_list",
16
- value: [
17
- {
18
- ast: {
19
- "with": null,
20
- type: "select",
21
- options: null,
22
- distinct: {
23
- type: null
24
- },
25
- columns: [
26
- {
27
- type: "expr",
28
- expr: {
29
- type: "function",
30
- name: "jsonb_array_elements_text",
31
- args: {
32
- type: "expr_list",
33
- value: [
34
- {
35
- type: "cast",
36
- keyword: "cast",
37
- expr: {
38
- type: "function",
39
- name: "current_setting",
40
- args: {
41
- type: "expr_list",
42
- value: [
43
- {
44
- type: "parameter",
45
- value: (0, escape_1.escapeLiteral)(setting.replace(/^___yates_context_/, ""))
46
- },
47
- ]
48
- }
49
- },
50
- as: null,
51
- symbol: "::",
52
- target: {
53
- dataType: "jsonb"
54
- },
55
- arrows: [],
56
- properties: []
57
- },
58
- ]
59
- }
60
- },
61
- as: null
62
- },
63
- ],
64
- into: {
65
- position: null
66
- },
67
- from: null,
68
- where: null,
69
- groupby: null,
70
- having: null,
71
- orderby: null,
72
- limit: {
73
- seperator: "",
74
- value: []
75
- },
76
- window: null
77
- }
78
- },
79
- ]
80
- }
81
- };
82
- };
83
- exports.jsonb_array_elements_text = jsonb_array_elements_text;
84
- //# sourceMappingURL=ast-fragments.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ast-fragments.js","sourceRoot":"","sources":["../src/ast-fragments.ts"],"names":[],"mappings":";;;AAAA,mCAAyC;AAEzC;;;;GAIG;AACI,IAAM,yBAAyB,GAAG,UAAC,OAAe;IACxD,OAAO;QACN,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,KAAK;QACX,IAAI,EAAE;YACL,IAAI,EAAE,WAAW;YACjB,KAAK,EAAE;gBACN;oBACC,GAAG,EAAE;wBACJ,MAAI,EAAE,IAAI;wBACV,IAAI,EAAE,QAAQ;wBACd,OAAO,EAAE,IAAI;wBACb,QAAQ,EAAE;4BACT,IAAI,EAAE,IAAI;yBACV;wBACD,OAAO,EAAE;4BACR;gCACC,IAAI,EAAE,MAAM;gCACZ,IAAI,EAAE;oCACL,IAAI,EAAE,UAAU;oCAChB,IAAI,EAAE,2BAA2B;oCACjC,IAAI,EAAE;wCACL,IAAI,EAAE,WAAW;wCACjB,KAAK,EAAE;4CACN;gDACC,IAAI,EAAE,MAAM;gDACZ,OAAO,EAAE,MAAM;gDACf,IAAI,EAAE;oDACL,IAAI,EAAE,UAAU;oDAChB,IAAI,EAAE,iBAAiB;oDACvB,IAAI,EAAE;wDACL,IAAI,EAAE,WAAW;wDACjB,KAAK,EAAE;4DACN;gEACC,IAAI,EAAE,WAAW;gEACjB,KAAK,EAAE,IAAA,sBAAa,EAAC,OAAO,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;6DAC/D;yDACD;qDACD;iDACD;gDACD,EAAE,EAAE,IAAI;gDACR,MAAM,EAAE,IAAI;gDACZ,MAAM,EAAE;oDACP,QAAQ,EAAE,OAAO;iDACjB;gDACD,MAAM,EAAE,EAAE;gDACV,UAAU,EAAE,EAAE;6CACd;yCACD;qCACD;iCACD;gCACD,EAAE,EAAE,IAAI;6BACR;yBACD;wBACD,IAAI,EAAE;4BACL,QAAQ,EAAE,IAAI;yBACd;wBACD,IAAI,EAAE,IAAI;wBACV,KAAK,EAAE,IAAI;wBACX,OAAO,EAAE,IAAI;wBACb,MAAM,EAAE,IAAI;wBACZ,OAAO,EAAE,IAAI;wBACb,KAAK,EAAE;4BACN,SAAS,EAAE,EAAE;4BACb,KAAK,EAAE,EAAE;yBACT;wBACD,MAAM,EAAE,IAAI;qBACZ;iBACD;aACD;SACD;KACD,CAAC;AACH,CAAC,CAAC;AAxEW,QAAA,yBAAyB,6BAwEpC"}
package/dist/escape.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare const escapeIdentifier: (str: string) => string;
2
- export declare const escapeLiteral: (str: string) => string;
package/dist/escape.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- // Source borrowed from node-postgrs (which borrows from PG itself)
3
- // https://github.com/brianc/node-postgres/blob/3f6760c62ee2a901d374b5e50c2f025b7d550315/packages/pg/lib/client.js#L408-L437
4
- // We need to manually escape strings because we're interpolating client values into SQL statements that don't support `PREPARE`, such as `CREATE POLICY`
5
- exports.__esModule = true;
6
- exports.escapeLiteral = exports.escapeIdentifier = void 0;
7
- // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
8
- var escapeIdentifier = function (str) {
9
- return "\"".concat(str.replace(/"/g, '""'), "\"");
10
- };
11
- exports.escapeIdentifier = escapeIdentifier;
12
- // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
13
- var escapeLiteral = function (str) {
14
- var hasBackslash = false;
15
- var escaped = "'";
16
- for (var i = 0; i < str.length; i++) {
17
- var c = str[i];
18
- if (c === "'") {
19
- escaped += c + c;
20
- }
21
- else if (c === "\\") {
22
- escaped += c + c;
23
- hasBackslash = true;
24
- }
25
- else {
26
- escaped += c;
27
- }
28
- }
29
- escaped += "'";
30
- if (hasBackslash === true) {
31
- escaped = " E".concat(escaped);
32
- }
33
- return escaped;
34
- };
35
- exports.escapeLiteral = escapeLiteral;
36
- //# sourceMappingURL=escape.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"escape.js","sourceRoot":"","sources":["../src/escape.ts"],"names":[],"mappings":";AAAA,mEAAmE;AACnE,4HAA4H;AAC5H,yJAAyJ;;;AAEzJ,6EAA6E;AACtE,IAAM,gBAAgB,GAAG,UAAU,GAAW;IACpD,OAAO,YAAI,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,OAAG,CAAC;AACvC,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B;AAEF,6EAA6E;AACtE,IAAM,aAAa,GAAG,UAAU,GAAW;IACjD,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,OAAO,GAAG,GAAG,CAAC;IAElB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACpC,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,EAAE;YACd,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;SACjB;aAAM,IAAI,CAAC,KAAK,IAAI,EAAE;YACtB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;YACjB,YAAY,GAAG,IAAI,CAAC;SACpB;aAAM;YACN,OAAO,IAAI,CAAC,CAAC;SACb;KACD;IAED,OAAO,IAAI,GAAG,CAAC;IAEf,IAAI,YAAY,KAAK,IAAI,EAAE;QAC1B,OAAO,GAAG,YAAK,OAAO,CAAE,CAAC;KACzB;IAED,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAvBW,QAAA,aAAa,iBAuBxB"}
@@ -1,7 +0,0 @@
1
- import { PrismaClient } from "@prisma/client";
2
- import { defineDmmfProperty } from "@prisma/client/runtime/library";
3
- export type RuntimeDataModel = Parameters<typeof defineDmmfProperty>[1];
4
- export type Expression<ContextKeys extends string = string> = string | ((client: PrismaClient, row: (col: string) => any, context: (key: ContextKeys) => string) => Promise<any> | {
5
- [col: string]: any;
6
- });
7
- export declare const expressionToSQL: (getExpression: Expression, table: string) => Promise<string>;
@@ -1,377 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- exports.__esModule = true;
53
- exports.expressionToSQL = void 0;
54
- var client_1 = require("@prisma/client");
55
- var random_1 = __importDefault(require("lodash/random"));
56
- var matches_1 = __importDefault(require("lodash/matches"));
57
- var node_sql_parser_1 = require("node-sql-parser");
58
- var escape_1 = require("./escape");
59
- var ast_fragments_1 = require("./ast-fragments");
60
- var PRISMA_NUMERIC_TYPES = ["Int", "BigInt", "Float", "Decimal"];
61
- var deepFind = function (obj, subObj) {
62
- var matcher = (0, matches_1["default"])(subObj);
63
- for (var key in obj) {
64
- if (matcher(obj[key])) {
65
- return obj[key];
66
- }
67
- else if (typeof obj[key] === "object") {
68
- var result = deepFind(obj[key], subObj);
69
- if (result) {
70
- return result;
71
- }
72
- }
73
- }
74
- };
75
- var expressionRowName = function (col) { return "___yates_row_".concat(col); };
76
- var expressionContext = function (context) { return "___yates_context_".concat(context); };
77
- // Generate a big 32bit signed integer to use as an ID
78
- var getLargeRandomInt = function () { return (0, random_1["default"])(1000000000, 2147483647); };
79
- var getDmmfMetaData = function (client, model, field) {
80
- var runtimeDataModel = client._runtimeDataModel;
81
- var modelData = runtimeDataModel.models[model];
82
- if (!modelData) {
83
- throw new Error("Could not retrieve model data from Prisma Client for model '".concat(model, "'"));
84
- }
85
- var fieldData = modelData.fields.find(function (f) { return f.name === field; });
86
- if (!fieldData) {
87
- throw new Error("Could not retrieve field data from Prisma Client for field '".concat(model, ".").concat(field, "'"));
88
- }
89
- return fieldData;
90
- };
91
- // Perform substitution of Ints so that Prisma doesn't throw an error due to mismatched type values
92
- // After we've captured the SQL, we can replace the Ints with the original values
93
- // The returned tokens are a map of the token int, and the AST fragment that will replace it.
94
- // We can then reconstruct the query using the AST fragments.
95
- var tokenizeWhereExpression = function (
96
- /** The Prisma client to use for metadata */
97
- client,
98
- /** The Prisma where expression to be tokenized */
99
- where,
100
- /** The base table we are generating an expression for */
101
- table,
102
- /** The model name being queried. e.g. 'User' */
103
- model,
104
- /** The tokens object to add the new tokens to */
105
- tokens) {
106
- if (tokens === void 0) { tokens = {}; }
107
- for (var field in where) {
108
- // Get field data from the prisma client for the model and field being queried
109
- var fieldData = getDmmfMetaData(client, model, field);
110
- var int = void 0;
111
- // Small loop to make sure we get a unique int for the token key
112
- do {
113
- int = getLargeRandomInt();
114
- } while (tokens[int]);
115
- var astFragment = {};
116
- var value = where[field];
117
- // Check if the field is an object, if so, we need to recurse
118
- // This is a fairly simple approach but covers most cases like "some", "every", "none" etc.
119
- if (fieldData.kind === "object") {
120
- // List queries will always have a sub-object of "every", "some" or "none", so we need to dropdown and iterate through them
121
- if (fieldData.isList) {
122
- for (var subField in value) {
123
- var subValue = value[subField];
124
- var _a = tokenizeWhereExpression(client, subValue, table, fieldData.type, tokens), subTokens = _a.tokens, subWhere = _a.where;
125
- tokens = __assign(__assign({}, tokens), subTokens);
126
- where[field][subField] = subWhere;
127
- }
128
- continue;
129
- }
130
- else {
131
- var _b = tokenizeWhereExpression(client, value, table, fieldData.type, tokens), subTokens = _b.tokens, subWhere = _b.where;
132
- tokens = __assign(__assign({}, tokens), subTokens);
133
- where[field] = subWhere;
134
- continue;
135
- }
136
- }
137
- var isNumeric = PRISMA_NUMERIC_TYPES.includes(fieldData.type);
138
- var isColumnName = typeof value === "string" && !!value.match(/^___yates_row_/);
139
- var isContext = typeof value === "string" && !!value.match(/^___yates_context_/);
140
- var isInStatement = !!value["in"];
141
- switch (true) {
142
- case isColumnName:
143
- // Substiture the yates row placeholder for the actual column name
144
- var column = value.replace(/^___yates_row_/, "");
145
- if (!getDmmfMetaData(client, table, column)) {
146
- throw new Error("Invalid field name \"".concat(column, "\""));
147
- }
148
- astFragment = {
149
- type: "column_ref",
150
- schema: "public",
151
- table: table,
152
- column: column
153
- };
154
- break;
155
- case isContext && isNumeric:
156
- astFragment = {
157
- as: null,
158
- type: "cast",
159
- expr: {
160
- type: "function",
161
- name: "current_setting",
162
- args: {
163
- type: "expr_list",
164
- value: [
165
- {
166
- type: "parameter",
167
- value: (0, escape_1.escapeLiteral)(value.replace(/^___yates_context_/, ""))
168
- },
169
- ]
170
- }
171
- },
172
- symbol: "::",
173
- target: {
174
- dataType: "float",
175
- suffix: []
176
- }
177
- };
178
- break;
179
- case isContext && !isNumeric:
180
- astFragment = {
181
- type: "function",
182
- name: "current_setting",
183
- args: {
184
- type: "expr_list",
185
- value: [
186
- {
187
- type: "parameter",
188
- value: (0, escape_1.escapeLiteral)(value.replace(/^___yates_context_/, ""))
189
- },
190
- ]
191
- }
192
- };
193
- break;
194
- case isNumeric:
195
- if (typeof value !== "number") {
196
- throw new Error("Numeric fields can only be queried with numbers: querying field '".concat(field, "' with value '").concat(value, "'"));
197
- }
198
- astFragment = {
199
- type: "number",
200
- value: value
201
- };
202
- break;
203
- case isInStatement:
204
- if (Array.isArray(value["in"])) {
205
- var values = [];
206
- for (var item in value["in"]) {
207
- values.push({
208
- type: "single_quote_string",
209
- value: item
210
- });
211
- }
212
- astFragment = {
213
- type: "binary_expr",
214
- operator: "IN",
215
- left: {
216
- type: "column_ref",
217
- schema: "public",
218
- table: table,
219
- column: field
220
- },
221
- right: {
222
- type: "expr_list",
223
- value: values
224
- }
225
- };
226
- }
227
- else {
228
- // If the value of `in` is a context value, we assume that it is an array that has been JSON encoded
229
- // We create an AST fragment representing a function call to `jsonb_array_elements_text` with the context value as the argument
230
- astFragment = (0, ast_fragments_1.jsonb_array_elements_text)(value["in"]);
231
- }
232
- break;
233
- // All other types are treated as strings
234
- default:
235
- astFragment = {
236
- type: "parameter",
237
- value: (0, escape_1.escapeLiteral)(value)
238
- };
239
- break;
240
- }
241
- tokens[int] = {
242
- astFragment: astFragment
243
- };
244
- where[field] = isNumeric ? int : "".concat(int);
245
- }
246
- return {
247
- tokens: tokens,
248
- where: where
249
- };
250
- };
251
- var expressionToSQL = function (getExpression, table) { return __awaiter(void 0, void 0, void 0, function () {
252
- var baseClient, tokens, expressionClient, sql;
253
- return __generator(this, function (_a) {
254
- switch (_a.label) {
255
- case 0:
256
- if (typeof getExpression === "string") {
257
- return [2 /*return*/, getExpression];
258
- }
259
- baseClient = new client_1.PrismaClient({
260
- log: [{ level: "query", emit: "event" }]
261
- });
262
- tokens = {};
263
- expressionClient = baseClient.$extends({
264
- name: "expressionClient",
265
- query: {
266
- $allModels: {
267
- $allOperations: function (_a) {
268
- var model = _a.model, operation = _a.operation, args = _a.args, query = _a.query;
269
- // if not findFirst or findUnique
270
- if (operation !== "findFirst" && operation !== "findUnique") {
271
- throw new Error('Only "findFirst" and "findUnique" are supported in client expressions');
272
- }
273
- if ("where" in args && args.where) {
274
- var where = tokenizeWhereExpression(baseClient, args.where, table, model, tokens).where;
275
- args.where = where;
276
- }
277
- return query(args);
278
- }
279
- }
280
- }
281
- });
282
- return [4 /*yield*/, new Promise(
283
- // rome-ignore lint/suspicious/noAsyncPromiseExecutor: future cleanup
284
- function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
285
- var rawExpression, isSubselect, error_1;
286
- return __generator(this, function (_a) {
287
- switch (_a.label) {
288
- case 0:
289
- rawExpression = getExpression(expressionClient, expressionRowName, expressionContext);
290
- isSubselect = typeof rawExpression === "object" && typeof rawExpression.then === "function";
291
- baseClient.$on("query", function (e) {
292
- try {
293
- var parser = new node_sql_parser_1.Parser();
294
- // Parse the query into an AST
295
- var ast = parser.astify(e.query, {
296
- database: "postgresql"
297
- });
298
- var params = JSON.parse(e.params);
299
- // By default Prisma will use a parameter for the limit, for Yates, the value is always "1"
300
- ast.limit = { seperator: "", value: [{ type: "number", value: 1 }] };
301
- // Now that the SQL has been generated, we can replace the tokens with the original values
302
- for (var i = 0; i < params.length; i++) {
303
- var param = params[i];
304
- var token = tokens[param];
305
- if (!token) {
306
- continue;
307
- }
308
- var parameterizedStatement = deepFind(ast, {
309
- right: {
310
- type: "var",
311
- name: i + 1,
312
- prefix: "$"
313
- }
314
- });
315
- if (!parameterizedStatement) {
316
- continue;
317
- }
318
- parameterizedStatement.right = token.astFragment;
319
- }
320
- if (isSubselect) {
321
- // For subselects, we need to convert the entire query and wrap in EXISTS so it converts to a binary expression
322
- var subSelect = parser.sqlify(ast, {
323
- database: "postgresql"
324
- });
325
- resolve("EXISTS(".concat(subSelect, ")"));
326
- }
327
- else {
328
- // For basic expressions, we're only interested in the WHERE clause and can convert just the WHERE clause into SQL
329
- var where = parser.exprToSQL(ast.where, {
330
- database: "postgresql"
331
- });
332
- resolve(where);
333
- }
334
- }
335
- catch (error) {
336
- reject(error);
337
- }
338
- });
339
- _a.label = 1;
340
- case 1:
341
- _a.trys.push([1, 6, , 7]);
342
- if (!isSubselect) return [3 /*break*/, 3];
343
- return [4 /*yield*/, rawExpression];
344
- case 2:
345
- _a.sent();
346
- return [3 /*break*/, 5];
347
- case 3: return [4 /*yield*/, expressionClient[table].findFirst({
348
- where: rawExpression
349
- })];
350
- case 4:
351
- _a.sent();
352
- _a.label = 5;
353
- case 5: return [3 /*break*/, 7];
354
- case 6:
355
- error_1 = _a.sent();
356
- reject(error_1);
357
- return [3 /*break*/, 7];
358
- case 7: return [2 /*return*/];
359
- }
360
- });
361
- }); })];
362
- case 1:
363
- sql = _a.sent();
364
- // Close the client
365
- return [4 /*yield*/, expressionClient.$disconnect()];
366
- case 2:
367
- // Close the client
368
- _a.sent();
369
- return [4 /*yield*/, baseClient.$disconnect()];
370
- case 3:
371
- _a.sent();
372
- return [2 /*return*/, sql];
373
- }
374
- });
375
- }); };
376
- exports.expressionToSQL = expressionToSQL;
377
- //# sourceMappingURL=expressions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"expressions.js","sourceRoot":"","sources":["../src/expressions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA8C;AAC9C,yDAAmC;AACnC,2DAAqC;AACrC,mDAAyC;AACzC,mCAAyC;AAEzC,iDAA4D;AAM5D,IAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;AAEnE,IAAM,QAAQ,GAAG,UAAC,GAAQ,EAAE,MAAW;IACtC,IAAM,OAAO,GAAG,IAAA,oBAAO,EAAC,MAAM,CAAC,CAAC;IAChC,KAAK,IAAM,GAAG,IAAI,GAAG,EAAE;QACtB,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE;YACtB,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;SAChB;aAAM,IAAI,OAAO,GAAG,CAAC,GAAG,CAAC,KAAK,QAAQ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