使用Ecto更改Postgres search_path

时间:2016-02-01 13:07:00

标签: postgresql elixir phoenix-framework ecto

我想为我的Phoenix应用程序使用特定的Postgres架构。

我尝试使用 $from_date_options = array(); $from_date_options['type'] = 'datetime'; $from_date_options['div'] = 'clearfix'; $from_date_options['div'] = 'input text required'; $from_date_options['orderYear'] = 'asc'; $from_date_options['minYear'] = date('Y') -10; $from_date_options['maxYear'] = date('Y') +10; $from_date_options['label'] = __('Starts'); $from_date_options['timeFormat'] = '24'; $from_date_options['dateFormat'] = 'DMY'; $from_date_options['separator'] = '/'; echo $this->Form->input('CustomPricePerTypestart_date', $from_date_options); 回调实现此目的,但似乎在超时之前以递归方式创建新的数据库连接约10次。

这是我的回购文件:

Ecto.Repo.after_connect/1

2 个答案:

答案 0 :(得分:6)

我认为超时发生是因为在ecto的设置周期中after_connect还为时尚早。使用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

答案 1 :(得分:4)

我遇到了同样的问题,我发现的第一个解决方案是在每次访问我的应用程序的Repo模块时添加prefix(在postgres中称为架构)。 但是在最近的ecto和phoenix_ecto版本中,只需添加属性@schema_prefix "your_schema"即可修改模型的postgres架构。

示例:

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"}  

我希望我能帮助你!