用 Ecto 改变 Postgres search_path
Change Postgres search_path with Ecto
我想为我的 Phoenix 应用程序使用特定的 Postgres 架构。
我试图通过 Ecto.Repo.after_connect/1
回调实现此目的,但它似乎在超时前递归创建新的数据库连接大约 10 次。
这是我的回购文件:
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app
use Scrivener, page_size: 20
def after_connect(_pid) do
IO.puts "after_connect"
Ecto.Adapters.SQL.query(MyApp.Repo, "SET search_path TO 'my_app';", [])
end
end
我遇到了同样的问题,我找到的第一个解决方案是在每次访问我的应用程序的 Repo 模块时添加 prefix
(在 postgres 中称为模式)。
但是在 ecto 和 phoenix_ecto 的最新版本中,您可以修改模型的 postgres 架构,只需添加属性 @schema_prefix "your_schema"
.
示例:
defmodule YourApp.YourModel do
use YourApp.Web, :model
@schema_prefix "your_schema"
schema "your_model" do
field :name, :string
end
# more stuff...
end
您可以在 ecto 的 github 查看有关此功能的讨论以及解决此问题的其他方法:https://github.com/elixir-lang/ecto/issues/978
PS:这解决了模型的数据库访问问题,但对于其他常规查询,您需要在查询中指定前缀:
%{query | prefix: "your_schema"}
希望对您有所帮助!
我认为超时的发生是因为 after_connect 在 ecto 的设置周期中还为时过早。使用 ecto 2(仍处于测试阶段)以下工作,它是否在 ecto 1 中工作取决于您是否将连接作为 after_connection 中的参数)。
在你的仓库中:
defmodule Et.Repo do
use Ecto.Repo, otp_app: :et
def set_search_path(conn, path) do
{:ok, _result} = Postgrex.query(conn, "SET search_path=#{path}", [])
end
end
在您的 config.exs 文件中:
config :et, Et.Repo,
adapter: Ecto.Adapters.Postgres,
database: "......",
username: "......",
hostname: "localhost",
after_connect: {Et.Repo, :set_search_path, ["app,public,extensions"]}
希望对您有所帮助,--Kip
我想为我的 Phoenix 应用程序使用特定的 Postgres 架构。
我试图通过 Ecto.Repo.after_connect/1
回调实现此目的,但它似乎在超时前递归创建新的数据库连接大约 10 次。
这是我的回购文件:
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app
use Scrivener, page_size: 20
def after_connect(_pid) do
IO.puts "after_connect"
Ecto.Adapters.SQL.query(MyApp.Repo, "SET search_path TO 'my_app';", [])
end
end
我遇到了同样的问题,我找到的第一个解决方案是在每次访问我的应用程序的 Repo 模块时添加 prefix
(在 postgres 中称为模式)。
但是在 ecto 和 phoenix_ecto 的最新版本中,您可以修改模型的 postgres 架构,只需添加属性 @schema_prefix "your_schema"
.
示例:
defmodule YourApp.YourModel do
use YourApp.Web, :model
@schema_prefix "your_schema"
schema "your_model" do
field :name, :string
end
# more stuff...
end
您可以在 ecto 的 github 查看有关此功能的讨论以及解决此问题的其他方法:https://github.com/elixir-lang/ecto/issues/978
PS:这解决了模型的数据库访问问题,但对于其他常规查询,您需要在查询中指定前缀:
%{query | prefix: "your_schema"}
希望对您有所帮助!
我认为超时的发生是因为 after_connect 在 ecto 的设置周期中还为时过早。使用 ecto 2(仍处于测试阶段)以下工作,它是否在 ecto 1 中工作取决于您是否将连接作为 after_connection 中的参数)。
在你的仓库中:
defmodule Et.Repo do
use Ecto.Repo, otp_app: :et
def set_search_path(conn, path) do
{:ok, _result} = Postgrex.query(conn, "SET search_path=#{path}", [])
end
end
在您的 config.exs 文件中:
config :et, Et.Repo,
adapter: Ecto.Adapters.Postgres,
database: "......",
username: "......",
hostname: "localhost",
after_connect: {Et.Repo, :set_search_path, ["app,public,extensions"]}
希望对您有所帮助,--Kip