Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/kura_app.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,38 @@
start(_StartType, _StartArgs) ->
configure_pg_types(),
kura_query_cache:init(),
ok = ensure_pool(),
kura_sup:start_link().

stop(_State) ->
ok.

-spec ensure_pool() -> ok.
ensure_pool() ->
case application:get_env(kura, repo) of
{ok, Repo} ->
Config = pool_config(),
case pgo_sup:start_child(Repo, Config) of
{ok, _Pid} -> ok;
{error, {already_started, _Pid}} -> ok
end;
undefined ->
ok
end.

-spec pool_config() -> map().
pool_config() ->
Env = fun(Key, Default) -> application:get_env(kura, Key, Default) end,
#{
host => Env(host, "localhost"),
port => Env(port, 5432),
database => Env(database, "postgres"),
user => Env(user, "postgres"),
password => Env(password, ""),
pool_size => Env(pool_size, 10),
decode_opts => [return_rows_as_maps, column_name_as_atom]
}.

-spec configure_pg_types() -> ok.
configure_pg_types() ->
Defaults = #{uuid_format => string},
Expand Down
32 changes: 26 additions & 6 deletions src/kura_repo.erl
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,33 @@ init(Config) ->
-doc "Read the repo configuration from application environment.".
-spec config(module()) -> map().
config(RepoMod) ->
App = RepoMod:otp_app(),
Config =
case application:get_env(App, RepoMod) of
{ok, C} when is_map(C) -> C;
_ -> #{}
end,
Config = read_config(RepoMod),
case erlang:function_exported(RepoMod, init, 1) of
true -> RepoMod:init(Config);
false -> Config
end.

-spec read_config(module()) -> map().
read_config(RepoMod) ->
%% Try kura app env first, fall back to repo's otp_app env for
%% backward compatibility.
case application:get_env(kura, repo) of
{ok, RepoMod} ->
Env = fun(Key, Default) ->
application:get_env(kura, Key, Default)
end,
#{
hostname => list_to_binary(Env(host, "localhost")),
port => Env(port, 5432),
database => list_to_binary(Env(database, "postgres")),
username => list_to_binary(Env(user, "postgres")),
password => list_to_binary(Env(password, "")),
pool_size => Env(pool_size, 10)
};
_ ->
App = RepoMod:otp_app(),
case application:get_env(App, RepoMod) of
{ok, C} when is_map(C) -> C;
_ -> #{}
end
end.
Loading