Created
December 2, 2023 07:36
-
-
Save dkuku/47da89f8faf4070854f36ecf30382326 to your computer and use it in GitHub Desktop.
Sqlcommenter with ecto examples
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
code from this post:
https://dev.to/dkuku/enhancing-sql-traceability-with-sqlcommenter-in-elixir-5d9f