-
Notifications
You must be signed in to change notification settings - Fork 863
/
SerializerBase.java
331 lines (284 loc) · 10.6 KB
/
SerializerBase.java
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.querydsl.core.support;
import com.querydsl.core.JoinFlag;
import com.querydsl.core.QueryFlag;
import com.querydsl.core.types.Constant;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.Operation;
import com.querydsl.core.types.Operator;
import com.querydsl.core.types.Ops;
import com.querydsl.core.types.ParamExpression;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathType;
import com.querydsl.core.types.Template;
import com.querydsl.core.types.TemplateExpression;
import com.querydsl.core.types.Templates;
import com.querydsl.core.types.Visitor;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* {@code SerializerBase} is a stub for Serializer implementations which serialize query metadata to Strings
*
* @param <S> concrete subtype
* @author tiwe
*/
public abstract class SerializerBase<S extends SerializerBase<S>> implements Visitor<Void, Void> {
private static final Set<? extends Operator> SAME_PRECEDENCE = Collections.unmodifiableSet(EnumSet.of(Ops.CASE,
Ops.CASE_WHEN, Ops.CASE_ELSE, Ops.CASE_EQ, Ops.CASE_EQ_WHEN, Ops.CASE_EQ_ELSE));
private final StringBuilder builder = new StringBuilder(128);
private String constantPrefix = "a";
private String paramPrefix = "p";
private String anonParamPrefix = "_";
protected final List<Object> constants = new LinkedList<>();
protected final Map<Object, String> constantToLabel = new IdentityHashMap<>();
@SuppressWarnings("unchecked")
private final S self = (S) this;
private final Templates templates;
private boolean strict = true;
public SerializerBase(Templates templates) {
this.templates = templates;
}
public final S prepend(final String str) {
builder.insert(0, str);
return self;
}
public final S insert(int position, String str) {
builder.insert(position, str);
return self;
}
public final S append(final String str) {
builder.append(str);
return self;
}
protected String getConstantPrefix() {
return constantPrefix;
}
public Map<Object, String> getConstantToLabel() {
return constantToLabel;
}
protected int getLength() {
return builder.length();
}
protected final Template getTemplate(Operator op) {
return templates.getTemplate(op);
}
public final S handle(Expression<?> expr) {
expr.accept(this, null);
return self;
}
public final S handle(Object arg) {
if (arg instanceof Expression) {
((Expression<?>) arg).accept(this, null);
} else {
visitConstant(arg);
}
return self;
}
public final S handle(JoinFlag joinFlag) {
return handle(joinFlag.getFlag());
}
public final S handle(final String sep, final Expression<?>[] expressions) {
handle(sep, Arrays.asList(expressions));
return self;
}
public final S handle(final String sep, final List<? extends Expression<?>> expressions) {
for (int i = 0; i < expressions.size(); i++) {
if (i != 0) {
append(sep);
}
handle(expressions.get(i));
}
return self;
}
protected void handleTemplate(final Template template, final List<?> args) {
for (final Template.Element element : template.getElements()) {
final Object rv = element.convert(args);
if (rv instanceof Expression) {
((Expression<?>) rv).accept(this, null);
} else if (element.isString()) {
builder.append(rv.toString());
} else {
visitConstant(rv);
}
}
}
public final boolean serialize(final QueryFlag.Position position, final Set<QueryFlag> flags) {
boolean handled = false;
for (final QueryFlag flag : flags) {
if (flag.getPosition() == position) {
handle(flag.getFlag());
handled = true;
}
}
return handled;
}
public final boolean serialize(final JoinFlag.Position position, final Set<JoinFlag> flags) {
boolean handled = false;
for (final JoinFlag flag : flags) {
if (flag.getPosition() == position) {
handle(flag.getFlag());
handled = true;
}
}
return handled;
}
public void setConstantPrefix(String prefix) {
this.constantPrefix = prefix;
}
public void setParamPrefix(String prefix) {
this.paramPrefix = prefix;
}
public void setAnonParamPrefix(String prefix) {
this.anonParamPrefix = prefix;
}
/**
* Not used anymore
*
* @deprecated normalization happens now at template level
*/
@Deprecated
public void setNormalize(boolean normalize) {
}
public void setStrict(boolean strict) {
this.strict = strict;
}
@Override
public String toString() {
return builder.toString();
}
@Override
public final Void visit(Constant<?> expr, Void context) {
visitConstant(expr.getConstant());
return null;
}
public void visitConstant(Object constant) {
final String constantLabel = getConstantToLabel().computeIfAbsent(constant, this::getConstantLabel);
constants.add(constant);
serializeConstant(constants.size(), constantLabel);
}
/**
* Serialize the constant as parameter to the query. The default implementation writes the
* label name for the constants. Some dialects may replace this by indexed based or
* positional parameterization.
* Dialects may also use this to prefix the parameter with for example ":" or "?".
*
* @param parameterIndex index at which this constant occurs in {@link #getConstants()}
* @param constantLabel label under which this constant occurs in {@link #getConstantToLabel()}
*/
protected void serializeConstant(int parameterIndex, String constantLabel) {
append(constantLabel);
}
/**
* Generate a constant value under which to register a new constant in {@link #getConstantToLabel()}.
*
* @param value the constant value or parameter to create a constant for
* @return the generated label
*/
@NotNull
protected String getConstantLabel(Object value) {
return constantPrefix + (getConstantToLabel().size() + 1);
}
public List<Object> getConstants() {
return constants;
}
@Override
public Void visit(ParamExpression<?> param, Void context) {
String paramLabel;
if (param.isAnon()) {
paramLabel = anonParamPrefix + param.getName();
} else {
paramLabel = paramPrefix + param.getName();
}
getConstantToLabel().put(param, paramLabel);
constants.add(param);
serializeConstant(constants.size(), paramLabel);
return null;
}
@Override
public Void visit(TemplateExpression<?> expr, Void context) {
handleTemplate(expr.getTemplate(), expr.getArgs());
return null;
}
@Override
public Void visit(FactoryExpression<?> expr, Void context) {
handle(", ", expr.getArgs());
return null;
}
@Override
public Void visit(Operation<?> expr, Void context) {
visitOperation(expr.getType(), expr.getOperator(), expr.getArgs());
return null;
}
@Override
public Void visit(Path<?> path, Void context) {
final PathType pathType = path.getMetadata().getPathType();
final Template template = templates.getTemplate(pathType);
final Object element = path.getMetadata().getElement();
List<Object> args;
if (path.getMetadata().getParent() != null) {
args = Arrays.asList(path.getMetadata().getParent(), element);
} else {
args = Collections.singletonList(element);
}
handleTemplate(template, args);
return null;
}
protected void visitOperation(Class<?> type, Operator operator, final List<? extends Expression<?>> args) {
final Template template = templates.getTemplate(operator);
if (template != null) {
final int precedence = templates.getPrecedence(operator);
boolean first = true;
for (final Template.Element element : template.getElements()) {
final Object rv = element.convert(args);
if (rv instanceof Expression) {
final Expression<?> expr = (Expression<?>) rv;
if (precedence > -1 && expr instanceof Operation) {
Operator op = ((Operation<?>) expr).getOperator();
int opPrecedence = templates.getPrecedence(op);
if (precedence < opPrecedence) {
append("(").handle(expr).append(")");
} else if (!first && precedence == opPrecedence && !SAME_PRECEDENCE.contains(op)) {
append("(").handle(expr).append(")");
} else {
handle(expr);
}
} else {
handle(expr);
}
first = false;
} else if (element.isString()) {
append(rv.toString());
} else {
visitConstant(rv);
}
}
} else if (strict) {
throw new IllegalArgumentException(String.format("No pattern found for %s. Make sure to register any custom functions with %s.", operator, templates.getClass()));
} else {
append(operator.toString());
append("(");
handle(", ", args);
append(")");
}
}
}