@mrnafisia/type-query 1.0.48 → 1.0.49

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 (74) hide show
  1. package/README.md +2 -2
  2. package/dist/U.d.ts +2 -2
  3. package/dist/U.d.ts.map +1 -1
  4. package/dist/U.js +28 -27
  5. package/dist/U.js.map +1 -1
  6. package/dist/context.d.ts +987 -987
  7. package/dist/context.d.ts.map +1 -1
  8. package/dist/context.js +84 -85
  9. package/dist/context.js.map +1 -1
  10. package/dist/dictionary.d.ts +12 -12
  11. package/dist/dictionary.d.ts.map +1 -1
  12. package/dist/dictionary.js +179 -179
  13. package/dist/dictionary.js.map +1 -1
  14. package/dist/entity.d.ts +3585 -3585
  15. package/dist/entity.d.ts.map +1 -1
  16. package/dist/entity.js +1053 -1007
  17. package/dist/entity.js.map +1 -1
  18. package/dist/error.d.ts +4 -4
  19. package/dist/error.d.ts.map +1 -1
  20. package/dist/error.js +7 -6
  21. package/dist/error.js.map +1 -1
  22. package/dist/index.d.ts +18 -36
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +56 -60
  25. package/dist/index.js.map +1 -1
  26. package/dist/model.d.ts +1005 -1005
  27. package/dist/model.d.ts.map +1 -1
  28. package/dist/model.js +282 -282
  29. package/dist/model.js.map +1 -1
  30. package/dist/parser.d.ts +11 -11
  31. package/dist/parser.d.ts.map +1 -1
  32. package/dist/parser.js +120 -120
  33. package/dist/parser.js.map +1 -1
  34. package/dist/pool.d.ts +5 -5
  35. package/dist/pool.d.ts.map +1 -1
  36. package/dist/pool.js +122 -121
  37. package/dist/pool.js.map +1 -1
  38. package/dist/schema.d.ts +25 -25
  39. package/dist/schema.d.ts.map +1 -1
  40. package/dist/schema.js +405 -395
  41. package/dist/schema.js.map +1 -1
  42. package/dist/testUtil.d.ts +4 -4
  43. package/dist/testUtil.d.ts.map +1 -1
  44. package/dist/testUtil.js +343 -333
  45. package/dist/testUtil.js.map +1 -1
  46. package/dist/types/context.d.ts +51 -55
  47. package/dist/types/context.d.ts.map +1 -1
  48. package/dist/types/context.js +2 -2
  49. package/dist/types/entity.d.ts +70 -70
  50. package/dist/types/entity.d.ts.map +1 -1
  51. package/dist/types/entity.js +2 -2
  52. package/dist/types/json.d.ts +8 -8
  53. package/dist/types/json.d.ts.map +1 -1
  54. package/dist/types/json.js +2 -2
  55. package/dist/types/model.d.ts +23 -23
  56. package/dist/types/model.d.ts.map +1 -1
  57. package/dist/types/model.js +2 -2
  58. package/dist/types/pool.d.ts +18 -18
  59. package/dist/types/pool.d.ts.map +1 -1
  60. package/dist/types/pool.js +2 -2
  61. package/dist/types/postgres.d.ts +9 -9
  62. package/dist/types/postgres.d.ts.map +1 -1
  63. package/dist/types/postgres.js +2 -2
  64. package/dist/types/table.d.ts +233 -234
  65. package/dist/types/table.d.ts.map +1 -1
  66. package/dist/types/table.js +2 -2
  67. package/dist/types/testUtil.d.ts +26 -26
  68. package/dist/types/testUtil.d.ts.map +1 -1
  69. package/dist/types/testUtil.js +2 -2
  70. package/dist/utils.d.ts +67 -67
  71. package/dist/utils.d.ts.map +1 -1
  72. package/dist/utils.js +220 -220
  73. package/dist/utils.js.map +1 -1
  74. package/package.json +40 -39
