forked from objectbox/objectbox-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBox.java
More file actions
742 lines (676 loc) · 22.5 KB
/
Box.java
File metadata and controls
742 lines (676 loc) · 22.5 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/*
* Copyright 2017-2019 ObjectBox Ltd. All rights reserved.
*
* 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 io.objectbox;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import io.objectbox.annotation.apihint.Beta;
import io.objectbox.annotation.apihint.Experimental;
import io.objectbox.annotation.apihint.Internal;
import io.objectbox.exception.DbException;
import io.objectbox.internal.CallWithHandle;
import io.objectbox.internal.IdGetter;
import io.objectbox.internal.ReflectionCache;
import io.objectbox.query.QueryBuilder;
import io.objectbox.query.QueryCondition;
import io.objectbox.relation.RelationInfo;
/**
* A Box to put and get Objects of a specific Entity class.
* <p>
* Thread-safe.
*/
@ThreadSafe
@SuppressWarnings("WeakerAccess,UnusedReturnValue,unused")
public class Box<T> {
private final BoxStore store;
private final Class<T> entityClass;
/** Set when running inside TX */
final ThreadLocal<Cursor<T>> activeTxCursor = new ThreadLocal<>();
private final ThreadLocal<Cursor<T>> threadLocalReader = new ThreadLocal<>();
private final IdGetter<T> idGetter;
private EntityInfo<T> entityInfo;
private volatile Field boxStoreField;
Box(BoxStore store, Class<T> entityClass) {
this.store = store;
this.entityClass = entityClass;
idGetter = store.getEntityInfo(entityClass).getIdGetter();
}
Cursor<T> getReader() {
Cursor<T> cursor = getActiveTxCursor();
if (cursor != null) {
return cursor;
} else {
cursor = threadLocalReader.get();
if (cursor != null) {
Transaction tx = cursor.tx;
if (tx.isClosed() || !tx.isRecycled()) {
throw new IllegalStateException("Illegal reader TX state");
}
tx.renew();
cursor.renew();
} else {
cursor = store.beginReadTx().createCursor(entityClass);
threadLocalReader.set(cursor);
}
}
return cursor;
}
Cursor<T> getActiveTxCursor() {
Transaction activeTx = store.activeTx.get();
if (activeTx != null) {
if (activeTx.isClosed()) {
throw new IllegalStateException("Active TX is closed");
}
Cursor<T> cursor = activeTxCursor.get();
if (cursor == null || cursor.getTx().isClosed()) {
cursor = activeTx.createCursor(entityClass);
activeTxCursor.set(cursor);
}
return cursor;
}
return null;
}
Cursor<T> getWriter() {
Cursor<T> cursor = getActiveTxCursor();
if (cursor != null) {
return cursor;
} else {
Transaction tx = store.beginTx();
try {
return tx.createCursor(entityClass);
} catch (RuntimeException e) {
tx.close();
throw e;
}
}
}
void commitWriter(Cursor<T> cursor) {
// NOP if TX is ongoing
if (activeTxCursor.get() == null) {
cursor.close();
cursor.getTx().commitAndClose();
}
}
void releaseWriter(Cursor<T> cursor) {
// NOP if TX is ongoing
if (activeTxCursor.get() == null) {
Transaction tx = cursor.getTx();
if (!tx.isClosed()) {
cursor.close();
tx.abort();
tx.close();
}
}
}
void releaseReader(Cursor<T> cursor) {
// NOP if TX is ongoing
if (activeTxCursor.get() == null) {
Transaction tx = cursor.getTx();
if (tx.isClosed() || tx.isRecycled() || !tx.isReadOnly()) {
throw new IllegalStateException("Illegal reader TX state");
}
tx.recycle();
}
}
/**
* Like {@link BoxStore#closeThreadResources()}, but limited to only this Box.
* <p>
* Rule of thumb: prefer {@link BoxStore#closeThreadResources()} unless you know that your thread only interacted
* with this Box.
*/
public void closeThreadResources() {
Cursor<T> cursor = threadLocalReader.get();
if (cursor != null) {
cursor.close();
cursor.getTx().close(); // a read TX is always started when the threadLocalReader is set
threadLocalReader.remove();
}
}
void txCommitted(Transaction tx) {
// Thread local readers will be renewed on next get, so we do not need clean them up
Cursor<T> cursor = activeTxCursor.get();
if (cursor != null) {
activeTxCursor.remove();
cursor.close();
}
}
/**
* Called by {@link BoxStore#callInReadTx(Callable)} - does not throw so caller does not need try/finally.
*/
void readTxFinished(Transaction tx) {
Cursor<T> cursor = activeTxCursor.get();
if (cursor != null && cursor.getTx() == tx) {
activeTxCursor.remove();
cursor.close();
}
}
/** Used by tests */
int getPropertyId(String propertyName) {
Cursor<T> reader = getReader();
try {
return reader.getPropertyId(propertyName);
} finally {
releaseReader(reader);
}
}
@Internal
public long getId(T entity) {
return idGetter.getId(entity);
}
/**
* Get the stored object for the given ID.
*
* @return null if not found
*/
public T get(long id) {
Cursor<T> reader = getReader();
try {
return reader.get(id);
} finally {
releaseReader(reader);
}
}
/**
* Get the stored objects for the given IDs.
*
* @return null if not found
*/
public List<T> get(Iterable<Long> ids) {
ArrayList<T> list = new ArrayList<>();
Cursor<T> reader = getReader();
try {
for (Long id : ids) {
T entity = reader.get(id);
if (entity != null) {
list.add(entity);
}
}
} finally {
releaseReader(reader);
}
return list;
}
/**
* Get the stored objects for the given IDs.
*
* @return null if not found
*/
public List<T> get(long[] ids) {
ArrayList<T> list = new ArrayList<>(ids.length);
Cursor<T> reader = getReader();
try {
for (Long id : ids) {
T entity = reader.get(id);
if (entity != null) {
list.add(entity);
}
}
} finally {
releaseReader(reader);
}
return list;
}
/**
* Get the stored objects for the given IDs as a Map with IDs as keys, and entities as values.
* IDs for which no entity is found will be put in the map with null values.
*
* @return null if not found
*/
public Map<Long, T> getMap(Iterable<Long> ids) {
HashMap<Long, T> map = new HashMap<>();
Cursor<T> reader = getReader();
try {
for (Long id : ids) {
map.put(id, reader.get(id));
}
} finally {
releaseReader(reader);
}
return map;
}
/**
* Returns the count of all stored objects in this box.
*/
public long count() {
return count(0);
}
/**
* Returns the count of all stored objects in this box or the given maxCount, whichever is lower.
*
* @param maxCount maximum value to count or 0 (zero) to have no maximum limit
*/
public long count(long maxCount) {
Cursor<T> reader = getReader();
try {
return reader.count(maxCount);
} finally {
releaseReader(reader);
}
}
/** Returns true if no objects are in this box. */
public boolean isEmpty() {
return count(1) == 0;
}
/**
* Returns all stored Objects in this Box.
* @return since 2.4 the returned list is always mutable (before an empty result list was immutable)
*/
public List<T> getAll() {
ArrayList<T> list = new ArrayList<>();
Cursor<T> cursor = getReader();
try {
for (T object = cursor.first(); object != null; object = cursor.next()) {
list.add(object);
}
return list;
} finally {
releaseReader(cursor);
}
}
/**
* Check if an object with the given ID exists in the database.
* This is more efficient than a {@link #get(long)} and comparing against null.
* @since 2.7
* @return true if a object with the given ID was found, false otherwise
*/
public boolean contains(long id) {
Cursor<T> reader = getReader();
try {
return reader.seek(id);
} finally {
releaseReader(reader);
}
}
/**
* Puts the given object in the box (aka persisting it). If this is a new entity (its ID property is 0), a new ID
* will be assigned to the entity (and returned). If the entity was already put in the box before, it will be
* overwritten.
* <p>
* Performance note: if you want to put several entities, consider {@link #put(Collection)},
* {@link #put(Object[])}, {@link BoxStore#runInTx(Runnable)}, etc. instead.
*/
public long put(T entity) {
Cursor<T> cursor = getWriter();
try {
long key = cursor.put(entity);
commitWriter(cursor);
return key;
} finally {
releaseWriter(cursor);
}
}
/**
* Puts the given entities in a box using a single transaction.
*/
@SafeVarargs // Not using T... as Object[], no ClassCastException expected.
public final void put(@Nullable T... entities) {
if (entities == null || entities.length == 0) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (T entity : entities) {
cursor.put(entity);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* Puts the given entities in a box using a single transaction.
*
* @param entities It is fine to pass null or an empty collection:
* this case is handled efficiently without overhead.
*/
public void put(@Nullable Collection<T> entities) {
if (entities == null || entities.isEmpty()) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (T entity : entities) {
cursor.put(entity);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* Puts the given entities in a box in batches using a separate transaction for each batch.
*
* @param entities It is fine to pass null or an empty collection:
* this case is handled efficiently without overhead.
* @param batchSize Number of entities that will be put in one transaction. Must be 1 or greater.
*/
public void putBatched(@Nullable Collection<T> entities, int batchSize) {
if (batchSize < 1) {
throw new IllegalArgumentException("Batch size must be 1 or greater but was " + batchSize);
}
if (entities == null) {
return;
}
Iterator<T> iterator = entities.iterator();
while (iterator.hasNext()) {
Cursor<T> cursor = getWriter();
try {
int number = 0;
while (number++ < batchSize && iterator.hasNext()) {
cursor.put(iterator.next());
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
}
/**
* Removes (deletes) the Object by its ID.
* @return true if an entity was actually removed (false if no entity exists with the given ID)
*/
public boolean remove(long id) {
Cursor<T> cursor = getWriter();
boolean removed;
try {
removed = cursor.deleteEntity(id);
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
return removed;
}
/**
* Removes (deletes) Objects by their ID in a single transaction.
*/
public void remove(@Nullable long... ids) {
if (ids == null || ids.length == 0) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (long key : ids) {
cursor.deleteEntity(key);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* @deprecated use {@link #removeByIds(Collection)} instead.
*/
@Deprecated
public void removeByKeys(@Nullable Collection<Long> ids) {
removeByIds(ids);
}
/**
* Due to type erasure collision, we cannot simply use "remove" as a method name here.
*/
public void removeByIds(@Nullable Collection<Long> ids) {
if (ids == null || ids.isEmpty()) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (long key : ids) {
cursor.deleteEntity(key);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* Removes (deletes) the given Object.
* @return true if an entity was actually removed (false if no entity exists with the given ID)
*/
public boolean remove(T object) {
Cursor<T> cursor = getWriter();
boolean removed;
try {
long id = cursor.getId(object);
removed = cursor.deleteEntity(id);
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
return removed;
}
/**
* Removes (deletes) the given Objects in a single transaction.
*/
@SafeVarargs // Not using T... as Object[], no ClassCastException expected.
@SuppressWarnings("Duplicates") // Detected duplicate has different type
public final void remove(@Nullable T... objects) {
if (objects == null || objects.length == 0) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (T entity : objects) {
long key = cursor.getId(entity);
cursor.deleteEntity(key);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* Removes (deletes) the given Objects in a single transaction.
*/
@SuppressWarnings("Duplicates") // Detected duplicate has different type
public void remove(@Nullable Collection<T> objects) {
if (objects == null || objects.isEmpty()) {
return;
}
Cursor<T> cursor = getWriter();
try {
for (T entity : objects) {
long key = cursor.getId(entity);
cursor.deleteEntity(key);
}
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* Removes (deletes) ALL Objects in a single transaction.
*/
public void removeAll() {
Cursor<T> cursor = getWriter();
try {
cursor.deleteAll();
commitWriter(cursor);
} finally {
releaseWriter(cursor);
}
}
/**
* WARNING: this method should generally be avoided as it is not transactional and thus may leave the DB in an
* inconsistent state. It may be the a last resort option to recover from a full DB.
* Like removeAll(), it removes all objects, returns the count of objects removed.
* Logs progress using warning log level.
*/
@Experimental
public long panicModeRemoveAll() {
return store.panicModeRemoveAllObjects(getEntityInfo().getEntityId());
}
/**
* Returns a builder to create queries for Object matching supplied criteria.
*/
public QueryBuilder<T> query() {
return new QueryBuilder<>(this, store.internalHandle(), store.getDbName(entityClass));
}
/**
* Experimental. This API might change or be removed in the future based on user feedback.
* <p>
* Applies the given query conditions and returns the builder for further customization, such as result order.
* Build the condition using the properties from your entity underscore classes.
* <p>
* An example with a nested OR condition:
* <pre>
* # Java
* box.query(User_.name.equal("Jane")
* .and(User_.age.less(12)
* .or(User_.status.equal("child"))));
*
* # Kotlin
* box.query(User_.name.equal("Jane")
* and (User_.age.less(12)
* or User_.status.equal("child")))
* </pre>
* This method is a shortcut for {@code query().apply(condition)}.
*
* @see QueryBuilder#apply(QueryCondition)
*/
@Experimental
public QueryBuilder<T> query(QueryCondition<T> queryCondition) {
return query().apply(queryCondition);
}
public BoxStore getStore() {
return store;
}
public synchronized EntityInfo<T> getEntityInfo() {
if (entityInfo == null) {
Cursor<T> reader = getReader();
try {
entityInfo = reader.getEntityInfo();
} finally {
releaseReader(reader);
}
}
return entityInfo;
}
@Beta
public void attach(T entity) {
if (boxStoreField == null) {
try {
boxStoreField = ReflectionCache.getInstance().getField(entityClass, "__boxStore");
} catch (Exception e) {
throw new DbException("Entity cannot be attached - only active entities with relationships support " +
"attaching (class has no __boxStore field(?)) : " + entityClass, e);
}
}
try {
boxStoreField.set(entity, store);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
// Sketching future API extension
private boolean isChanged(T entity) {
return false;
}
// Sketching future API extension
private boolean putIfChanged(T entity) {
return false;
}
public Class<T> getEntityClass() {
return entityClass;
}
@Internal
public List<T> internalGetBacklinkEntities(int entityId, Property<?> relationIdProperty, long key) {
Cursor<T> reader = getReader();
try {
return reader.getBacklinkEntities(entityId, relationIdProperty, key);
} finally {
releaseReader(reader);
}
}
@Internal
public List<T> internalGetRelationEntities(int sourceEntityId, int relationId, long key, boolean backlink) {
Cursor<T> reader = getReader();
try {
return reader.getRelationEntities(sourceEntityId, relationId, key, backlink);
} finally {
releaseReader(reader);
}
}
@Internal
public long[] internalGetRelationIds(int sourceEntityId, int relationId, long key, boolean backlink) {
Cursor<T> reader = getReader();
try {
return reader.getRelationIds(sourceEntityId, relationId, key, backlink);
} finally {
releaseReader(reader);
}
}
/**
* Given a ToMany relation and the ID of a source entity gets the target entities of the relation from their box,
* for example {@code orderBox.getRelationEntities(Customer_.orders, customer.getId())}.
*/
public List<T> getRelationEntities(RelationInfo<?, T> relationInfo, long id) {
return internalGetRelationEntities(relationInfo.sourceInfo.getEntityId(), relationInfo.relationId, id, false);
}
/**
* Given a ToMany relation and the ID of a target entity gets all source entities pointing to this target entity,
* for example {@code customerBox.getRelationEntities(Customer_.orders, order.getId())}.
*/
public List<T> getRelationBacklinkEntities(RelationInfo<T, ?> relationInfo, long id) {
return internalGetRelationEntities(relationInfo.sourceInfo.getEntityId(), relationInfo.relationId, id, true);
}
/**
* Like {@link #getRelationEntities(RelationInfo, long)}, but only returns the IDs of the target entities.
*/
public long[] getRelationIds(RelationInfo<?, T> relationInfo, long id) {
return internalGetRelationIds(relationInfo.sourceInfo.getEntityId(), relationInfo.relationId, id, false);
}
/**
* Like {@link #getRelationBacklinkEntities(RelationInfo, long)}, but only returns the IDs of the source entities.
*/
public long[] getRelationBacklinkIds(RelationInfo<T, ?> relationInfo, long id) {
return internalGetRelationIds(relationInfo.sourceInfo.getEntityId(), relationInfo.relationId, id, true);
}
@Internal
public <RESULT> RESULT internalCallWithReaderHandle(CallWithHandle<RESULT> task) {
Cursor<T> reader = getReader();
try {
return task.call(reader.internalHandle());
} finally {
releaseReader(reader);
}
}
@Internal
public <RESULT> RESULT internalCallWithWriterHandle(CallWithHandle<RESULT> task) {
Cursor<T> writer = getWriter();
RESULT result;
try {
result = task.call(writer.internalHandle());
commitWriter(writer);
} finally {
releaseWriter(writer);
}
return result;
}
public String getReaderDebugInfo() {
Cursor<T> reader = getReader();
try {
return reader + " with " + reader.getTx() + "; store's commit count: " + getStore().commitCount;
} finally {
releaseReader(reader);
}
}
}