commanded / eventstore

Event store using PostgreSQL for persistence
MIT License
1.06k stars 146 forks source link

Dynamic event store #184

Closed slashdotdash closed 4 years ago

slashdotdash commented 4 years ago

Allow a name to be provided when starting an event store. All event store operations can be provided with an optional name to determine the event store instance.

Example

Define an event store:

defmodule MyApp.EventStore do
  use EventStore, otp_app: :eventstore
end

Start multiple instances of the event store, each with a unique name:

{:ok, _pid} = MyApp.EventStore.start_link(name: :eventstore1)
{:ok, _pid} = MyApp.EventStore.start_link(name: :eventstore2)
{:ok, _pid} = MyApp.EventStore.start_link(name: :eventstore3)

Use an event store by providing a name:

:ok = MyApp.EventStore.append_to_stream(stream_uuid, expected_version, events, name: :eventstore1)

{:ok, events} = MyApp.EventStore.read_stream_forward(stream_uuid, 0, 1_000, name: :eventstore1)

Dynamic schemas

This feature also allows you to start each event store instance using a different schema:

{:ok, _pid} = MyApp.EventStore.start_link(name: :tenant1, schema: "tenant1")
{:ok, _pid} = MyApp.EventStore.start_link(name: :tenant2, schema: "tenant2")

Or start supervised:

children = 
  for tenant <- [:tenant1, :tenant2, :tenant3] do
    {MyApp.EventStore, name: :tenant1, schema: "#{tenant}"}
  end

opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)

The above can be used for multi-tenancy where the data for each tenant is stored in a separate schema.