-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
attribute-syntax.ts
276 lines (235 loc) · 8.82 KB
/
attribute-syntax.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { pojo } from '@sequelize/utils';
import type { SyntaxNode } from 'bnf-parser';
import { BNF, Compile, ParseError } from 'bnf-parser';
import memoize from 'lodash/memoize.js';
import type { Class } from 'type-fest';
import { AssociationPath } from '../expression-builders/association-path.js';
import { Attribute } from '../expression-builders/attribute.js';
import { Cast } from '../expression-builders/cast.js';
import type { DialectAwareFn } from '../expression-builders/dialect-aware-fn.js';
import { Unquote } from '../expression-builders/dialect-aware-fn.js';
import { JsonPath } from '../expression-builders/json-path.js';
/**
* Parses the attribute syntax (the syntax of keys in WHERE POJOs) into its "BaseExpression" representation.
*
* @example
* ```ts
* parseAttribute('id') // => attribute('id')
* parseAttribute('$user.id$') // => association(['user'], 'id')
* parseAttribute('json.key') // => jsonPath(attribute('json'), ['key'])
* parseAttribute('name::number') // => cast(attribute('name'), 'number')
* parseAttribute('json.key::number') // => cast(jsonPath(attribute('json'), ['key']), 'number')
* ```
*
* @param attribute The syntax to parse
*/
export const parseAttributeSyntax = memoize(parseAttributeSyntaxInternal);
/**
* Parses the syntax supported by nested JSON properties.
* This is a subset of {@link parseAttributeSyntax}, which does not parse associations, and returns raw data
* instead of a BaseExpression.
*/
export const parseNestedJsonKeySyntax = memoize(parseJsonPropertyKeyInternal);
/**
* List of supported attribute modifiers.
* They can be specified in the attribute syntax, e.g. `foo:upper` will call the `upper` modifier on the `foo` attribute.
*
* All names should be lowercase, as they are case-insensitive.
*/
const builtInModifiers: Record<string, Class<DialectAwareFn>> = pojo({
unquote: Unquote,
});
function getModifier(name: string): Class<DialectAwareFn> {
const ModifierClass = builtInModifiers[name.toLowerCase()];
if (!ModifierClass) {
throw new Error(
`${name} is not a recognized built-in modifier. Here is the list of supported modifiers: ${Object.keys(builtInModifiers).join(', ')}`,
);
}
return ModifierClass;
}
const attributeParser = (() => {
const advancedAttributeBnf = `
# Entry points
## Used when parsing the attribute
attribute ::= ( ...association | ...identifier ) jsonPath? castOrModifiers?;
## Used when parsing a nested JSON path used inside of an attribute
## Difference with "attribute" is in the first part. Instead of accepting:
## $association.attribute$ & attribute
## It accepts:
## key, "quotedKey", and [0] (index access)
partialJsonPath ::= ( ...indexAccess | ...key ) jsonPath? castOrModifiers? ;
# Internals
identifier ::= ( "A"->"Z" | "a"->"z" | digit | "_" )+ ;
digit ::= "0"->"9" ;
number ::= ...digit+ ;
association ::= %"$" identifier ("." identifier)* %"$" ;
jsonPath ::= ( ...indexAccess | ...keyAccess )+ ;
indexAccess ::= %"[" number %"]" ;
keyAccess ::= %"." key ;
# path segments accept dashes without needing to be quoted
key ::= nonEmptyString | ( "A"->"Z" | "a"->"z" | digit | "_" | "-" )+ ;
nonEmptyString ::= ...(%"\\"" (anyExceptQuoteOrBackslash | escapedCharacter)+ %"\\"") ;
escapedCharacter ::= %"\\\\" ( "\\"" | "\\\\" );
any ::= !"" ;
anyExceptQuoteOrBackslash ::= !("\\"" | "\\\\");
castOrModifiers ::= (...cast | ...modifier)+;
cast ::= %"::" identifier ;
modifier ::= %":" identifier ;
`;
const parsedAttributeBnf = BNF.parse(advancedAttributeBnf);
if (parsedAttributeBnf instanceof ParseError) {
throw new Error(
`Failed to initialize attribute syntax parser. This is a Sequelize bug: ${parsedAttributeBnf.toString()}`,
);
}
return Compile(parsedAttributeBnf);
})();
interface UselessNode<Type extends string, WrappedValue extends SyntaxNode[]> extends SyntaxNode {
type: Type;
value: WrappedValue;
}
export interface StringNode<Type extends string> extends SyntaxNode {
type: Type;
value: string;
}
interface AttributeAst extends SyntaxNode {
type: 'attribute';
value: [
attribute: StringNode<'association' | 'identifier'>,
jsonPath: UselessNode<
'jsonPath?',
[
UselessNode<
'jsonPath',
[UselessNode<'(...)+', Array<StringNode<'keyAccess' | 'indexAccess'>>>]
>,
]
>,
castOrModifiers: UselessNode<
'castOrModifiers?',
[
UselessNode<
'castOrModifiers',
[UselessNode<'(...)+', Array<StringNode<'cast' | 'modifier'>>>]
>,
]
>,
];
}
function parseAttributeSyntaxInternal(
code: string,
): Cast | JsonPath | AssociationPath | Attribute | DialectAwareFn {
// This function is expensive (parsing produces a lot of objects), but we cache the final result, so it's only
// going to be slow once per attribute.
const parsed = attributeParser.parse(code, false, 'attribute') as AttributeAst | ParseError;
if (parsed instanceof ParseError) {
throw new TypeError(`Failed to parse syntax of attribute. Parse error at index ${parsed.ref.start.index}:
${code}
${' '.repeat(parsed.ref.start.index)}^`);
}
const [attributeNode, jsonPathNodeRaw, castOrModifiersNodeRaw] = parsed.value;
let result: Cast | JsonPath | AssociationPath | Attribute | DialectAwareFn = parseAssociationPath(
attributeNode.value,
);
const jsonPathNodes = jsonPathNodeRaw.value[0]?.value[0].value;
if (jsonPathNodes) {
const path = jsonPathNodes.map(pathNode => {
return parseJsonPathSegment(pathNode);
});
result = new JsonPath(result, path);
}
const castOrModifierNodes = castOrModifiersNodeRaw.value[0]?.value[0].value;
if (castOrModifierNodes) {
// casts & modifiers can be chained, the last one is applied last
// foo:upper:lower needs to produce LOWER(UPPER(foo))
for (const castOrModifierNode of castOrModifierNodes) {
if (castOrModifierNode.type === 'cast') {
result = new Cast(result, castOrModifierNode.value);
continue;
}
const ModifierClass = getModifier(castOrModifierNode.value);
result = new ModifierClass(result);
}
}
return result;
}
function parseAssociationPath(syntax: string): AssociationPath | Attribute {
const path = syntax.split('.');
if (path.length > 1) {
const attr = path.pop()!;
return new AssociationPath(path, attr);
}
return new Attribute(syntax);
}
/**
* Do not mutate this! It is memoized to avoid re-parsing the same path over and over.
*/
export interface ParsedJsonPropertyKey {
readonly pathSegments: ReadonlyArray<string | number>;
/**
* If it's a string, it's a cast. If it's a class, it's a modifier.
*/
readonly castsAndModifiers: ReadonlyArray<string | Class<DialectAwareFn>>;
}
interface JsonPathAst extends SyntaxNode {
type: 'partialJsonPath';
value: [
firstKey: StringNode<'key' | 'indexAccess'>,
jsonPath: UselessNode<
'jsonPath?',
[
UselessNode<
'jsonPath',
[UselessNode<'(...)+', Array<StringNode<'keyAccess' | 'indexAccess'>>>]
>,
]
>,
castOrModifiers: UselessNode<
'castOrModifiers?',
[
UselessNode<
'castOrModifiers',
[UselessNode<'(...)+', Array<StringNode<'cast' | 'modifier'>>>]
>,
]
>,
];
}
function parseJsonPropertyKeyInternal(code: string): ParsedJsonPropertyKey {
const parsed = attributeParser.parse(code, false, 'partialJsonPath') as JsonPathAst | ParseError;
if (parsed instanceof ParseError) {
throw new TypeError(`Failed to parse syntax of json path. Parse error at index ${parsed.ref.start.index}:
${code}
${' '.repeat(parsed.ref.start.index)}^`);
}
const [firstKey, jsonPathNodeRaw, castOrModifiersNodeRaw] = parsed.value;
const pathSegments: Array<string | number> = [parseJsonPathSegment(firstKey)];
const jsonPathNodes = jsonPathNodeRaw.value[0]?.value[0].value;
if (jsonPathNodes) {
for (const pathNode of jsonPathNodes) {
pathSegments.push(parseJsonPathSegment(pathNode));
}
}
const castOrModifierNodes = castOrModifiersNodeRaw.value[0]?.value[0].value;
const castsAndModifiers: Array<string | Class<DialectAwareFn>> = [];
if (castOrModifierNodes) {
// casts & modifiers can be chained, the last one is applied last
// foo:upper:lower needs to produce LOWER(UPPER(foo))
for (const castOrModifierNode of castOrModifierNodes) {
if (castOrModifierNode.type === 'cast') {
castsAndModifiers.push(castOrModifierNode.value);
continue;
}
const ModifierClass = getModifier(castOrModifierNode.value);
castsAndModifiers.push(ModifierClass);
}
}
return { pathSegments, castsAndModifiers };
}
function parseJsonPathSegment(node: StringNode<string>): string | number {
if (node.type === 'indexAccess') {
return Number(node.value);
}
return node.value;
}