将 Ecto Schema 转储到其数据库表示

发布于 2025-01-13 12:52:24 字数 436 浏览 0 评论 0原文

我有一个存储过程,需要使用 Ecto Schema 中的几个字段作为参数来调用:

Ecto.Adapters.SQL.query(My.Repo, "CALL my_stored_procedure($1, $2, $3)", [myschema.id, myschema.field1, myschema.field2])

当函数调用有效时,我传入 Elixir 值,而不是它们的数据库表示形式。如果不先转储到数据库类型,则无法使用 Elixir 值。例如,一个字段是一个 Ecto.Enum,它在 Elixir 中表示为一个原子,但实际上在数据库中是一个不同的字符串值。我需要将每个字段“转储”到其数据库类型,就像插入记录时 Ecto.Repo.insert/2 处理所有字段一样。我在文档中没有看到任何 Ecto 辅助函数来促进这一点。

I have a stored procedure I need to invoke with a couple fields from my Ecto Schema as arguments:

Ecto.Adapters.SQL.query(My.Repo, "CALL my_stored_procedure($1, $2, $3)", [myschema.id, myschema.field1, myschema.field2])

While the function call works I'm passing in the Elixir values, not the database representation of them. The Elixir values can't be used without first being dumped to the database type. For example, one field is an Ecto.Enum that is represented as an atom in Elixir, but is actually a different string value in the database. I need to "dump" each field to their database type, just like Ecto.Repo.insert/2 does all fields when inserting a record. I do not see any Ecto helper functions in docs to facilitate this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅此而已 2025-01-20 12:52:24

您可以对 Ecto 架构进行一些检查,但不幸的是,架构模块不包含有关实际迁移的数据的完整信息。这是我所能达到的最接近的结果:检查模块的结构及其 __changeset__/0 函数。您最终会得到这样的结果:

defmodule SchemaInspector do

  def inspect_schema(module) do
    %{
      source: module,
      fields:
        module.__struct__()
        |> Map.from_struct()
        |> Map.delete(:__meta__)
        |> Enum.map(fn {fieldname, default} ->
          %{name: fieldname, type: fieldtype(module, fieldname), default: default}
        end)
    }
  end

  defp fieldtype(module, fieldname) do
    module.__changeset__()
    |> Map.get(fieldname)
    |> case do
      {:embed, %Ecto.Embedded{cardinality: :many, related: related}} -> "ARRAY(#{related})"
      other -> other
    end
  end
end

然后您可以在其中传递 Elixir Ecto 架构模块名称,例如:

iex> SchemaInspector.inspect_schema(SomeModel)
%{
    fields: [
      %{default: nil, name: :created_at, type: :naive_datetime},
      %{default: nil, name: :created_by, type: :string},
      %{default: nil, name: :creation_date, type: :naive_datetime},
      %{default: nil, name: :id, type: :string},
      %{default: nil, name: :some_number, type: :integer},
      %{default: nil, name: :status, type: :string},
      %{default: nil, name: :updated_at, type: :naive_datetime}
    ],
    source: SomeModel
  }

模块的 __changeset__/0 函数包含有关数据类型的一些信息,但可能还不够满足您的需求。

我编写了一个相关的包来帮助完成此任务:https://hex.pm/packages/inspecto

You can do some inspection on the Ecto schemas, but the schema modules unfortunately don't contain full info about what data was actually migrated. This is as close as I've been able to come: inspecting the module's struct and its __changeset__/0 function. You end up with something like this:

defmodule SchemaInspector do

  def inspect_schema(module) do
    %{
      source: module,
      fields:
        module.__struct__()
        |> Map.from_struct()
        |> Map.delete(:__meta__)
        |> Enum.map(fn {fieldname, default} ->
          %{name: fieldname, type: fieldtype(module, fieldname), default: default}
        end)
    }
  end

  defp fieldtype(module, fieldname) do
    module.__changeset__()
    |> Map.get(fieldname)
    |> case do
      {:embed, %Ecto.Embedded{cardinality: :many, related: related}} -> "ARRAY(#{related})"
      other -> other
    end
  end
end

Where then you can pass the Elixir Ecto schema module name, something like:

iex> SchemaInspector.inspect_schema(SomeModel)
%{
    fields: [
      %{default: nil, name: :created_at, type: :naive_datetime},
      %{default: nil, name: :created_by, type: :string},
      %{default: nil, name: :creation_date, type: :naive_datetime},
      %{default: nil, name: :id, type: :string},
      %{default: nil, name: :some_number, type: :integer},
      %{default: nil, name: :status, type: :string},
      %{default: nil, name: :updated_at, type: :naive_datetime}
    ],
    source: SomeModel
  }

The module's __changeset__/0 function contains some info about the data type, but it may not be sufficient for your needs.

I authored a related package to help with this task: https://hex.pm/packages/inspecto

命比纸薄 2025-01-20 12:52:24

我最终这样做了:

# Build a dummy update query
query = from(m in MySchema, update: [set: [id: ^myschema.id,
  field1: ^myschema.field1,
  field2: ^myschema.field2]])

# Pass the query to to_sql/2 so we get the raw query and the parameters
# converted to database types
{_query, params} = Repo.to_sql(:update_all, query)

# Then we invoke the stored procedure query with the converted parameters
sql = "CALL my_stored_procedure(:1, :2, :3)"
Ecto.Adapters.SQL.query(Repo, sql, params)

这感觉很hacky,但这是让 Ecto 为我进行转换的最直接的方法。

I ended up doing this:

# Build a dummy update query
query = from(m in MySchema, update: [set: [id: ^myschema.id,
  field1: ^myschema.field1,
  field2: ^myschema.field2]])

# Pass the query to to_sql/2 so we get the raw query and the parameters
# converted to database types
{_query, params} = Repo.to_sql(:update_all, query)

# Then we invoke the stored procedure query with the converted parameters
sql = "CALL my_stored_procedure(:1, :2, :3)"
Ecto.Adapters.SQL.query(Repo, sql, params)

It feels hacky but it was the most straightforward way to have Ecto do the conversion for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文