/
SparqlTupleExprRenderer.java
309 lines (248 loc) · 7.74 KB
/
SparqlTupleExprRenderer.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
/*******************************************************************************
* Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.queryrender.sparql;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.rdf4j.query.algebra.Difference;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.Intersection;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.LeftJoin;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.Union;
import org.eclipse.rdf4j.query.algebra.ValueConstant;
import org.eclipse.rdf4j.query.algebra.ValueExpr;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.queryrender.BaseTupleExprRenderer;
import org.eclipse.rdf4j.queryrender.RenderUtils;
/**
* <p>
* Extends the BaseTupleExprRenderer to provide support for rendering tuple expressions as SPARQL queries.
* </p>
*
* @author Michael Grove
*/
public final class SparqlTupleExprRenderer extends BaseTupleExprRenderer {
private StringBuffer mJoinBuffer = new StringBuffer();
private Map<TupleExpr, Var> mContexts = new HashMap<>();
private int mIndent = 2;
/**
* @inheritDoc
*/
@Override
public void reset() {
super.reset();
mJoinBuffer = new StringBuffer();
mContexts.clear();
}
/**
* @inheritDoc
*/
@Override
public String render(final TupleExpr theExpr) throws Exception {
mContexts = ContextCollector.collectContexts(theExpr);
theExpr.visit(this);
return mJoinBuffer.toString();
}
private String indent() {
final StringBuilder aBuilder = new StringBuilder();
for (int i = 0; i < mIndent; i++) {
aBuilder.append(" ");
}
return aBuilder.toString();
}
/**
* @inheritDoc
*/
@Override
protected String renderValueExpr(final ValueExpr theExpr) throws Exception {
return new SparqlValueExprRenderer().render(theExpr);
}
private void ctxOpen(TupleExpr theExpr) {
Var aContext = mContexts.get(theExpr);
if (aContext != null) {
mJoinBuffer.append(indent()).append("GRAPH ");
if (aContext.hasValue()) {
mJoinBuffer.append(RenderUtils.getSPARQLQueryString(aContext.getValue()));
} else {
mJoinBuffer.append("?").append(aContext.getName());
}
mJoinBuffer.append(" {\n");
mIndent += 2;
}
}
private void ctxClose(TupleExpr theExpr) {
Var aContext = mContexts.get(theExpr);
if (aContext != null) {
mJoinBuffer.append("}");
mIndent -= 2;
}
}
/**
* @inheritDoc
*/
@Override
public void meet(Join theJoin) throws Exception {
ctxOpen(theJoin);
theJoin.getLeftArg().visit(this);
theJoin.getRightArg().visit(this);
ctxClose(theJoin);
}
/**
* @inheritDoc
*/
@Override
public void meet(LeftJoin theJoin) throws Exception {
ctxOpen(theJoin);
// try and reverse engineer the original scoping intent of the query
final boolean aNeedsNewScope = theJoin.getParentNode() != null
&& (theJoin.getParentNode() instanceof Join || theJoin.getParentNode() instanceof LeftJoin);
if (aNeedsNewScope) {
mJoinBuffer.append("{\n");
}
theJoin.getLeftArg().visit(this);
mJoinBuffer.append(indent()).append("OPTIONAL {\n");
mIndent += 2;
theJoin.getRightArg().visit(this);
if (theJoin.getCondition() != null) {
mJoinBuffer.append(indent()).append("filter").append(renderValueExpr(theJoin.getCondition())).append("\n");
}
mIndent -= 2;
mJoinBuffer.append(indent()).append("}.\n");
if (aNeedsNewScope) {
mJoinBuffer.append("}.\n");
}
ctxClose(theJoin);
}
/**
* Renders the tuple expression as a query string. It creates a new SparqlTupleExprRenderer rather than reusing this
* one.
*
* @param theExpr the expr to render
* @return the rendered expression
* @throws Exception if there is an error while rendering
*/
private String renderTupleExpr(TupleExpr theExpr) throws Exception {
SparqlTupleExprRenderer aRenderer = new SparqlTupleExprRenderer();
// aRenderer.mProjection = new ArrayList<ProjectionElemList>(mProjection);
// aRenderer.mDistinct = mDistinct;
// aRenderer.mReduced = mReduced;
// aRenderer.mExtensions = new HashMap<String, ValueExpr>(mExtensions);
// aRenderer.mOrdering = new ArrayList<OrderElem>(mOrdering);
// aRenderer.mLimit = mLimit;
// aRenderer.mOffset = mOffset;
aRenderer.mIndent = mIndent;
aRenderer.mContexts = new HashMap<>(mContexts);
return aRenderer.render(theExpr);
}
/**
* @inheritDoc
*/
@Override
public void meet(Union theOp) throws Exception {
ctxOpen(theOp);
String aLeft = renderTupleExpr(theOp.getLeftArg());
if (aLeft.endsWith("\n")) {
aLeft = aLeft.substring(0, aLeft.length() - 1);
}
String aRight = renderTupleExpr(theOp.getRightArg());
if (aRight.endsWith("\n")) {
aRight = aRight.substring(0, aRight.length() - 1);
}
mJoinBuffer.append(indent())
.append("{\n")
.append(aLeft)
.append("\n")
.append(indent())
.append("}\n")
.append(indent())
.append("union\n")
.append(indent())
.append("{\n")
.append(aRight)
.append("\n")
.append(indent())
.append("}.\n");
ctxClose(theOp);
}
/**
* @inheritDoc
*/
@Override
public void meet(Difference theOp) throws Exception {
String aLeft = renderTupleExpr(theOp.getLeftArg());
String aRight = renderTupleExpr(theOp.getRightArg());
mJoinBuffer.append("\n{")
.append(aLeft)
.append("}")
.append("\nminus\n")
.append("{")
.append(aRight)
.append("}.\n");
}
/**
* @inheritDoc
*/
@Override
public void meet(Intersection theOp) throws Exception {
String aLeft = renderTupleExpr(theOp.getLeftArg());
String aRight = renderTupleExpr(theOp.getRightArg());
mJoinBuffer.append("\n")
.append(aLeft)
.append("}")
.append("\nintersection\n")
.append("{")
.append(aRight)
.append("}.\n");
}
/**
* @inheritDoc
*/
@Override
public void meet(final Filter theFilter) throws Exception {
ctxOpen(theFilter);
if (theFilter.getArg() != null) {
theFilter.getArg().visit(this);
}
// try and reverse engineer the original scoping intent of the query
final boolean aNeedsNewScope = theFilter.getParentNode() != null
&& (theFilter.getParentNode() instanceof Join || theFilter.getParentNode() instanceof LeftJoin);
String aFilter = renderValueExpr(theFilter.getCondition());
if (theFilter.getCondition() instanceof ValueConstant || theFilter.getCondition() instanceof Var) {
// means the filter is something like "filter (true)" or "filter (?v)"
// so we'll need to wrap it in parens since they can't live
// in the query w/o them, but we can't always wrap them in parens in
// the normal renderer
aFilter = "(" + aFilter + ")";
}
mJoinBuffer.append(indent());
// if (aNeedsNewScope) {
// mJoinBuffer.append("{ ");
// }
mJoinBuffer.append("filter ").append(aFilter).append(".");
// if (aNeedsNewScope) {
// mJoinBuffer.append("}.");
// }
mJoinBuffer.append("\n");
ctxClose(theFilter);
}
/**
* @inheritDoc
*/
@Override
public void meet(StatementPattern thePattern) throws Exception {
ctxOpen(thePattern);
mJoinBuffer.append(indent()).append(renderPattern(thePattern));
ctxClose(thePattern);
}
String renderPattern(StatementPattern thePattern) throws Exception {
return renderValueExpr(thePattern.getSubjectVar()) + " " + renderValueExpr(thePattern.getPredicateVar()) + " "
+ "" + renderValueExpr(thePattern.getObjectVar()) + ".\n";
}
}