1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Pagination do
7 Implements Mastodon-compatible pagination.
17 def fetch_paginated(query, params, type \\ :keyset)
19 def fetch_paginated(query, %{"total" => true} = params, :keyset) do
20 total = Repo.aggregate(query, :count, :id)
24 items: fetch_paginated(query, Map.drop(params, ["total"]), :keyset)
28 def fetch_paginated(query, params, :keyset) do
29 options = cast_params(params)
32 |> paginate(options, :keyset)
34 |> enforce_order(options)
37 def fetch_paginated(query, %{"total" => true} = params, :offset) do
38 total = Repo.aggregate(query, :count, :id)
42 items: fetch_paginated(query, Map.drop(params, ["total"]), :offset)
46 def fetch_paginated(query, params, :offset) do
47 options = cast_params(params)
50 |> paginate(options, :offset)
54 def paginate(query, options, method \\ :keyset)
56 def paginate(query, options, :keyset) do
58 |> restrict(:min_id, options)
59 |> restrict(:since_id, options)
60 |> restrict(:max_id, options)
61 |> restrict(:order, options)
62 |> restrict(:limit, options)
65 def paginate(query, options, :offset) do
67 |> restrict(:offset, options)
68 |> restrict(:limit, options)
71 defp cast_params(params) do
81 Enum.reduce(params, %{}, fn
82 {key, _value}, acc when is_atom(key) -> Map.drop(acc, [key])
83 {key, value}, acc -> Map.put(acc, key, value)
86 changeset = cast({%{}, param_types}, params, Map.keys(param_types))
90 defp restrict(query, :min_id, %{min_id: min_id}) do
91 where(query, [q], q.id > ^min_id)
94 defp restrict(query, :since_id, %{since_id: since_id}) do
95 where(query, [q], q.id > ^since_id)
98 defp restrict(query, :max_id, %{max_id: max_id}) do
99 where(query, [q], q.id < ^max_id)
102 defp restrict(query, :order, %{min_id: _}) do
103 order_by(query, [u], fragment("? asc nulls last", u.id))
106 defp restrict(query, :order, _options) do
107 order_by(query, [u], fragment("? desc nulls last", u.id))
110 defp restrict(query, :offset, %{offset: offset}) do
111 offset(query, ^offset)
114 defp restrict(query, :limit, options) do
115 limit = Map.get(options, :limit, @default_limit)
121 defp restrict(query, _, _), do: query
123 defp enforce_order(result, %{min_id: _}) do
128 defp enforce_order(result, _), do: result