Re-key all documents and secondary indexes for `(tenant_id, old_collection)` to `(tenant_id, new_collection)` in a single write transaction. Reads every row with the old prefix from both the DOCUMENTS and INDEXES tables, writes them under the new prefix, and deletes the old rows — all inside one transaction so the rename is atomic. Returns the count of document rows that were moved.
(
&self,
tenant_id: u64,
old_collection: &str,
new_collection: &str,
)
| 334 | /// |
| 335 | /// Returns the count of document rows that were moved. |
| 336 | pub fn rename_collection( |
| 337 | &self, |
| 338 | tenant_id: u64, |
| 339 | old_collection: &str, |
| 340 | new_collection: &str, |
| 341 | ) -> crate::Result<usize> { |
| 342 | let old_prefix = format!("{tenant_id}:{old_collection}:"); |
| 343 | let old_end = format!("{tenant_id}:{old_collection}:\u{ffff}"); |
| 344 | let new_prefix_len = format!("{tenant_id}:{new_collection}:").len(); |
| 345 | |
| 346 | // Collect document rows. |
| 347 | let doc_rows: Vec<(String, Vec<u8>)> = { |
| 348 | let read_txn = self.db.begin_read().map_err(|e| redb_err("read txn", e))?; |
| 349 | let table = read_txn |
| 350 | .open_table(DOCUMENTS) |
| 351 | .map_err(|e| redb_err("open docs", e))?; |
| 352 | let mut out = Vec::new(); |
| 353 | for entry in table |
| 354 | .range::<&str>(old_prefix.as_str()..old_end.as_str()) |
| 355 | .map_err(|e| redb_err("range docs", e))? |
| 356 | { |
| 357 | let (k, v) = entry.map_err(|e| redb_err("scan doc row", e))?; |
| 358 | if let Some(suffix) = k.value().strip_prefix(&old_prefix) { |
| 359 | out.push(( |
| 360 | format!("{tenant_id}:{new_collection}:{suffix}"), |
| 361 | v.value().to_vec(), |
| 362 | )); |
| 363 | } |
| 364 | } |
| 365 | out |
| 366 | }; |
| 367 | |
| 368 | // Collect index rows. |
| 369 | let idx_rows: Vec<String> = { |
| 370 | let read_txn = self.db.begin_read().map_err(|e| redb_err("read txn", e))?; |
| 371 | let table = read_txn |
| 372 | .open_table(INDEXES) |
| 373 | .map_err(|e| redb_err("open indexes", e))?; |
| 374 | let mut out = Vec::new(); |
| 375 | for entry in table |
| 376 | .range::<&str>(old_prefix.as_str()..old_end.as_str()) |
| 377 | .map_err(|e| redb_err("range indexes", e))? |
| 378 | { |
| 379 | let (k, _) = entry.map_err(|e| redb_err("scan idx row", e))?; |
| 380 | if let Some(suffix) = k.value().strip_prefix(&old_prefix) { |
| 381 | out.push(suffix.to_string()); |
| 382 | } |
| 383 | } |
| 384 | out |
| 385 | }; |
| 386 | |
| 387 | if doc_rows.is_empty() && idx_rows.is_empty() { |
| 388 | return Ok(0); |
| 389 | } |
| 390 | let doc_count = doc_rows.len(); |
| 391 | |
| 392 | let write_txn = self |
| 393 | .db |
no test coverage detected