Delete entries and update same collection in 1 command

I would like to delete entries in a collection and add entries to the same collection, both in one command. This is useful in case the collection needs to be completely updated.

With ensure I can update already existing entries in the target collection with information from the source collection, but entries not in the source collection remain in the target collection.

'root' {
   'Source collection': collection ['Source entry'] {
      'Source entry': text
   }
   'Update target collection': command { } => walk .'Source collection'* as $ (
      update .'Target collection' = ensure (
         'Target entry' = $ .'Source entry
      )
   )
   'Target collection': collection ['Target entry'] {
      'Target entry': text
   }
}

Solution: Extend the command execution by checking whether an entry in the source collection also exists in the target collection. If not delete it.

This could look like this:

'root' {
   'Source collection': collection ['Source entry'] {
      'Source entry': text
   }
   'Update target collection': command { } 
      => walk .'Source collection'* as $ (
         update .'Target collection' = ensure (
            'Target entry' = $ .'Source entry
         )
      )
      => walk .'Target collection'* as $'tar' (
         switch $'tar'.'Source exists' (
            |'Yes' => ignore
            |'No' => update .'Target collection' = delete $'tar'
         )
      )
   'Target collection': collection ['Target entry'] {
      'Target entry': text ~> ^ .'Source collection'[]
      'Source exists': state group = switch >'Target entry' (
         | node => 'Yes' ( )
         | none => 'Nee' ( )
      )
   }
}

Notice an optional reference is added to Target entry, which is used in the derived stategroup. This stategroup is used in the command execution.

1 Like