How to merge two nix stores?

I’m currently working on nix-community/cache-nix-action. The action caches and restores a Nix store.

The action should also be able to restore two caches, each with a Nix store, and build a single store (Fix merging stores · Issue #31 · nix-community/cache-nix-action · GitHub).

You can reproduce this scenario locally.

To get two stores, run

nix build --no-link nixpkgs#hello --store store1
nix build --no-link nixpkgs#gawk --store store2

Then, the databases are in

store1/nix/var/nix/db/db.sqlite
store2/nix/var/nix/db/db.sqlite

I can copy paths from one store to another via cp.

How do I merge the databases?