package/dist/entity.js CHANGED
@@ -1,1008 +1,1054 @@
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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
14
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
15
- if (ar || !(i in from)) {
16
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
17
- ar[i] = from[i];
18
- }
19
- }
20
- return to.concat(ar || Array.prototype.slice.call(from));
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.partialQuery = exports.resolveColumn = exports.getTableDataOfJoinSelectColumn = exports.resolveExpression = exports.resolveReturning = exports.resolveResult = exports.createQueryResult = exports.ReservedExpressionKeys = exports.createJoinSelectEntity = exports.createEntity = void 0;
27
- var U_1 = __importDefault(require("./U"));
28
- var decimal_js_1 = __importDefault(require("decimal.js"));
29
- var context_1 = require("./context");
30
- var never_catch_1 = require("never-catch");
31
- var dictionary_1 = require("./dictionary");
32
- // entity
33
- var createEntity = function (table) { return ({
34
- table: table,
35
- context: (0, context_1.createContext)(table),
36
- select: function (returning, where, options) {
37
- var _this = this;
38
- var _a, _b, _c, _d, _e, _f;
39
- var ignoreInWhere = (_a = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _a !== void 0 ? _a : false;
40
- var ignoreInReturning = (_b = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _b !== void 0 ? _b : false;
41
- var ignoreInGroupBy = (_c = options === null || options === void 0 ? void 0 : options.ignoreInGroupBy) !== null && _c !== void 0 ? _c : false;
42
- var distinct = (_d = options === null || options === void 0 ? void 0 : options.distinct) !== null && _d !== void 0 ? _d : false;
43
- var groupBy = (_e = options === null || options === void 0 ? void 0 : options.groupBy) !== null && _e !== void 0 ? _e : [];
44
- var orders = (_f = options === null || options === void 0 ? void 0 : options.orders) !== null && _f !== void 0 ? _f : [];
45
- var start = options === null || options === void 0 ? void 0 : options.start;
46
- var step = options === null || options === void 0 ? void 0 : options.step;
47
- var _returning = typeof returning === 'function' ? returning(this.context) : returning;
48
- var createQuery = function (params) {
49
- var tokens = ['SELECT'];
50
- // distinct
51
- if (distinct) {
52
- tokens.push('DISTINCT');
53
- }
54
- // select
55
- var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
56
- if (!resolvedReturning.ok) {
57
- return (0, never_catch_1.err)("<select> -> ".concat(resolvedReturning.error));
58
- }
59
- params.push.apply(params, resolvedReturning.value.params);
60
- tokens.push(resolvedReturning.value.text);
61
- // from
62
- tokens.push("FROM \"".concat(table.schema, "\".\"").concat(table.title, "\""));
63
- // where
64
- var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
65
- if (!resolvedWhereResult.ok) {
66
- return (0, never_catch_1.err)("<select>[where] -> ".concat(resolvedWhereResult.error));
67
- }
68
- if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
69
- return (0, never_catch_1.err)("<select>[where] -> neutral");
70
- }
71
- params.push.apply(params, resolvedWhereResult.value.params);
72
- tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'TRUE' : resolvedWhereResult.value.text);
73
- // groupBy
74
- var _groupBy = typeof groupBy === 'function' ? groupBy(_this.context) : groupBy;
75
- if (groupBy.length !== 0) {
76
- var groupByTextArray = [];
77
- for (var _i = 0, _groupBy_1 = _groupBy; _i < _groupBy_1.length; _i++) {
78
- var aGroupBy = _groupBy_1[_i];
79
- var resolvedGroupBy = resolveExpression(aGroupBy, params.length + 1, ignoreInGroupBy);
80
- if (!resolvedGroupBy.ok) {
81
- return (0, never_catch_1.err)("<select> -> ".concat(resolvedGroupBy.error));
82
- }
83
- params.push.apply(params, resolvedGroupBy.value.params);
84
- groupByTextArray.push(resolvedGroupBy.value.text);
85
- }
86
- tokens.push('GROUP BY', groupByTextArray.join(', '));
87
- }
88
- // orders
89
- if (orders.length !== 0) {
90
- var ordersTextArray = [];
91
- for (var _a = 0, orders_1 = orders; _a < orders_1.length; _a++) {
92
- var order = orders_1[_a];
93
- var by = order.by, direction = order.direction;
94
- ordersTextArray.push("".concat(resolveColumn(table, by, false), " ").concat((0, dictionary_1.toOrderDirection)(direction)));
95
- }
96
- tokens.push('ORDER BY', ordersTextArray.join(', '));
97
- }
98
- // pagination
99
- if (start !== undefined) {
100
- if (start < 0) {
101
- return (0, never_catch_1.err)("<select>[start] -> invalid");
102
- }
103
- tokens.push('OFFSET', start.toString());
104
- }
105
- if (step !== undefined) {
106
- if (step <= 0) {
107
- return (0, never_catch_1.err)("<select>[step] -> invalid");
108
- }
109
- tokens.push('LIMIT', step.toString());
110
- }
111
- tokens.push(';');
112
- var sql = tokens.join(' ');
113
- return (0, never_catch_1.ok)({ sql: sql, params: params });
114
- };
115
- return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
116
- },
117
- insert: function (rows, returning, options) {
118
- var _this = this;
119
- var _a, _b, _c;
120
- var nullableDefaultColumns = (_a = (options === null || options === void 0 ? void 0 : options.nullableDefaultColumns)) !== null && _a !== void 0 ? _a : [];
121
- var ignoreInValues = (_b = (options === null || options === void 0 ? void 0 : options.ignoreInValues)) !== null && _b !== void 0 ? _b : false;
122
- var ignoreInReturning = (_c = (options === null || options === void 0 ? void 0 : options.ignoreInValues)) !== null && _c !== void 0 ? _c : false;
123
- var _returning = typeof returning === 'function' ? returning(this.context) : returning;
124
- var createQuery = function (params) {
125
- var tokens = ["INSERT INTO \"".concat(table.schema, "\".\"").concat(table.title, "\"")];
126
- // columns
127
- var insertingColumns = [];
128
- var columnsTextArray = [];
129
- for (var column in table.columns) {
130
- if (nullableDefaultColumns.includes(column) || !table.columns[column].nullable) {
131
- insertingColumns.push(column);
132
- columnsTextArray.push(resolveColumn(table, column, false));
133
- }
134
- }
135
- tokens.push("( ".concat(columnsTextArray.join(', '), " )"), 'VALUES');
136
- // values
137
- if (rows.length === 0) {
138
- return (0, never_catch_1.err)('<insert>[values] -> empty');
139
- }
140
- var valuesTextArray = [];
141
- var _rows = typeof rows === 'function' ? rows(_this.context) : rows;
142
- for (var _i = 0, _rows_1 = _rows; _i < _rows_1.length; _i++) {
143
- var _row = _rows_1[_i];
144
- var rowTokens = [];
145
- for (var _a = 0, insertingColumns_1 = insertingColumns; _a < insertingColumns_1.length; _a++) {
146
- var insertingColumn = insertingColumns_1[_a];
147
- if (_row[insertingColumn] === undefined) {
148
- var column = table.columns[insertingColumn];
149
- switch (column.default) {
150
- case 'value':
151
- rowTokens.push(U_1.default.stringify(column.value, true));
152
- continue;
153
- case true:
154
- case 'auto-increment':
155
- rowTokens.push('DEFAULT');
156
- continue;
157
- case 'created-at':
158
- case 'updated-at':
159
- rowTokens.push(U_1.default.stringify(new Date(), true));
160
- continue;
161
- }
162
- if (column.nullable) {
163
- rowTokens.push(U_1.default.stringify(null));
164
- continue;
165
- }
166
- // never going to happen!
167
- return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> no-value"));
168
- }
169
- else {
170
- var resolvedExpressionResult = resolveExpression(_row[insertingColumn], params.length + 1, ignoreInValues);
171
- if (!resolvedExpressionResult.ok) {
172
- return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> ").concat(resolvedExpressionResult.error));
173
- }
174
- if (resolvedExpressionResult.value.text === '') {
175
- return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> neutral"));
176
- }
177
- params.push.apply(params, resolvedExpressionResult.value.params);
178
- rowTokens.push(resolvedExpressionResult.value.text);
179
- }
180
- }
181
- valuesTextArray.push("( ".concat(rowTokens.join(', '), " )"));
182
- }
183
- tokens.push(valuesTextArray.join(', '));
184
- // returning
185
- if (_returning.length !== 0) {
186
- var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
187
- if (!resolvedReturning.ok) {
188
- return (0, never_catch_1.err)("<insert> -> ".concat(resolvedReturning.error));
189
- }
190
- params.push.apply(params, resolvedReturning.value.params);
191
- tokens.push('RETURNING', resolvedReturning.value.text);
192
- }
193
- tokens.push(';');
194
- var sql = tokens.join(' ');
195
- return (0, never_catch_1.ok)({ sql: sql, params: params });
196
- };
197
- return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
198
- },
199
- update: function (sets, where, returning, options) {
200
- var _this = this;
201
- var _a, _b, _c;
202
- var ignoreInSets = (_a = (options === null || options === void 0 ? void 0 : options.ignoreInSets)) !== null && _a !== void 0 ? _a : false;
203
- var ignoreInWhere = (_b = (options === null || options === void 0 ? void 0 : options.ignoreInWhere)) !== null && _b !== void 0 ? _b : false;
204
- var ignoreInReturning = (_c = (options === null || options === void 0 ? void 0 : options.ignoreInReturning)) !== null && _c !== void 0 ? _c : false;
205
- var _returning = typeof returning === 'function' ? returning(this.context) : returning;
206
- var createQuery = function (params) {
207
- var tokens = ["UPDATE \"".concat(table.schema, "\".\"").concat(table.title, "\" SET")];
208
- // set
209
- var _set = typeof sets === 'function' ? sets(_this.context) : sets;
210
- var setsTextArray = [];
211
- var key;
212
- for (key in _set) {
213
- var setExpressionResult = resolveExpression(_set[key], params.length + 1, ignoreInSets);
214
- if (!setExpressionResult.ok) {
215
- return (0, never_catch_1.err)("<update>[sets][".concat(key, "] -> ").concat(setExpressionResult.error));
216
- }
217
- if (setExpressionResult.value.text === '') {
218
- if (ignoreInSets) {
219
- continue;
220
- }
221
- else {
222
- return (0, never_catch_1.err)("<update>[sets][".concat(key, "] -> neutral"));
223
- }
224
- }
225
- params.push.apply(params, setExpressionResult.value.params);
226
- setsTextArray.push("".concat(resolveColumn(table, key, false), " = ").concat(setExpressionResult.value.text));
227
- }
228
- for (var column in table.columns) {
229
- switch (table.columns[column].default) {
230
- case 'updated-at':
231
- setsTextArray.push("".concat(resolveColumn(table, column, false), " = ").concat(U_1.default.stringify(new Date(), true)));
232
- break;
233
- }
234
- }
235
- if (setsTextArray.length === 0) {
236
- return (0, never_catch_1.err)('<update>[sets] -> empty');
237
- }
238
- tokens.push(setsTextArray.join(', '));
239
- // where
240
- var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
241
- if (!resolvedWhereResult.ok) {
242
- return (0, never_catch_1.err)("<update>[where] -> ".concat(resolvedWhereResult.error));
243
- }
244
- if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
245
- return (0, never_catch_1.err)("<update>[where] -> neutral");
246
- }
247
- params.push.apply(params, resolvedWhereResult.value.params);
248
- tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
249
- // returning
250
- if (_returning.length !== 0) {
251
- var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
252
- if (!resolvedReturning.ok) {
253
- return (0, never_catch_1.err)("<update> -> ".concat(resolvedReturning.error));
254
- }
255
- params.push.apply(params, resolvedReturning.value.params);
256
- tokens.push('RETURNING', resolvedReturning.value.text);
257
- }
258
- tokens.push(';');
259
- var sql = tokens.join(' ');
260
- return (0, never_catch_1.ok)({ sql: sql, params: params });
261
- };
262
- return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
263
- },
264
- delete: function (where, returning, options) {
265
- var _this = this;
266
- var _a, _b;
267
- var ignoreInWhere = (_a = (options === null || options === void 0 ? void 0 : options.ignoreInWhere)) !== null && _a !== void 0 ? _a : false;
268
- var ignoreInReturning = (_b = (options === null || options === void 0 ? void 0 : options.ignoreInReturning)) !== null && _b !== void 0 ? _b : false;
269
- var _returning = typeof returning === 'function' ? returning(this.context) : returning;
270
- var createQuery = function (params) {
271
- var tokens = ["DELETE FROM \"".concat(table.schema, "\".\"").concat(table.title, "\"")];
272
- // where
273
- var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
274
- if (!resolvedWhereResult.ok) {
275
- return (0, never_catch_1.err)("<delete>[where] -> ".concat(resolvedWhereResult.error));
276
- }
277
- if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
278
- return (0, never_catch_1.err)("<delete>[where] -> neutral");
279
- }
280
- params.push.apply(params, resolvedWhereResult.value.params);
281
- tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
282
- // returning
283
- if (_returning.length !== 0) {
284
- var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
285
- if (!resolvedReturning.ok) {
286
- return (0, never_catch_1.err)("<delete> -> ".concat(resolvedReturning.error));
287
- }
288
- params.push.apply(params, resolvedReturning.value.params);
289
- tokens.push('RETURNING', resolvedReturning.value.text);
290
- }
291
- tokens.push(';');
292
- var sql = tokens.join(' ');
293
- return (0, never_catch_1.ok)({ sql: sql, params: params });
294
- };
295
- return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
296
- },
297
- join: function (mainAlias, joinType, joinTable, joinAlias, on) {
298
- var _a;
299
- return createJoinSelectEntity({ table: table, alias: mainAlias }, [{ table: joinTable, joinType: joinType, alias: joinAlias, on: on }], (_a = {}, _a[mainAlias] = (0, context_1.createContext)(table, mainAlias), _a[joinAlias] = (0, context_1.createContext)(joinTable, joinAlias), _a));
300
- }
301
- }); };
302
- exports.createEntity = createEntity;
303
- var createJoinSelectEntity = function (main, joinTables, contexts) { return ({
304
- contexts: contexts,
305
- select: function (returning, where, options) {
306
- var _this = this;
307
- var _a, _b, _c, _d, _e, _f, _g;
308
- var ignoreInWhere = (_a = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _a !== void 0 ? _a : false;
309
- var ignoreInReturning = (_b = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _b !== void 0 ? _b : false;
310
- var ignoreInJoin = (_c = options === null || options === void 0 ? void 0 : options.ignoreInJoin) !== null && _c !== void 0 ? _c : false;
311
- var ignoreInGroupBy = (_d = options === null || options === void 0 ? void 0 : options.ignoreInGroupBy) !== null && _d !== void 0 ? _d : false;
312
- var distinct = (_e = options === null || options === void 0 ? void 0 : options.distinct) !== null && _e !== void 0 ? _e : false;
313
- var groupBy = (_f = options === null || options === void 0 ? void 0 : options.groupBy) !== null && _f !== void 0 ? _f : [];
314
- var orders = (_g = options === null || options === void 0 ? void 0 : options.orders) !== null && _g !== void 0 ? _g : [];
315
- var start = options === null || options === void 0 ? void 0 : options.start;
316
- var step = options === null || options === void 0 ? void 0 : options.step;
317
- var allTables = __spreadArray([main], joinTables, true);
318
- var _returning = typeof returning === 'function' ? returning(this.contexts) : returning;
319
- var createQuery = function (params) {
320
- var tokens = ['SELECT'];
321
- // distinct
322
- if (distinct) {
323
- tokens.push('DISTINCT');
324
- }
325
- // select
326
- var resolvedReturning = resolveReturning(function (column) {
327
- var _a = getTableDataOfJoinSelectColumn(allTables, column), table = _a.table, alias = _a.alias;
328
- var columnKey = column.substring((alias + '_').length);
329
- return { type: table.columns[columnKey].type, title: table.columns[columnKey].title, alias: alias };
330
- }, _returning, params.length + 1, ignoreInReturning);
331
- if (!resolvedReturning.ok) {
332
- return (0, never_catch_1.err)("<join-select>[columns] -> ".concat(resolvedReturning.error));
333
- }
334
- params.push.apply(params, resolvedReturning.value.params);
335
- tokens.push(resolvedReturning.value.text, "FROM \"".concat(main.table.schema, "\".\"").concat(main.table.title, "\" \"").concat(main.alias, "\""));
336
- // join
337
- for (var _i = 0, joinTables_1 = joinTables; _i < joinTables_1.length; _i++) {
338
- var joinTable = joinTables_1[_i];
339
- var onExpressionResult = resolveExpression(typeof joinTable.on === 'function' ? joinTable.on(_this.contexts) : joinTable.on, params.length + 1, ignoreInJoin);
340
- if (!onExpressionResult.ok) {
341
- return (0, never_catch_1.err)("<join-select>[join][".concat(joinTables.indexOf(joinTable), "] -> ").concat(onExpressionResult.error));
342
- }
343
- if (onExpressionResult.value.text === '' && !ignoreInJoin) {
344
- return (0, never_catch_1.err)("<join-select>[join][".concat(joinTables.indexOf(joinTable), "] -> neutral"));
345
- }
346
- params.push.apply(params, onExpressionResult.value.params);
347
- tokens.push("".concat((0, dictionary_1.toJoinType)(joinTable.joinType), " \"").concat(joinTable.table.schema, "\".\"").concat(joinTable.table.title, "\" \"").concat(joinTable.alias, "\" ON ").concat(onExpressionResult.value.text));
348
- }
349
- // where
350
- var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.contexts) : where, params.length + 1, ignoreInWhere);
351
- if (!resolvedWhereResult.ok) {
352
- return (0, never_catch_1.err)("<join-select>[where] -> ".concat(resolvedWhereResult.error));
353
- }
354
- if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
355
- return (0, never_catch_1.err)("<join-select>[where] -> neutral");
356
- }
357
- params.push.apply(params, resolvedWhereResult.value.params);
358
- tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
359
- // groupBy
360
- var _groupBy = typeof groupBy === 'function' ? groupBy(_this.contexts) : groupBy;
361
- if (groupBy.length !== 0) {
362
- var groupByTextArray = [];
363
- for (var _a = 0, _groupBy_2 = _groupBy; _a < _groupBy_2.length; _a++) {
364
- var aGroupBy = _groupBy_2[_a];
365
- var resolvedGroupBy = resolveExpression(aGroupBy, params.length + 1, ignoreInGroupBy);
366
- if (!resolvedGroupBy.ok) {
367
- return (0, never_catch_1.err)("<join-select> -> ".concat(resolvedGroupBy.error));
368
- }
369
- params.push.apply(params, resolvedGroupBy.value.params);
370
- groupByTextArray.push(resolvedGroupBy.value.text);
371
- }
372
- tokens.push('GROUP BY', groupByTextArray.join(', '));
373
- }
374
- // orders
375
- if (orders.length !== 0) {
376
- var ordersTextArray = [];
377
- for (var _b = 0, orders_2 = orders; _b < orders_2.length; _b++) {
378
- var order = orders_2[_b];
379
- var by = order.by, direction = order.direction;
380
- ordersTextArray.push("\"".concat(by, "\" ").concat(direction));
381
- }
382
- tokens.push('ORDER BY', ordersTextArray.join(', '));
383
- }
384
- // pagination
385
- if (start !== undefined) {
386
- if (start < 0) {
387
- return (0, never_catch_1.err)("<join-select>[start] -> invalid");
388
- }
389
- tokens.push('OFFSET', start.toString());
390
- }
391
- if (step !== undefined) {
392
- if (step <= 0) {
393
- return (0, never_catch_1.err)("<join-select>[step] -> invalid");
394
- }
395
- tokens.push('LIMIT', step.toString());
396
- }
397
- tokens.push(';');
398
- var sql = tokens.join(' ');
399
- return (0, never_catch_1.ok)({ sql: sql, params: params });
400
- };
401
- return createQueryResult(function (column) {
402
- var _a = getTableDataOfJoinSelectColumn(allTables, column), alias = _a.alias, columns = _a.table.columns;
403
- var targetCol = columns[column.substring((alias + '_').length)];
404
- return [targetCol.type, targetCol.nullable];
405
- }, createQuery, _returning);
406
- },
407
- join: function (joinType, joinTable, joinAlias, on) {
408
- var _a;
409
- joinTables.push({ table: joinTable, on: on, joinType: joinType, alias: joinAlias });
410
- return createJoinSelectEntity(main, joinTables, __assign(__assign({}, contexts), (_a = {}, _a[joinAlias] = (0, context_1.createContext)(joinTable, joinAlias), _a)));
411
- }
412
- }); };
413
- exports.createJoinSelectEntity = createJoinSelectEntity;
414
- // utils
415
- var ReservedExpressionKeys = ['val', '=n', '!=n', '=t', '=f', 'not', '+', '-', '*', '/', '||', 'and', 'or',
416
- '**', 'fun', 'swt', 'col', 'raw', '=', '!=', '>', '>=', '<', '<=', 'lk', '@>', '<@', '?', 'j-', 'in', 'nin',
417
- 'lka', 'lks', '?|', '?&', 'j-a', 'bt', 'qry', 'exists'];
418
- exports.ReservedExpressionKeys = ReservedExpressionKeys;
419
- var createQueryResult = function (getColumnType, createQuery, returning) {
420
- var query = undefined;
421
- return ({
422
- getData: function (params) {
423
- if (params === void 0) { params = []; }
424
- if (query === undefined) {
425
- var createQueryResult_1 = createQuery(params);
426
- if (createQueryResult_1.ok) {
427
- query = createQueryResult_1.value;
428
- }
429
- else {
430
- return createQueryResult_1;
431
- }
432
- }
433
- return (0, never_catch_1.ok)(query);
434
- },
435
- exec: function (client, mode, params) {
436
- if (params === void 0) { params = []; }
437
- if (query === undefined) {
438
- var createQueryResult_2 = createQuery(params);
439
- if (createQueryResult_2.ok) {
440
- query = createQueryResult_2.value;
441
- }
442
- else {
443
- return Promise.resolve(createQueryResult_2);
444
- }
445
- }
446
- return client.query(query.sql, query.params)
447
- .then(function (_a) {
448
- var rows = _a.rows;
449
- return resolveResult(getColumnType, returning, rows, mode);
450
- })
451
- .catch(function (e) { return (0, never_catch_1.err)(e); });
452
- }
453
- });
454
- };
455
- exports.createQueryResult = createQueryResult;
456
- /*
457
- * take getColumnType instead of table to support join-select too.
458
- * this cause hard to call this function directly, but it is only solution I could come up with.
459
- */
460
- var resolveResult = function (getColumnType, columns, rows, mode) {
461
- // check size in count and get mode
462
- if (mode[0] === 'count') {
463
- return rows.length === mode[1] ? (0, never_catch_1.ok)(undefined) : (0, never_catch_1.err)(false);
464
- }
465
- if (mode[0] === 'get' && rows.length !== (mode[1] === 'one' ? 1 : mode[1])) {
466
- return (0, never_catch_1.err)(false);
467
- }
468
- // parse result
469
- rows.forEach(function (_, i) {
470
- columns.forEach(function (column) {
471
- if (typeof column !== 'object') {
472
- rows[i][column] = U_1.default.cast(rows[i][column], getColumnType(column));
473
- }
474
- });
475
- });
476
- // return first element for [get, one] mode and all for [get, number] and []
477
- if (mode[0] === 'get' && mode[1] === 'one') {
478
- return (0, never_catch_1.ok)(rows[0]);
479
- }
480
- else {
481
- return (0, never_catch_1.ok)(rows);
482
- }
483
- };
484
- exports.resolveResult = resolveResult;
485
- /*
486
- * take getColumnTypeTitleAlias instead of table to support join-select too.
487
- * this cause hard to call this function directly, but it is only solution I could come up with.
488
- */
489
- var resolveReturning = function (getColumnTypeTitleAlias, columns, paramsStart, ignore) {
490
- var tokens = [];
491
- var params = [];
492
- for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
493
- var column = columns_1[_i];
494
- if (typeof column === 'object') {
495
- var resolvedExpResult = resolveExpression(column.exp, paramsStart, ignore);
496
- if (!resolvedExpResult.ok) {
497
- return (0, never_catch_1.err)("<returning>[".concat(column.as, "] -> ").concat(resolvedExpResult.error));
498
- }
499
- if (resolvedExpResult.value.text === '') {
500
- return (0, never_catch_1.err)("<returning>[".concat(column.as, "] -> neutral"));
501
- }
502
- params.push.apply(params, resolvedExpResult.value.params);
503
- paramsStart += resolvedExpResult.value.params.length;
504
- tokens.push("( ".concat(resolvedExpResult.value.text, " ) AS \"").concat(column.as, "\""));
505
- }
506
- else {
507
- var _a = getColumnTypeTitleAlias(column), _type = _a.type, title = _a.title, alias = _a.alias;
508
- // TODO cast time with/without timezone to custom object
509
- if (title === undefined) {
510
- if (alias !== undefined) {
511
- tokens.push("\"".concat(alias, "\".") +
512
- "\"".concat(column.substring((alias + '_').length), "\"") +
513
- " AS \"".concat(column, "\""));
514
- }
515
- else {
516
- tokens.push("\"".concat(column, "\""));
517
- }
518
- }
519
- else {
520
- tokens.push((alias !== undefined ? "\"".concat(alias, "\".") : '') +
521
- "\"".concat(title, "\"") +
522
- " AS \"".concat(column, "\""));
523
- }
524
- }
525
- }
526
- if (tokens.length === 0) {
527
- return (0, never_catch_1.err)('<returning> -> empty');
528
- }
529
- return (0, never_catch_1.ok)(partialQuery(tokens.join(', '), params));
530
- };
531
- exports.resolveReturning = resolveReturning;
532
- /*
533
- ** currently all errors are handled with types and no dynamic check is required.
534
- ** errors return only when ignore is false and an expression needs ignorance.
535
- ** so, some errors written in function, but they will never be returned.
536
- ** e.g.
537
- ** if (e1Result.value.text === '') {
538
- ** return ignore ? ok(partialQuery()) : err(`<${toDescription(expression[0])}> -> neutral`);
539
- ** }
540
- * if result is neutral then ignore is true, so error in this example will never be returned.
541
- * but they exist in case new errors with dynamic check added.
542
- */
543
- var resolveExpression = function (expression, paramsStart, ignore) {
544
- if (ignore === void 0) { ignore = false; }
545
- // primitive expression
546
- if (expression === undefined) {
547
- return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)('undefined');
548
- }
549
- if (expression === null || typeof expression === 'boolean' || expression instanceof decimal_js_1.default
550
- || expression instanceof Date || typeof expression === 'number' || typeof expression === 'bigint') {
551
- return (0, never_catch_1.ok)(partialQuery("".concat(U_1.default.stringify(expression, true))));
552
- }
553
- if (typeof expression === 'string') {
554
- return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++), [U_1.default.stringify(expression, false)]));
555
- }
556
- if (!(Array.isArray(expression) && ReservedExpressionKeys.includes(expression[0]))) {
557
- return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++, "::jsonb"), [U_1.default.stringify(expression, false)]));
558
- }
559
- // wrapped expression
560
- var tokens = [];
561
- var params = [];
562
- var e1Result, e2Result, e3Result;
563
- switch (expression[0]) {
564
- case 'val':
565
- if (expression[1] === undefined) {
566
- return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)('val'), "> -> undefined"));
567
- }
568
- params.push(U_1.default.stringify(expression[1], false));
569
- return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++), params));
570
- case '=n':
571
- case '!=n':
572
- case '=t':
573
- case '=f':
574
- case 'not':
575
- e1Result = resolveExpression(expression[1], paramsStart, ignore);
576
- if (!e1Result.ok) {
577
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> ").concat(e1Result.error));
578
- }
579
- if (e1Result.value.text === '') {
580
- return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> neutral"));
581
- }
582
- params.push.apply(params, e1Result.value.params);
583
- paramsStart += e1Result.value.params.length;
584
- switch (expression[0]) {
585
- case '=n':
586
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IS NULL"), params));
587
- case '!=n':
588
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IS NOT NULL"), params));
589
- case '=t':
590
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text), params));
591
- case '=f':
592
- case 'not':
593
- return (0, never_catch_1.ok)(partialQuery("NOT ".concat(e1Result.value.text), params));
594
- }
595
- case '+':
596
- case '-':
597
- case '*':
598
- case '/':
599
- case '||':
600
- case 'and':
601
- case 'or':
602
- case '**':
603
- if (expression[1] === undefined) {
604
- return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> undefined"));
605
- }
606
- for (var _i = 0, _a = expression[1]; _i < _a.length; _i++) {
607
- var v1 = _a[_i];
608
- var v1Result = resolveExpression(v1, paramsStart, ignore);
609
- if (!v1Result.ok) {
610
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[").concat(expression[1].indexOf(v1), "] -> ").concat(v1Result.error));
611
- }
612
- if (v1Result.value.text === '') {
613
- if (ignore) {
614
- continue;
615
- }
616
- else {
617
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[").concat(expression[1].indexOf(v1), "] -> neutral"));
618
- }
619
- }
620
- params.push.apply(params, v1Result.value.params);
621
- paramsStart += v1Result.value.params.length;
622
- tokens.push(v1Result.value.text);
623
- }
624
- switch (tokens.length) {
625
- case 0:
626
- return ignore ? (0, never_catch_1.ok)(partialQuery())
627
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> no operands given"));
628
- case 1:
629
- return (0, never_catch_1.ok)(partialQuery(tokens[0], params));
630
- default:
631
- switch (expression[0]) {
632
- case '+':
633
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' + '), " )"), params));
634
- case '-':
635
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' - '), " )"), params));
636
- case '*':
637
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' * '), " )"), params));
638
- case '/':
639
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' / '), " )"), params));
640
- case '||':
641
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' || '), " )"), params));
642
- case 'and':
643
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' AND '), " )"), params));
644
- case 'or':
645
- return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' OR '), " )"), params));
646
- case '**':
647
- var tmp = tokens.pop();
648
- tokens.splice(0, 0, 'a');
649
- return (0, never_catch_1.ok)({
650
- text: tokens.join(', power( ').substring(3) + ', ' + tmp + ' )'.repeat(tokens.length - 1),
651
- params: params
652
- });
653
- }
654
- }
655
- case 'fun':
656
- if (expression[1] === undefined) {
657
- return ignore ? (0, never_catch_1.ok)(partialQuery())
658
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[name] -> undefined"));
659
- }
660
- if (expression[2] === undefined) {
661
- return ignore ? (0, never_catch_1.ok)(partialQuery())
662
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters] -> undefined"));
663
- }
664
- for (var _b = 0, _c = expression[2]; _b < _c.length; _b++) {
665
- var v2 = _c[_b];
666
- var v2Result = resolveExpression(v2, paramsStart, ignore);
667
- if (!v2Result.ok) {
668
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters][").concat(expression[2].indexOf(v2), "] -> ").concat(v2Result.error));
669
- }
670
- if (v2Result.value.text === '') {
671
- return ignore ? (0, never_catch_1.ok)(partialQuery())
672
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters][").concat(expression[2].indexOf(v2), "] -> neutral"));
673
- }
674
- params.push.apply(params, v2Result.value.params);
675
- paramsStart += v2Result.value.params.length;
676
- tokens.push(v2Result.value.text);
677
- }
678
- return (0, never_catch_1.ok)(partialQuery("".concat(expression[1], "( ").concat(tokens.join(', '), " )").concat(expression[3]), params));
679
- case 'swt':
680
- var cases = expression[1];
681
- var otherwise = expression[2];
682
- if (cases === undefined) {
683
- if (!ignore) {
684
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases] -> undefined"));
685
- }
686
- }
687
- else {
688
- for (var _d = 0, cases_1 = cases; _d < cases_1.length; _d++) {
689
- var caseElement = cases_1[_d];
690
- if (caseElement === undefined) {
691
- if (ignore) {
692
- continue;
693
- }
694
- else {
695
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "] -> undefined"));
696
- }
697
- }
698
- var whenResult = resolveExpression(caseElement.when, paramsStart, ignore);
699
- if (!whenResult.ok) {
700
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][when] -> ").concat(whenResult.error));
701
- }
702
- if (whenResult.value.text === '') {
703
- if (ignore) {
704
- continue;
705
- }
706
- else {
707
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][when] -> neutral"));
708
- }
709
- }
710
- params.push.apply(params, whenResult.value.params);
711
- paramsStart += whenResult.value.params.length;
712
- var thenResult = resolveExpression(caseElement.then, paramsStart, ignore);
713
- if (!thenResult.ok) {
714
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][then] -> ").concat(thenResult.error));
715
- }
716
- if (thenResult.value.text === '') {
717
- if (ignore) {
718
- continue;
719
- }
720
- else {
721
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][then] -> neutral"));
722
- }
723
- }
724
- params.push.apply(params, thenResult.value.params);
725
- paramsStart += thenResult.value.params.length;
726
- if (tokens.length === 0) {
727
- tokens.push('CASE');
728
- }
729
- tokens.push("WHEN ".concat(whenResult.value.text, " THEN ").concat(thenResult.value.text));
730
- }
731
- }
732
- if (tokens.length === 0 && !ignore) {
733
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases] -> empty"));
734
- }
735
- if (otherwise === undefined) {
736
- if (tokens.length === 0) {
737
- return (0, never_catch_1.ok)(partialQuery());
738
- }
739
- else {
740
- tokens.push('END');
741
- }
742
- }
743
- else {
744
- var isOtherwiseNeutral = false;
745
- var otherwiseResult = resolveExpression(otherwise, paramsStart, ignore);
746
- if (!otherwiseResult.ok) {
747
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[otherwise] -> ").concat(otherwiseResult.error));
748
- }
749
- if (otherwiseResult.value.text === '') {
750
- if (ignore) {
751
- isOtherwiseNeutral = true;
752
- }
753
- else {
754
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[otherwise] -> neutral"));
755
- }
756
- }
757
- params.push.apply(params, otherwiseResult.value.params);
758
- paramsStart += otherwiseResult.value.params.length;
759
- if (tokens.length === 0) {
760
- if (isOtherwiseNeutral) {
761
- return (0, never_catch_1.ok)(partialQuery());
762
- }
763
- else {
764
- tokens.push(otherwiseResult.value.text);
765
- }
766
- }
767
- else {
768
- if (!isOtherwiseNeutral) {
769
- tokens.push('ELSE', otherwiseResult.value.text);
770
- }
771
- tokens.push('END');
772
- }
773
- }
774
- return (0, never_catch_1.ok)(partialQuery(tokens.join(' '), params));
775
- case 'col':
776
- case 'raw':
777
- return (0, never_catch_1.ok)(partialQuery("".concat(expression[1])));
778
- case 'qry':
779
- case 'exists':
780
- var subQueryDataResult = expression[1].getData(params);
781
- if (!subQueryDataResult.ok) {
782
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> ").concat(subQueryDataResult.error));
783
- }
784
- paramsStart += subQueryDataResult.value.params.length;
785
- switch (expression[0]) {
786
- case 'qry':
787
- return (0, never_catch_1.ok)(partialQuery("( ".concat(subQueryDataResult.value.sql, " )"), params));
788
- case 'exists':
789
- return (0, never_catch_1.ok)(partialQuery("EXISTS ( ".concat(subQueryDataResult.value.sql, " )"), params));
790
- }
791
- case '=':
792
- case '!=':
793
- case '>':
794
- case '>=':
795
- case '<':
796
- case '<=':
797
- case 'lk':
798
- case '@>':
799
- case '<@':
800
- case '?':
801
- case 'j-':
802
- e1Result = resolveExpression(expression[1], paramsStart, ignore);
803
- if (!e1Result.ok) {
804
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
805
- }
806
- if (e1Result.value.text === '') {
807
- return ignore ? (0, never_catch_1.ok)(partialQuery())
808
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
809
- }
810
- params.push.apply(params, e1Result.value.params);
811
- paramsStart += e1Result.value.params.length;
812
- e2Result = resolveExpression(expression[2], paramsStart, ignore);
813
- if (!e2Result.ok) {
814
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> ").concat(e2Result.error));
815
- }
816
- if (e2Result.value.text === '') {
817
- return ignore ? (0, never_catch_1.ok)(partialQuery())
818
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> netural"));
819
- }
820
- params.push.apply(params, e2Result.value.params);
821
- paramsStart += e2Result.value.params.length;
822
- switch (expression[0]) {
823
- case '=':
824
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " = ").concat(e2Result.value.text), params));
825
- case '!=':
826
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <> ").concat(e2Result.value.text), params));
827
- case '>':
828
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " > ").concat(e2Result.value.text), params));
829
- case '>=':
830
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " >= ").concat(e2Result.value.text), params));
831
- case '<':
832
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " < ").concat(e2Result.value.text), params));
833
- case '<=':
834
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <= ").concat(e2Result.value.text), params));
835
- case 'lk':
836
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(e2Result.value.text), params));
837
- case '@>':
838
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " @> ").concat(e2Result.value.text), params));
839
- case '<@':
840
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <@ ").concat(e2Result.value.text), params));
841
- case '?':
842
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(e2Result.value.text), params));
843
- case 'j-':
844
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ").concat(e2Result.value.text), params));
845
- }
846
- case 'in':
847
- case 'nin':
848
- case 'lka':
849
- case 'lks':
850
- case '?|':
851
- case '?&':
852
- case 'j-a':
853
- e1Result = resolveExpression(expression[1], paramsStart, ignore);
854
- if (!e1Result.ok) {
855
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
856
- }
857
- if (e1Result.value.text === '') {
858
- return ignore ? (0, never_catch_1.ok)(partialQuery())
859
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
860
- }
861
- params.push.apply(params, e1Result.value.params);
862
- paramsStart += e1Result.value.params.length;
863
- if (expression[2] === undefined) {
864
- return ignore ? (0, never_catch_1.ok)(partialQuery())
865
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> undefined"));
866
- }
867
- for (var _e = 0, _f = expression[2]; _e < _f.length; _e++) {
868
- var v2 = _f[_e];
869
- var v2Result = resolveExpression(v2, paramsStart, ignore);
870
- if (!v2Result.ok) {
871
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand][").concat(expression[2].indexOf(v2), "] -> ").concat(v2Result.error));
872
- }
873
- if (v2Result.value.text === '') {
874
- if (ignore) {
875
- continue;
876
- }
877
- else {
878
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand][").concat(expression[1].indexOf(v2), "] -> neutral"));
879
- }
880
- }
881
- params.push.apply(params, v2Result.value.params);
882
- paramsStart += v2Result.value.params.length;
883
- tokens.push(v2Result.value.text);
884
- }
885
- switch (tokens.length) {
886
- case 0:
887
- return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> empty"));
888
- case 1:
889
- switch (expression[0]) {
890
- case 'in':
891
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " = ").concat(tokens[0]), params));
892
- case 'nin':
893
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <> ").concat(tokens[0]), params));
894
- case 'lka':
895
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(tokens[0]), params));
896
- case 'lks':
897
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(tokens[0]), params));
898
- case '?|':
899
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(tokens[0]), params));
900
- case '?&':
901
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(tokens[0]), params));
902
- case 'j-a':
903
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ").concat(tokens[0]), params));
904
- }
905
- default:
906
- switch (expression[0]) {
907
- case 'in':
908
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IN ( ").concat(tokens.join(', '), " )"), params));
909
- case 'nin':
910
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " NOT IN ( ").concat(tokens.join(', '), " )"), params));
911
- case 'lka':
912
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ALL( ARRAY[ ").concat(tokens.join(', '), " ] )"), params));
913
- case 'lks':
914
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE SOME( ARRAY[ ").concat(tokens.join(', '), " ] )"), params));
915
- case '?|':
916
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ?| ARRAY[ ").concat(tokens.join(', '), " ]"), params));
917
- case '?&':
918
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ?& ARRAY[ ").concat(tokens.join(', '), " ]"), params));
919
- case 'j-a':
920
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ARRAY[ ").concat(tokens.join(', '), " ]"), params));
921
- }
922
- }
923
- case 'bt':
924
- e1Result = resolveExpression(expression[1], paramsStart, ignore);
925
- if (!e1Result.ok) {
926
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
927
- }
928
- if (e1Result.value.text === '') {
929
- return ignore ? (0, never_catch_1.ok)(partialQuery())
930
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
931
- }
932
- params.push.apply(params, e1Result.value.params);
933
- paramsStart += e1Result.value.params.length;
934
- e2Result = resolveExpression(expression[2], paramsStart, ignore);
935
- if (!e2Result.ok) {
936
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> ").concat(e2Result.error));
937
- }
938
- if (e2Result.value.text === '') {
939
- return ignore ? (0, never_catch_1.ok)(partialQuery())
940
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> netural"));
941
- }
942
- params.push.apply(params, e2Result.value.params);
943
- paramsStart += e2Result.value.params.length;
944
- e3Result = resolveExpression(expression[3], paramsStart, ignore);
945
- if (!e3Result.ok) {
946
- return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[third operand] -> ").concat(e3Result.error));
947
- }
948
- if (e3Result.value.text === '') {
949
- return ignore ? (0, never_catch_1.ok)(partialQuery())
950
- : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[third operand] -> netural"));
951
- }
952
- params.push.apply(params, e3Result.value.params);
953
- paramsStart += e3Result.value.params.length;
954
- return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " BETWEEN ").concat(e2Result.value.text, " AND ").concat(e3Result.value.text), params));
955
- default:
956
- throw 'unexpected error. expect first element to be reserved key.';
957
- }
958
- };
959
- exports.resolveExpression = resolveExpression;
960
- var getTableDataOfJoinSelectColumn = function (tablesData, column) {
961
- var splitColumn = column.split('_');
962
- if (splitColumn.length < 2) {
963
- throw "no separator";
964
- }
965
- // in case alias or column key have "_". iterate on all of them until a match.
966
- var tableAliasUntilIndex = 1;
967
- while (true) {
968
- var tableAlias = splitColumn.slice(0, tableAliasUntilIndex).join('_');
969
- for (var _i = 0, tablesData_1 = tablesData; _i < tablesData_1.length; _i++) {
970
- var tableData = tablesData_1[_i];
971
- if (tableData.alias === tableAlias && tableData.table.columns[splitColumn.slice(tableAliasUntilIndex).join('_')] !== undefined) {
972
- return tableData;
973
- }
974
- }
975
- if (splitColumn.length > tableAliasUntilIndex + 1) {
976
- tableAliasUntilIndex++;
977
- }
978
- else {
979
- throw "column not found";
980
- }
981
- }
982
- };
983
- exports.getTableDataOfJoinSelectColumn = getTableDataOfJoinSelectColumn;
984
- var resolveColumn = function (table, column, full, alias) {
985
- var _a;
986
- if (full === void 0) { full = true; }
987
- var prefix;
988
- if (full) {
989
- if (alias !== undefined) {
990
- prefix = "\"".concat(alias, "\".");
991
- }
992
- else {
993
- prefix = "\"".concat(table.schema, "\".\"").concat(table.title, "\".");
994
- }
995
- }
996
- else {
997
- prefix = '';
998
- }
999
- return prefix + "\"".concat((_a = table.columns[column].title) !== null && _a !== void 0 ? _a : column, "\"");
1000
- };
1001
- exports.resolveColumn = resolveColumn;
1002
- var partialQuery = function (text, params) {
1003
- if (text === void 0) { text = ''; }
1004
- if (params === void 0) { params = []; }
1005
- return ({ text: text, params: params });
1006
- };
1007
- exports.partialQuery = partialQuery;
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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
14
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
15
+ if (ar || !(i in from)) {
16
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
17
+ ar[i] = from[i];
18
+ }
19
+ }
20
+ return to.concat(ar || Array.prototype.slice.call(from));
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.partialQuery = exports.resolveColumn = exports.getTableDataOfJoinSelectColumn = exports.resolveExpression = exports.resolveReturning = exports.resolveResult = exports.createQueryResult = exports.ReservedExpressionKeys = exports.createJoinSelectEntity = exports.createEntity = void 0;
27
+ var U_1 = require("./U");
28
+ var decimal_js_1 = __importDefault(require("decimal.js"));
29
+ var context_1 = require("./context");
30
+ var never_catch_1 = require("never-catch");
31
+ var dictionary_1 = require("./dictionary");
32
+ // entity
33
+ var createEntity = function (table) {
34
+ return ({
35
+ table: table,
36
+ context: (0, context_1.createContext)(table),
37
+ select: function (returning, where, options) {
38
+ var _this = this;
39
+ var _a, _b, _c, _d, _e, _f;
40
+ var ignoreInWhere = (_a = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _a !== void 0 ? _a : false;
41
+ var ignoreInReturning = (_b = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _b !== void 0 ? _b : false;
42
+ var ignoreInGroupBy = (_c = options === null || options === void 0 ? void 0 : options.ignoreInGroupBy) !== null && _c !== void 0 ? _c : false;
43
+ var distinct = (_d = options === null || options === void 0 ? void 0 : options.distinct) !== null && _d !== void 0 ? _d : false;
44
+ var groupBy = (_e = options === null || options === void 0 ? void 0 : options.groupBy) !== null && _e !== void 0 ? _e : [];
45
+ var orders = (_f = options === null || options === void 0 ? void 0 : options.orders) !== null && _f !== void 0 ? _f : [];
46
+ var start = options === null || options === void 0 ? void 0 : options.start;
47
+ var step = options === null || options === void 0 ? void 0 : options.step;
48
+ var _returning = typeof returning === 'function' ? returning(this.context) : returning;
49
+ var createQuery = function (params) {
50
+ var tokens = ['SELECT'];
51
+ // distinct
52
+ if (distinct) {
53
+ tokens.push('DISTINCT');
54
+ }
55
+ // select
56
+ var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
57
+ if (!resolvedReturning.ok) {
58
+ return (0, never_catch_1.err)("<select> -> ".concat(resolvedReturning.error));
59
+ }
60
+ params.push.apply(params, resolvedReturning.value.params);
61
+ tokens.push(resolvedReturning.value.text);
62
+ // from
63
+ tokens.push("FROM \"".concat(table.schema, "\".\"").concat(table.title, "\""));
64
+ // where
65
+ var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
66
+ if (!resolvedWhereResult.ok) {
67
+ return (0, never_catch_1.err)("<select>[where] -> ".concat(resolvedWhereResult.error));
68
+ }
69
+ if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
70
+ return (0, never_catch_1.err)("<select>[where] -> neutral");
71
+ }
72
+ params.push.apply(params, resolvedWhereResult.value.params);
73
+ tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'TRUE' : resolvedWhereResult.value.text);
74
+ // groupBy
75
+ var _groupBy = typeof groupBy === 'function' ? groupBy(_this.context) : groupBy;
76
+ if (_groupBy.length !== 0) {
77
+ var groupByTextArray = [];
78
+ for (var _i = 0, _groupBy_1 = _groupBy; _i < _groupBy_1.length; _i++) {
79
+ var aGroupBy = _groupBy_1[_i];
80
+ var resolvedGroupBy = resolveExpression(aGroupBy, params.length + 1, ignoreInGroupBy);
81
+ if (!resolvedGroupBy.ok) {
82
+ return (0, never_catch_1.err)("<select> -> ".concat(resolvedGroupBy.error));
83
+ }
84
+ params.push.apply(params, resolvedGroupBy.value.params);
85
+ groupByTextArray.push(resolvedGroupBy.value.text);
86
+ }
87
+ tokens.push('GROUP BY', groupByTextArray.join(', '));
88
+ }
89
+ // orders
90
+ if (orders.length !== 0) {
91
+ var ordersTextArray = [];
92
+ for (var _a = 0, orders_1 = orders; _a < orders_1.length; _a++) {
93
+ var order = orders_1[_a];
94
+ var by = order.by, direction = order.direction;
95
+ ordersTextArray.push("".concat(resolveColumn(table, by, false), " ").concat((0, dictionary_1.toOrderDirection)(direction)));
96
+ }
97
+ tokens.push('ORDER BY', ordersTextArray.join(', '));
98
+ }
99
+ // pagination
100
+ if (start !== undefined) {
101
+ if (start < 0) {
102
+ return (0, never_catch_1.err)("<select>[start] -> invalid");
103
+ }
104
+ tokens.push('OFFSET', start.toString());
105
+ }
106
+ if (step !== undefined) {
107
+ if (step <= 0) {
108
+ return (0, never_catch_1.err)("<select>[step] -> invalid");
109
+ }
110
+ tokens.push('LIMIT', step.toString());
111
+ }
112
+ tokens.push(';');
113
+ var sql = tokens.join(' ');
114
+ return (0, never_catch_1.ok)({ sql: sql, params: params });
115
+ };
116
+ return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
117
+ },
118
+ insert: function (rows, returning, options) {
119
+ var _this = this;
120
+ var _a, _b, _c;
121
+ var nullableDefaultColumns = (_a = options === null || options === void 0 ? void 0 : options.nullableDefaultColumns) !== null && _a !== void 0 ? _a : [];
122
+ var ignoreInValues = (_b = options === null || options === void 0 ? void 0 : options.ignoreInValues) !== null && _b !== void 0 ? _b : false;
123
+ var ignoreInReturning = (_c = options === null || options === void 0 ? void 0 : options.ignoreInValues) !== null && _c !== void 0 ? _c : false;
124
+ var _returning = typeof returning === 'function' ? returning(this.context) : returning;
125
+ var createQuery = function (params) {
126
+ var tokens = ["INSERT INTO \"".concat(table.schema, "\".\"").concat(table.title, "\"")];
127
+ // columns
128
+ var insertingColumns = [];
129
+ var columnsTextArray = [];
130
+ for (var column in table.columns) {
131
+ if (nullableDefaultColumns.includes(column) || !table.columns[column].nullable) {
132
+ insertingColumns.push(column);
133
+ columnsTextArray.push(resolveColumn(table, column, false));
134
+ }
135
+ }
136
+ tokens.push("( ".concat(columnsTextArray.join(', '), " )"), 'VALUES');
137
+ // values
138
+ var valuesTextArray = [];
139
+ var _rows = typeof rows === 'function' ? rows(_this.context) : rows;
140
+ if (_rows.length === 0) {
141
+ return (0, never_catch_1.err)('<insert>[values] -> empty');
142
+ }
143
+ for (var _i = 0, _rows_1 = _rows; _i < _rows_1.length; _i++) {
144
+ var _row = _rows_1[_i];
145
+ var rowTokens = [];
146
+ for (var _a = 0, insertingColumns_1 = insertingColumns; _a < insertingColumns_1.length; _a++) {
147
+ var insertingColumn = insertingColumns_1[_a];
148
+ if (_row[insertingColumn] === undefined) {
149
+ var column = table.columns[insertingColumn];
150
+ switch (column.default) {
151
+ case 'value':
152
+ rowTokens.push(U_1.U.stringify(column.value, true));
153
+ continue;
154
+ case true:
155
+ case 'auto-increment':
156
+ rowTokens.push('DEFAULT');
157
+ continue;
158
+ case 'created-at':
159
+ case 'updated-at':
160
+ rowTokens.push(U_1.U.stringify(new Date(), true));
161
+ continue;
162
+ }
163
+ if (column.nullable) {
164
+ rowTokens.push(U_1.U.stringify(null));
165
+ continue;
166
+ }
167
+ // never going to happen!
168
+ return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> no-value"));
169
+ }
170
+ else {
171
+ var resolvedExpressionResult = resolveExpression(_row[insertingColumn], params.length + 1, ignoreInValues);
172
+ if (!resolvedExpressionResult.ok) {
173
+ return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> ").concat(resolvedExpressionResult.error));
174
+ }
175
+ if (resolvedExpressionResult.value.text === '') {
176
+ return (0, never_catch_1.err)("<insert>[rows][".concat(_rows.indexOf(_row), "][").concat(insertingColumn, "] -> neutral"));
177
+ }
178
+ params.push.apply(params, resolvedExpressionResult.value.params);
179
+ rowTokens.push(resolvedExpressionResult.value.text);
180
+ }
181
+ }
182
+ valuesTextArray.push("( ".concat(rowTokens.join(', '), " )"));
183
+ }
184
+ tokens.push(valuesTextArray.join(', '));
185
+ // returning
186
+ if (_returning.length !== 0) {
187
+ var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
188
+ if (!resolvedReturning.ok) {
189
+ return (0, never_catch_1.err)("<insert> -> ".concat(resolvedReturning.error));
190
+ }
191
+ params.push.apply(params, resolvedReturning.value.params);
192
+ tokens.push('RETURNING', resolvedReturning.value.text);
193
+ }
194
+ tokens.push(';');
195
+ var sql = tokens.join(' ');
196
+ return (0, never_catch_1.ok)({ sql: sql, params: params });
197
+ };
198
+ return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
199
+ },
200
+ update: function (sets, where, returning, options) {
201
+ var _this = this;
202
+ var _a, _b, _c;
203
+ var ignoreInSets = (_a = options === null || options === void 0 ? void 0 : options.ignoreInSets) !== null && _a !== void 0 ? _a : false;
204
+ var ignoreInWhere = (_b = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _b !== void 0 ? _b : false;
205
+ var ignoreInReturning = (_c = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _c !== void 0 ? _c : false;
206
+ var _returning = typeof returning === 'function' ? returning(this.context) : returning;
207
+ var createQuery = function (params) {
208
+ var tokens = ["UPDATE \"".concat(table.schema, "\".\"").concat(table.title, "\" SET")];
209
+ // set
210
+ var _set = typeof sets === 'function' ? sets(_this.context) : sets;
211
+ var setsTextArray = [];
212
+ var key;
213
+ for (key in _set) {
214
+ var setExpressionResult = resolveExpression(_set[key], params.length + 1, ignoreInSets);
215
+ if (!setExpressionResult.ok) {
216
+ return (0, never_catch_1.err)("<update>[sets][".concat(key, "] -> ").concat(setExpressionResult.error));
217
+ }
218
+ if (setExpressionResult.value.text === '') {
219
+ if (ignoreInSets) {
220
+ continue;
221
+ }
222
+ else {
223
+ return (0, never_catch_1.err)("<update>[sets][".concat(key, "] -> neutral"));
224
+ }
225
+ }
226
+ params.push.apply(params, setExpressionResult.value.params);
227
+ setsTextArray.push("".concat(resolveColumn(table, key, false), " = ").concat(setExpressionResult.value.text));
228
+ }
229
+ for (var column in table.columns) {
230
+ switch (table.columns[column].default) {
231
+ case 'updated-at':
232
+ setsTextArray.push("".concat(resolveColumn(table, column, false), " = ").concat(U_1.U.stringify(new Date(), true)));
233
+ break;
234
+ }
235
+ }
236
+ if (setsTextArray.length === 0) {
237
+ return (0, never_catch_1.err)('<update>[sets] -> empty');
238
+ }
239
+ tokens.push(setsTextArray.join(', '));
240
+ // where
241
+ var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
242
+ if (!resolvedWhereResult.ok) {
243
+ return (0, never_catch_1.err)("<update>[where] -> ".concat(resolvedWhereResult.error));
244
+ }
245
+ if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
246
+ return (0, never_catch_1.err)("<update>[where] -> neutral");
247
+ }
248
+ params.push.apply(params, resolvedWhereResult.value.params);
249
+ tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
250
+ // returning
251
+ if (_returning.length !== 0) {
252
+ var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
253
+ if (!resolvedReturning.ok) {
254
+ return (0, never_catch_1.err)("<update> -> ".concat(resolvedReturning.error));
255
+ }
256
+ params.push.apply(params, resolvedReturning.value.params);
257
+ tokens.push('RETURNING', resolvedReturning.value.text);
258
+ }
259
+ tokens.push(';');
260
+ var sql = tokens.join(' ');
261
+ return (0, never_catch_1.ok)({ sql: sql, params: params });
262
+ };
263
+ return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
264
+ },
265
+ delete: function (where, returning, options) {
266
+ var _this = this;
267
+ var _a, _b;
268
+ var ignoreInWhere = (_a = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _a !== void 0 ? _a : false;
269
+ var ignoreInReturning = (_b = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _b !== void 0 ? _b : false;
270
+ var _returning = typeof returning === 'function' ? returning(this.context) : returning;
271
+ var createQuery = function (params) {
272
+ var tokens = ["DELETE FROM \"".concat(table.schema, "\".\"").concat(table.title, "\"")];
273
+ // where
274
+ var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.context) : where, params.length + 1, ignoreInWhere);
275
+ if (!resolvedWhereResult.ok) {
276
+ return (0, never_catch_1.err)("<delete>[where] -> ".concat(resolvedWhereResult.error));
277
+ }
278
+ if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
279
+ return (0, never_catch_1.err)("<delete>[where] -> neutral");
280
+ }
281
+ params.push.apply(params, resolvedWhereResult.value.params);
282
+ tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
283
+ // returning
284
+ if (_returning.length !== 0) {
285
+ var resolvedReturning = resolveReturning(function (column) { return ({ type: table.columns[column].type, title: table.columns[column].title }); }, _returning, params.length + 1, ignoreInReturning);
286
+ if (!resolvedReturning.ok) {
287
+ return (0, never_catch_1.err)("<delete> -> ".concat(resolvedReturning.error));
288
+ }
289
+ params.push.apply(params, resolvedReturning.value.params);
290
+ tokens.push('RETURNING', resolvedReturning.value.text);
291
+ }
292
+ tokens.push(';');
293
+ var sql = tokens.join(' ');
294
+ return (0, never_catch_1.ok)({ sql: sql, params: params });
295
+ };
296
+ return createQueryResult(function (column) { return [table.columns[column].type, table.columns[column].nullable]; }, createQuery, _returning);
297
+ },
298
+ join: function (mainAlias, joinType, joinTable, joinAlias, on) {
299
+ var _a;
300
+ return createJoinSelectEntity({ table: table, alias: mainAlias }, [{ table: joinTable, joinType: joinType, alias: joinAlias, on: on }], (_a = {},
301
+ _a[mainAlias] = (0, context_1.createContext)(table, mainAlias),
302
+ _a[joinAlias] = (0, context_1.createContext)(joinTable, joinAlias),
303
+ _a));
304
+ }
305
+ });
306
+ };
307
+ exports.createEntity = createEntity;
308
+ var createJoinSelectEntity = function (main, joinTables, contexts) {
309
+ return ({
310
+ contexts: contexts,
311
+ select: function (returning, where, options) {
312
+ var _this = this;
313
+ var _a, _b, _c, _d, _e, _f, _g;
314
+ var ignoreInWhere = (_a = options === null || options === void 0 ? void 0 : options.ignoreInWhere) !== null && _a !== void 0 ? _a : false;
315
+ var ignoreInReturning = (_b = options === null || options === void 0 ? void 0 : options.ignoreInReturning) !== null && _b !== void 0 ? _b : false;
316
+ var ignoreInJoin = (_c = options === null || options === void 0 ? void 0 : options.ignoreInJoin) !== null && _c !== void 0 ? _c : false;
317
+ var ignoreInGroupBy = (_d = options === null || options === void 0 ? void 0 : options.ignoreInGroupBy) !== null && _d !== void 0 ? _d : false;
318
+ var distinct = (_e = options === null || options === void 0 ? void 0 : options.distinct) !== null && _e !== void 0 ? _e : false;
319
+ var groupBy = (_f = options === null || options === void 0 ? void 0 : options.groupBy) !== null && _f !== void 0 ? _f : [];
320
+ var orders = (_g = options === null || options === void 0 ? void 0 : options.orders) !== null && _g !== void 0 ? _g : [];
321
+ var start = options === null || options === void 0 ? void 0 : options.start;
322
+ var step = options === null || options === void 0 ? void 0 : options.step;
323
+ var allTables = __spreadArray([main], joinTables, true);
324
+ var _returning = typeof returning === 'function' ? returning(this.contexts) : returning;
325
+ var createQuery = function (params) {
326
+ var tokens = ['SELECT'];
327
+ // distinct
328
+ if (distinct) {
329
+ tokens.push('DISTINCT');
330
+ }
331
+ // select
332
+ var resolvedReturning = resolveReturning(function (column) {
333
+ var _a = getTableDataOfJoinSelectColumn(allTables, column), table = _a.table, alias = _a.alias;
334
+ var columnKey = column.substring((alias + '_').length);
335
+ return { type: table.columns[columnKey].type, title: table.columns[columnKey].title, alias: alias };
336
+ }, _returning, params.length + 1, ignoreInReturning);
337
+ if (!resolvedReturning.ok) {
338
+ return (0, never_catch_1.err)("<join-select>[columns] -> ".concat(resolvedReturning.error));
339
+ }
340
+ params.push.apply(params, resolvedReturning.value.params);
341
+ tokens.push(resolvedReturning.value.text, "FROM \"".concat(main.table.schema, "\".\"").concat(main.table.title, "\" \"").concat(main.alias, "\""));
342
+ // join
343
+ for (var _i = 0, joinTables_1 = joinTables; _i < joinTables_1.length; _i++) {
344
+ var joinTable = joinTables_1[_i];
345
+ var onExpressionResult = resolveExpression(typeof joinTable.on === 'function' ? joinTable.on(_this.contexts) : joinTable.on, params.length + 1, ignoreInJoin);
346
+ if (!onExpressionResult.ok) {
347
+ return (0, never_catch_1.err)("<join-select>[join][".concat(joinTables.indexOf(joinTable), "] -> ").concat(onExpressionResult.error));
348
+ }
349
+ if (onExpressionResult.value.text === '' && !ignoreInJoin) {
350
+ return (0, never_catch_1.err)("<join-select>[join][".concat(joinTables.indexOf(joinTable), "] -> neutral"));
351
+ }
352
+ params.push.apply(params, onExpressionResult.value.params);
353
+ tokens.push("".concat((0, dictionary_1.toJoinType)(joinTable.joinType), " \"").concat(joinTable.table.schema, "\".\"").concat(joinTable.table.title, "\" \"").concat(joinTable.alias, "\" ON ").concat(onExpressionResult.value.text));
354
+ }
355
+ // where
356
+ var resolvedWhereResult = resolveExpression(typeof where === 'function' ? where(_this.contexts) : where, params.length + 1, ignoreInWhere);
357
+ if (!resolvedWhereResult.ok) {
358
+ return (0, never_catch_1.err)("<join-select>[where] -> ".concat(resolvedWhereResult.error));
359
+ }
360
+ if (resolvedWhereResult.value.text === '' && !ignoreInWhere) {
361
+ return (0, never_catch_1.err)("<join-select>[where] -> neutral");
362
+ }
363
+ params.push.apply(params, resolvedWhereResult.value.params);
364
+ tokens.push('WHERE', resolvedWhereResult.value.text === '' ? 'FALSE' : resolvedWhereResult.value.text);
365
+ // groupBy
366
+ var _groupBy = typeof groupBy === 'function' ? groupBy(_this.contexts) : groupBy;
367
+ if (_groupBy.length !== 0) {
368
+ var groupByTextArray = [];
369
+ for (var _a = 0, _groupBy_2 = _groupBy; _a < _groupBy_2.length; _a++) {
370
+ var aGroupBy = _groupBy_2[_a];
371
+ var resolvedGroupBy = resolveExpression(aGroupBy, params.length + 1, ignoreInGroupBy);
372
+ if (!resolvedGroupBy.ok) {
373
+ return (0, never_catch_1.err)("<join-select> -> ".concat(resolvedGroupBy.error));
374
+ }
375
+ params.push.apply(params, resolvedGroupBy.value.params);
376
+ groupByTextArray.push(resolvedGroupBy.value.text);
377
+ }
378
+ tokens.push('GROUP BY', groupByTextArray.join(', '));
379
+ }
380
+ // orders
381
+ if (orders.length !== 0) {
382
+ var ordersTextArray = [];
383
+ for (var _b = 0, orders_2 = orders; _b < orders_2.length; _b++) {
384
+ var order = orders_2[_b];
385
+ var by = order.by, direction = order.direction;
386
+ ordersTextArray.push("\"".concat(by, "\" ").concat(direction));
387
+ }
388
+ tokens.push('ORDER BY', ordersTextArray.join(', '));
389
+ }
390
+ // pagination
391
+ if (start !== undefined) {
392
+ if (start < 0) {
393
+ return (0, never_catch_1.err)("<join-select>[start] -> invalid");
394
+ }
395
+ tokens.push('OFFSET', start.toString());
396
+ }
397
+ if (step !== undefined) {
398
+ if (step <= 0) {
399
+ return (0, never_catch_1.err)("<join-select>[step] -> invalid");
400
+ }
401
+ tokens.push('LIMIT', step.toString());
402
+ }
403
+ tokens.push(';');
404
+ var sql = tokens.join(' ');
405
+ return (0, never_catch_1.ok)({ sql: sql, params: params });
406
+ };
407
+ return createQueryResult(function (column) {
408
+ var _a = getTableDataOfJoinSelectColumn(allTables, column), alias = _a.alias, columns = _a.table.columns;
409
+ var targetCol = columns[column.substring((alias + '_').length)];
410
+ return [targetCol.type, targetCol.nullable];
411
+ }, createQuery, _returning);
412
+ },
413
+ join: function (joinType, joinTable, joinAlias, on) {
414
+ var _a;
415
+ joinTables.push({ table: joinTable, on: on, joinType: joinType, alias: joinAlias });
416
+ return createJoinSelectEntity(main, joinTables, __assign(__assign({}, contexts), (_a = {}, _a[joinAlias] = (0, context_1.createContext)(joinTable, joinAlias), _a)));
417
+ }
418
+ });
419
+ };
420
+ exports.createJoinSelectEntity = createJoinSelectEntity;
421
+ // utils
422
+ var ReservedExpressionKeys = [
423
+ 'val',
424
+ '=n',
425
+ '!=n',
426
+ '=t',
427
+ '=f',
428
+ 'not',
429
+ '+',
430
+ '-',
431
+ '*',
432
+ '/',
433
+ '||',
434
+ 'and',
435
+ 'or',
436
+ '**',
437
+ 'fun',
438
+ 'swt',
439
+ 'col',
440
+ 'raw',
441
+ '=',
442
+ '!=',
443
+ '>',
444
+ '>=',
445
+ '<',
446
+ '<=',
447
+ 'lk',
448
+ '@>',
449
+ '<@',
450
+ '?',
451
+ 'j-',
452
+ 'in',
453
+ 'nin',
454
+ 'lka',
455
+ 'lks',
456
+ '?|',
457
+ '?&',
458
+ 'j-a',
459
+ 'bt',
460
+ 'qry',
461
+ 'exists'
462
+ ];
463
+ exports.ReservedExpressionKeys = ReservedExpressionKeys;
464
+ var createQueryResult = function (getColumnType, createQuery, returning) {
465
+ var query = undefined;
466
+ return {
467
+ getData: function (params) {
468
+ if (params === void 0) { params = []; }
469
+ if (query === undefined) {
470
+ var createQueryResult_1 = createQuery(params);
471
+ if (createQueryResult_1.ok) {
472
+ query = createQueryResult_1.value;
473
+ }
474
+ else {
475
+ return createQueryResult_1;
476
+ }
477
+ }
478
+ return (0, never_catch_1.ok)(query);
479
+ },
480
+ exec: function (client, mode, params) {
481
+ if (params === void 0) { params = []; }
482
+ if (query === undefined) {
483
+ var createQueryResult_2 = createQuery(params);
484
+ if (createQueryResult_2.ok) {
485
+ query = createQueryResult_2.value;
486
+ }
487
+ else {
488
+ return Promise.resolve(createQueryResult_2);
489
+ }
490
+ }
491
+ return client
492
+ .query(query.sql, query.params)
493
+ .then(function (_a) {
494
+ var rows = _a.rows;
495
+ return resolveResult(getColumnType, returning, rows, mode);
496
+ })
497
+ .catch(function (e) { return (0, never_catch_1.err)(e); });
498
+ }
499
+ };
500
+ };
501
+ exports.createQueryResult = createQueryResult;
502
+ /*
503
+ * take getColumnType instead of table to support join-select too.
504
+ * this cause hard to call this function directly, but it is only solution I could come up with.
505
+ */
506
+ var resolveResult = function (getColumnType, columns, rows, mode) {
507
+ // check size in count and get mode
508
+ if (mode[0] === 'count') {
509
+ return rows.length === mode[1] ? (0, never_catch_1.ok)(undefined) : (0, never_catch_1.err)(false);
510
+ }
511
+ if (mode[0] === 'get' && rows.length !== (mode[1] === 'one' ? 1 : mode[1])) {
512
+ return (0, never_catch_1.err)(false);
513
+ }
514
+ // parse result
515
+ rows.forEach(function (_, i) {
516
+ columns.forEach(function (column) {
517
+ if (typeof column !== 'object') {
518
+ rows[i][column] = U_1.U.cast(rows[i][column], getColumnType(column));
519
+ }
520
+ });
521
+ });
522
+ // return first element for [get, one] mode and all for [get, number] and []
523
+ if (mode[0] === 'get' && mode[1] === 'one') {
524
+ return (0, never_catch_1.ok)(rows[0]);
525
+ }
526
+ else {
527
+ return (0, never_catch_1.ok)(rows);
528
+ }
529
+ };
530
+ exports.resolveResult = resolveResult;
531
+ /*
532
+ * take getColumnTypeTitleAlias instead of table to support join-select too.
533
+ * this cause hard to call this function directly, but it is only solution I could come up with.
534
+ */
535
+ var resolveReturning = function (getColumnTypeTitleAlias, columns, paramsStart, ignore) {
536
+ var tokens = [];
537
+ var params = [];
538
+ for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
539
+ var column = columns_1[_i];
540
+ if (typeof column === 'object') {
541
+ var resolvedExpResult = resolveExpression(column.exp, paramsStart, ignore);
542
+ if (!resolvedExpResult.ok) {
543
+ return (0, never_catch_1.err)("<returning>[".concat(column.as, "] -> ").concat(resolvedExpResult.error));
544
+ }
545
+ if (resolvedExpResult.value.text === '') {
546
+ return (0, never_catch_1.err)("<returning>[".concat(column.as, "] -> neutral"));
547
+ }
548
+ params.push.apply(params, resolvedExpResult.value.params);
549
+ paramsStart += resolvedExpResult.value.params.length;
550
+ tokens.push("( ".concat(resolvedExpResult.value.text, " ) AS \"").concat(column.as, "\""));
551
+ }
552
+ else {
553
+ var _a = getColumnTypeTitleAlias(column), _type = _a.type, title = _a.title, alias = _a.alias;
554
+ // TODO cast time with/without timezone to custom object
555
+ if (title === undefined) {
556
+ if (alias !== undefined) {
557
+ tokens.push("\"".concat(alias, "\".") + "\"".concat(column.substring((alias + '_').length), "\"") + " AS \"".concat(column, "\""));
558
+ }
559
+ else {
560
+ tokens.push("\"".concat(column, "\""));
561
+ }
562
+ }
563
+ else {
564
+ tokens.push((alias !== undefined ? "\"".concat(alias, "\".") : '') + "\"".concat(title, "\"") + " AS \"".concat(column, "\""));
565
+ }
566
+ }
567
+ }
568
+ if (tokens.length === 0) {
569
+ return (0, never_catch_1.err)('<returning> -> empty');
570
+ }
571
+ return (0, never_catch_1.ok)(partialQuery(tokens.join(', '), params));
572
+ };
573
+ exports.resolveReturning = resolveReturning;
574
+ /*
575
+ ** currently all errors are handled with types and no dynamic check is required.
576
+ ** errors return only when ignore is false and an expression needs ignorance.
577
+ ** so, some errors written in function, but they will never be returned.
578
+ ** e.g.
579
+ ** if (e1Result.value.text === '') {
580
+ ** return ignore ? ok(partialQuery()) : err(`<${toDescription(expression[0])}> -> neutral`);
581
+ ** }
582
+ * if result is neutral then ignore is true, so error in this example will never be returned.
583
+ * but they exist in case new errors with dynamic check added.
584
+ */
585
+ var resolveExpression = function (expression, paramsStart, ignore) {
586
+ if (ignore === void 0) { ignore = false; }
587
+ // primitive expression
588
+ if (expression === undefined) {
589
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)('undefined');
590
+ }
591
+ if (expression === null ||
592
+ typeof expression === 'boolean' ||
593
+ expression instanceof decimal_js_1.default ||
594
+ expression instanceof Date ||
595
+ typeof expression === 'number' ||
596
+ typeof expression === 'bigint') {
597
+ return (0, never_catch_1.ok)(partialQuery("".concat(U_1.U.stringify(expression, true))));
598
+ }
599
+ if (typeof expression === 'string') {
600
+ return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++), [U_1.U.stringify(expression, false)]));
601
+ }
602
+ if (!(Array.isArray(expression) && ReservedExpressionKeys.includes(expression[0]))) {
603
+ return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++, "::jsonb"), [U_1.U.stringify(expression, false)]));
604
+ }
605
+ // wrapped expression
606
+ var tokens = [];
607
+ var params = [];
608
+ var e1Result, e2Result, e3Result;
609
+ switch (expression[0]) {
610
+ case 'val':
611
+ if (expression[1] === undefined) {
612
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)('val'), "> -> undefined"));
613
+ }
614
+ params.push(U_1.U.stringify(expression[1], false));
615
+ return (0, never_catch_1.ok)(partialQuery("$".concat(paramsStart++), params));
616
+ case '=n':
617
+ case '!=n':
618
+ case '=t':
619
+ case '=f':
620
+ case 'not':
621
+ e1Result = resolveExpression(expression[1], paramsStart, ignore);
622
+ if (!e1Result.ok) {
623
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> ").concat(e1Result.error));
624
+ }
625
+ if (e1Result.value.text === '') {
626
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> neutral"));
627
+ }
628
+ params.push.apply(params, e1Result.value.params);
629
+ paramsStart += e1Result.value.params.length;
630
+ switch (expression[0]) {
631
+ case '=n':
632
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IS NULL"), params));
633
+ case '!=n':
634
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IS NOT NULL"), params));
635
+ case '=t':
636
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text), params));
637
+ case '=f':
638
+ case 'not':
639
+ return (0, never_catch_1.ok)(partialQuery("NOT ".concat(e1Result.value.text), params));
640
+ }
641
+ case '+':
642
+ case '-':
643
+ case '*':
644
+ case '/':
645
+ case '||':
646
+ case 'and':
647
+ case 'or':
648
+ case '**':
649
+ if (expression[1] === undefined) {
650
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> undefined"));
651
+ }
652
+ for (var _i = 0, _a = expression[1]; _i < _a.length; _i++) {
653
+ var v1 = _a[_i];
654
+ var v1Result = resolveExpression(v1, paramsStart, ignore);
655
+ if (!v1Result.ok) {
656
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[").concat(expression[1].indexOf(v1), "] -> ").concat(v1Result.error));
657
+ }
658
+ if (v1Result.value.text === '') {
659
+ if (ignore) {
660
+ continue;
661
+ }
662
+ else {
663
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[").concat(expression[1].indexOf(v1), "] -> neutral"));
664
+ }
665
+ }
666
+ params.push.apply(params, v1Result.value.params);
667
+ paramsStart += v1Result.value.params.length;
668
+ tokens.push(v1Result.value.text);
669
+ }
670
+ switch (tokens.length) {
671
+ case 0:
672
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> no operands given"));
673
+ case 1:
674
+ return (0, never_catch_1.ok)(partialQuery(tokens[0], params));
675
+ default:
676
+ switch (expression[0]) {
677
+ case '+':
678
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' + '), " )"), params));
679
+ case '-':
680
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' - '), " )"), params));
681
+ case '*':
682
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' * '), " )"), params));
683
+ case '/':
684
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' / '), " )"), params));
685
+ case '||':
686
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' || '), " )"), params));
687
+ case 'and':
688
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' AND '), " )"), params));
689
+ case 'or':
690
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(tokens.join(' OR '), " )"), params));
691
+ case '**':
692
+ var tmp = tokens.pop();
693
+ tokens.splice(0, 0, 'a');
694
+ return (0, never_catch_1.ok)({
695
+ text: tokens.join(', power( ').substring(3) + ', ' + tmp + ' )'.repeat(tokens.length - 1),
696
+ params: params
697
+ });
698
+ }
699
+ }
700
+ case 'fun':
701
+ if (expression[1] === undefined) {
702
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[name] -> undefined"));
703
+ }
704
+ if (expression[2] === undefined) {
705
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters] -> undefined"));
706
+ }
707
+ for (var _b = 0, _c = expression[2]; _b < _c.length; _b++) {
708
+ var v2 = _c[_b];
709
+ var v2Result = resolveExpression(v2, paramsStart, ignore);
710
+ if (!v2Result.ok) {
711
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters][").concat(expression[2].indexOf(v2), "] -> ").concat(v2Result.error));
712
+ }
713
+ if (v2Result.value.text === '') {
714
+ return ignore
715
+ ? (0, never_catch_1.ok)(partialQuery())
716
+ : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[parameters][").concat(expression[2].indexOf(v2), "] -> neutral"));
717
+ }
718
+ params.push.apply(params, v2Result.value.params);
719
+ paramsStart += v2Result.value.params.length;
720
+ tokens.push(v2Result.value.text);
721
+ }
722
+ return (0, never_catch_1.ok)(partialQuery("".concat(expression[1], "( ").concat(tokens.join(', '), " )").concat(expression[3]), params));
723
+ case 'swt':
724
+ var cases = expression[1];
725
+ var otherwise = expression[2];
726
+ if (cases === undefined) {
727
+ if (!ignore) {
728
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases] -> undefined"));
729
+ }
730
+ }
731
+ else {
732
+ for (var _d = 0, cases_1 = cases; _d < cases_1.length; _d++) {
733
+ var caseElement = cases_1[_d];
734
+ if (caseElement === undefined) {
735
+ if (ignore) {
736
+ continue;
737
+ }
738
+ else {
739
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "] -> undefined"));
740
+ }
741
+ }
742
+ var whenResult = resolveExpression(caseElement.when, paramsStart, ignore);
743
+ if (!whenResult.ok) {
744
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][when] -> ").concat(whenResult.error));
745
+ }
746
+ if (whenResult.value.text === '') {
747
+ if (ignore) {
748
+ continue;
749
+ }
750
+ else {
751
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][when] -> neutral"));
752
+ }
753
+ }
754
+ params.push.apply(params, whenResult.value.params);
755
+ paramsStart += whenResult.value.params.length;
756
+ var thenResult = resolveExpression(caseElement.then, paramsStart, ignore);
757
+ if (!thenResult.ok) {
758
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][then] -> ").concat(thenResult.error));
759
+ }
760
+ if (thenResult.value.text === '') {
761
+ if (ignore) {
762
+ continue;
763
+ }
764
+ else {
765
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases][").concat(cases.indexOf(caseElement), "][then] -> neutral"));
766
+ }
767
+ }
768
+ params.push.apply(params, thenResult.value.params);
769
+ paramsStart += thenResult.value.params.length;
770
+ if (tokens.length === 0) {
771
+ tokens.push('CASE');
772
+ }
773
+ tokens.push("WHEN ".concat(whenResult.value.text, " THEN ").concat(thenResult.value.text));
774
+ }
775
+ }
776
+ if (tokens.length === 0 && !ignore) {
777
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[cases] -> empty"));
778
+ }
779
+ if (otherwise === undefined) {
780
+ if (tokens.length === 0) {
781
+ return (0, never_catch_1.ok)(partialQuery());
782
+ }
783
+ else {
784
+ tokens.push('END');
785
+ }
786
+ }
787
+ else {
788
+ var isOtherwiseNeutral = false;
789
+ var otherwiseResult = resolveExpression(otherwise, paramsStart, ignore);
790
+ if (!otherwiseResult.ok) {
791
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[otherwise] -> ").concat(otherwiseResult.error));
792
+ }
793
+ if (otherwiseResult.value.text === '') {
794
+ if (ignore) {
795
+ isOtherwiseNeutral = true;
796
+ }
797
+ else {
798
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[otherwise] -> neutral"));
799
+ }
800
+ }
801
+ params.push.apply(params, otherwiseResult.value.params);
802
+ paramsStart += otherwiseResult.value.params.length;
803
+ if (tokens.length === 0) {
804
+ if (isOtherwiseNeutral) {
805
+ return (0, never_catch_1.ok)(partialQuery());
806
+ }
807
+ else {
808
+ tokens.push(otherwiseResult.value.text);
809
+ }
810
+ }
811
+ else {
812
+ if (!isOtherwiseNeutral) {
813
+ tokens.push('ELSE', otherwiseResult.value.text);
814
+ }
815
+ tokens.push('END');
816
+ }
817
+ }
818
+ return (0, never_catch_1.ok)(partialQuery(tokens.join(' '), params));
819
+ case 'col':
820
+ case 'raw':
821
+ return (0, never_catch_1.ok)(partialQuery("".concat(expression[1])));
822
+ case 'qry':
823
+ case 'exists':
824
+ var subQueryDataResult = expression[1].getData(params);
825
+ if (!subQueryDataResult.ok) {
826
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), "> -> ").concat(subQueryDataResult.error));
827
+ }
828
+ paramsStart += subQueryDataResult.value.params.length;
829
+ switch (expression[0]) {
830
+ case 'qry':
831
+ return (0, never_catch_1.ok)(partialQuery("( ".concat(subQueryDataResult.value.sql, " )"), params));
832
+ case 'exists':
833
+ return (0, never_catch_1.ok)(partialQuery("EXISTS ( ".concat(subQueryDataResult.value.sql, " )"), params));
834
+ }
835
+ case '=':
836
+ case '!=':
837
+ case '>':
838
+ case '>=':
839
+ case '<':
840
+ case '<=':
841
+ case 'lk':
842
+ case '@>':
843
+ case '<@':
844
+ case '?':
845
+ case 'j-':
846
+ e1Result = resolveExpression(expression[1], paramsStart, ignore);
847
+ if (!e1Result.ok) {
848
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
849
+ }
850
+ if (e1Result.value.text === '') {
851
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
852
+ }
853
+ params.push.apply(params, e1Result.value.params);
854
+ paramsStart += e1Result.value.params.length;
855
+ e2Result = resolveExpression(expression[2], paramsStart, ignore);
856
+ if (!e2Result.ok) {
857
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> ").concat(e2Result.error));
858
+ }
859
+ if (e2Result.value.text === '') {
860
+ return ignore
861
+ ? (0, never_catch_1.ok)(partialQuery())
862
+ : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> netural"));
863
+ }
864
+ params.push.apply(params, e2Result.value.params);
865
+ paramsStart += e2Result.value.params.length;
866
+ switch (expression[0]) {
867
+ case '=':
868
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " = ").concat(e2Result.value.text), params));
869
+ case '!=':
870
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <> ").concat(e2Result.value.text), params));
871
+ case '>':
872
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " > ").concat(e2Result.value.text), params));
873
+ case '>=':
874
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " >= ").concat(e2Result.value.text), params));
875
+ case '<':
876
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " < ").concat(e2Result.value.text), params));
877
+ case '<=':
878
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <= ").concat(e2Result.value.text), params));
879
+ case 'lk':
880
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(e2Result.value.text), params));
881
+ case '@>':
882
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " @> ").concat(e2Result.value.text), params));
883
+ case '<@':
884
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <@ ").concat(e2Result.value.text), params));
885
+ case '?':
886
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(e2Result.value.text), params));
887
+ case 'j-':
888
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ").concat(e2Result.value.text), params));
889
+ }
890
+ case 'in':
891
+ case 'nin':
892
+ case 'lka':
893
+ case 'lks':
894
+ case '?|':
895
+ case '?&':
896
+ case 'j-a':
897
+ e1Result = resolveExpression(expression[1], paramsStart, ignore);
898
+ if (!e1Result.ok) {
899
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
900
+ }
901
+ if (e1Result.value.text === '') {
902
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
903
+ }
904
+ params.push.apply(params, e1Result.value.params);
905
+ paramsStart += e1Result.value.params.length;
906
+ if (expression[2] === undefined) {
907
+ return ignore
908
+ ? (0, never_catch_1.ok)(partialQuery())
909
+ : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> undefined"));
910
+ }
911
+ for (var _e = 0, _f = expression[2]; _e < _f.length; _e++) {
912
+ var v2 = _f[_e];
913
+ var v2Result = resolveExpression(v2, paramsStart, ignore);
914
+ if (!v2Result.ok) {
915
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand][").concat(expression[2].indexOf(v2), "] -> ").concat(v2Result.error));
916
+ }
917
+ if (v2Result.value.text === '') {
918
+ if (ignore) {
919
+ continue;
920
+ }
921
+ else {
922
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand][").concat(expression[1].indexOf(v2), "] -> neutral"));
923
+ }
924
+ }
925
+ params.push.apply(params, v2Result.value.params);
926
+ paramsStart += v2Result.value.params.length;
927
+ tokens.push(v2Result.value.text);
928
+ }
929
+ switch (tokens.length) {
930
+ case 0:
931
+ return ignore
932
+ ? (0, never_catch_1.ok)(partialQuery())
933
+ : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> empty"));
934
+ case 1:
935
+ switch (expression[0]) {
936
+ case 'in':
937
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " = ").concat(tokens[0]), params));
938
+ case 'nin':
939
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " <> ").concat(tokens[0]), params));
940
+ case 'lka':
941
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(tokens[0]), params));
942
+ case 'lks':
943
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ").concat(tokens[0]), params));
944
+ case '?|':
945
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(tokens[0]), params));
946
+ case '?&':
947
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ? ").concat(tokens[0]), params));
948
+ case 'j-a':
949
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ").concat(tokens[0]), params));
950
+ }
951
+ default:
952
+ switch (expression[0]) {
953
+ case 'in':
954
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " IN ( ").concat(tokens.join(', '), " )"), params));
955
+ case 'nin':
956
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " NOT IN ( ").concat(tokens.join(', '), " )"), params));
957
+ case 'lka':
958
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE ALL( ARRAY[ ").concat(tokens.join(', '), " ] )"), params));
959
+ case 'lks':
960
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " LIKE SOME( ARRAY[ ").concat(tokens.join(', '), " ] )"), params));
961
+ case '?|':
962
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ?| ARRAY[ ").concat(tokens.join(', '), " ]"), params));
963
+ case '?&':
964
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " ?& ARRAY[ ").concat(tokens.join(', '), " ]"), params));
965
+ case 'j-a':
966
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " - ARRAY[ ").concat(tokens.join(', '), " ]"), params));
967
+ }
968
+ }
969
+ case 'bt':
970
+ e1Result = resolveExpression(expression[1], paramsStart, ignore);
971
+ if (!e1Result.ok) {
972
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> ").concat(e1Result.error));
973
+ }
974
+ if (e1Result.value.text === '') {
975
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[first operand] -> netural"));
976
+ }
977
+ params.push.apply(params, e1Result.value.params);
978
+ paramsStart += e1Result.value.params.length;
979
+ e2Result = resolveExpression(expression[2], paramsStart, ignore);
980
+ if (!e2Result.ok) {
981
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> ").concat(e2Result.error));
982
+ }
983
+ if (e2Result.value.text === '') {
984
+ return ignore
985
+ ? (0, never_catch_1.ok)(partialQuery())
986
+ : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[second operand] -> netural"));
987
+ }
988
+ params.push.apply(params, e2Result.value.params);
989
+ paramsStart += e2Result.value.params.length;
990
+ e3Result = resolveExpression(expression[3], paramsStart, ignore);
991
+ if (!e3Result.ok) {
992
+ return (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[third operand] -> ").concat(e3Result.error));
993
+ }
994
+ if (e3Result.value.text === '') {
995
+ return ignore ? (0, never_catch_1.ok)(partialQuery()) : (0, never_catch_1.err)("<".concat((0, dictionary_1.toReservedExpressionKeyDescription)(expression[0]), ">[third operand] -> netural"));
996
+ }
997
+ params.push.apply(params, e3Result.value.params);
998
+ paramsStart += e3Result.value.params.length;
999
+ return (0, never_catch_1.ok)(partialQuery("".concat(e1Result.value.text, " BETWEEN ").concat(e2Result.value.text, " AND ").concat(e3Result.value.text), params));
1000
+ default:
1001
+ throw 'unexpected error. expect first element to be reserved key.';
1002
+ }
1003
+ };
1004
+ exports.resolveExpression = resolveExpression;
1005
+ var getTableDataOfJoinSelectColumn = function (tablesData, column) {
1006
+ var splitColumn = column.split('_');
1007
+ if (splitColumn.length < 2) {
1008
+ throw "no separator";
1009
+ }
1010
+ // in case alias or column key have "_". iterate on all of them until a match.
1011
+ var tableAliasUntilIndex = 1;
1012
+ while (true) {
1013
+ var tableAlias = splitColumn.slice(0, tableAliasUntilIndex).join('_');
1014
+ for (var _i = 0, tablesData_1 = tablesData; _i < tablesData_1.length; _i++) {
1015
+ var tableData = tablesData_1[_i];
1016
+ if (tableData.alias === tableAlias &&
1017
+ tableData.table.columns[splitColumn.slice(tableAliasUntilIndex).join('_')] !== undefined) {
1018
+ return tableData;
1019
+ }
1020
+ }
1021
+ if (splitColumn.length > tableAliasUntilIndex + 1) {
1022
+ tableAliasUntilIndex++;
1023
+ }
1024
+ else {
1025
+ throw "column not found";
1026
+ }
1027
+ }
1028
+ };
1029
+ exports.getTableDataOfJoinSelectColumn = getTableDataOfJoinSelectColumn;
1030
+ var resolveColumn = function (table, column, full, alias) {
1031
+ var _a;
1032
+ if (full === void 0) { full = true; }
1033
+ var prefix;
1034
+ if (full) {
1035
+ if (alias !== undefined) {
1036
+ prefix = "\"".concat(alias, "\".");
1037
+ }
1038
+ else {
1039
+ prefix = "\"".concat(table.schema, "\".\"").concat(table.title, "\".");
1040
+ }
1041
+ }
1042
+ else {
1043
+ prefix = '';
1044
+ }
1045
+ return prefix + "\"".concat((_a = table.columns[column].title) !== null && _a !== void 0 ? _a : column, "\"");
1046
+ };
1047
+ exports.resolveColumn = resolveColumn;
1048
+ var partialQuery = function (text, params) {
1049
+ if (text === void 0) { text = ''; }
1050
+ if (params === void 0) { params = []; }
1051
+ return ({ text: text, params: params });
1052
+ };
1053
+ exports.partialQuery = partialQuery;
1008
1054
  //# sourceMappingURL=entity.js.map