Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions guides/Upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ GRANT SELECT, UPDATE ON "public".subscriptions TO session_mode_role;

Without these grants, persistent subscriptions never subscribe and the node logs an error naming the missing privileges.

This fork records its own migrations by name in a `fork_schema_migrations` table and leaves `schema_migrations` to upstream's versions, so a database moved back to upstream EventStore still runs every upstream migration it has not applied.

## Migrate before rolling nodes

Run the migration before starting nodes on the new version. A node on a version that expects a newer schema cannot acquire subscription locks against an unmigrated database and keeps retrying until the migration has run. Nodes on the previous version keep working against the migrated schema once the migration is in place.
Expand Down
25 changes: 23 additions & 2 deletions lib/event_store/sql/init.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ defmodule EventStore.Sql.Init do
create_subscription_index(),
create_snapshots_table(column_data_type),
create_schema_migrations_table(),
record_event_store_schema_version()
record_event_store_schema_version(),
create_fork_schema_migrations_table(),
record_fork_schema_migrations()
]
end

Expand Down Expand Up @@ -277,7 +279,26 @@ defmodule EventStore.Sql.Init do
defp record_event_store_schema_version do
"""
INSERT INTO schema_migrations (major_version, minor_version, patch_version)
VALUES (1, 5, 0);
VALUES (1, 3, 2);
"""
end

# record execution of the fork's own upgrade scripts, apart from upstream's
# versions so that upstream's migrate still sees the versions it has not run
def create_fork_schema_migrations_table do
"""
CREATE TABLE IF NOT EXISTS fork_schema_migrations
(
name text PRIMARY KEY NOT NULL,
migrated_at timestamp with time zone DEFAULT NOW() NOT NULL
);
"""
end

defp record_fork_schema_migrations do
"""
INSERT INTO fork_schema_migrations (name)
VALUES ('subscription_lock_generation');
"""
end
end
46 changes: 21 additions & 25 deletions lib/event_store/tasks/migrate.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ defmodule EventStore.Tasks.Migrate do
import EventStore.Tasks.Output

alias EventStore.{Config, Storage}
alias EventStore.Sql.Init
alias EventStore.Tasks.Migrations

@dialyzer {:no_return, exec: 2, handle_response: 1}
Expand Down Expand Up @@ -69,32 +70,27 @@ defmodule EventStore.Tasks.Migrate do
Storage.Lock.try_acquire_exclusive_lock(conn, -1, schema: schema)
end

# Upstream can record its own 1.5.0, which would otherwise hide the fork's
# lock generation migration behind a version that is already recorded.
defp available_migrations(conn, schema) do
migrations = newer_migrations(conn, schema)
upstream =
conn |> newer_migrations(schema) |> Enum.map(&{"v#{&1}", "migrations/v#{&1}.sql"})

if "1.5.0" in migrations or lock_generation?(conn, schema),
do: migrations,
else: migrations ++ ["1.5.0"]
fork =
conn
|> pending_fork_migrations(schema)
|> Enum.map(&{&1, "fork_migrations/#{&1}.sql"})

upstream ++ fork
end

defp lock_generation?(conn, schema) do
%Postgrex.Result{rows: [[exists]]} =
Postgrex.query!(
conn,
"""
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = $1
AND table_name = 'subscriptions'
AND column_name = 'lock_generation'
)
""",
[schema]
)

exists
defp pending_fork_migrations(conn, schema) do
{:ok, %Postgrex.Result{rows: rows}} =
Postgrex.transaction(conn, fn transaction ->
Postgrex.query!(transaction, ~s(SET LOCAL search_path TO "#{schema}";), [])
Postgrex.query!(transaction, Init.create_fork_schema_migrations_table(), [])
Postgrex.query!(transaction, "SELECT name FROM fork_schema_migrations", [])
end)

Migrations.available_fork_migrations() -- List.flatten(rows)
end

defp newer_migrations(conn, schema) do
Expand All @@ -116,10 +112,10 @@ defmodule EventStore.Tasks.Migrate do
end

defp migrate(conn, schema, opts, migrations) do
for migration <- migrations do
write_info("Running migration v#{migration}...", opts)
for {migration, file} <- migrations do
write_info("Running migration #{migration}...", opts)

path = Application.app_dir(:eventstore, "priv/event_store/migrations/v#{migration}.sql")
path = Application.app_dir(:eventstore, "priv/event_store/#{file}")
script = File.read!(path)

