Merge branch 'issue/1348' into 'develop'
[akkoma] / lib / pleroma / repo.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Repo do
6 use Ecto.Repo,
7 otp_app: :pleroma,
8 adapter: Ecto.Adapters.Postgres,
9 migration_timestamps: [type: :naive_datetime_usec]
10
11 defmodule Instrumenter do
12 use Prometheus.EctoInstrumenter
13 end
14
15 @doc """
16 Dynamically loads the repository url from the
17 DATABASE_URL environment variable.
18 """
19 def init(_, opts) do
20 {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
21 end
22
23 @doc "find resource based on prepared query"
24 @spec find_resource(Ecto.Query.t()) :: {:ok, struct()} | {:error, :not_found}
25 def find_resource(%Ecto.Query{} = query) do
26 case __MODULE__.one(query) do
27 nil -> {:error, :not_found}
28 resource -> {:ok, resource}
29 end
30 end
31
32 def find_resource(_query), do: {:error, :not_found}
33
34 @doc """
35 Gets association from cache or loads if need
36
37 ## Examples
38
39 iex> Repo.get_assoc(token, :user)
40 %User{}
41
42 """
43 @spec get_assoc(struct(), atom()) :: {:ok, struct()} | {:error, :not_found}
44 def get_assoc(resource, association) do
45 case __MODULE__.preload(resource, association) do
46 %{^association => assoc} when not is_nil(assoc) -> {:ok, assoc}
47 _ -> {:error, :not_found}
48 end
49 end
50 end