将 Ecto Schema 转储到其数据库表示
我有一个存储过程,需要使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以对
Ecto
架构进行一些检查,但不幸的是,架构模块不包含有关实际迁移的数据的完整信息。这是我所能达到的最接近的结果:检查模块的结构及其 __changeset__/0 函数。您最终会得到这样的结果:然后您可以在其中传递 Elixir Ecto 架构模块名称,例如:
模块的
__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:Where then you can pass the Elixir Ecto schema module name, something like:
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
我最终这样做了:
这感觉很hacky,但这是让 Ecto 为我进行转换的最直接的方法。
I ended up doing this:
It feels hacky but it was the most straightforward way to have Ecto do the conversion for me.