statements = [
Expand Down
62 changes: 42 additions & 20 deletions lib/event_store/tasks/migrations.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ defmodule EventStore.Tasks.Migration do
defstruct version: nil, state: :pending, migrated_at: nil
end

defmodule EventStore.Tasks.ForkMigration do
defstruct name: nil, state: :pending, migrated_at: nil
end

defmodule EventStore.Tasks.Migrations do
@moduledoc """
Task to show the migration status of EventStore
Expand All @@ -10,7 +14,7 @@ defmodule EventStore.Tasks.Migrations do
import EventStore.Tasks.Output

alias EventStore.Config
alias EventStore.Tasks.Migration
alias EventStore.Tasks.{ForkMigration, Migration}

@available_migrations [
"0.13.0",
Expand All @@ -19,8 +23,11 @@ defmodule EventStore.Tasks.Migrations do
"1.1.0",
"1.2.0",
"1.3.0",
"1.3.2",
"1.5.0"
"1.3.2"
]

@available_fork_migrations [
"subscription_lock_generation"
]

@dialyzer {:no_return, exec: 2, handle_response: 1}
Expand Down Expand Up @@ -59,6 +66,17 @@ defmodule EventStore.Tasks.Migrations do
@doc false
def available_migrations(), do: @available_migrations

@doc false
def available_fork_migrations(), do: @available_fork_migrations

defp list_migration(%ForkMigration{name: name, state: :pending}, opts) do
write_info(" #{name |> String.pad_trailing(10)}\tpending", opts)
end

defp list_migration(%ForkMigration{name: name, state: :completed, migrated_at: time}, opts) do
write_info(" #{name |> String.pad_trailing(10)}\tcompleted\t#{time}", opts)
end

defp list_migration(%Migration{version: version, state: :pending}, opts) do
write_info(" #{version |> String.pad_trailing(10)}\tpending", opts)
end
Expand All @@ -80,27 +98,31 @@ defmodule EventStore.Tasks.Migrations do
completed = query_schema_migrations(config, schema)
latest_migration = completed |> Enum.reverse() |> Enum.at(0, nil)

pending = pending_migrations(latest_migration)
completed ++ pending_migrations(latest_migration) ++ fork_migrations(config, schema)
end

defp fork_migrations(config, schema) do
completed = query_fork_schema_migrations(config, schema)

# Upstream can record its own 1.5.0, which would otherwise hide the fork's
# lock generation migration behind a version that is already recorded.
if Enum.any?(pending, &(&1.version == "1.5.0")) or lock_generation?(config, schema),
do: completed ++ pending,
else: completed ++ pending ++ [%Migration{version: "1.5.0"}]
Enum.map(@available_fork_migrations, fn name ->
Map.get(completed, name, %ForkMigration{name: name})
end)
end

defp lock_generation?(config, schema) do
defp query_fork_schema_migrations(config, schema) do
%Postgrex.Result{rows: [[exists]]} =
run_query(config, """
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = '#{schema}'
AND table_name = 'subscriptions'
AND column_name = 'lock_generation'
)
""")

exists
run_query(config, "SELECT to_regclass('\"#{schema}\".fork_schema_migrations') IS NOT NULL")

if exists do
%Postgrex.Result{rows: rows} =
run_query(config, ~s(SELECT name, migrated_at FROM "#{schema}".fork_schema_migrations))

Map.new(rows, fn [name, migrated_at] ->
{name, %ForkMigration{name: name, state: :completed, migrated_at: migrated_at}}
end)
else
%{}
end
end

defp pending_migrations(nil), do: @available_migrations
Expand Down
27 changes: 27 additions & 0 deletions priv/event_store/fork_migrations/subscription_lock_generation.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
DO $migration$
BEGIN
-- Unreleased builds of the fork added the lock generation and recorded it as
-- schema version 1.5.0, which would hide upstream migrations up to 1.5.0
-- from upstream's migrate.
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name = 'subscriptions'
AND column_name = 'lock_generation'
) THEN
DELETE FROM schema_migrations
WHERE (major_version, minor_version, patch_version) = (1, 5, 0);
Comment thread
yordis marked this conversation as resolved.
Resolved

-- Event stores those builds created recorded 1.5.0 alone, and an empty
-- history makes upstream's migrate run every migration again.
IF NOT EXISTS (SELECT 1 FROM schema_migrations) THEN
INSERT INTO schema_migrations (major_version, minor_version, patch_version)
VALUES (1, 3, 2);
END IF;
ELSE
ALTER TABLE subscriptions ADD COLUMN lock_generation bigint NOT NULL DEFAULT 0;
END IF;

INSERT INTO fork_schema_migrations (name) VALUES ('subscription_lock_generation');
END;
$migration$ LANGUAGE plpgsql;
9 changes: 0 additions & 9 deletions priv/event_store/migrations/v1.5.0.sql

This file was deleted.

4 changes: 3 additions & 1 deletion test/list_event_store_migrations_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ defmodule EventStore.ListEventStoreMigrationsTest do
1.2.0 \tpending
1.3.0 \tpending
1.3.2 \tpending
1.5.0 \tpending
subscription_lock_generation\tpending

"""

Expand Down Expand Up @@ -63,6 +63,7 @@ defmodule EventStore.ListEventStoreMigrationsTest do
output |> String.split("\n") |> Enum.drop(5) |> Enum.filter(&(String.trim(&1) != ""))

assert Enum.all?(migrations, &String.contains?(&1, "completed"))
assert Enum.any?(migrations, &String.contains?(&1, "subscription_lock_generation"))
end

test "exits normally when running via mix", %{config: config} do
Expand All @@ -78,6 +79,7 @@ defmodule EventStore.ListEventStoreMigrationsTest do
create_new_database(config)

{:ok, conn} = Postgrex.start_link(config)
Postgrex.query!(conn, "DROP TABLE fork_schema_migrations", [])
Postgrex.query!(conn, "ALTER TABLE subscriptions DROP COLUMN lock_generation", [])
:ok = GenServer.stop(conn)

Expand Down
72 changes: 71 additions & 1 deletion test/migrate_event_store_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,61 @@ defmodule EventStore.MigrateEventStoreTest do
migrate_eventstore(Keyword.put(config, :schema, "example"), quiet: true, is_mix: false)

assert has_lock_generation?(config, "example")
assert "1.5.0" == latest_version(config, "example")
assert "1.3.2" == latest_version(config, "example")
assert public_history == migration_history(config, "public")
end
end

describe "event store created by the fork" do
test "should record no schema version above upstream's", %{config: config} do
create_new_database(config)

assert "1.3.2" == latest_version(config, "public")
end
end

describe "migrate an event store the fork recorded as 1.5.0" do
test "should leave no schema version above upstream's", %{config: config} do
create_new_database(config)

with_conn(config, fn conn ->
Postgrex.query!(conn, "DROP TABLE fork_schema_migrations", [])

Postgrex.query!(
conn,
"INSERT INTO schema_migrations (major_version, minor_version, patch_version) VALUES (1, 5, 0)",
[]
)
end)

migrate_eventstore(config, quiet: true, is_mix: false)

assert has_lock_generation?(config, "public")
assert "1.3.2" == latest_version(config, "public")
end

test "should keep upstream's latest version when 1.5.0 was the only one recorded", %{
config: config
} do
create_new_database(config)

with_conn(config, fn conn ->
Postgrex.query!(conn, "DROP TABLE fork_schema_migrations", [])
Postgrex.query!(conn, "DELETE FROM schema_migrations", [])

Postgrex.query!(
conn,
"INSERT INTO schema_migrations (major_version, minor_version, patch_version) VALUES (1, 5, 0)",
[]
)
end)

migrate_eventstore(config, quiet: true, is_mix: false)

assert "1.3.2" == latest_version(config, "public")
end
end

describe "migrate an event store that recorded upstream's 1.5.0" do
test "should still add the lock generation", %{config: config} do
restore_pre_migration_event_store(config)
Expand All @@ -104,6 +154,26 @@ defmodule EventStore.MigrateEventStoreTest do

assert has_lock_generation?(config, "public")
end

test "should keep upstream's 1.5.0 when migrated again", %{config: config} do
create_new_database(config)

with_conn(config, fn conn ->
Postgrex.query!(conn, "DROP TABLE fork_schema_migrations", [])
Postgrex.query!(conn, "ALTER TABLE subscriptions DROP COLUMN lock_generation", [])

Postgrex.query!(
conn,
"INSERT INTO schema_migrations (major_version, minor_version, patch_version) VALUES (1, 5, 0)",
[]
)
end)

migrate_eventstore(config, quiet: true, is_mix: false)
migrate_eventstore(config, quiet: true, is_mix: false)

assert "1.5.0" == latest_version(config, "public")
end
end

defp has_lock_generation?(config, schema) do
Expand Down
Loading