-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMongoQuery.java
387 lines (333 loc) · 11.5 KB
/
MongoQuery.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.db.mongo;
import com.mongodb.ReadPreference;
import sirius.db.mixing.EntityDescriptor;
import sirius.db.mixing.Mapping;
import sirius.db.mixing.Mixing;
import sirius.db.mixing.query.Query;
import sirius.db.mixing.query.constraints.FilterFactory;
import sirius.db.mongo.constraints.MongoConstraint;
import sirius.db.mongo.facets.MongoFacet;
import sirius.kernel.async.TaskContext;
import sirius.kernel.commons.PullBasedSpliterator;
import sirius.kernel.commons.Value;
import sirius.kernel.di.std.Part;
import sirius.kernel.health.Exceptions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Creates a new query against MongoDB.
*
* @param <E> the type of entities being queried.
*/
public class MongoQuery<E extends MongoEntity> extends Query<MongoQuery<E>, E, MongoConstraint> {
private final Finder finder;
private List<MongoFacet> facets;
@Part
private static Mango mango;
@Part
private static Mongo mongo;
/**
* Creates a new query for the given descriptor.
*
* @param descriptor the descriptor of the entities being queried
* @param readPreference the read preference to enforce
*/
protected MongoQuery(EntityDescriptor descriptor, ReadPreference readPreference) {
super(descriptor);
this.finder = mongo.find(descriptor.getRealm(), readPreference);
}
/**
* Limits the fields being returned to the given list.
*
* @param fieldsToReturn specified the list of fields to return
* @return the builder itself for fluent method calls
*/
public MongoQuery<E> fields(Mapping... fieldsToReturn) {
finder.selectFields(fieldsToReturn);
return this;
}
@Override
public MongoQuery<E> eq(Mapping key, Object value) {
finder.where(key.toString(), value);
return this;
}
@Override
public MongoQuery<E> eqIgnoreNull(Mapping field, Object value) {
if (value != null) {
return eq(field, value);
} else {
return this;
}
}
@Override
public MongoQuery<E> where(MongoConstraint constraint) {
if (constraint != null) {
finder.where(constraint);
}
return this;
}
@Override
public MongoQuery<E> orderAsc(Mapping field) {
finder.orderByAsc(field.toString());
return this;
}
@Override
public MongoQuery<E> orderDesc(Mapping field) {
finder.orderByDesc(field.toString());
return this;
}
/**
* Adds a limit to the query.
*
* @param skip the number of items to skip (used for pagination).
* @param limit the max. number of items to return (excluding those who have been skipped).
* @return the builder itself for fluent method calls
*/
public MongoQuery<E> limit(int skip, int limit) {
this.skip = skip;
this.limit = limit;
finder.limit(skip, limit);
return this;
}
@Override
public MongoQuery<E> skip(int skip) {
this.skip = skip;
finder.skip(skip);
return this;
}
@Override
public MongoQuery<E> limit(int limit) {
this.limit = limit;
finder.limit(limit);
return this;
}
/**
* Marks the query as potentially long-running.
*
* @return the query itself for fluent method calls
*/
public MongoQuery<E> markLongRunning() {
finder.markLongRunning();
return this;
}
@Override
protected void doIterate(Predicate<E> resultHandler) {
if (forceFail) {
return;
}
finder.eachIn(descriptor.getRelationName(), doc -> resultHandler.test(Mango.make(descriptor, doc)));
}
@Override
public Stream<E> streamBlockwise() {
if (forceFail) {
return Stream.empty();
}
String relation = descriptor.getRelationName();
if (limit > 0) {
throw new UnsupportedOperationException("MongoQuery doesn't allow 'limit' in streamBlockwise");
}
if (skip > 0) {
throw new UnsupportedOperationException("MongoQuery doesn't allow 'skip' in streamBlockwise");
}
if (finder.orderBy != null && !finder.orderBy.isEmpty()) {
throw new UnsupportedOperationException("MongoQuery doesn't allow any explicit ordering in streamBlockwise");
}
return StreamSupport.stream(new MongoQuerySpliterator(relation), false);
}
private class MongoQuerySpliterator extends PullBasedSpliterator<E> {
private final String relation;
private final TaskContext taskContext = TaskContext.get();
private String lastId = null;
protected MongoQuerySpliterator(String relation) {
this.relation = relation;
}
@Override
public int characteristics() {
return Spliterator.NONNULL | Spliterator.IMMUTABLE;
}
@Nullable
@Override
protected Iterator<E> pullNextBlock() {
if (!taskContext.isActive()) {
return null;
}
List<E> buffer = new ArrayList<>(MAX_LIST_SIZE);
Finder query = finder.copyFilters().orderByAsc(MongoEntity.ID).limit(MAX_LIST_SIZE);
if (lastId != null) {
query.where(QueryBuilder.FILTERS.gt(MongoEntity.ID, lastId));
}
query.allIn(relation, doc -> buffer.add(Mango.make(descriptor, doc)));
if (!buffer.isEmpty()) {
lastId = buffer.getLast().getId();
}
return buffer.iterator();
}
}
@Override
public long count() {
if (forceFail) {
return 0;
}
return finder.countIn(descriptor.getRelationName());
}
/**
* Executes the query and counts the number of results.
* <p>
* In contrast to {@link #count()} adds some mongo specific performance related options.
*
* @param forceAccurate always count the actual query using countDocuments
* @param maxTimeMillis the maximum process time for this cursor in milliseconds, 0 for unlimited
* @return the number of matched result entries, wrapped in an Optional, or an empty Optional if the query failed
* @see Finder#countIn(String, boolean, long)
*/
public Optional<Long> count(boolean forceAccurate, long maxTimeMillis) {
if (forceFail) {
return Optional.empty();
}
return finder.countIn(descriptor.getRelationName(), forceAccurate, maxTimeMillis);
}
@Override
public boolean exists() {
if (forceFail) {
return false;
}
return finder.copyFilters().selectFields(MongoEntity.ID).singleIn(descriptor.getRelationName()).isPresent();
}
/**
* Returns a list of all items in the result, in a random order.
* <p>
* Internally, this uses a <tt>$sample</tt> aggregation with size equal to {@link #limit}.
* Note that large results should be processed using {@link #iterate(Predicate)} or
* {@link #iterateAll(Consumer)} as they are more memory efficient.
*
* @return a list of items in the query or an empty list if the query did not match any items
*/
public List<E> randomList() {
List<E> result = new ArrayList<>();
if (forceFail) {
return result;
}
// Ensure a sane limit...
if (limit <= 0 || limit > MAX_LIST_SIZE) {
throw Exceptions.handle()
.to(Mixing.LOG)
.withSystemErrorMessage("When using 'randomList' a limit (below %s) has to be provided. "
+ "Query: %s", MAX_LIST_SIZE, this)
.handle();
}
finder.sample(descriptor.getRelationName(), doc -> {
result.add(Mango.make(descriptor, doc));
failOnOverflow(result);
return true;
});
return result;
}
/**
* Aggregates the documents in the result of the given query with a sum operator.
* <p>
* Note that limits are ignored for this query.
*
* @param field the field to aggregate
* @return the result of the accumulation (int or double depending on the field)
*/
public Value aggregateSum(@Nonnull Mapping field) {
return finder.aggregateIn(descriptor.getRelationName(), field, "$sum");
}
/**
* Aggregates the documents in the result of the given query with an average operator.
* <p>
* Note that limits are ignored for this query.
*
* @param field the field to aggregate
* @return the result of the accumulation (double)
*/
public Value aggregateAverage(@Nonnull Mapping field) {
return finder.aggregateIn(descriptor.getRelationName(), field, "$avg");
}
/**
* Aggregates the documents in the result of the given query and returns the highest expression.
* <p>
* Note that limits are ignored for this query.
*
* @param field the field to aggregate
* @return the result of the accumulation (int or double depending on the field)
*/
public Value aggregateMax(@Nonnull Mapping field) {
return finder.aggregateIn(descriptor.getRelationName(), field, "$max");
}
/**
* Aggregates the documents in the result of the given query returns the lowest expression.
* <p>
* Note that limits are ignored for this query.
*
* @param field the field to aggregate
* @return the result of the accumulation (int or double depending on the field)
*/
public Value aggregateMin(@Nonnull Mapping field) {
return finder.aggregateIn(descriptor.getRelationName(), field, "$min");
}
@Override
public void delete(@Nullable Consumer<E> entityCallback) {
streamBlockwise().forEach(entity -> {
if (entityCallback != null) {
entityCallback.accept(entity);
}
mango.delete(entity);
});
}
@Override
public void truncate() {
if (forceFail) {
return;
}
Deleter deleter = mongo.delete();
finder.transferFilters(deleter);
deleter.manyFrom(descriptor.getRelationName());
}
@Override
public FilterFactory<MongoConstraint> filters() {
return QueryBuilder.FILTERS;
}
/**
* Adds a facet to be later executed using {@link #executeFacets()}.
*
* @param facet the facet to add
* @return the query itself for fluent method calls
*/
public MongoQuery<E> addFacet(MongoFacet facet) {
if (facets == null) {
facets = new ArrayList<>();
}
facets.add(facet);
return this;
}
/**
* Executes all previously attached facets in one go.
*/
public void executeFacets() {
if (forceFail) {
throw new IllegalStateException("Facets can not be executed on a failed query.");
}
finder.executeFacets(descriptor, facets);
}
@Override
public String toString() {
return descriptor.getType() + ": " + finder.toString();
}
}