move to 2.5.5
[anni] / priv / repo / migrations / 20190414125034_migrate_old_bookmarks.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Repo.Migrations.MigrateOldBookmarks do
6   use Ecto.Migration
7   import Ecto.Query
8   alias Pleroma.Activity
9   alias Pleroma.Bookmark
10   alias Pleroma.Repo
11
12   def up do
13     query =
14       from(u in "users",
15         where: u.local == true,
16         where: fragment("array_length(?, 1)", u.bookmarks) > 0,
17         select: %{id: u.id, bookmarks: u.bookmarks}
18       )
19
20     Repo.stream(query)
21     |> Enum.each(fn %{id: user_id, bookmarks: bookmarks} ->
22       Enum.each(bookmarks, fn ap_id ->
23         activity =
24           ap_id
25           |> Activity.create_by_object_ap_id()
26           |> Repo.one()
27
28         unless is_nil(activity), do: {:ok, _} = Bookmark.create(user_id, activity.id)
29       end)
30     end)
31
32     alter table(:users) do
33       remove(:bookmarks)
34     end
35   end
36
37   def down do
38     alter table(:users) do
39       add(:bookmarks, {:array, :string}, null: false, default: [])
40     end
41   end
42 end