Merge branch 'develop' into 'remove-twitter-api'
[akkoma] / priv / repo / migrations / 20190414125034_migrate_old_bookmarks.exs
index 1930fc3cf30a3894ebc234093bc5b4a209311bf0..b6f0ac66b3dde98f6a1e95d9b38edeceed381788 100644 (file)
@@ -1,21 +1,38 @@
 defmodule Pleroma.Repo.Migrations.MigrateOldBookmarks do
   use Ecto.Migration
+  import Ecto.Query
   alias Pleroma.Activity
   alias Pleroma.Bookmark
-  alias Pleroma.User
   alias Pleroma.Repo
 
   def up do
-    Repo.all(User)
-    |> Enum.each(fn user ->
-      Enum.each(user.old_bookmarks, fn id ->
-        activity = Activity.get_create_by_object_ap_id(id)
-        {:ok, _} = Bookmark.create(user.id, activity.id)
+    query =
+      from(u in "users",
+        where: u.local == true,
+        where: fragment("array_length(?, 1)", u.bookmarks) > 0,
+        select: %{id: u.id, bookmarks: u.bookmarks}
+      )
+
+    Repo.stream(query)
+    |> Enum.each(fn %{id: user_id, bookmarks: bookmarks} ->
+      Enum.each(bookmarks, fn ap_id ->
+        activity =
+          ap_id
+          |> Activity.create_by_object_ap_id()
+          |> Repo.one()
+
+        unless is_nil(activity), do: {:ok, _} = Bookmark.create(user_id, activity.id)
       end)
     end)
+
+    alter table(:users) do
+      remove(:bookmarks)
+    end
   end
 
   def down do
-    execute("TRUNCATE TABLE bookmarks")
+    alter table(:users) do
+      add(:bookmarks, {:array, :string}, null: false, default: [])
+    end
   end
 end