如何在运行时配置 Ecto?
How to configure Ecto at runtime?
在 setup instructions 之后,我的 config/config.exs
文件中有以下 Ecto 配置:
config :my_app, MyApp.Repo,
adapter: Ecto.Adapters.Postgres,
url: "postgresql://postgres@localhost/myrepo",
size: 20
如果我的理解是正确的,config.exs
是在编译时评估的。
有没有办法在运行时执行此配置步骤?
这适用于将作为编译二进制文件分发的应用程序(通过 exrm
)。最终用户应该能够通过标志或环境变量自定义数据库 url 和池大小,而不是通过编辑 sys.config
可以使用 {:system, "KEY" }
从系统加载,例如:
config :my_app Repo
url: {:system, "DATABASE_URL" },
size: {:system, "DATABASE_POOL_SIZE" }
改为
config :my_app, Repo,
url: "ecto://postgres:postgres@localhost/ecto_simple",
size: 20
在这种情况下,您将 Ecto 设置为使用系统属性。当然,用户必须配置它。
使用 {:system, "KEY"}
已经 deprecated in Ecto v3。
相反,建议您在 Repo 模块中定义一个 init/2
callback function 来设置运行时配置:
def init(_type, config) do
config = Keyword.put(config, :url, System.get_env("DATABASE_URL"))
{:ok, config}
end
使用运行时 init/2
函数允许从环境变量以外的地方读取配置。
在 setup instructions 之后,我的 config/config.exs
文件中有以下 Ecto 配置:
config :my_app, MyApp.Repo,
adapter: Ecto.Adapters.Postgres,
url: "postgresql://postgres@localhost/myrepo",
size: 20
如果我的理解是正确的,config.exs
是在编译时评估的。
有没有办法在运行时执行此配置步骤?
这适用于将作为编译二进制文件分发的应用程序(通过 exrm
)。最终用户应该能够通过标志或环境变量自定义数据库 url 和池大小,而不是通过编辑 sys.config
可以使用 {:system, "KEY" }
从系统加载,例如:
config :my_app Repo
url: {:system, "DATABASE_URL" },
size: {:system, "DATABASE_POOL_SIZE" }
改为
config :my_app, Repo,
url: "ecto://postgres:postgres@localhost/ecto_simple",
size: 20
在这种情况下,您将 Ecto 设置为使用系统属性。当然,用户必须配置它。
使用 {:system, "KEY"}
已经 deprecated in Ecto v3。
相反,建议您在 Repo 模块中定义一个 init/2
callback function 来设置运行时配置:
def init(_type, config) do
config = Keyword.put(config, :url, System.get_env("DATABASE_URL"))
{:ok, config}
end
使用运行时 init/2
函数允许从环境变量以外的地方读取配置。