forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathin_memory_document_session_operations.go
1365 lines (1157 loc) · 42.4 KB
/
in_memory_document_session_operations.go
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
package ravendb
import (
"fmt"
"reflect"
"sync/atomic"
"time"
)
var (
clientSessionIDCounter int32 = 1
)
func newClientSessionID() int {
newID := atomic.AddInt32(&clientSessionIDCounter, 1)
return int(newID)
}
type onLazyEval struct {
fn func()
result interface{}
}
// InMemoryDocumentSessionOperations represents database operations queued
// in memory
type InMemoryDocumentSessionOperations struct {
clientSessionID int
deletedEntities *objectSet
requestExecutor *RequestExecutor
operationExecutor *OperationExecutor
pendingLazyOperations []ILazyOperation
onEvaluateLazy map[ILazyOperation]*onLazyEval
generateDocumentKeysOnStore bool
sessionInfo *SessionInfo
saveChangesOptions *BatchOptions
isDisposed bool
// Note: skipping unused isDisposed
id string
onBeforeStore []func(*BeforeStoreEventArgs)
onAfterSaveChanges []func(*AfterSaveChangesEventArgs)
onBeforeDelete []func(*BeforeDeleteEventArgs)
onBeforeQuery []func(*BeforeQueryEventArgs)
// ids of entities that were deleted
knownMissingIds []string // case insensitive
// Note: skipping unused externalState
documentsByID *documentsByID
// Translate between an ID and its associated entity
// TODO: ignore case for keys
includedDocumentsByID map[string]*documentInfo
// hold the data required to manage the data for RavenDB's Unit of Work
// Note: in Java it's LinkedHashMap where iteration order is same
// as insertion order. In Go map has random iteration order so we must
// use an array
documentsByEntity []*documentInfo
documentStore *DocumentStore
DatabaseName string
numberOfRequests int
Conventions *DocumentConventions
maxNumberOfRequestsPerSession int
useOptimisticConcurrency bool
deferredCommands []ICommandData
// Note: using value type so that lookups are based on value
deferredCommandsMap map[idTypeAndName]ICommandData
generateEntityIDOnTheClient *generateEntityIDOnTheClient
entityToJSON *entityToJSON
// Note: in java DocumentSession inherits from InMemoryDocumentSessionOperations
// so we can upcast/downcast between them
// In Go we need a backlink to reach DocumentSession
session *DocumentSession
}
func newInMemoryDocumentSessionOperations(dbName string, store *DocumentStore, re *RequestExecutor, id string) *InMemoryDocumentSessionOperations {
clientSessionID := newClientSessionID()
res := &InMemoryDocumentSessionOperations{
id: id,
clientSessionID: clientSessionID,
deletedEntities: newObjectSet(),
requestExecutor: re,
generateDocumentKeysOnStore: true,
sessionInfo: &SessionInfo{SessionID: clientSessionID},
documentsByID: newDocumentsByID(),
includedDocumentsByID: map[string]*documentInfo{},
documentsByEntity: []*documentInfo{},
documentStore: store,
DatabaseName: dbName,
maxNumberOfRequestsPerSession: re.conventions.MaxNumberOfRequestsPerSession,
useOptimisticConcurrency: re.conventions.UseOptimisticConcurrency,
deferredCommandsMap: map[idTypeAndName]ICommandData{},
}
genIDFunc := func(entity interface{}) (string, error) {
return res.GenerateID(entity)
}
res.generateEntityIDOnTheClient = newGenerateEntityIDOnTheClient(re.conventions, genIDFunc)
res.entityToJSON = newEntityToJSON(res)
return res
}
func (s *InMemoryDocumentSessionOperations) GetCurrentSessionNode() (*ServerNode, error) {
var result *CurrentIndexAndNode
readBalance := s.documentStore.GetConventions().ReadBalanceBehavior
var err error
switch readBalance {
case ReadBalanceBehaviorNone:
result, err = s.requestExecutor.getPreferredNode()
case ReadBalanceBehaviorRoundRobin:
result, err = s.requestExecutor.getNodeBySessionID(s.clientSessionID)
case ReadBalanceBehaviorFastestNode:
result, err = s.requestExecutor.getFastestNode()
default:
return nil, newIllegalArgumentError("unknown readBalance value %s", readBalance)
}
if err != nil {
return nil, err
}
return result.currentNode, nil
}
// GetDeferredCommandsCount returns number of deferred commands
func (s *InMemoryDocumentSessionOperations) GetDeferredCommandsCount() int {
return len(s.deferredCommands)
}
// AddBeforeStoreStoreListener registers a function that will be called before storing an entity.
// Returns listener id that can be passed to RemoveBeforeStoreListener to unregister
// the listener.
func (s *InMemoryDocumentSessionOperations) AddBeforeStoreListener(handler func(*BeforeStoreEventArgs)) int {
s.onBeforeStore = append(s.onBeforeStore, handler)
return len(s.onBeforeStore) - 1
}
// RemoveBeforeStoreListener removes a listener given id returned by AddBeforeStoreListener
func (s *InMemoryDocumentSessionOperations) RemoveBeforeStoreListener(handlerID int) {
s.onBeforeStore[handlerID] = nil
}
// AddAfterSaveChangesListener registers a function that will be called before saving changes.
// Returns listener id that can be passed to RemoveAfterSaveChangesListener to unregister
// the listener.
func (s *InMemoryDocumentSessionOperations) AddAfterSaveChangesListener(handler func(*AfterSaveChangesEventArgs)) int {
s.onAfterSaveChanges = append(s.onAfterSaveChanges, handler)
return len(s.onAfterSaveChanges) - 1
}
// RemoveAfterSaveChangesListener removes a listener given id returned by AddAfterSaveChangesListener
func (s *InMemoryDocumentSessionOperations) RemoveAfterSaveChangesListener(handlerID int) {
s.onAfterSaveChanges[handlerID] = nil
}
// AddBeforeDeleteListener registers a function that will be called before deleting an entity.
// Returns listener id that can be passed to RemoveBeforeDeleteListener to unregister
// the listener.
func (s *InMemoryDocumentSessionOperations) AddBeforeDeleteListener(handler func(*BeforeDeleteEventArgs)) int {
s.onBeforeDelete = append(s.onBeforeDelete, handler)
return len(s.onBeforeDelete) - 1
}
// RemoveBeforeDeleteListener removes a listener given id returned by AddBeforeDeleteListener
func (s *InMemoryDocumentSessionOperations) RemoveBeforeDeleteListener(handlerID int) {
s.onBeforeDelete[handlerID] = nil
}
// AddBeforeQueryListener registers a function that will be called before running a query.
// It allows customizing query via DocumentQueryCustomization.
// Returns listener id that can be passed to RemoveBeforeQueryListener to unregister
// the listener.
func (s *InMemoryDocumentSessionOperations) AddBeforeQueryListener(handler func(*BeforeQueryEventArgs)) int {
s.onBeforeQuery = append(s.onBeforeQuery, handler)
return len(s.onBeforeQuery) - 1
}
// RemoveBeforeQueryListener removes a listener given id returned by AddBeforeQueryListener
func (s *InMemoryDocumentSessionOperations) RemoveBeforeQueryListener(handlerID int) {
s.onBeforeQuery[handlerID] = nil
}
func (s *InMemoryDocumentSessionOperations) getEntityToJSON() *entityToJSON {
return s.entityToJSON
}
// GetNumberOfEntitiesInUnitOfWork returns number of entities
func (s *InMemoryDocumentSessionOperations) GetNumberOfEntitiesInUnitOfWork() int {
return len(s.documentsByEntity)
}
// GetConventions returns DocumentConventions
func (s *InMemoryDocumentSessionOperations) GetConventions() *DocumentConventions {
return s.requestExecutor.conventions
}
func (s *InMemoryDocumentSessionOperations) GenerateID(entity interface{}) (string, error) {
return s.GetConventions().GenerateDocumentID(s.DatabaseName, entity)
}
func (s *InMemoryDocumentSessionOperations) GetDocumentStore() *DocumentStore {
return s.documentStore
}
func (s *InMemoryDocumentSessionOperations) GetRequestExecutor() *RequestExecutor {
return s.requestExecutor
}
func (s *InMemoryDocumentSessionOperations) GetOperations() *OperationExecutor {
if s.operationExecutor == nil {
dbName := s.DatabaseName
s.operationExecutor = s.GetDocumentStore().Operations().ForDatabase(dbName)
}
return s.operationExecutor
}
// GetNumberOfRequests returns number of requests sent to the server
func (s *InMemoryDocumentSessionOperations) GetNumberOfRequests() int {
return s.numberOfRequests
}
// GetMetadataFor gets the metadata for the specified entity.
// TODO: should we make the API more robust by accepting **struct as well as
// *struct and doing the necessary tweaking automatically? It looks like
// GetMetadataFor(&foo) might be used reflexively and it might not be easy
// to figure out why it fails. Alternatively, error out early with informative
// error message
func (s *InMemoryDocumentSessionOperations) GetMetadataFor(instance interface{}) (*MetadataAsDictionary, error) {
err := checkValidEntityIn(instance, "instance")
if err != nil {
return nil, err
}
documentInfo, err := s.getDocumentInfo(instance)
if err != nil {
return nil, err
}
if documentInfo.metadataInstance != nil {
return documentInfo.metadataInstance, nil
}
metadataAsJSON := documentInfo.metadata
metadata := NewMetadataAsDictionaryWithSource(metadataAsJSON)
documentInfo.metadataInstance = metadata
return metadata, nil
}
// GetChangeVectorFor returns metadata for a given instance
// empty string means there is not change vector
func (s *InMemoryDocumentSessionOperations) GetChangeVectorFor(instance interface{}) (*string, error) {
err := checkValidEntityIn(instance, "instance")
if err != nil {
return nil, err
}
documentInfo, err := s.getDocumentInfo(instance)
if err != nil {
return nil, err
}
changeVector := jsonGetAsTextPointer(documentInfo.metadata, MetadataChangeVector)
return changeVector, nil
}
// GetLastModifiedFor returns last modified time for a given instance
func (s *InMemoryDocumentSessionOperations) GetLastModifiedFor(instance interface{}) (*time.Time, error) {
err := checkValidEntityIn(instance, "instance")
if err != nil {
return nil, err
}
documentInfo, err := s.getDocumentInfo(instance)
if err != nil {
return nil, err
}
lastModified, ok := jsonGetAsString(documentInfo.metadata, MetadataLastModified)
if !ok {
return nil, nil
}
t, err := ParseTime(lastModified)
if err != nil {
return nil, err
}
return &t, err
}
func getDocumentInfoByEntity(docs []*documentInfo, entity interface{}) *documentInfo {
for _, doc := range docs {
if doc.entity == entity {
return doc
}
}
return nil
}
// adds or replaces documentInfo in a list by entity
func setDocumentInfo(docsRef *[]*documentInfo, toAdd *documentInfo) {
docs := *docsRef
entity := toAdd.entity
for i, doc := range docs {
if doc.entity == entity {
docs[i] = toAdd
return
}
}
*docsRef = append(docs, toAdd)
}
// returns deleted documentInfo
func deleteDocumentInfoByEntity(docsRef *[]*documentInfo, entity interface{}) *documentInfo {
docs := *docsRef
for i, doc := range docs {
if doc.entity == entity {
docs = append(docs[:i], docs[i+1:]...)
*docsRef = docs
return doc
}
}
return nil
}
// getDocumentInfo returns documentInfo for a given instance
// Returns nil if not found
func (s *InMemoryDocumentSessionOperations) getDocumentInfo(instance interface{}) (*documentInfo, error) {
documentInfo := getDocumentInfoByEntity(s.documentsByEntity, instance)
if documentInfo != nil {
return documentInfo, nil
}
id, ok := s.generateEntityIDOnTheClient.tryGetIDFromInstance(instance)
if !ok {
return nil, newIllegalStateError("Could not find the document id for %s", instance)
}
if err := s.assertNoNonUniqueInstance(instance, id); err != nil {
return nil, err
}
err := fmt.Errorf("Document %#v doesn't exist in the session", instance)
return nil, err
}
// IsLoaded returns true if document with this id is loaded
func (s *InMemoryDocumentSessionOperations) IsLoaded(id string) bool {
return s.IsLoadedOrDeleted(id)
}
// IsLoadedOrDeleted returns true if document with this id is loaded
func (s *InMemoryDocumentSessionOperations) IsLoadedOrDeleted(id string) bool {
documentInfo := s.documentsByID.getValue(id)
if documentInfo != nil && documentInfo.document != nil {
// is loaded
return true
}
if s.IsDeleted(id) {
return true
}
_, found := s.includedDocumentsByID[id]
return found
}
// IsDeleted returns true if document with this id is deleted in this session
func (s *InMemoryDocumentSessionOperations) IsDeleted(id string) bool {
return stringArrayContainsNoCase(s.knownMissingIds, id)
}
// GetDocumentID returns id of a given instance
func (s *InMemoryDocumentSessionOperations) GetDocumentID(instance interface{}) string {
if instance == nil {
return ""
}
value := getDocumentInfoByEntity(s.documentsByEntity, instance)
if value == nil {
return ""
}
return value.id
}
// IncrementRequestCount increments requests count
func (s *InMemoryDocumentSessionOperations) incrementRequestCount() error {
s.numberOfRequests++
if s.numberOfRequests > s.maxNumberOfRequestsPerSession {
return newIllegalStateError("exceeded max number of requests per session of %d", s.maxNumberOfRequestsPerSession)
}
return nil
}
// result is a pointer to expected value
func (s *InMemoryDocumentSessionOperations) TrackEntityInDocumentInfo(result interface{}, documentFound *documentInfo) error {
return s.TrackEntity(result, documentFound.id, documentFound.document, documentFound.metadata, false)
}
// TrackEntity tracks a given object
// result is a pointer to a decoded value (e.g. **Foo) and will be set with
// value decoded from JSON (e.g. *result = &Foo{})
func (s *InMemoryDocumentSessionOperations) TrackEntity(result interface{}, id string, document map[string]interface{}, metadata map[string]interface{}, noTracking bool) error {
if id == "" {
return s.deserializeFromTransformer(result, "", document)
}
docInfo := s.documentsByID.getValue(id)
if docInfo != nil {
// the local instance may have been changed, we adhere to the current Unit of Work
// instance, and return that, ignoring anything new.
if docInfo.entity == nil {
err := s.entityToJSON.convertToEntity2(result, id, document)
if err != nil {
return err
}
docInfo.setEntity(result)
} else {
err := setInterfaceToValue(result, docInfo.entity)
if err != nil {
return err
}
}
if !noTracking {
delete(s.includedDocumentsByID, id)
setDocumentInfo(&s.documentsByEntity, docInfo)
}
return nil
}
docInfo = s.includedDocumentsByID[id]
if docInfo != nil {
// TODO: figure out a test case that fails if I invert setResultToDocEntity
setResultToDocEntity := true
if docInfo.entity == nil {
err := s.entityToJSON.convertToEntity2(result, id, document)
if err != nil {
return err
}
docInfo.setEntity(result)
setResultToDocEntity = false
}
if !noTracking {
delete(s.includedDocumentsByID, id)
s.documentsByID.add(docInfo)
setDocumentInfo(&s.documentsByEntity, docInfo)
}
if setResultToDocEntity {
return setInterfaceToValue(result, docInfo.entity)
}
return nil
}
err := s.entityToJSON.convertToEntity2(result, id, document)
if err != nil {
return err
}
changeVector := jsonGetAsTextPointer(metadata, MetadataChangeVector)
if changeVector == nil {
return newIllegalStateError("Document %s must have Change Vector", id)
}
if !noTracking {
newDocumentInfo := &documentInfo{}
newDocumentInfo.id = id
newDocumentInfo.document = document
newDocumentInfo.metadata = metadata
newDocumentInfo.setEntity(result)
newDocumentInfo.changeVector = changeVector
s.documentsByID.add(newDocumentInfo)
setDocumentInfo(&s.documentsByEntity, newDocumentInfo)
}
return nil
}
// will convert **Foo => *Foo if tp is *Foo and o is **Foo
// TODO: probably there's a better way
// Test case: TestCachingOfDocumentInclude.cofi_can_avoid_using_server_for_multiload_with_include_if_everything_is_in_session_cache
func matchValueToType(o interface{}, tp reflect.Type) interface{} {
vt := reflect.TypeOf(o)
if vt == tp {
return o
}
panicIf(vt.Kind() != reflect.Ptr, "couldn't match type ov v (%T) to %s\n", o, tp)
vt = vt.Elem()
panicIf(vt != tp, "couldn't match type ov v (%T) to %s\n", o, tp)
v := reflect.ValueOf(o)
v = v.Elem()
return v.Interface()
}
// Delete marks the specified entity for deletion. The entity will be deleted when SaveChanges is called.
func (s *InMemoryDocumentSessionOperations) Delete(entity interface{}) error {
err := checkValidEntityIn(entity, "entity")
if err != nil {
return err
}
value := getDocumentInfoByEntity(s.documentsByEntity, entity)
if value == nil {
return newIllegalStateError("%#v is not associated with the session, cannot delete unknown entity instance", entity)
}
s.deletedEntities.add(entity)
delete(s.includedDocumentsByID, value.id)
s.knownMissingIds = append(s.knownMissingIds, value.id)
return nil
}
// DeleteByID marks the specified entity for deletion. The entity will be deleted when SaveChanges is called.
// WARNING: This method will not call beforeDelete listener!
func (s *InMemoryDocumentSessionOperations) DeleteByID(id string, expectedChangeVector string) error {
if id == "" {
return newIllegalArgumentError("id cannot be empty")
}
var changeVector string
documentInfo := s.documentsByID.getValue(id)
if documentInfo != nil {
newObj := convertEntityToJSON(documentInfo.entity, documentInfo)
if documentInfo.entity != nil && s.entityChanged(newObj, documentInfo, nil) {
return newIllegalStateError("Can't delete changed entity using identifier. Use delete(Class clazz, T entity) instead.")
}
if documentInfo.entity != nil {
deleteDocumentInfoByEntity(&s.documentsByEntity, documentInfo.entity)
}
s.documentsByID.remove(id)
if documentInfo.changeVector != nil {
changeVector = *documentInfo.changeVector
}
}
s.knownMissingIds = append(s.knownMissingIds, id)
if !s.useOptimisticConcurrency {
changeVector = ""
}
cmdData := NewDeleteCommandData(id, firstNonEmptyString(expectedChangeVector, changeVector))
s.Defer(cmdData)
return nil
}
// checks if entity is of valid type for operations like Store(), Delete(), GetMetadataFor() etc.
// We support non-nil values of *struct and *map[string]interface{}
// see handling_maps.md for why *map[string]interface{} and not map[string]interface{}
func checkValidEntityIn(v interface{}, argName string) error {
if v == nil {
return newIllegalArgumentError("%s can't be nil", argName)
}
if _, ok := v.(map[string]interface{}); ok {
// possibly a common mistake, so try to provide a helpful error message
typeGot := fmt.Sprintf("%T", v)
typeExpect := "*" + typeGot
return newIllegalArgumentError("%s can't be of type %s, try passing %s", argName, typeGot, typeExpect)
}
if _, ok := v.(*map[string]interface{}); ok {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return newIllegalArgumentError("%s can't be a nil pointer to a map", argName)
}
rv = rv.Elem()
if rv.IsNil() {
return newIllegalArgumentError("%s can't be a pointer to a nil map", argName)
}
return nil
}
tp := reflect.TypeOf(v)
if tp.Kind() == reflect.Struct {
// possibly a common mistake, so try to provide a helpful error message
typeGot := fmt.Sprintf("%T", v)
typeExpect := "*" + typeGot
return newIllegalArgumentError("%s can't be of type %s, try passing %s", argName, typeGot, typeExpect)
}
if tp.Kind() != reflect.Ptr {
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
// at this point it's a pointer to some type
if reflect.ValueOf(v).IsNil() {
return newIllegalArgumentError("%s of type %T can't be nil", argName, v)
}
// we only allow pointer to struct
elem := tp.Elem()
if elem.Kind() == reflect.Struct {
return nil
}
if elem.Kind() == reflect.Ptr {
// possibly a common mistake, so try to provide a helpful error message
typeGot := fmt.Sprintf("%T", v)
typeExpect := typeGot[1:]
for len(typeExpect) > 0 && typeExpect[0] == '*' {
typeExpect = typeExpect[1:]
}
typeExpect = "*" + typeExpect
return newIllegalArgumentError("%s can't be of type %s, try passing %s", argName, typeGot, typeExpect)
}
return newIllegalArgumentError("%s can't be of type %T", argName, v)
}
// Store stores entity in the session. The entity will be saved when SaveChanges is called.
func (s *InMemoryDocumentSessionOperations) Store(entity interface{}) error {
err := checkValidEntityIn(entity, "entity")
if err != nil {
return err
}
_, hasID := s.generateEntityIDOnTheClient.tryGetIDFromInstance(entity)
concu := ConcurrencyCheckAuto
if !hasID {
concu = ConcurrencyCheckForced
}
return s.storeInternal(entity, "", "", concu)
}
// StoreWithID stores entity in the session, explicitly specifying its Id. The entity will be saved when SaveChanges is called.
func (s *InMemoryDocumentSessionOperations) StoreWithID(entity interface{}, id string) error {
err := checkValidEntityIn(entity, "entity")
if err != nil {
return err
}
return s.storeInternal(entity, "", id, ConcurrencyCheckAuto)
}
// StoreWithChangeVectorAndID stores entity in the session, explicitly specifying its id and change vector. The entity will be saved when SaveChanges is called.
func (s *InMemoryDocumentSessionOperations) StoreWithChangeVectorAndID(entity interface{}, changeVector string, id string) error {
err := checkValidEntityIn(entity, "entity")
if err != nil {
return err
}
concurr := ConcurrencyCheckDisabled
if changeVector != "" {
concurr = ConcurrencyCheckForced
}
return s.storeInternal(entity, changeVector, id, concurr)
}
func (s *InMemoryDocumentSessionOperations) rememberEntityForDocumentIdGeneration(entity interface{}) error {
return newNotImplementedError("You cannot set GenerateDocumentIDsOnStore to false without implementing rememberEntityForDocumentIdGeneration")
}
func (s *InMemoryDocumentSessionOperations) storeInternal(entity interface{}, changeVector string, id string, forceConcurrencyCheck ConcurrencyCheckMode) error {
value := getDocumentInfoByEntity(s.documentsByEntity, entity)
if value != nil {
if changeVector != "" {
value.changeVector = &changeVector
}
value.concurrencyCheckMode = forceConcurrencyCheck
return nil
}
var err error
if id == "" {
if s.generateDocumentKeysOnStore {
if id, err = s.generateEntityIDOnTheClient.generateDocumentKeyForStorage(entity); err != nil {
return err
}
} else {
if err = s.rememberEntityForDocumentIdGeneration(entity); err != nil {
return err
}
}
} else {
// Store it back into the Id field so the client has access to it
s.generateEntityIDOnTheClient.trySetIdentity(entity, id)
}
tmp := newIDTypeAndName(id, CommandClientAnyCommand, "")
if _, ok := s.deferredCommandsMap[tmp]; ok {
return newIllegalStateError("Can't Store document, there is a deferred command registered for this document in the session. Document id: %s", id)
}
if s.deletedEntities.contains(entity) {
return newIllegalStateError("Can't Store object, it was already deleted in this session. Document id: %s", id)
}
// we make the check here even if we just generated the ID
// users can override the ID generation behavior, and we need
// to detect if they generate duplicates.
if err := s.assertNoNonUniqueInstance(entity, id); err != nil {
return err
}
collectionName := s.requestExecutor.GetConventions().getCollectionName(entity)
metadata := map[string]interface{}{}
if collectionName != "" {
metadata[MetadataCollection] = collectionName
}
goType := s.requestExecutor.GetConventions().getGoTypeName(entity)
if goType != "" {
metadata[MetadataRavenGoType] = goType
}
if id != "" {
s.knownMissingIds = stringArrayRemoveNoCase(s.knownMissingIds, id)
}
var changeVectorPtr *string
if changeVector != "" {
changeVectorPtr = &changeVector
}
s.storeEntityInUnitOfWork(id, entity, changeVectorPtr, metadata, forceConcurrencyCheck)
return nil
}
func (s *InMemoryDocumentSessionOperations) storeEntityInUnitOfWork(id string, entity interface{}, changeVector *string, metadata map[string]interface{}, forceConcurrencyCheck ConcurrencyCheckMode) {
s.deletedEntities.remove(entity)
if id != "" {
s.knownMissingIds = stringArrayRemoveNoCase(s.knownMissingIds, id)
}
documentInfo := &documentInfo{}
documentInfo.id = id
documentInfo.metadata = metadata
documentInfo.changeVector = changeVector
documentInfo.concurrencyCheckMode = forceConcurrencyCheck
documentInfo.setEntity(entity)
documentInfo.newDocument = true
documentInfo.document = nil
setDocumentInfo(&s.documentsByEntity, documentInfo)
if id != "" {
s.documentsByID.add(documentInfo)
}
}
func (s *InMemoryDocumentSessionOperations) assertNoNonUniqueInstance(entity interface{}, id string) error {
nLastChar := len(id) - 1
if len(id) == 0 || id[nLastChar] == '|' || id[nLastChar] == '/' {
return nil
}
info := s.documentsByID.getValue(id)
if info == nil || info.entity == entity {
return nil
}
return newNonUniqueObjectError("Attempted to associate a different object with id '" + id + "'.")
}
func (s *InMemoryDocumentSessionOperations) prepareForSaveChanges() (*saveChangesData, error) {
result := newSaveChangesData(s)
s.deferredCommands = nil
s.deferredCommandsMap = make(map[idTypeAndName]ICommandData)
err := s.prepareForEntitiesDeletion(result, nil)
if err != nil {
return nil, err
}
err = s.prepareForEntitiesPuts(result)
if err != nil {
return nil, err
}
if len(s.deferredCommands) > 0 {
// this allow OnBeforeStore to call Defer during the call to include
// additional values during the same SaveChanges call
result.deferredCommands = append(result.deferredCommands, s.deferredCommands...)
for k, v := range s.deferredCommandsMap {
result.deferredCommandsMap[k] = v
}
s.deferredCommands = nil
s.deferredCommandsMap = nil
}
return result, nil
}
func (s *InMemoryDocumentSessionOperations) UpdateMetadataModifications(documentInfo *documentInfo) bool {
dirty := false
metadataInstance := documentInfo.metadataInstance
metadata := documentInfo.metadata
if metadataInstance != nil {
if metadataInstance.IsDirty() {
dirty = true
}
props := metadataInstance.KeySet()
for _, prop := range props {
propValue, ok := metadataInstance.Get(prop)
if !ok {
dirty = true
continue
}
if d, ok := propValue.(*MetadataAsDictionary); ok {
if d.IsDirty() {
dirty = true
}
}
metadata[prop] = propValue
}
}
return dirty
}
func (s *InMemoryDocumentSessionOperations) prepareForEntitiesDeletion(result *saveChangesData, changes map[string][]*DocumentsChanges) error {
for deletedEntity := range s.deletedEntities.items {
documentInfo := getDocumentInfoByEntity(s.documentsByEntity, deletedEntity)
if documentInfo == nil {
continue
}
if changes != nil {
docChanges := []*DocumentsChanges{}
change := &DocumentsChanges{
FieldNewValue: "",
FieldOldValue: "",
Change: DocumentChangeDocumentDeleted,
}
docChanges = append(docChanges, change)
changes[documentInfo.id] = docChanges
} else {
idType := newIDTypeAndName(documentInfo.id, CommandClientAnyCommand, "")
command := result.deferredCommandsMap[idType]
if command != nil {
err := s.throwInvalidDeletedDocumentWithDeferredCommand(command)
if err != nil {
return err
}
}
var changeVector *string
documentInfo = s.documentsByID.getValue(documentInfo.id)
if documentInfo != nil {
changeVector = documentInfo.changeVector
if documentInfo.entity != nil {
deleteDocumentInfoByEntity(&s.documentsByEntity, documentInfo.entity)
result.addEntity(documentInfo.entity)
}
s.documentsByID.remove(documentInfo.id)
}
if !s.useOptimisticConcurrency {
changeVector = nil
}
beforeDeleteEventArgs := newBeforeDeleteEventArgs(s, documentInfo.id, documentInfo.entity)
for _, handler := range s.onBeforeDelete {
if handler != nil {
handler(beforeDeleteEventArgs)
}
}
cmdData := NewDeleteCommandData(documentInfo.id, stringPtrToString(changeVector))
result.addSessionCommandData(cmdData)
}
if len(changes) == 0 {
s.deletedEntities.clear()
}
}
return nil
}
func (s *InMemoryDocumentSessionOperations) prepareForEntitiesPuts(result *saveChangesData) error {
for _, entityValue := range s.documentsByEntity {
if entityValue.ignoreChanges {
continue
}
entityKey := entityValue.entity
dirtyMetadata := s.UpdateMetadataModifications(entityValue)
document := convertEntityToJSON(entityKey, entityValue)
if !s.entityChanged(document, entityValue, nil) && !dirtyMetadata {
continue
}
idType := newIDTypeAndName(entityValue.id, CommandClientNotAttachment, "")
command := result.deferredCommandsMap[idType]
if command != nil {
err := s.throwInvalidModifiedDocumentWithDeferredCommand(command)
if err != nil {
return err
}
}
if len(s.onBeforeStore) > 0 {
beforeStoreEventArgs := newBeforeStoreEventArgs(s, entityValue.id, entityKey)
for _, handler := range s.onBeforeStore {
if handler != nil {
handler(beforeStoreEventArgs)
}
}
if beforeStoreEventArgs.isMetadataAccessed() {
s.UpdateMetadataModifications(entityValue)
}
if beforeStoreEventArgs.isMetadataAccessed() || s.entityChanged(document, entityValue, nil) {
document = convertEntityToJSON(entityKey, entityValue)
}
}
entityValue.newDocument = false
result.addEntity(entityKey)
if entityValue.id != "" {
s.documentsByID.remove(entityValue.id)
}
entityValue.document = document
var changeVector *string
if s.useOptimisticConcurrency {
if entityValue.concurrencyCheckMode != ConcurrencyCheckDisabled {
// if the user didn't provide a change vector, we'll test for an empty one
tmp := ""
changeVector = firstNonNilString(entityValue.changeVector, &tmp)
} else {
changeVector = nil // TODO: redundant
}
} else if entityValue.concurrencyCheckMode == ConcurrencyCheckForced {
changeVector = entityValue.changeVector
} else {
changeVector = nil // TODO: redundant
}
cmdData := newPutCommandDataWithJSON(entityValue.id, changeVector, document)
result.addSessionCommandData(cmdData)
}
return nil
}
func (s *InMemoryDocumentSessionOperations) throwInvalidModifiedDocumentWithDeferredCommand(resultCommand ICommandData) error {
err := newIllegalStateError("Cannot perform save because document " + resultCommand.getId() + " has been modified by the session and is also taking part in deferred " + resultCommand.getType() + " command")
return err
}
func (s *InMemoryDocumentSessionOperations) throwInvalidDeletedDocumentWithDeferredCommand(resultCommand ICommandData) error {
err := newIllegalStateError("Cannot perform save because document " + resultCommand.getId() + " has been deleted by the session and is also taking part in deferred " + resultCommand.getType() + " command")
return err
}
func (s *InMemoryDocumentSessionOperations) entityChanged(newObj map[string]interface{}, documentInfo *documentInfo, changes map[string][]*DocumentsChanges) bool {
return jsonOperationEntityChanged(newObj, documentInfo, changes)
}
func (s *InMemoryDocumentSessionOperations) WhatChanged() (map[string][]*DocumentsChanges, error) {
changes := map[string][]*DocumentsChanges{}
err := s.prepareForEntitiesDeletion(nil, changes)
if err != nil {
return nil, err
}
s.getAllEntitiesChanges(changes)
return changes, nil
}
// Gets a value indicating whether any of the entities tracked by the session has changes.
func (s *InMemoryDocumentSessionOperations) HasChanges() bool {
if !s.deletedEntities.isEmpty() {
return true
}
for _, documentInfo := range s.documentsByEntity {
entity := documentInfo.entity
document := convertEntityToJSON(entity, documentInfo)
changed := s.entityChanged(document, documentInfo, nil)
if changed {
return true
}
}
return false
}
// HasChanged returns true if an entity has changed.
func (s *InMemoryDocumentSessionOperations) HasChanged(entity interface{}) (bool, error) {
err := checkValidEntityIn(entity, "entity")
if err != nil {
return false, err
}
documentInfo := getDocumentInfoByEntity(s.documentsByEntity, entity)
if documentInfo == nil {
return false, nil
}
document := convertEntityToJSON(entity, documentInfo)
return s.entityChanged(document, documentInfo, nil), nil
}
func (s *InMemoryDocumentSessionOperations) WaitForReplicationAfterSaveChanges(options func(*ReplicationWaitOptsBuilder)) {