summaryrefslogtreecommitdiff
path: root/lib/pleroma/repo_streamer.ex
blob: cb4d7bb7a80dfcc00393fe451e0e296fc666d13b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.RepoStreamer do
  alias Pleroma.Repo
  import Ecto.Query

  def chunk_stream(query, chunk_size) do
    Stream.unfold(0, fn
      :halt ->
        {[], :halt}

      last_id ->
        query
        |> order_by(asc: :id)
        |> where([r], r.id > ^last_id)
        |> limit(^chunk_size)
        |> Repo.all()
        |> case do
          [] ->
            {[], :halt}

          records ->
            last_id = List.last(records).id
            {records, last_id}
        end
    end)
    |> Stream.take_while(fn
      [] -> false
      _ -> true
    end)
  end
end