Created
March 4, 2026 04:10
-
-
Save sb8244/0bec1b8541380cfdbcb901d7fc121a92 to your computer and use it in GitHub Desktop.
(Hacky) solution to extract the call site of an Ecto Repo query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defp extract_caller do | |
| {:current_stacktrace, stack} = Process.info(self(), :current_stacktrace) | |
| closest_caller = | |
| Enum.reduce_while(stack, false, fn | |
| caller = {mod, _fun, _a, [file: file_charlist, line: _]}, found_repo? -> | |
| is_repo_caller? = mod in [Super.Repo, DBConnection] || List.starts_with?(file_charlist, ~c"lib/ecto") | |
| skip? = file_charlist in [~c"lib/enum.ex"] | |
| cond do | |
| skip? -> {:cont, found_repo?} | |
| found_repo? && !is_repo_caller? -> {:halt, caller} | |
| !found_repo? && is_repo_caller? -> {:cont, true} | |
| true -> {:cont, found_repo?} | |
| end | |
| _, acc -> | |
| {:cont, acc} | |
| end) | |
| |> case do | |
| {_m, _f, _a, [file: filename, line: line]} -> "#{filename}:#{line}" | |
| _ -> nil | |
| end | |
| closest_super_caller = | |
| Enum.find(stack, fn | |
| {_m, _f, _a, [file: file_charlist, line: _]} -> | |
| file_charlist not in [~c"lib/super/repo.ex", ~c"lib/super_web/endpoint.ex"] && | |
| (List.starts_with?(file_charlist, ~c"lib/super/") || | |
| List.starts_with?(file_charlist, ~c"lib/super_web/") || | |
| List.starts_with?(file_charlist, ~c"lib/users/")) | |
| _ -> | |
| false | |
| end) | |
| |> case do | |
| {_m, _f, _a, [file: filename, line: line]} -> "#{filename}:#{line}" | |
| _ -> nil | |
| end | |
| [closest_caller, closest_super_caller] | |
| |> Enum.reject(&is_nil/1) | |
| |> Enum.uniq() | |
| |> Enum.join(", ") | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment