-
Notifications
You must be signed in to change notification settings - Fork 199
/
MongoDBDialect.java
2126 lines (1851 loc) · 87.1 KB
/
MongoDBDialect.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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.datastore.mongodb;
import static java.lang.Boolean.FALSE;
import static org.hibernate.ogm.datastore.document.impl.DotPatternMapHelpers.getColumnSharedPrefixOfAssociatedEntityLink;
import static org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoHelpers.hasField;
import java.lang.invoke.MethodHandles;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.hibernate.AssertionFailure;
import org.hibernate.ogm.datastore.document.association.impl.DocumentHelpers;
import org.hibernate.ogm.datastore.document.cfg.DocumentStoreProperties;
import org.hibernate.ogm.datastore.document.impl.DotPatternMapHelpers;
import org.hibernate.ogm.datastore.document.impl.EmbeddableStateFinder;
import org.hibernate.ogm.datastore.document.options.AssociationStorageType;
import org.hibernate.ogm.datastore.document.options.MapStorageType;
import org.hibernate.ogm.datastore.document.options.spi.AssociationStorageOption;
import org.hibernate.ogm.datastore.map.impl.MapTupleSnapshot;
import org.hibernate.ogm.datastore.mongodb.binarystorage.GridFSStorageManager;
import org.hibernate.ogm.datastore.mongodb.configuration.impl.MongoDBConfiguration;
import org.hibernate.ogm.datastore.mongodb.dialect.impl.AssociationStorageStrategy;
import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBAssociationSnapshot;
import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoDBTupleSnapshot;
import org.hibernate.ogm.datastore.mongodb.dialect.impl.MongoHelpers;
import org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider;
import org.hibernate.ogm.datastore.mongodb.logging.impl.Log;
import org.hibernate.ogm.datastore.mongodb.logging.impl.LoggerFactory;
import org.hibernate.ogm.datastore.mongodb.options.AssociationDocumentStorageType;
import org.hibernate.ogm.datastore.mongodb.options.impl.AssociationDocumentStorageOption;
import org.hibernate.ogm.datastore.mongodb.options.impl.ReadConcernOption;
import org.hibernate.ogm.datastore.mongodb.options.impl.ReadPreferenceOption;
import org.hibernate.ogm.datastore.mongodb.options.impl.WriteConcernOption;
import org.hibernate.ogm.datastore.mongodb.query.impl.MongoDBQueryDescriptor;
import org.hibernate.ogm.datastore.mongodb.query.parsing.nativequery.impl.MongoDBQueryDescriptorBuilder;
import org.hibernate.ogm.datastore.mongodb.query.parsing.nativequery.impl.NativeQueryParser;
import org.hibernate.ogm.datastore.mongodb.type.GeoCollection;
import org.hibernate.ogm.datastore.mongodb.type.GeoLineString;
import org.hibernate.ogm.datastore.mongodb.type.GeoMultiLineString;
import org.hibernate.ogm.datastore.mongodb.type.GeoMultiPoint;
import org.hibernate.ogm.datastore.mongodb.type.GeoMultiPolygon;
import org.hibernate.ogm.datastore.mongodb.type.GeoPoint;
import org.hibernate.ogm.datastore.mongodb.type.GeoPolygon;
import org.hibernate.ogm.datastore.mongodb.type.impl.BinaryAsBsonBinaryGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoCollectionGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoLineStringGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoMultiLineStringGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoMultiPointGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoMultiPolygonGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoPointGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GeoPolygonGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GridFSGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.GridFSType;
import org.hibernate.ogm.datastore.mongodb.type.impl.ObjectIdGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.SerializableAsBinaryGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.StringAsObjectIdGridType;
import org.hibernate.ogm.datastore.mongodb.type.impl.StringAsObjectIdType;
import org.hibernate.ogm.datastore.mongodb.utils.DocumentUtil;
import org.hibernate.ogm.dialect.batch.spi.BatchableGridDialect;
import org.hibernate.ogm.dialect.batch.spi.GroupedChangesToEntityOperation;
import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateAssociationOperation;
import org.hibernate.ogm.dialect.batch.spi.InsertOrUpdateTupleOperation;
import org.hibernate.ogm.dialect.batch.spi.Operation;
import org.hibernate.ogm.dialect.batch.spi.OperationsQueue;
import org.hibernate.ogm.dialect.batch.spi.RemoveAssociationOperation;
import org.hibernate.ogm.dialect.batch.spi.RemoveTupleOperation;
import org.hibernate.ogm.dialect.identity.spi.IdentityColumnAwareGridDialect;
import org.hibernate.ogm.dialect.multiget.spi.MultigetGridDialect;
import org.hibernate.ogm.dialect.optimisticlock.spi.OptimisticLockingAwareGridDialect;
import org.hibernate.ogm.dialect.query.spi.BackendQuery;
import org.hibernate.ogm.dialect.query.spi.ClosableIterator;
import org.hibernate.ogm.dialect.query.spi.NoOpParameterMetadataBuilder;
import org.hibernate.ogm.dialect.query.spi.ParameterMetadataBuilder;
import org.hibernate.ogm.dialect.query.spi.QueryParameters;
import org.hibernate.ogm.dialect.query.spi.QueryableGridDialect;
import org.hibernate.ogm.dialect.spi.AssociationContext;
import org.hibernate.ogm.dialect.spi.AssociationTypeContext;
import org.hibernate.ogm.dialect.spi.BaseGridDialect;
import org.hibernate.ogm.dialect.spi.DuplicateInsertPreventionStrategy;
import org.hibernate.ogm.dialect.spi.ModelConsumer;
import org.hibernate.ogm.dialect.spi.NextValueRequest;
import org.hibernate.ogm.dialect.spi.OperationContext;
import org.hibernate.ogm.dialect.spi.TransactionContext;
import org.hibernate.ogm.dialect.spi.TupleAlreadyExistsException;
import org.hibernate.ogm.dialect.spi.TupleContext;
import org.hibernate.ogm.dialect.spi.TupleTypeContext;
import org.hibernate.ogm.dialect.spi.TuplesSupplier;
import org.hibernate.ogm.dialect.storedprocedure.spi.StoredProcedureAwareGridDialect;
import org.hibernate.ogm.entityentry.impl.TuplePointer;
import org.hibernate.ogm.model.key.spi.AssociationKey;
import org.hibernate.ogm.model.key.spi.AssociationKeyMetadata;
import org.hibernate.ogm.model.key.spi.AssociationKind;
import org.hibernate.ogm.model.key.spi.AssociationType;
import org.hibernate.ogm.model.key.spi.EntityKey;
import org.hibernate.ogm.model.key.spi.EntityKeyMetadata;
import org.hibernate.ogm.model.key.spi.IdSourceKey;
import org.hibernate.ogm.model.key.spi.RowKey;
import org.hibernate.ogm.model.spi.Association;
import org.hibernate.ogm.model.spi.Tuple;
import org.hibernate.ogm.model.spi.Tuple.SnapshotType;
import org.hibernate.ogm.model.spi.TupleOperation;
import org.hibernate.ogm.options.spi.OptionsContext;
import org.hibernate.ogm.storedprocedure.ProcedureQueryParameters;
import org.hibernate.ogm.type.impl.ByteStringType;
import org.hibernate.ogm.type.impl.CharacterStringType;
import org.hibernate.ogm.type.impl.LocalDateAsStringType;
import org.hibernate.ogm.type.impl.LocalDateTimeAsStringType;
import org.hibernate.ogm.type.impl.LocalTimeAsStringType;
import org.hibernate.ogm.type.impl.StringCalendarDateType;
import org.hibernate.ogm.type.impl.TimestampAsDateType;
import org.hibernate.ogm.type.spi.GridType;
import org.hibernate.ogm.util.impl.CollectionHelper;
import org.hibernate.ogm.util.impl.StringHelper;
import org.hibernate.type.MaterializedBlobType;
import org.hibernate.type.SerializableToBlobType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import org.parboiled.Parboiled;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.parserunners.RecoveringParseRunner;
import org.parboiled.support.ParsingResult;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.MongoCommandException;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MapReduceIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.CollationAlternate;
import com.mongodb.client.model.CollationCaseFirst;
import com.mongodb.client.model.CollationMaxVariable;
import com.mongodb.client.model.CollationStrength;
import com.mongodb.client.model.FindOneAndDeleteOptions;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.MapReduceAction;
import com.mongodb.client.model.ReplaceOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
/**
* Each Tuple entry is stored as a property in a MongoDB document.
*
* Each association is stored in an association document containing three properties:
* - the association table name (optionally)
* - the RowKey column names and values
* - the tuples as an array of elements
*
* Associations can be stored as:
* - one MongoDB collection per association class. The collection name is prefixed.
* - one MongoDB collection for all associations (the association table name property in then used)
* - embed the collection info in the owning entity document is planned but not supported at the moment (OGM-177)
*
* Collection of embeddable are stored within the owning entity document under the
* unqualified collection role
*
* In MongoDB is possible to batch operations but only for the creation of new documents
* and only if they don't have invalid characters in the field name.
* If these conditions are not met, the MongoDB mechanism for batch operations
* is not going to be used.
*
* @author Guillaume Scheibel <guillaume.scheibel@gmail.com>
* @author Alan Fitton <alan at eth0.org.uk>
* @author Emmanuel Bernard <emmanuel@hibernate.org>
* @author Thorsten Möller <thorsten.moeller@sbi.ch>
* @author Guillaume Smet
* @author Aleksandr Mylnikov
*/
public class MongoDBDialect extends BaseGridDialect implements QueryableGridDialect<MongoDBQueryDescriptor>, BatchableGridDialect, IdentityColumnAwareGridDialect, MultigetGridDialect, OptimisticLockingAwareGridDialect,
StoredProcedureAwareGridDialect {
public static final String ID_FIELDNAME = "_id";
public static final String PROPERTY_SEPARATOR = ".";
public static final String ROWS_FIELDNAME = "rows";
public static final String TABLE_FIELDNAME = "table";
public static final String ASSOCIATIONS_COLLECTION_PREFIX = "associations_";
private static final Log log = LoggerFactory.make( MethodHandles.lookup() );
/**
* This is not Threadsafe!
*/
private static final NativeQueryParser NATIVE_QUERY_PARSER = Parboiled.createParser( NativeQueryParser.class );
private static final List<String> ROWS_FIELDNAME_LIST = Collections.singletonList( ROWS_FIELDNAME );
// match a number with optional '-' and decimal
private static final Pattern NUMBER_PATTERN = Pattern.compile( "\\d+(\\.\\d+)?" );
/**
* Pattern used to recognize a constraint violation on the primary key.
*
* MongoDB returns an exception with {@code .$_id_ } or {@code _id_ } while Fongo returns an exception with {@code ._id }
*/
private static final Pattern PRIMARY_KEY_CONSTRAINT_VIOLATION_MESSAGE = Pattern.compile( ".*[. ]\\$?_id_? .*" );
private final MongoDBDatastoreProvider provider;
private final MongoDatabase currentDB;
public MongoDBDialect(MongoDBDatastoreProvider provider) {
this.provider = provider;
this.currentDB = this.provider.getDatabase();
}
@Override
public Tuple getTuple(EntityKey key, OperationContext operationContext) {
Document found = this.getObject( key, operationContext );
return createTuple( key, operationContext, found );
}
@Override
public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) {
if ( keys.length == 0 ) {
return Collections.emptyList();
}
Object[] searchObjects = new Object[keys.length];
for ( int i = 0; i < keys.length; i++ ) {
searchObjects[i] = prepareIdObjectValue( keys[i].getColumnNames(), keys[i].getColumnValues() );
}
MongoCursor<Document> cursor = this.getObjects( keys[0].getMetadata(), searchObjects, tupleContext );
try {
return tuplesResult( keys, searchObjects, tupleContext, cursor );
}
finally {
if ( cursor != null ) {
cursor.close();
}
}
}
/*
* This method assumes that the entries in the cursor might not be in the same order as the keys and some keys might
* not have a matching result in the db.
*/
private static List<Tuple> tuplesResult(EntityKey[] keys, Object[] searchObjects, TupleContext tupleContext, MongoCursor<Document> cursor) {
// The list is initialized with null because some keys might not have a corresponding value in the cursor
Tuple[] tuples = new Tuple[searchObjects.length];
while ( cursor.hasNext() ) {
Document document = cursor.next();
for ( int i = 0; i < searchObjects.length; i++ ) {
if ( document.get( ID_FIELDNAME ).equals( searchObjects[i] ) ) {
tuples[i] = createTuple( keys[i], tupleContext, document );
// We assume there are no duplicated keys
break;
}
}
}
return Arrays.asList( tuples );
}
private static Tuple createTuple(EntityKey key, OperationContext operationContext, Document found) {
if ( found != null ) {
return new Tuple( new MongoDBTupleSnapshot( found, key.getMetadata() ), SnapshotType.UPDATE );
}
else if ( isInTheInsertionQueue( key, operationContext ) ) {
// The key has not been inserted in the db but it is in the queue
return new Tuple( new MongoDBTupleSnapshot( prepareIdObject( key ), key.getMetadata() ), SnapshotType.INSERT );
}
else {
return null;
}
}
@Override
public Tuple createTuple(EntityKeyMetadata entityKeyMetadata, OperationContext operationContext) {
return new Tuple( new MongoDBTupleSnapshot( new Document(), entityKeyMetadata ), SnapshotType.INSERT );
}
@Override
public Tuple createTuple(EntityKey key, OperationContext OperationContext) {
Document toSave = prepareIdObject( key );
return new Tuple( new MongoDBTupleSnapshot( toSave, key.getMetadata() ), SnapshotType.INSERT );
}
/**
* Returns a {@link Document} representing the entity which embeds the specified association.
*/
private Document getEmbeddingEntity(AssociationKey key, AssociationContext associationContext) {
Document embeddingEntityDocument = associationContext.getEntityTuplePointer().getTuple() != null ?
( (MongoDBTupleSnapshot) associationContext.getEntityTuplePointer().getTuple().getSnapshot() ).getDbObject() : null;
if ( embeddingEntityDocument != null ) {
return embeddingEntityDocument;
}
else {
MongoCollection<Document> collection = getCollection( key.getEntityKey(), associationContext.getAssociationTypeContext().getOptionsContext() );
Document searchObject = prepareIdObject( key.getEntityKey() );
Document projection = getProjection( key, true );
return collection.find( searchObject ).projection( projection ).first();
}
}
private Document getObject(EntityKey key, OperationContext operationContext) {
MongoCollection<Document> collection = getCollection( key, operationContext.getTupleTypeContext().getOptionsContext() );
Document searchObject = prepareIdObject( key );
Document projection = getProjection( operationContext );
FindIterable<Document> fi = collection.find( searchObject );
Document targetDocument = fi != null ? fi.projection( projection ).first() : null;
provider.getBinaryStorageManager().loadContentFromBinaryStorage( targetDocument, key.getMetadata() );
return targetDocument;
}
private MongoCursor<Document> getObjects(EntityKeyMetadata entityKeyMetadata, Object[] searchObjects, TupleContext
tupleContext) {
MongoCollection<Document> collection = getCollection( entityKeyMetadata.getTable(), tupleContext.getTupleTypeContext().getOptionsContext() );
Document projection = getProjection( tupleContext );
Document query = new Document();
query.put( ID_FIELDNAME, new Document( "$in", Arrays.asList( searchObjects ) ) );
return collection.find( query ).projection( projection ).iterator();
}
private static Document getProjection(OperationContext operationContext) {
Set<String> columns = new HashSet<>();
columns.addAll( operationContext.getTupleTypeContext().getPolymorphicEntityColumns() );
columns.addAll( operationContext.getTupleTypeContext().getSelectableColumns() );
return getProjection( new ArrayList<>( columns ) );
}
/**
* Returns a projection object for specifying the fields to retrieve during a specific find operation.
*/
private static Document getProjection(List<String> fieldNames) {
Document projection = new Document();
for ( String column : fieldNames ) {
projection.put( column, 1 );
}
return projection;
}
/**
* Create a Document which represents the _id field.
* In case of simple id objects the json representation will look like {_id: "theIdValue"}
* In case of composite id objects the json representation will look like {_id: {author: "Guillaume", title: "What this method is used for?"}}
*
* @param key
*
* @return the Document which represents the id field
*/
private static Document prepareIdObject(EntityKey key) {
return prepareIdObject( key.getColumnNames(), key.getColumnValues() );
}
private static Document prepareIdObject(IdSourceKey key) {
return prepareIdObject( key.getColumnName(), key.getColumnValue() );
}
private static Document prepareIdObject(String columnName, String columnValue) {
return new Document( ID_FIELDNAME, prepareIdObjectValue( columnName, columnValue ) );
}
private static Document prepareIdObject(String[] columnNames, Object[] columnValues) {
return new Document( ID_FIELDNAME, prepareIdObjectValue( columnNames, columnValues ) );
}
private static Object prepareIdObjectValue(String columnName, String columnValue) {
return columnValue;
}
private static Object prepareIdObjectValue(String[] columnNames, Object[] columnValues) {
if ( columnNames.length == 1 ) {
return columnValues[0];
}
else {
Document idObject = new Document();
for ( int i = 0; i < columnNames.length; i++ ) {
String columnName = columnNames[i];
Object columnValue = columnValues[i];
if ( columnName.contains( PROPERTY_SEPARATOR ) ) {
int dotIndex = columnName.indexOf( PROPERTY_SEPARATOR );
String shortColumnName = columnName.substring( dotIndex + 1 );
idObject.put( shortColumnName, columnValue );
}
else {
idObject.put( columnNames[i], columnValue );
}
}
return idObject;
}
}
private MongoCollection<Document> getCollection(String table, OptionsContext context) {
MongoCollection<Document> collection = currentDB.getCollection( table );
if ( context != null ) {
return withOptions( collection, context );
}
return collection;
}
private MongoCollection<Document> getCollection( EntityKey key) {
return getCollection( key.getTable(), null );
}
private MongoCollection<Document> getCollection( EntityKey key, OptionsContext context ) {
return getCollection( key.getTable(), context );
}
private MongoCollection<Document> withOptions(MongoCollection<Document> collection, OptionsContext context) {
MongoCollection<Document> newCollection = collection;
newCollection = withReadPreference( context, newCollection );
newCollection = withReadConcern( context, newCollection );
newCollection = withWriteConcern( context, newCollection );
return newCollection;
}
private MongoCollection<Document> withReadConcern(OptionsContext context, MongoCollection<Document> newCollection) {
ReadConcern readConcern = context.getUnique( ReadConcernOption.class );
if ( readConcern != null ) {
newCollection = newCollection.withReadConcern( readConcern );
}
return newCollection;
}
private MongoCollection<Document> withReadPreference(OptionsContext context, MongoCollection<Document> newCollection) {
ReadPreference readPreference = context.getUnique( ReadPreferenceOption.class );
if ( readPreference != null ) {
return newCollection.withReadPreference( readPreference );
}
return newCollection;
}
private MongoCollection<Document> withWriteConcern(OptionsContext context, MongoCollection<Document> newCollection) {
WriteConcern writeConcern = context.getUnique( WriteConcernOption.class );
if ( writeConcern != null ) {
return newCollection.withWriteConcern( writeConcern );
}
return newCollection;
}
private MongoCollection<Document> getAssociationCollection(AssociationKey key, AssociationStorageStrategy storageStrategy, AssociationContext associationContext) {
if ( storageStrategy == AssociationStorageStrategy.GLOBAL_COLLECTION ) {
return getCollection( MongoDBConfiguration.DEFAULT_ASSOCIATION_STORE, associationContext.getAssociationTypeContext().getOptionsContext() );
}
else {
return getCollection( ASSOCIATIONS_COLLECTION_PREFIX + key.getTable(), associationContext.getAssociationTypeContext().getOptionsContext() );
}
}
private static Document getSubQuery(String operator, Document query) {
return query.get( operator ) != null ? (Document) query.get( operator ) : new Document();
}
private static void addSubQuery(String operator, Document query, String column, Object value) {
Document subQuery = getSubQuery( operator, query );
query.append( operator, subQuery.append( column, value ) );
}
private static void addSetToQuery(Document query, String column, Object value) {
removeSubQuery( "$unset", query, column );
addSubQuery( "$set", query, column, value );
}
private static void addUnsetToQuery(Document query, String column) {
removeSubQuery( "$set", query, column );
addSubQuery( "$unset", query, column, Integer.valueOf( 1 ) );
}
private static void removeSubQuery(String operator, Document query, String column) {
Document subQuery = getSubQuery( operator, query );
subQuery.remove( column );
if ( subQuery.isEmpty() ) {
query.remove( operator );
}
}
@Override
public void insertOrUpdateTuple(EntityKey key, TuplePointer tuplePointer, TupleContext tupleContext) {
throw new UnsupportedOperationException( "Method not supported in GridDialect anymore" );
}
@Override
//TODO deal with dotted column names once this method is used for ALL / Dirty optimistic locking
public boolean updateTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, Tuple tuple, TupleContext tupleContext) {
Document idObject = prepareIdObject( entityKey );
for ( String versionColumn : oldLockState.getColumnNames() ) {
idObject.put( versionColumn, oldLockState.get( versionColumn ) );
}
Document updater = objectForUpdate( tuple, tupleContext );
if ( updater.isEmpty() ) {
return false;
}
Document doc = getCollection( entityKey ).findOneAndUpdate( idObject, updater );
return doc != null;
}
@Override
public void insertTuple(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext) {
Document objectWithId = insertDocument( entityKeyMetadata, tuple, tupleContext );
String idColumnName = entityKeyMetadata.getColumnNames()[0];
tuple.put( idColumnName, objectWithId.get( ID_FIELDNAME ) );
}
/*
* InsertOne the tuple and return an object containing the id in the field ID_FIELDNAME
*/
private Document insertDocument(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext ) {
Document dbObject = objectForInsert( tuple, ( (MongoDBTupleSnapshot) tuple.getSnapshot() ).getDbObject() );
getCollection( entityKeyMetadata.getTable(), tupleContext.getTupleTypeContext().getOptionsContext() ).insertOne( dbObject );
return dbObject;
}
/**
* Creates a Document that can be passed to the MongoDB batch insert function
*/
private static Document objectForInsert(Tuple tuple, Document dbObject) {
MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();
for ( TupleOperation operation : tuple.getOperations() ) {
String column = operation.getColumn();
if ( notInIdField( snapshot, column ) ) {
switch ( operation.getType() ) {
case PUT:
MongoHelpers.setValue( dbObject, column, operation.getValue() );
break;
case PUT_NULL:
case REMOVE:
MongoHelpers.resetValue( dbObject, column );
break;
}
}
}
return dbObject;
}
private static Document objectForUpdate(Tuple tuple, TupleContext tupleContext) {
return objectForUpdate( tuple, tupleContext, new Document() );
}
private static Document objectForUpdate(Tuple tuple, TupleContext tupleContext, Document updateStatement) {
MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();
EmbeddableStateFinder embeddableStateFinder = new EmbeddableStateFinder( tuple, tupleContext );
Set<String> nullEmbeddables = new HashSet<>();
for ( TupleOperation operation : tuple.getOperations() ) {
String column = operation.getColumn();
if ( notInIdField( snapshot, column ) ) {
switch ( operation.getType() ) {
case PUT:
addSetToQuery( updateStatement, column, operation.getValue() );
break;
case PUT_NULL:
case REMOVE:
// try and find if this column is within an embeddable and if that embeddable is null
// if true, unset the full embeddable
String nullEmbeddable = embeddableStateFinder.getOuterMostNullEmbeddableIfAny( column );
if ( nullEmbeddable != null ) {
// we have a null embeddable
if ( ! nullEmbeddables.contains( nullEmbeddable ) ) {
// we have not processed it yet
addUnsetToQuery( updateStatement, nullEmbeddable );
nullEmbeddables.add( nullEmbeddable );
}
}
else {
// simply unset the column
addUnsetToQuery( updateStatement, column );
}
break;
}
}
}
return updateStatement;
}
private static boolean notInIdField(MongoDBTupleSnapshot snapshot, String column) {
return !column.equals( ID_FIELDNAME ) && !column.endsWith( PROPERTY_SEPARATOR + ID_FIELDNAME ) && !snapshot.isKeyColumn( column );
}
@Override
public void removeTuple(EntityKey key, TupleContext tupleContext) {
Document toDelete = prepareIdObject( key );
WriteConcern writeConcern = getWriteConcern( tupleContext );
MongoCollection<Document> collection = getCollection( key ).withWriteConcern( writeConcern );
Document deleted = collection.findOneAndDelete( toDelete );
if ( deleted != null ) {
provider.getBinaryStorageManager().removeEntityFromBinaryStorage( deleted, key.getMetadata() );
}
}
@Override
public boolean removeTupleWithOptimisticLock(EntityKey entityKey, Tuple oldLockState, TupleContext tupleContext) {
Document toDelete = prepareIdObject( entityKey );
for ( String versionColumn : oldLockState.getColumnNames() ) {
toDelete.put( versionColumn, oldLockState.get( versionColumn ) );
}
MongoCollection<Document> collection = getCollection( entityKey );
Document deleted = collection.findOneAndDelete( toDelete );
return deleted != null;
}
//not for embedded
private Document findAssociation(AssociationKey key, AssociationContext associationContext, AssociationStorageStrategy storageStrategy) {
final Document associationKeyObject = associationKeyToObject( key, storageStrategy );
MongoCollection<Document> associationCollection = getAssociationCollection( key, storageStrategy, associationContext );
FindIterable<Document> fi = associationCollection.find( associationKeyObject );
return fi != null ? ( fi.projection( getProjection( key, false ) ).first() ) : null ;
}
private static Document getProjection(AssociationKey key, boolean embedded) {
if ( embedded ) {
return getProjection( Collections.singletonList( key.getMetadata().getCollectionRole() ) );
}
else {
return getProjection( ROWS_FIELDNAME_LIST );
}
}
private static boolean isInTheInsertionQueue(EntityKey key, AssociationContext associationContext) {
OperationsQueue queue = associationContext.getOperationsQueue();
return queue != null && queue.isInTheInsertionQueue( key );
}
@Override
public Association getAssociation(AssociationKey key, AssociationContext associationContext) {
AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext );
if ( isEmbeddedAssociation( key ) && isInTheInsertionQueue( key.getEntityKey(), associationContext ) ) {
// The association is embedded and the owner of the association is in the insertion queue
Document idObject = prepareIdObject( key.getEntityKey() );
return new Association( new MongoDBAssociationSnapshot( idObject, key, storageStrategy ) );
}
// We need to execute the previous operations first or it won't be able to find the key that should have
// been created
executeBatch( associationContext.getOperationsQueue() );
if ( storageStrategy == AssociationStorageStrategy.IN_ENTITY ) {
Document entity = getEmbeddingEntity( key, associationContext );
if ( entity != null && hasField( entity, key.getMetadata().getCollectionRole() ) ) {
return new Association( new MongoDBAssociationSnapshot( entity, key, storageStrategy ) );
}
else {
return null;
}
}
final Document result = findAssociation( key, associationContext, storageStrategy );
if ( result == null ) {
return null;
}
else {
return new Association( new MongoDBAssociationSnapshot( result, key, storageStrategy ) );
}
}
private static boolean isEmbeddedAssociation(AssociationKey key) {
return AssociationKind.EMBEDDED_COLLECTION == key.getMetadata().getAssociationKind();
}
@Override
public Association createAssociation(AssociationKey key, AssociationContext associationContext) {
AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( key, associationContext );
Document document = storageStrategy == AssociationStorageStrategy.IN_ENTITY
? getEmbeddingEntity( key, associationContext )
: associationKeyToObject( key, storageStrategy );
Association association = new Association( new MongoDBAssociationSnapshot( document, key, storageStrategy ) );
// in the case of an association stored in the entity structure, we might end up with rows present in the
// current snapshot of the entity while we want an empty association here. So, in this case, we clear the
// snapshot to be sure the association created is empty.
if ( !association.isEmpty() ) {
association.clear();
}
return association;
}
/**
* Returns the rows of the given association as to be stored in the database. The return value is one of the
* following:
* <ul>
* <li>A list of plain values such as {@code String}s, {@code int}s etc. in case there is exactly one row key column
* which is not part of the association key (in this case we don't need to persist the key name as it can be
* restored from the association key upon loading) or</li>
* <li>A list of {@code Document}s with keys/values for all row key columns which are not part of the association
* key</li>
* <li>A {@link Document} with a key for each entry in case the given association has exactly one row key column
* which is of type {@code String} (e.g. a hash map) and {@link DocumentStoreProperties#MAP_STORAGE} is not set to
* {@link MapStorageType#AS_LIST}. The map values will either be plain values (in case it's single values) or
* another {@code Document}.
* </ul>
*/
private static Object getAssociationRows(Association association, AssociationKey key, AssociationContext associationContext) {
boolean organizeByRowKey = DotPatternMapHelpers.organizeAssociationMapByRowKey( association, key, associationContext );
// transform map entries such as ( addressType='home', address_id=123) into the more
// natural ( { 'home'=123 }
if ( organizeByRowKey ) {
String rowKeyColumn = organizeByRowKey ? key.getMetadata().getRowKeyIndexColumnNames()[0] : null;
Document rows = new Document();
for ( RowKey rowKey : association.getKeys() ) {
Document row = (Document) getAssociationRow( association.get( rowKey ), key );
String rowKeyValue = (String) row.remove( rowKeyColumn );
// if there is a single column on the value side left, unwrap it
if ( row.keySet().size() == 1 ) {
rows.put( rowKeyValue, DocumentUtil.toMap( row ).values().iterator().next() );
}
else {
rows.put( rowKeyValue, row );
}
}
return rows;
}
// non-map rows can be taken as is
else {
List<Object> rows = new ArrayList<>();
for ( RowKey rowKey : association.getKeys() ) {
rows.add( getAssociationRow( association.get( rowKey ), key ) );
}
return rows;
}
}
private static Object getAssociationRow(Tuple row, AssociationKey associationKey) {
String[] rowKeyColumnsToPersist = associationKey.getMetadata().getColumnsWithoutKeyColumns( row.getColumnNames() );
// return value itself if there is only a single column to store
if ( rowKeyColumnsToPersist.length == 1 ) {
return row.get( rowKeyColumnsToPersist[0] );
}
// otherwise a Document with the row contents
else {
// if the columns are only made of the embedded id columns, remove the embedded id property prefix
// collectionrole: [ { id: { id1: "foo", id2: "bar" } } ] becomes collectionrole: [ { id1: "foo", id2: "bar" } ]
String prefix = getColumnSharedPrefixOfAssociatedEntityLink( associationKey );
Document rowObject = new Document();
for ( String column : rowKeyColumnsToPersist ) {
Object value = row.get( column );
if ( value != null ) {
// remove the prefix if present
String columnName = column.startsWith( prefix ) ? column.substring( prefix.length() ) : column;
MongoHelpers.setValue( rowObject, columnName, value );
}
}
return rowObject;
}
}
@Override
public void insertOrUpdateAssociation(AssociationKey key, Association association, AssociationContext associationContext) {
throw new UnsupportedOperationException( "Method not supported in GridDialect anymore" );
}
@Override
public void removeAssociation(AssociationKey key, AssociationContext associationContext) {
throw new UnsupportedOperationException( "Method not supported in GridDialect anymore" );
}
@Override
public Number nextValue(NextValueRequest request) {
String valueColumnName = request.getKey().getMetadata().getValueColumnName();
MongoCollection<Document> sequenceCollection = getCollection( request.getKey().getTable(), null );
Document sequenceId = prepareIdObject( request.getKey() );
Document setInitialValueOnInsert = new Document();
addSubQuery( "$setOnInsert", setInitialValueOnInsert, valueColumnName, request.getInitialValue() + request.getIncrement() );
// I don't trust to make this a constant because the object is not immutable
FindOneAndUpdateOptions enableUpsert = new FindOneAndUpdateOptions().upsert( true );
Document originalDocument = sequenceCollection.findOneAndUpdate( sequenceId, setInitialValueOnInsert, enableUpsert );
Object nextValue = null;
if ( originalDocument == null ) {
return request.getInitialValue(); // first time we ask this value
}
else {
// all columns should match to find the value
Document incrementUpdate = new Document();
addSubQuery( "$inc", incrementUpdate, valueColumnName, request.getIncrement() );
Document beforeUpdateDoc = sequenceCollection.findOneAndUpdate( sequenceId, incrementUpdate, new FindOneAndUpdateOptions().upsert( true ) );
nextValue = beforeUpdateDoc.get( valueColumnName );
}
return (Number) nextValue;
}
@Override
public boolean isStoredInEntityStructure(AssociationKeyMetadata associationKeyMetadata, AssociationTypeContext associationTypeContext) {
return getAssociationStorageStrategy( associationKeyMetadata, associationTypeContext ) == AssociationStorageStrategy.IN_ENTITY;
}
@Override
public GridType overrideType(Type type) {
// Override handling of calendar types
if ( type == StandardBasicTypes.CALENDAR || type == StandardBasicTypes.CALENDAR_DATE ) {
return StringCalendarDateType.INSTANCE;
}
else if ( type == StandardBasicTypes.TIMESTAMP ) {
return TimestampAsDateType.INSTANCE;
}
else if ( type == StandardBasicTypes.BINARY ) {
return BinaryAsBsonBinaryGridType.INSTANCE;
}
else if ( type == StandardBasicTypes.BYTE ) {
return ByteStringType.INSTANCE;
}
else if ( type == StandardBasicTypes.CHARACTER ) {
return CharacterStringType.INSTANCE;
}
else if ( type.getReturnedClass() == ObjectId.class ) {
return ObjectIdGridType.INSTANCE;
}
else if ( type instanceof StringAsObjectIdType ) {
return StringAsObjectIdGridType.INSTANCE;
}
else if ( type == GridFSType.INSTANCE ) {
return GridFSGridType.INSTANCE;
}
else if ( type instanceof SerializableToBlobType ) {
SerializableToBlobType<?> exposedType = (SerializableToBlobType<?>) type;
return new SerializableAsBinaryGridType<>( exposedType.getJavaTypeDescriptor() );
}
else if ( type instanceof MaterializedBlobType ) {
MaterializedBlobType exposedType = (MaterializedBlobType) type;
return new SerializableAsBinaryGridType<>( exposedType.getJavaTypeDescriptor() );
}
else if ( type.getReturnedClass() == GeoPoint.class ) {
return GeoPointGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoMultiPoint.class ) {
return GeoMultiPointGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoLineString.class ) {
return GeoLineStringGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoMultiLineString.class ) {
return GeoMultiLineStringGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoPolygon.class ) {
return GeoPolygonGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoMultiPolygon.class ) {
return GeoMultiPolygonGridType.INSTANCE;
}
else if ( type.getReturnedClass() == GeoCollection.class ) {
return GeoCollectionGridType.INSTANCE;
}
else if ( type.getReturnedClass().equals( LocalDate.class ) ) {
return LocalDateAsStringType.INSTANCE;
}
else if ( type.getReturnedClass().equals( LocalDateTime.class ) ) {
return LocalDateTimeAsStringType.INSTANCE;
}
else if ( type.getReturnedClass().equals( LocalTime.class ) ) {
return LocalTimeAsStringType.INSTANCE;
}
return null; // all other types handled as in hibernate-ogm-core
}
@Override
public void forEachTuple(ModelConsumer consumer, TupleTypeContext tupleTypeContext, EntityKeyMetadata entityKeyMetadata) {
MongoCollection<Document> collection = getCollection( entityKeyMetadata.getTable(), tupleTypeContext.getOptionsContext() );
consumer.consume( new MongoDBTuplesSupplier( collection, entityKeyMetadata, provider.getBinaryStorageManager() ) );
}
@Override
public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<MongoDBQueryDescriptor> backendQuery, QueryParameters queryParameters, TupleContext tupleContext) {
MongoDBQueryDescriptor queryDescriptor = backendQuery.getQuery();
EntityKeyMetadata entityKeyMetadata = backendQuery.getSingleEntityMetadataInformationOrNull() == null
? null
: backendQuery.getSingleEntityMetadataInformationOrNull().getEntityKeyMetadata();
// Projections and addEntities are not allowed in the same query at the same time
if ( entityKeyMetadata != null && queryDescriptor.getProjection() != null ) {
throw log.addEntityNotAllowedInNativeQueriesUsingProjection( entityKeyMetadata.getTable(), backendQuery.toString() );
}
String collectionName = getCollectionName( backendQuery, queryDescriptor, entityKeyMetadata );
OptionsContext typeContext = entityKeyMetadata == null ? null : getOptionsContext( tupleContext );
MongoCollection<Document> collection = getCollection( collectionName, typeContext );
if ( !queryParameters.getPositionalParameters().isEmpty() ) { // TODO Implement binding positional parameters.
throw new UnsupportedOperationException( "Positional parameters are not yet supported for MongoDB native queries." );
}
switch ( queryDescriptor.getOperation() ) {
case FIND:
return doFind( queryDescriptor, queryParameters, collection, entityKeyMetadata );
case FINDONE:
return doFindOne( queryDescriptor, collection, entityKeyMetadata );
case FINDANDMODIFY:
return doFindAndModify( queryDescriptor, collection, entityKeyMetadata );
case AGGREGATE:
return doAggregate( queryDescriptor, queryParameters, collection, entityKeyMetadata );
case AGGREGATE_PIPELINE:
return doAggregatePipeline( queryDescriptor, queryParameters, collection, entityKeyMetadata );
case COUNT:
return doCount( queryDescriptor, collection );
case DISTINCT:
return doDistinct( queryDescriptor, collection );
case MAP_REDUCE:
return doMapReduce( queryDescriptor, collection );
case INSERT:
case INSERTONE:
case INSERTMANY:
case REMOVE:
case DELETEMANY:
case DELETEONE:
case UPDATE:
case UPDATEONE:
case UPDATEMANY:
case REPLACEONE:
throw log.updateQueryMustBeExecutedViaExecuteUpdate( queryDescriptor );
default:
throw new IllegalArgumentException( "Unexpected query operation: " + queryDescriptor );
}
}
@Override
public int executeBackendUpdateQuery(final BackendQuery<MongoDBQueryDescriptor> backendQuery, final QueryParameters queryParameters, final TupleContext tupleContext) {
MongoDBQueryDescriptor queryDescriptor = backendQuery.getQuery();
EntityKeyMetadata entityKeyMetadata =
backendQuery.getSingleEntityMetadataInformationOrNull() == null ? null :
backendQuery.getSingleEntityMetadataInformationOrNull().getEntityKeyMetadata();
String collectionName = getCollectionName( backendQuery, queryDescriptor, entityKeyMetadata );
MongoCollection<Document> collection = provider.getDatabase().getCollection( collectionName );
if ( !queryParameters.getPositionalParameters().isEmpty() ) { // TODO Implement binding positional parameters.
throw new UnsupportedOperationException( "Positional parameters are not yet supported for MongoDB native queries." );
}
switch ( queryDescriptor.getOperation() ) {
case INSERTMANY:
case INSERTONE:
case INSERT:
return doInsert( queryDescriptor, collection );
case REPLACEONE:
return doReplaceOne( queryDescriptor, collection );
case REMOVE:
case DELETEMANY:
case DELETEONE:
return doRemove( queryDescriptor, collection, queryDescriptor.getOperation() );
case UPDATE:
case UPDATEONE:
case UPDATEMANY: