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
//! Firestore WriteBatch type
//!
//! # C++ Reference
//! - `firestore/src/include/firebase/firestore/write_batch.h:46`
use super::field_value::{MapValue, proto};
use crate::firestore::firestore::{FirestoreInner, FirestoreInterceptor};
use proto::google::firestore::v1::firestore_client::FirestoreClient as GrpcClient;
/// Write batch for atomic operations
///
/// # C++ Reference
/// - `firestore/src/include/firebase/firestore/write_batch.h:46`
pub struct WriteBatch {
operations: Vec<WriteOperation>,
/// Reference to Firestore client for commit operation
firestore: std::sync::Arc<FirestoreInner>,
}
/// Write operations for batch writes and transactions
///
/// Represents different types of Firestore write operations that can be performed.
#[derive(Debug, Clone)]
pub enum WriteOperation {
/// Set (overwrite) a document
Set {
/// Document path
path: String,
/// Document data
data: MapValue,
},
/// Update specific fields in a document
Update {
/// Document path
path: String,
/// Fields to update
data: MapValue,
},
/// Delete a document
Delete {
/// Document path to delete
path: String,
},
}
impl WriteBatch {
/// Create a new write batch
///
/// # C++ Reference
/// - `firebase-ios-sdk/Firestore/core/src/api/write_batch.cc:26` - WriteBatch constructor
pub(crate) fn new(firestore: std::sync::Arc<FirestoreInner>) -> Self {
Self {
operations: Vec::new(),
firestore,
}
}
/// Set document data (overwrites existing document)
///
/// # C++ Reference
/// - `write_batch.h:117` - Set() method
///
/// # Example
/// ```no_run
/// # use firebase_rust_sdk::firestore::Firestore;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let firestore = Firestore::new("project-id", "default", None).await?;
/// let batch = firestore.batch()
/// .set("cities/LA", Default::default())
/// .commit()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn set(mut self, path: impl Into<String>, data: MapValue) -> Self {
self.operations.push(WriteOperation::Set {
path: path.into(),
data,
});
self
}
/// Update document fields (document must exist)
///
/// # C++ Reference
/// - `write_batch.h:131` - Update() method
///
/// # Example
/// ```no_run
/// # use firebase_rust_sdk::firestore::Firestore;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let firestore = Firestore::new("project-id", "default", None).await?;
/// let batch = firestore.batch()
/// .update("cities/LA", Default::default())
/// .commit()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn update(mut self, path: impl Into<String>, data: MapValue) -> Self {
self.operations.push(WriteOperation::Update {
path: path.into(),
data,
});
self
}
/// Delete document
///
/// # C++ Reference
/// - `write_batch.h:151` - Delete() method
///
/// # Example
/// ```no_run
/// # use firebase_rust_sdk::firestore::Firestore;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let firestore = Firestore::new("project-id", "default", None).await?;
/// let batch = firestore.batch()
/// .delete("cities/LA")
/// .commit()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn delete(mut self, path: impl Into<String>) -> Self {
self.operations
.push(WriteOperation::Delete { path: path.into() });
self
}
/// Commit the batch
///
/// # C++ Reference
/// - `firestore/src/main/write_batch_main.cc:70` - WriteBatchInternal::Commit
/// - `firestore/src/common/write_batch.cc:140` - WriteBatch::Commit
///
/// Commits all batched write operations atomically. If any operation fails,
/// none of the operations are applied.
///
/// # Errors
/// Returns `FirestoreError` if:
/// - Batch is empty (nothing to commit)
/// - Network request fails
/// - Any write operation fails (entire batch is rolled back)
pub async fn commit(self) -> Result<(), crate::error::FirebaseError> {
use proto::google::firestore::v1::{CommitRequest, Write, write::Operation};
if self.operations.is_empty() {
return Err(crate::error::FirestoreError::InvalidArgument(
"Cannot commit empty batch".to_string()
).into());
}
let database_path = format!("projects/{}/databases/{}",
self.firestore.project_id, self.firestore.database_id);
// Convert WriteOperations to gRPC Write messages
let mut writes = Vec::new();
for op in self.operations {
let write = match op {
WriteOperation::Set { path, data } => {
let full_path = format!("{}/documents/{}", database_path, path);
Write {
operation: Some(Operation::Update(proto::google::firestore::v1::Document {
name: full_path,
fields: data.fields,
create_time: None,
update_time: None,
})),
update_mask: None, // None = replace entire document
update_transforms: vec![],
current_document: None,
}
},
WriteOperation::Update { path, data } => {
let full_path = format!("{}/documents/{}", database_path, path);
let field_paths: Vec<String> = data.fields.keys().cloned().collect();
Write {
operation: Some(Operation::Update(proto::google::firestore::v1::Document {
name: full_path,
fields: data.fields,
create_time: None,
update_time: None,
})),
update_mask: Some(proto::google::firestore::v1::DocumentMask { field_paths }),
update_transforms: vec![],
current_document: Some(proto::google::firestore::v1::Precondition {
condition_type: Some(proto::google::firestore::v1::precondition::ConditionType::Exists(true)),
}),
}
},
WriteOperation::Delete { path } => {
let full_path = format!("{}/documents/{}", database_path, path);
Write {
operation: Some(Operation::Delete(full_path)),
update_mask: None,
update_transforms: vec![],
current_document: None,
}
},
};
writes.push(write);
}
let request = CommitRequest {
database: database_path,
writes,
transaction: vec![],
};
let interceptor = FirestoreInterceptor {
auth_data: self.firestore.auth_data.clone(),
};
let mut client = GrpcClient::with_interceptor(self.firestore.channel.clone(), interceptor);
let _response = client.commit(request)
.await
.map_err(|e| crate::error::FirestoreError::Connection(format!("gRPC commit failed: {}", e)))?;
Ok(())
}
/// Check if batch is empty
pub fn is_empty(&self) -> bool {
self.operations.is_empty()
}
/// Get number of operations
pub fn len(&self) -> usize {
self.operations.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn test_write_batch_operations() {
// Test WriteBatch without needing FirestoreInner
// Just verify the WriteOperation enum works correctly
let data = MapValue {
fields: HashMap::new(),
};
let set_op = WriteOperation::Set {
path: "cities/LA".to_string(),
data: data.clone(),
};
match set_op {
WriteOperation::Set { ref path, .. } => {
assert_eq!(path, "cities/LA");
}
_ => panic!("Expected Set operation"),
}
let update_op = WriteOperation::Update {
path: "cities/SF".to_string(),
data: data.clone(),
};
match update_op {
WriteOperation::Update { ref path, .. } => {
assert_eq!(path, "cities/SF");
}
_ => panic!("Expected Update operation"),
}
let delete_op = WriteOperation::Delete {
path: "cities/NYC".to_string(),
};
match delete_op {
WriteOperation::Delete { ref path } => {
assert_eq!(path, "cities/NYC");
}
_ => panic!("Expected Delete operation"),
}
}
}