Skip to content

Commit

Permalink
Add example db migration file for aggregate unique keys
Browse files Browse the repository at this point in the history
  • Loading branch information
erikrozendaal committed Jan 15, 2025
1 parent a4a6790 commit 8775b6f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
transaction is committed, reducing the need for having aggregates to
ensure uniqueness or relying on projectors. See
lib/sequent/core/helpers/unique_keys.rb for details.

This feature requires a new database, you can find an example
migration at `db/migrate/20250108162754_aggregate_unique_keys.rb`.
- `CommandHandlerHelpers` has been updated to:
- Load aggregates using the `given_events` so that unique keys can
be tested. This may require changing your test to correctly set up
Expand Down
42 changes: 42 additions & 0 deletions db/migrate/20250108162754_aggregate_unique_keys.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# frozen_string_literal: true

class AggregateUniqueKeys < ActiveRecord::Migration[7.2]
def up
say 'Setting up search path', true
suppress_messages do
execute <<~SQL
SELECT set_config('tmp.search_path', current_setting('search_path'), true);
SELECT set_config('search_path', '#{Sequent.configuration.event_store_schema_name}', true);
SQL
end

say 'Creating aggregate_unique_keys table', true
suppress_messages do
execute <<~SQL
CREATE TABLE IF NOT EXISTS aggregate_unique_keys (
aggregate_id uuid NOT NULL,
scope text NOT NULL,
key jsonb NOT NULL,
PRIMARY KEY (aggregate_id, scope),
UNIQUE (scope, key),
FOREIGN KEY (aggregate_id) REFERENCES aggregates (aggregate_id) ON UPDATE CASCADE ON DELETE CASCADE
)
SQL
end

say 'Creating event store stored procedures and views', true
suppress_messages do
sequent_pgsql_filename = File.join(Sequent.configuration.database_schema_directory, 'sequent_pgsql.sql')
execute File.read(sequent_pgsql_filename)
end

say 'Restoring search path', true
suppress_messages do
execute "SELECT set_config('search_path', current_setting('tmp.search_path'), true)"
end
end

def down
fail ActiveRecord::IrreversibleMigration
end
end

0 comments on commit 8775b6f

Please sign in to comment.