1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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]
15 Dynamically loads the repository url from the
16 DATABASE_URL environment variable.
19 {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
22 @doc "find resource based on prepared query"
23 @spec find_resource(Ecto.Query.t()) :: {:ok, struct()} | {:error, :not_found}
24 def find_resource(%Ecto.Query{} = query) do
25 case __MODULE__.one(query) do
26 nil -> {:error, :not_found}
27 resource -> {:ok, resource}
31 def find_resource(_query), do: {:error, :not_found}
34 Gets association from cache or loads if need
38 iex> Repo.get_assoc(token, :user)
42 @spec get_assoc(struct(), atom()) :: {:ok, struct()} | {:error, :not_found}
43 def get_assoc(resource, association) do
44 case __MODULE__.preload(resource, association) do
45 %{^association => assoc} when not is_nil(assoc) -> {:ok, assoc}
46 _ -> {:error, :not_found}
51 Returns a lazy enumerable that emits all entries from the data store matching the given query.
53 `returns_as` use to group records. use the `batches` option to fetch records in bulk.
57 # fetch records one-by-one
58 iex> Pleroma.Repo.chunk_stream(Pleroma.Activity.Queries.by_actor(ap_id), 500)
60 # fetch records in bulk
61 iex> Pleroma.Repo.chunk_stream(Pleroma.Activity.Queries.by_actor(ap_id), 500, :batches)
63 @spec chunk_stream(Ecto.Query.t(), integer(), atom()) :: Enumerable.t()
64 def chunk_stream(query, chunk_size, returns_as \\ :one, query_options \\ []) do
65 # We don't actually need start and end functions of resource streaming,
66 # but it seems to be the only way to not fetch records one-by-one and
67 # have individual records be the elements of the stream, instead of
75 |> where([r], r.id > ^last_id)
83 last_id = List.last(records).id
85 if returns_as == :one do