Skip to content

Commit

Permalink
Potential optimisation
Browse files Browse the repository at this point in the history
  • Loading branch information
robacourt committed Sep 26, 2024
1 parent 85ba982 commit c9841a8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
4 changes: 1 addition & 3 deletions packages/sync-service/lib/electric/shapes/consumer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ defmodule Electric.Shapes.Consumer do
end

defp selector(%Transaction{changes: changes}, shape) do
changes
|> Stream.flat_map(&Shape.convert_change(shape, &1))
|> Enum.any?()
Shape.any_relevant?(shape, changes)
end

defp selector(_, _), do: false
Expand Down
34 changes: 34 additions & 0 deletions packages/sync-service/lib/electric/shapes/shape.ex
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,40 @@ defmodule Electric.Shapes.Shape do
end
end

def any_relevant?(_shape, []), do: false

def any_relevant?(shape, [change | changes]) do
if relevant?(shape, change) do
true
else
any_relevant?(shape, changes)
end
end

defp relevant?(%__MODULE__{root_table: table}, %{relation: relation})
when table != relation,
do: false

defp relevant?(%__MODULE__{where: nil}, _change), do: true
defp relevant?(%__MODULE__{where: _}, %Changes.TruncatedRelation{}), do: true

defp relevant?(%__MODULE__{where: where}, change)
when is_struct(change, Changes.NewRecord)
when is_struct(change, Changes.DeletedRecord) do
record = if is_struct(change, Changes.NewRecord), do: change.record, else: change.old_record
record_in_shape?(where, record)
end

defp relevant?(
%__MODULE__{where: where},
%Changes.UpdatedRecord{old_record: old_record, record: record}
) do
old_record_in_shape = record_in_shape?(where, old_record)
new_record_in_shape = record_in_shape?(where, record)

old_record_in_shape || new_record_in_shape
end

defp record_in_shape?(where, record) do
with {:ok, refs} <- Runner.record_to_ref_values(where.used_refs, record),
{:ok, evaluated} <- Runner.execute(where, refs) do
Expand Down

0 comments on commit c9841a8

Please sign in to comment.