Correctly deal with Ecto.Schema.Metadata for cascading delete

Im working with a database where table B has a foreign key (not null) referencing table A. A and B has a one-to-one relationship.

Furthermore the fk in Table B is created with the delete_all option

references(:A, on_delete: :delete_all)

most importantly, all deletions of b are done by deleting the corresponding a entry. Relying on the on the cascading delete functionality of the database.

Is there a nice way to implement a helper

 def delete_b(b) do
      # preload a,
      # delete a
      # return {:ok, b} with b.__meta__: #Ecto.Schema.Metadata<:deleted, "b">,

so that the b returned has the proper metadata state?

(I’ve resorted to a hack for now…

defp delete_b(b) do
    b = Repo.preload(b, :a)
    with {:ok, _deleted_a} <- Repo.delete(b.a) do
      meta = Kernel.struct(%Ecto.Schema.Metadata{}, %{state: :deleted, source: "b"})
      deleted_b = Kernel.struct(%B{}, %{id:, __meta__: meta}))
      {:ok, deleted_b}
      err -> err