1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Repo do
8 adapter: Ecto.Adapters.Postgres,
9 migration_timestamps: [type: :naive_datetime_usec]
14 defmodule Instrumenter, do: use(Prometheus.EctoInstrumenter)
17 Dynamically loads the repository url from the
18 DATABASE_URL environment variable.
21 {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
24 @doc "find resource based on prepared query"
25 @spec find_resource(Ecto.Query.t()) :: {:ok, struct()} | {:error, :not_found}
26 def find_resource(%Ecto.Query{} = query) do
27 case __MODULE__.one(query) do
28 nil -> {:error, :not_found}
29 resource -> {:ok, resource}
33 def find_resource(_query), do: {:error, :not_found}
36 Gets association from cache or loads if need
40 iex> Repo.get_assoc(token, :user)
44 @spec get_assoc(struct(), atom()) :: {:ok, struct()} | {:error, :not_found}
45 def get_assoc(resource, association) do
46 case __MODULE__.preload(resource, association) do
47 %{^association => assoc} when not is_nil(assoc) -> {:ok, assoc}
48 _ -> {:error, :not_found}
52 def chunk_stream(query, chunk_size) do
53 # We don't actually need start and end funcitons of resource streaming,
54 # but it seems to be the only way to not fetch records one-by-one and
55 # have individual records be the elements of the stream, instead of
63 |> where([r], r.id > ^last_id)
71 last_id = List.last(records).id