| 421 | } |
| 422 | |
| 423 | pub fn apply<T: MutTxnT>(&self, txn: &mut T) -> Result<(), TreeProjectionError> { |
| 424 | // Revalidate immediately before the first write. This makes incomplete |
| 425 | // metadata and destination conflicts fail without partially updating a |
| 426 | // forward/reverse pair. |
| 427 | self.validate(txn)?; |
| 428 | |
| 429 | let mut removals = Vec::new(); |
| 430 | for (inode, entry) in &self.entries { |
| 431 | if entry.path.is_none() && !entry.retire { |
| 432 | continue; |
| 433 | } |
| 434 | let current_path = txn |
| 435 | .get_path(*inode) |
| 436 | .map_err(|error| TreeProjectionError::Database(error.to_string()))?; |
| 437 | let desired_path = entry.path.as_ref().and_then(|path| path.as_ref()); |
| 438 | if current_path.as_deref() != desired_path.map(String::as_str) { |
| 439 | if let Some(path) = current_path { |
| 440 | let primary = Self::validated_primary(txn, &path)?.ok_or_else(|| { |
| 441 | TreeProjectionError::IncompleteMetadata(format!( |
| 442 | "cannot remove inode {} from '{}': TREE has no primary", |
| 443 | inode.get(), |
| 444 | path |
| 445 | )) |
| 446 | })?; |
| 447 | if primary != *inode { |
| 448 | return Err(TreeProjectionError::IncompleteMetadata(format!( |
| 449 | "TREE/REV_TREE disagree while removing '{}' for inode {}", |
| 450 | path, |
| 451 | inode.get() |
| 452 | ))); |
| 453 | } |
| 454 | removals.push((path, *inode)); |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | removals.sort_by(|left, right| (&left.0, left.1.get()).cmp(&(&right.0, right.1.get()))); |
| 459 | for (path, inode) in removals { |
| 460 | let removed = txn |
| 461 | .del_tree(&path) |
| 462 | .map_err(|error| TreeProjectionError::Database(error.to_string()))?; |
| 463 | if removed != Some(inode) { |
| 464 | return Err(TreeProjectionError::IncompleteMetadata(format!( |
| 465 | "TREE changed while removing '{}' for inode {}", |
| 466 | path, |
| 467 | inode.get() |
| 468 | ))); |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | let mut ordered_entries: Vec<(Inode, &PlannedTreeEntry)> = self |
| 473 | .entries |
| 474 | .iter() |
| 475 | .map(|(inode, entry)| (*inode, entry)) |
| 476 | .collect(); |
| 477 | ordered_entries.sort_by_key(|(inode, _)| inode.get()); |
| 478 | for (inode, entry) in &ordered_entries { |
| 479 | if let Some(position) = entry.binding { |
| 480 | if txn |