Skip to content

Commit

Permalink
Use persistent_term for faster adapter config lookups (#4521)
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim authored Oct 6, 2024
1 parent 407912c commit e75c32a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
9 changes: 5 additions & 4 deletions lib/ecto/repo/registry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ defmodule Ecto.Repo.Registry do
end

def lookup(repo) when is_atom(repo) do
GenServer.whereis(repo)
|> Kernel.||(raise "could not lookup Ecto repo #{inspect repo} because it was not started or it does not exist")
|> lookup()
:persistent_term.get(repo, nil) ||
raise "could not lookup Ecto repo #{inspect(repo)} because it was not started or it does not exist"
end

def lookup(pid) when is_pid(pid) do
Expand All @@ -38,13 +37,15 @@ defmodule Ecto.Repo.Registry do
@impl true
def handle_call({:associate, pid, name, value}, _from, table) do
ref = Process.monitor(pid)
name && :persistent_term.put(name, value)
true = :ets.insert(table, {pid, ref, name, value})
{:reply, :ok, table}
end

@impl true
def handle_info({:DOWN, ref, _type, pid, _reason}, table) do
[{^pid, ^ref, _, _}] = :ets.lookup(table, pid)
[{^pid, ^ref, name, _}] = :ets.lookup(table, pid)
name && :persistent_term.erase(name)
:ets.delete(table, pid)
{:noreply, table}
end
Expand Down
10 changes: 3 additions & 7 deletions lib/ecto/repo/supervisor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,6 @@ defmodule Ecto.Repo.Supervisor do

@doc false
def init({name, repo, otp_app, adapter, opts}) do
# Normalize name to atom, ignore via/global names
name = if is_atom(name), do: name, else: nil

case init_config(:supervisor, repo, otp_app, opts) do
{:ok, opts} ->
:telemetry.execute(
Expand All @@ -199,6 +196,9 @@ defmodule Ecto.Repo.Supervisor do
)

{:ok, child, meta} = adapter.init([repo: repo] ++ opts)

# Normalize name to atom, ignore via/global names
name = if is_atom(name), do: name, else: nil
cache = Ecto.Query.Planner.new_query_cache(name)
meta = Map.merge(meta, %{repo: repo, cache: cache})
child_spec = wrap_child_spec(child, [name, adapter, meta])
Expand All @@ -221,10 +221,6 @@ defmodule Ecto.Repo.Supervisor do
end
end

defp wrap_child_spec({id, start, restart, shutdown, type, mods}, args) do
{id, {__MODULE__, :start_child, [start | args]}, restart, shutdown, type, mods}
end

defp wrap_child_spec(%{start: start} = spec, args) do
%{spec | start: {__MODULE__, :start_child, [start | args]}}
end
Expand Down

0 comments on commit e75c32a

Please sign in to comment.