@digitalwalletcorp/sql-builder 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -0
- package/package.json +1 -1
- package/src/abstract-syntax-tree.ts +334 -0
- package/src/common.ts +19 -0
- package/src/sql-builder.ts +57 -79
package/README.md
CHANGED
|
@@ -234,6 +234,49 @@ Parameters: [ 123, 'project_a', 'project_b' ]
|
|
|
234
234
|
| Bind Variable | `/*variable*/` | Binds a value from the `entity`. It automatically formats values: strings are quoted (`'value'`), numbers are left as is (`123`), and arrays are turned into comma-separated lists in parentheses (`('a','b',123)`). |
|
|
235
235
|
| END | `/*END*/` | Marks the end of an `IF`, `BEGIN`, or `FOR` block. |
|
|
236
236
|
|
|
237
|
+
---
|
|
238
|
+
### 💡 Supported Property Paths
|
|
239
|
+
|
|
240
|
+
For `/*variable*/` (Bind Variable) tags and the `collection` part of `/*FOR item:collection*/` tags, you can specify a path to access properties within the `entity` object.
|
|
241
|
+
|
|
242
|
+
* **Syntax:** `propertyName`, `nested.property`.
|
|
243
|
+
* **Supported:** Direct property access (e.g., `user.id`, `order.items.length`).
|
|
244
|
+
* **Unsupported:** Function calls (e.g., `user.name.trim()`, `order.items.map(...)`) or any complex JavaScript expressions.
|
|
245
|
+
|
|
246
|
+
**Example:**
|
|
247
|
+
|
|
248
|
+
* **Valid Expression:** `/*userId*/` (accesses `entity.userId` as simple property)
|
|
249
|
+
* **Valid Expression:** `/*items*/` (accesses `entity.items` as array)
|
|
250
|
+
* **Invalid Expression:** `/*userId.slice(0, 10)*/` (Function call)
|
|
251
|
+
* **Invalid Expression:** `/*items.filter(...)*/` (Function call)
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
### 💡 Supported `IF` Condition Syntax
|
|
256
|
+
|
|
257
|
+
The `condition` inside an `/*IF ...*/` tag is evaluated as a JavaScript expression against the `entity` object. To ensure security and maintain simplicity, only a **limited subset of JavaScript syntax** is supported.
|
|
258
|
+
|
|
259
|
+
**Supported Operations:**
|
|
260
|
+
|
|
261
|
+
* **Entity Property Access:** You can reference properties from the `entity` object (e.g., `propertyName`, `nested.property`).
|
|
262
|
+
* **Object Property Access:** Access the `length`, `size` or other property of object (e.g., `String.length`, `Array.length`, `Set.size`, `Map.size`).
|
|
263
|
+
* **Comparison Operators:** `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`
|
|
264
|
+
* **Logical Operators:** `&&` (AND), `||` (OR), `!` (NOT)
|
|
265
|
+
* **Literals:** Numbers (`123`, `0.5`), Booleans (`true`, `false`), `null`, `undefined`, and string literals (`'value'`, `"value"`).
|
|
266
|
+
* **Parentheses:** `()` for grouping expressions.
|
|
267
|
+
|
|
268
|
+
**Unsupported Operations (and will cause an error if used):**
|
|
269
|
+
|
|
270
|
+
* **Function Calls:** You **cannot** call functions on properties (e.g., `user.name.startsWith('A')`, `array.map(...)`).
|
|
271
|
+
|
|
272
|
+
**Example:**
|
|
273
|
+
|
|
274
|
+
* **Valid Condition:** `user.age > 18 && user.name.length > 0 && user.id != null`
|
|
275
|
+
* **Invalid Condition:** `user.name.startsWith('A')` (Function call)
|
|
276
|
+
* **Invalid Condition:** `user.role = 'admin'` (Assignment)
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
237
280
|
## 📜 License
|
|
238
281
|
|
|
239
282
|
This project is licensed under the MIT License. See the [LICENSE](https://opensource.org/licenses/MIT) file for details.
|
package/package.json
CHANGED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import * as common from './common';
|
|
2
|
+
|
|
3
|
+
type Token =
|
|
4
|
+
| { type: 'IDENTIFIER'; value: string } // 例: param, length
|
|
5
|
+
| { type: 'OPERATOR'; value: string } // 例: >, &&, ===, !=
|
|
6
|
+
| { type: 'NUMBER'; value: number } // 例: 100.123
|
|
7
|
+
| { type: 'BOOLEAN'; value: boolean } // 例: true, false
|
|
8
|
+
| { type: 'NULL' }
|
|
9
|
+
| { type: 'UNDEFINED' }
|
|
10
|
+
| { type: 'STRING'; value: string } // 例: 'abc'
|
|
11
|
+
| { type: 'PARENTHESIS'; value: '(' | ')' };
|
|
12
|
+
|
|
13
|
+
type RpnToken = Token | { type: 'MEMBER_ACCESS_PART', value: string };
|
|
14
|
+
|
|
15
|
+
// 演算子の優先順位と結合性 (より長い演算子を先に定義)
|
|
16
|
+
const PRECEDENCE: {
|
|
17
|
+
[op: string]: {
|
|
18
|
+
precedence: number;
|
|
19
|
+
associativity: 'left' | 'right'
|
|
20
|
+
}
|
|
21
|
+
} = {
|
|
22
|
+
'||': { precedence: 1, associativity: 'left' },
|
|
23
|
+
'&&': { precedence: 2, associativity: 'left' },
|
|
24
|
+
'==': { precedence: 3, associativity: 'left' },
|
|
25
|
+
'!=': { precedence: 3, associativity: 'left' },
|
|
26
|
+
'===': { precedence: 3, associativity: 'left' },
|
|
27
|
+
'!==': { precedence: 3, associativity: 'left' },
|
|
28
|
+
'<': { precedence: 4, associativity: 'left' },
|
|
29
|
+
'<=': { precedence: 4, associativity: 'left' },
|
|
30
|
+
'>': { precedence: 4, associativity: 'left' },
|
|
31
|
+
'>=': { precedence: 4, associativity: 'left' },
|
|
32
|
+
'!': { precedence: 5, associativity: 'right' } // 単項演算子は高優先度
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* SQLBuilderの条件文(*IF*)で指定された条件文字列を解析するためのAST。
|
|
37
|
+
* JavaScriptの文法をカバーするものではなく、SQLBuilderで利用可能な限定的な構文のみサポートする。
|
|
38
|
+
*/
|
|
39
|
+
export class AbstractSyntaxTree {
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 与えられた条件文字列を構文解析し、entityに対する条件として成立するか評価する
|
|
43
|
+
*
|
|
44
|
+
* @param {string} condition "params != null && params.length > 10" のような条件
|
|
45
|
+
* @param {Record<string, any>} entity
|
|
46
|
+
* @returns {boolean}
|
|
47
|
+
*/
|
|
48
|
+
public evaluateCondition(condition: string, entity: Record<string, any>): boolean {
|
|
49
|
+
try {
|
|
50
|
+
const tokens = this.tokenize(condition); // トークン化
|
|
51
|
+
const rpnTokens = this.shuntingYard(tokens); // RPN変換
|
|
52
|
+
const result = this.evaluateRpn(rpnTokens, entity); // 評価
|
|
53
|
+
return result;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
console.warn('Error evaluating condition:', condition, entity, error);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 与えられた条件文字列をトークンに分割する
|
|
62
|
+
*
|
|
63
|
+
* @param {string} condition
|
|
64
|
+
* @returns {Token[]}
|
|
65
|
+
*/
|
|
66
|
+
public tokenize(condition: string): Token[] {
|
|
67
|
+
const tokens: Token[] = [];
|
|
68
|
+
let i = 0;
|
|
69
|
+
while (i < condition.length) {
|
|
70
|
+
const char = condition[i];
|
|
71
|
+
// 空白をスキップ
|
|
72
|
+
if (/\s/.test(char)) {
|
|
73
|
+
i++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 演算子 (長いものからチェック)
|
|
78
|
+
// 3桁定義
|
|
79
|
+
const chunk3 = condition.substring(i, i + 3);
|
|
80
|
+
switch (chunk3) {
|
|
81
|
+
case '===':
|
|
82
|
+
case '!==':
|
|
83
|
+
tokens.push({ type: 'OPERATOR', value: chunk3 });
|
|
84
|
+
i += 3;
|
|
85
|
+
continue;
|
|
86
|
+
default:
|
|
87
|
+
}
|
|
88
|
+
// 2桁定義
|
|
89
|
+
const chunk2 = condition.substring(i, i + 2);
|
|
90
|
+
switch (chunk2) {
|
|
91
|
+
case '==':
|
|
92
|
+
case '!=':
|
|
93
|
+
case '<=':
|
|
94
|
+
case '>=':
|
|
95
|
+
case '&&':
|
|
96
|
+
case '||':
|
|
97
|
+
tokens.push({ type: 'OPERATOR', value: chunk2 });
|
|
98
|
+
i += 2;
|
|
99
|
+
continue;
|
|
100
|
+
default:
|
|
101
|
+
}
|
|
102
|
+
// 1桁定義
|
|
103
|
+
const chunk1 = char;
|
|
104
|
+
switch (chunk1) {
|
|
105
|
+
case '>':
|
|
106
|
+
case '<':
|
|
107
|
+
case '!':
|
|
108
|
+
case '=':
|
|
109
|
+
tokens.push({ type: 'OPERATOR', value: chunk1 });
|
|
110
|
+
i += 1;
|
|
111
|
+
continue;
|
|
112
|
+
// case '.':
|
|
113
|
+
// tokens.push({ type: 'IDENTIFIER', value: chunk1 }); // '.'も識別子の一部として扱う
|
|
114
|
+
// i += 1;
|
|
115
|
+
// continue;
|
|
116
|
+
case '(':
|
|
117
|
+
case ')':
|
|
118
|
+
tokens.push({ type: 'PARENTHESIS', value: chunk1 });
|
|
119
|
+
i += 1;
|
|
120
|
+
continue;
|
|
121
|
+
default:
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const reststring = condition.substring(i); // 現在のインデックスから末尾までの文字列
|
|
125
|
+
// 数値リテラル
|
|
126
|
+
const numMatch = reststring.match(/^-?\d+(\.\d+)?/);
|
|
127
|
+
if (numMatch) {
|
|
128
|
+
tokens.push({ type: 'NUMBER', value: parseFloat(numMatch[0]) });
|
|
129
|
+
i += numMatch[0].length;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 文字列リテラル
|
|
134
|
+
switch (chunk1) {
|
|
135
|
+
case '\'':
|
|
136
|
+
case '"':
|
|
137
|
+
const quote = chunk1;
|
|
138
|
+
let j = i + 1;
|
|
139
|
+
let strValue = '';
|
|
140
|
+
while (j < condition.length && condition[j] !== quote) {
|
|
141
|
+
// エスケープ文字の処理 (\' や \\) は必要に応じて追加
|
|
142
|
+
if (condition[j] === '\\' && j + 1 < condition.length) {
|
|
143
|
+
strValue += condition[j+1];
|
|
144
|
+
j += 2;
|
|
145
|
+
} else {
|
|
146
|
+
strValue += condition[j];
|
|
147
|
+
j++;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (condition[j] === quote) {
|
|
151
|
+
tokens.push({ type: 'STRING', value: strValue });
|
|
152
|
+
i = j + 1;
|
|
153
|
+
continue;
|
|
154
|
+
} else {
|
|
155
|
+
// クォートが閉じられていない
|
|
156
|
+
throw new Error('Unterminated string literal');
|
|
157
|
+
}
|
|
158
|
+
default:
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 識別子 (変数名, true, false, null, undefined, length)
|
|
162
|
+
const identMatch = reststring.match(/^[a-zA-Z_][a-zA-Z0-9_.]*/); // ドットを含む識別子
|
|
163
|
+
if (identMatch) {
|
|
164
|
+
const ident = identMatch[0];
|
|
165
|
+
switch (ident) {
|
|
166
|
+
case 'true':
|
|
167
|
+
tokens.push({ type: 'BOOLEAN', value: true });
|
|
168
|
+
break;
|
|
169
|
+
case 'false':
|
|
170
|
+
tokens.push({ type: 'BOOLEAN', value: false });
|
|
171
|
+
break;
|
|
172
|
+
case 'null':
|
|
173
|
+
tokens.push({ type: 'NULL' });
|
|
174
|
+
break;
|
|
175
|
+
case 'undefined':
|
|
176
|
+
tokens.push({ type: 'UNDEFINED' });
|
|
177
|
+
break;
|
|
178
|
+
default:
|
|
179
|
+
tokens.push({ type: 'IDENTIFIER', value: ident }); // プロパティ名
|
|
180
|
+
}
|
|
181
|
+
i += ident.length;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 未知の文字
|
|
186
|
+
throw new Error(`Unexpected character in condition: ${char} at index ${i}`);
|
|
187
|
+
}
|
|
188
|
+
return tokens;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Shunting Yardアルゴリズムで構文を逆ポーランド記法(Reverse Polish Notation)に変換する
|
|
193
|
+
*
|
|
194
|
+
* @param {Token[]} tokens
|
|
195
|
+
* @returns {RpnToken[]}
|
|
196
|
+
*/
|
|
197
|
+
private shuntingYard(tokens: Token[]): RpnToken[] {
|
|
198
|
+
const output: RpnToken[] = [];
|
|
199
|
+
const operatorStack: Token[] = [];
|
|
200
|
+
|
|
201
|
+
for (const token of tokens) {
|
|
202
|
+
const type = token.type;
|
|
203
|
+
switch (type) {
|
|
204
|
+
case 'NUMBER':
|
|
205
|
+
case 'BOOLEAN':
|
|
206
|
+
case 'NULL':
|
|
207
|
+
case 'UNDEFINED':
|
|
208
|
+
case 'STRING':
|
|
209
|
+
output.push(token);
|
|
210
|
+
break;
|
|
211
|
+
case 'IDENTIFIER':
|
|
212
|
+
// 識別子(プロパティパスの可能性)をそのまま出力
|
|
213
|
+
output.push(token);
|
|
214
|
+
break;
|
|
215
|
+
case 'OPERATOR':
|
|
216
|
+
const op1 = token;
|
|
217
|
+
while (operatorStack.length) {
|
|
218
|
+
// TODO: 型キャストが必要になるので、Geniericsを強化する
|
|
219
|
+
const op2 = operatorStack[operatorStack.length - 1] as { type: string, value: string };
|
|
220
|
+
|
|
221
|
+
// 括弧内は処理しない
|
|
222
|
+
if (op2.value === '(') {
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// 優先順位のルールに従う
|
|
227
|
+
if (
|
|
228
|
+
(PRECEDENCE[op1.value].associativity === 'left' && PRECEDENCE[op1.value].precedence <= PRECEDENCE[op2.value].precedence)
|
|
229
|
+
// ||
|
|
230
|
+
// (PRECEDENCE[op1.value].associativity === 'right' && PRECEDENCE[op1.value].precedence < PRECEDENCE[op2.value].precedence)
|
|
231
|
+
) {
|
|
232
|
+
output.push(operatorStack.pop()!);
|
|
233
|
+
} else {
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
operatorStack.push(op1);
|
|
238
|
+
break;
|
|
239
|
+
case 'PARENTHESIS':
|
|
240
|
+
if (token.value === '(') {
|
|
241
|
+
operatorStack.push(token);
|
|
242
|
+
} else if (token.value === ')') {
|
|
243
|
+
let foundLeftParen = false;
|
|
244
|
+
while (operatorStack.length > 0) {
|
|
245
|
+
const op = operatorStack.pop()!;
|
|
246
|
+
if ('value' in op && op.value === '(') {
|
|
247
|
+
foundLeftParen = true;
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
output.push(op);
|
|
251
|
+
}
|
|
252
|
+
if (!foundLeftParen) {
|
|
253
|
+
throw new Error('Mismatched parentheses');
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
break;
|
|
257
|
+
default:
|
|
258
|
+
throw new Error(`Unexpected token type: ${type}`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
while (operatorStack.length) {
|
|
263
|
+
const op = operatorStack.pop()!;
|
|
264
|
+
if ('value' in op && (op.value === '(' || op.value === ')')) {
|
|
265
|
+
throw new Error('Mismatched parentheses');
|
|
266
|
+
}
|
|
267
|
+
output.push(op);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return output;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 逆ポーランド記法(Reverse Polish Notation)のトークンを評価する
|
|
275
|
+
*
|
|
276
|
+
* @param {RpnToken[]} rpnTokens
|
|
277
|
+
* @param {Record<string, any>} entity
|
|
278
|
+
* @returns {boolean}
|
|
279
|
+
*/
|
|
280
|
+
private evaluateRpn(rpnTokens: RpnToken[], entity: Record<string, any>): boolean {
|
|
281
|
+
const stack: any[] = [];
|
|
282
|
+
|
|
283
|
+
for (const token of rpnTokens) {
|
|
284
|
+
const type = token.type;
|
|
285
|
+
switch (type) {
|
|
286
|
+
case 'NUMBER':
|
|
287
|
+
case 'BOOLEAN':
|
|
288
|
+
case 'NULL':
|
|
289
|
+
case 'UNDEFINED':
|
|
290
|
+
case 'STRING':
|
|
291
|
+
if ('value' in token) {
|
|
292
|
+
stack.push(token.value);
|
|
293
|
+
}
|
|
294
|
+
break;
|
|
295
|
+
case 'IDENTIFIER':
|
|
296
|
+
stack.push(common.getProperty(entity, token.value));
|
|
297
|
+
break;
|
|
298
|
+
case 'OPERATOR':
|
|
299
|
+
// 単項演算子 '!'
|
|
300
|
+
if (token.value === '!') {
|
|
301
|
+
const operand = stack.pop();
|
|
302
|
+
stack.push(!operand);
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// 二項演算子
|
|
307
|
+
const right = stack.pop();
|
|
308
|
+
const left = stack.pop();
|
|
309
|
+
|
|
310
|
+
switch (token.value) {
|
|
311
|
+
case '==': stack.push(left == right); break;
|
|
312
|
+
case '!=': stack.push(left != right); break;
|
|
313
|
+
case '===': stack.push(left === right); break;
|
|
314
|
+
case '!==': stack.push(left !== right); break;
|
|
315
|
+
case '<': stack.push(left < right); break;
|
|
316
|
+
case '<=': stack.push(left <= right); break;
|
|
317
|
+
case '>': stack.push(left > right); break;
|
|
318
|
+
case '>=': stack.push(left >= right); break;
|
|
319
|
+
case '&&': stack.push(left && right); break;
|
|
320
|
+
case '||': stack.push(left || right); break;
|
|
321
|
+
default: throw new Error(`Unknown operator: ${token.value}`);
|
|
322
|
+
}
|
|
323
|
+
break;
|
|
324
|
+
default:
|
|
325
|
+
throw new Error(`Unexpected token type in RPN: ${type}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (stack.length !== 1) {
|
|
330
|
+
throw new Error('Invalid expression');
|
|
331
|
+
}
|
|
332
|
+
return !!stack[0];
|
|
333
|
+
}
|
|
334
|
+
}
|
package/src/common.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* entityで指定したオブジェクトからドットで連結されたプロパティキーに該当する値を取得する
|
|
3
|
+
*
|
|
4
|
+
* @param {Record<string, any>} entity
|
|
5
|
+
* @param {string} property
|
|
6
|
+
* @returns {any}
|
|
7
|
+
*/
|
|
8
|
+
export function getProperty(entity: Record<string, any>, property: string): any {
|
|
9
|
+
const propertyPath = property.split('.');
|
|
10
|
+
let value = entity;
|
|
11
|
+
for (const prop of propertyPath) {
|
|
12
|
+
if (value && value.hasOwnProperty(prop)) {
|
|
13
|
+
value = value[prop];
|
|
14
|
+
} else {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
package/src/sql-builder.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import * as common from './common';
|
|
2
|
+
import { AbstractSyntaxTree } from './abstract-syntax-tree';
|
|
3
|
+
|
|
1
4
|
type TagType = 'BEGIN' | 'IF' | 'FOR' | 'END' | 'BIND';
|
|
2
5
|
type ExtractValueType<T extends 'string' | 'array' | 'object'>
|
|
3
6
|
= T extends 'string'
|
|
@@ -164,57 +167,56 @@ export class SQLBuilder {
|
|
|
164
167
|
/**
|
|
165
168
|
* 「\/* *\/」で囲まれたすべての箇所を抽出
|
|
166
169
|
*/
|
|
167
|
-
const
|
|
170
|
+
const matches = template.matchAll(this.REGEX_TAG_PATTERN);
|
|
168
171
|
|
|
169
172
|
// まず最初にREGEX_TAG_PATTERNで解析した情報をそのままフラットにTagContextの配列に格納
|
|
170
173
|
let pos = 0;
|
|
171
174
|
const tagContexts: TagContext[] = [];
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
}
|
|
175
|
+
for (const match of matches) {
|
|
176
|
+
const matchContent = match[0];
|
|
177
|
+
const index = match.index;
|
|
178
|
+
pos = index + 1;
|
|
179
|
+
const tagContext: TagContext = {
|
|
180
|
+
type: 'BIND', // ダミーの初期値。後続処理で適切なタイプに変更する。
|
|
181
|
+
match: matchContent,
|
|
182
|
+
contents: '',
|
|
183
|
+
startIndex: index,
|
|
184
|
+
endIndex: index + matchContent.length,
|
|
185
|
+
sub: [],
|
|
186
|
+
parent: null,
|
|
187
|
+
status: 0
|
|
188
|
+
};
|
|
189
|
+
switch (true) {
|
|
190
|
+
case matchContent === '/*BEGIN*/': {
|
|
191
|
+
tagContext.type = 'BEGIN';
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case matchContent.startsWith('/*IF'): {
|
|
195
|
+
tagContext.type = 'IF';
|
|
196
|
+
const contentMatcher = matchContent.match(/^\/\*IF\s+(.*?)\*\/$/);
|
|
197
|
+
tagContext.contents = contentMatcher && contentMatcher[1] || '';
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
case matchContent.startsWith('/*FOR'): {
|
|
201
|
+
tagContext.type = 'FOR';
|
|
202
|
+
const contentMatcher = matchContent.match(/^\/\*FOR\s+(.*?)\*\/$/);
|
|
203
|
+
tagContext.contents = contentMatcher && contentMatcher[1] || '';
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
case matchContent === '/*END*/': {
|
|
207
|
+
tagContext.type = 'END';
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
default: {
|
|
211
|
+
tagContext.type = 'BIND';
|
|
212
|
+
const contentMatcher = matchContent.match(/\/\*(.*?)\*\//);
|
|
213
|
+
tagContext.contents = contentMatcher && contentMatcher[1] || '';
|
|
214
|
+
// ダミー値の終了位置をendIndexに設定
|
|
215
|
+
const dummyEndIndex = this.getDummyParamEndIndex(template, tagContext);
|
|
216
|
+
tagContext.endIndex = dummyEndIndex;
|
|
215
217
|
}
|
|
216
|
-
tagContexts.push(tagContext);
|
|
217
218
|
}
|
|
219
|
+
tagContexts.push(tagContext);
|
|
218
220
|
}
|
|
219
221
|
|
|
220
222
|
// できあがったTagContextの配列から、BEGEN、IFの場合は次の対応するENDが出てくるまでをsubに入れ直して構造化し、
|
|
@@ -326,7 +328,10 @@ export class SQLBuilder {
|
|
|
326
328
|
for (const value of array) {
|
|
327
329
|
// 再帰呼び出しによりposが進むので、ループのたびにposを戻す必要がある
|
|
328
330
|
pos.index = tagContext.endIndex;
|
|
329
|
-
result += this.parse(pos, template, {
|
|
331
|
+
result += this.parse(pos, template, {
|
|
332
|
+
...entity,
|
|
333
|
+
[bindName]: value
|
|
334
|
+
}, tagContext.sub, options);
|
|
330
335
|
// FORループするときは各行で改行する
|
|
331
336
|
result += '\n';
|
|
332
337
|
}
|
|
@@ -353,7 +358,7 @@ export class SQLBuilder {
|
|
|
353
358
|
case 'BIND': {
|
|
354
359
|
result += template.substring(pos.index, tagContext.startIndex);
|
|
355
360
|
pos.index = tagContext.endIndex;
|
|
356
|
-
const value =
|
|
361
|
+
const value = common.getProperty(entity, tagContext.contents);
|
|
357
362
|
switch (options?.bindType) {
|
|
358
363
|
case 'postgres': {
|
|
359
364
|
// PostgreSQL形式の場合、$Nでバインドパラメータを展開
|
|
@@ -405,7 +410,7 @@ export class SQLBuilder {
|
|
|
405
410
|
default: {
|
|
406
411
|
// generateSQLの場合
|
|
407
412
|
const escapedValue = this.extractValue(tagContext.contents, entity);
|
|
408
|
-
result +=
|
|
413
|
+
result += escapedValue ?? '';
|
|
409
414
|
}
|
|
410
415
|
}
|
|
411
416
|
break;
|
|
@@ -499,42 +504,15 @@ export class SQLBuilder {
|
|
|
499
504
|
*/
|
|
500
505
|
private evaluateCondition(condition: string, entity: Record<string, any>): boolean {
|
|
501
506
|
try {
|
|
502
|
-
const
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
return ${condition};
|
|
506
|
-
} catch(error) {
|
|
507
|
-
return false;
|
|
508
|
-
}
|
|
509
|
-
}`
|
|
510
|
-
);
|
|
511
|
-
return !!evaluate(entity);
|
|
507
|
+
const ast = new AbstractSyntaxTree();
|
|
508
|
+
const result = ast.evaluateCondition(condition, entity);
|
|
509
|
+
return result;
|
|
512
510
|
} catch (error) {
|
|
513
511
|
console.warn('Error evaluating condition:', condition, entity, error);
|
|
514
512
|
return false;
|
|
515
513
|
}
|
|
516
514
|
}
|
|
517
515
|
|
|
518
|
-
/**
|
|
519
|
-
* entityで指定したオブジェクトからドットで連結されたプロパティキーに該当する値を取得する
|
|
520
|
-
*
|
|
521
|
-
* @param {Record<string, any>} entity
|
|
522
|
-
* @param {string} property
|
|
523
|
-
* @returns {any}
|
|
524
|
-
*/
|
|
525
|
-
private getProperty(entity: Record<string, any>, property: string): any {
|
|
526
|
-
const propertyPath = property.split('.');
|
|
527
|
-
let value = entity;
|
|
528
|
-
for (const prop of propertyPath) {
|
|
529
|
-
if (value && value.hasOwnProperty(prop)) {
|
|
530
|
-
value = value[prop];
|
|
531
|
-
} else {
|
|
532
|
-
return undefined;
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
return value;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
516
|
/**
|
|
539
517
|
* entityからparamで指定した値を文字列で取得する
|
|
540
518
|
* entityの値がstringの場合、SQLインジェクションの危険のある文字はエスケープする
|
|
@@ -557,7 +535,7 @@ export class SQLBuilder {
|
|
|
557
535
|
responseType?: T
|
|
558
536
|
}): ExtractValueType<T> {
|
|
559
537
|
try {
|
|
560
|
-
const value =
|
|
538
|
+
const value = common.getProperty(entity, property);
|
|
561
539
|
let result = '';
|
|
562
540
|
switch (options?.responseType) {
|
|
563
541
|
case 'array':
|