Skip to content

Instantly share code, notes, and snippets.

@dkuku
Created December 2, 2023 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkuku/47da89f8faf4070854f36ecf30382326 to your computer and use it in GitHub Desktop.
Save dkuku/47da89f8faf4070854f36ecf30382326 to your computer and use it in GitHub Desktop.
Sqlcommenter with ecto examples
defmodule AdventureWorks.TracedRepo do
use Ecto.Repo,
otp_app: :adventure_works,
adapter: Ecto.Adapters.Postgres
def all_traced(queryable, opts \\ []) do
{metadata, opts} = Keyword.pop(opts, :metadata, %{})
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
stacktrace =
stacktrace |> Enum.drop(2) |> Enum.take(1) |> Exception.format_stacktrace() |> String.trim()
queryable = Ecto.Queryable.to_query(queryable)
{query, params} = __MODULE__.to_sql(:all, queryable)
query = Sqlcommenter.append_to_query(query, put_in(metadata, [:stacktrace], stacktrace))
{:ok, result} =
__MODULE__.query(query, params, opts)
struct =
case queryable.from do
# maybe other load types
%{source: {_, struct}} -> struct
end
Enum.map(
result.rows,
&__MODULE__.load(struct, {result.columns, &1})
)
end
def all_traced_lock(queryable, opts \\ []) do
{metadata, opts} = Keyword.pop(opts, :metadata, %{})
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
stacktrace =
stacktrace |> Enum.drop(2) |> Enum.take(1) |> Exception.format_stacktrace() |> String.trim()
metadata = put_in(metadata, [:stacktrace], stacktrace)
queryable =
queryable
|> Ecto.Queryable.to_query()
|> Map.update(:lock, nil, fn
nil -> Sqlcommenter.to_str(metadata)
lock -> Sqlcommenter.append_to_query(lock, metadata)
end)
__MODULE__.all(queryable, opts)
end
end
defmodule AdventureWorks.Repo do
def all(queryable, x) do
AdventureWorks.TracedRepo.all_traced(queryable, x)
end
def all2(queryable, x) do
AdventureWorks.TracedRepo.all_traced_lock(queryable, x)
end
end
@dkuku
Copy link
Author

dkuku commented Dec 2, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment