forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_operation.go
90 lines (76 loc) · 2.56 KB
/
batch_operation.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
package ravendb
// BatchOperation represents a batch operation
type BatchOperation struct {
session *InMemoryDocumentSessionOperations
entities []interface{}
sessionCommandsCount int
}
func newBatchOperation(session *InMemoryDocumentSessionOperations) *BatchOperation {
return &BatchOperation{
session: session,
}
}
func (b *BatchOperation) createRequest() (*BatchCommand, error) {
result, err := b.session.prepareForSaveChanges()
if err != nil {
return nil, err
}
b.sessionCommandsCount = len(result.sessionCommands)
result.sessionCommands = append(result.sessionCommands, result.deferredCommands...)
if len(result.sessionCommands) == 0 {
return nil, nil
}
if err = b.session.incrementRequestCount(); err != nil {
return nil, err
}
b.entities = result.entities
return newBatchCommand(b.session.GetConventions(), result.sessionCommands, result.options)
}
func (b *BatchOperation) setResult(result []map[string]interface{}) error {
if len(result) == 0 {
return throwOnNullResult()
}
for i := 0; i < b.sessionCommandsCount; i++ {
batchResult := result[i]
if batchResult == nil {
return newIllegalArgumentError("batchResult cannot be nil")
}
typ, _ := jsonGetAsText(batchResult, "Type")
if typ != "PUT" {
continue
}
entity := b.entities[i]
documentInfo := getDocumentInfoByEntity(b.session.documentsByEntity, entity)
if documentInfo == nil {
continue
}
changeVector := jsonGetAsTextPointer(batchResult, MetadataChangeVector)
if changeVector == nil {
return newIllegalStateError("PUT response is invalid. @change-vector is missing on " + documentInfo.id)
}
id, _ := jsonGetAsText(batchResult, MetadataID)
if id == "" {
return newIllegalStateError("PUT response is invalid. @id is missing on " + documentInfo.id)
}
for propertyName, v := range batchResult {
if propertyName == "Type" {
continue
}
meta := documentInfo.metadata
meta[propertyName] = v
}
documentInfo.id = id
documentInfo.changeVector = changeVector
doc := documentInfo.document
doc[MetadataKey] = documentInfo.metadata
documentInfo.metadataInstance = nil
b.session.documentsByID.add(documentInfo)
b.session.generateEntityIDOnTheClient.trySetIdentity(entity, id)
afterSaveChangesEventArgs := newAfterSaveChangesEventArgs(b.session, documentInfo.id, documentInfo.entity)
b.session.onAfterSaveChangesInvoke(afterSaveChangesEventArgs)
}
return nil
}
func throwOnNullResult() error {
return newIllegalStateError("Received empty response from the server. This is not supposed to happen and is likely a bug.")
}