Skip to content

Instantly share code, notes, and snippets.

@ftes
Created November 5, 2021 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftes/e3379be28a4a5a57b8632070295a5a17 to your computer and use it in GitHub Desktop.
Save ftes/e3379be28a4a5a57b8632070295a5a17 to your computer and use it in GitHub Desktop.
Reset all commanded read model projections via macro and module attribute
defmodule Mixins.Projection do
defmacro __using__(params) do
table = Keyword.get(params, :table) || raise "Missing param :table"
Module.register_attribute(__CALLER__.module, :table, persist: true)
Module.put_attribute(__CALLER__.module, :table, table)
quote do
use Ecto.Schema
end
end
def tables() do
{:ok, modules} = :application.get_key(:my_app, :modules)
modules
|> Enum.map(fn m -> m.module_info(:attributes)[:table] end)
|> Enum.filter(&(&1))
|> List.flatten()
end
end
defmodule Projections.SomeModel do
use Mixins.Projection, table: "some_model"
@primary_key {:id, :binary_id, autogenerate: false}
schema @table do
end
end
defmodule TestSupport.Storage do
def reset! do
:ok = Application.stop(:my_app)
reset_eventstore!()
reset_readstore!()
{:ok, _} = Application.ensure_all_started(:my_app)
end
defp reset_eventstore! do
config = MyEventStore.config()
{:ok, conn} =
config
|> EventStore.Config.default_postgrex_opts()
|> Postgrex.start_link()
EventStore.Storage.Initializer.reset!(conn, config)
end
defp reset_readstore! do
{:ok, conn} = Postgrex.start_link(MyRepo.config())
Postgrex.query!(conn, truncate_readstore_tables(), [])
end
defp truncate_readstore_tables do
projection_tables = Mixins.Projection.tables()
"""
TRUNCATE TABLE
#{Enum.join(projection_tables, ", ")},
projection_versions
RESTART IDENTITY
CASCADE;
"""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment