Skip to content

Commit

Permalink
fix: don't alter table on every shape creation (#2033)
Browse files Browse the repository at this point in the history
  • Loading branch information
icehaunter authored Nov 22, 2024
1 parent e58d794 commit 72c7c46
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/mean-keys-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@core/sync-service": patch
---

fix: don't execute `ALTER TABLE` statements if not necessary
13 changes: 12 additions & 1 deletion packages/sync-service/lib/electric/postgres/configuration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ defmodule Electric.Postgres.Configuration do
Module for functions that configure Postgres in some way using
a provided connection.
"""
require Logger
alias Electric.Utils
alias Electric.Shapes.Shape

Expand Down Expand Up @@ -103,7 +104,17 @@ defmodule Electric.Postgres.Configuration do
defp set_replica_identity!(conn, relations) do
for {relation, _} <- relations,
table = Utils.relation_to_sql(relation) do
Postgrex.query!(conn, "ALTER TABLE #{table} REPLICA IDENTITY FULL", [])
%Postgrex.Result{rows: [[correct_identity?]]} =
Postgrex.query!(
conn,
"SELECT relreplident = 'f' FROM pg_class JOIN pg_namespace ON relnamespace = pg_namespace.oid WHERE nspname = $1 AND relname = $2;",
Tuple.to_list(relation)
)

if not correct_identity? do
Logger.info("Altering identity of #{table} to FULL")
Postgrex.query!(conn, "ALTER TABLE #{table} REPLICA IDENTITY FULL", [])
end
end
end

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defmodule Electric.Postgres.ConfigurationTest do
use ExUnit.Case, async: true
import ExUnit.CaptureLog

alias Electric.Postgres.Configuration

Expand Down Expand Up @@ -72,6 +73,32 @@ defmodule Electric.Postgres.ConfigurationTest do
)
end

test "doesn't execute `ALTER TABLE` if table identity is already full",
%{pool: conn, publication_name: publication, get_pg_version: get_pg_version} do
assert get_table_identity(conn, {"public", "items"}) == "d"
assert list_tables_in_publication(conn, publication) == []

assert capture_log(fn ->
Configuration.configure_tables_for_replication!(
conn,
[{{"public", "items"}, "(value ILIKE 'yes%')"}],
get_pg_version,
publication
)
end) =~ "Altering identity"

assert get_table_identity(conn, {"public", "items"}) == "f"

refute capture_log(fn ->
Configuration.configure_tables_for_replication!(
conn,
[{{"public", "items"}, "(value ILIKE 'no%')"}],
get_pg_version,
publication
)
end) =~ "Altering identity"
end

test "works with multiple tables", %{
pool: conn,
publication_name: publication,
Expand Down

0 comments on commit 72c7c46

Please sign in to comment.