1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Mix.Tasks.Pleroma.Database do
6 alias Pleroma.Conversation
7 alias Pleroma.Maintenance
13 require Pleroma.Constants
20 @shortdoc "A collection of database related tasks"
21 @moduledoc File.read!("docs/administration/CLI_tasks/database.md")
23 def run(["remove_embedded_objects" | args]) do
33 Logger.info("Removing embedded objects")
36 "update activities set data = safe_jsonb_set(data, '{object}'::text[], data->'object'->'id') where data->'object'->>'id' is not null;",
41 if Keyword.get(options, :vacuum) do
42 Maintenance.vacuum("full")
46 def run(["bump_all_conversations"]) do
48 Conversation.bump_for_all_activities()
51 def run(["update_users_following_followers_counts"]) do
56 from(u in User, select: u)
58 |> Stream.each(&User.update_follower_count/1)
65 def run(["prune_objects" | args]) do
76 deadline = Pleroma.Config.get([:instance, :remote_post_retention_days])
78 Logger.info("Pruning objects older than #{deadline} days")
81 NaiveDateTime.utc_now()
82 |> NaiveDateTime.add(-(deadline * 86_400))
87 "?->'to' \\? ? OR ?->'cc' \\? ?",
89 ^Pleroma.Constants.as_public(),
91 ^Pleroma.Constants.as_public()
93 where: o.inserted_at < ^time_deadline,
95 fragment("split_part(?->>'actor', '/', 3) != ?", o.data, ^Pleroma.Web.Endpoint.host())
97 |> Repo.delete_all(timeout: :infinity)
99 if Keyword.get(options, :vacuum) do
100 Maintenance.vacuum("full")
104 def run(["fix_likes_collections"]) do
107 from(object in Object,
108 where: fragment("(?)->>'likes' is not null", object.data),
109 select: %{id: object.id, likes: fragment("(?)->>'likes'", object.data)}
111 |> Pleroma.Repo.chunk_stream(100, :batches)
112 |> Stream.each(fn objects ->
115 |> Enum.filter(fn object -> object.likes |> Jason.decode!() |> is_map() end)
119 |> where([object], object.id in ^ids)
124 "safe_jsonb_set(?, '{likes}', '[]'::jsonb, true)",
129 |> Repo.update_all([], timeout: :infinity)
134 def run(["vacuum", args]) do
137 Maintenance.vacuum(args)
140 def run(["ensure_expiration"]) do
142 days = Pleroma.Config.get([:mrf_activity_expiration, :days], 365)
145 |> join(:inner, [a], o in Object,
148 "(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
154 |> where(local: true)
155 |> where([a], fragment("(? ->> 'type'::text) = 'Create'", a.data))
156 |> where([_a, o], fragment("?->>'type' = 'Note'", o.data))
157 |> Pleroma.Repo.chunk_stream(100, :batches)
158 |> Stream.each(fn activities ->
159 Enum.each(activities, fn activity ->
162 |> DateTime.from_naive!("Etc/UTC")
163 |> Timex.shift(days: days)
165 Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
166 activity_id: activity.id,
167 expires_at: expires_at
174 # Rolls back a specific migration (leaving subsequent migrations applied).
175 # WARNING: imposes a risk of unrecoverable data loss — proceed at your own responsibility.
176 # Based on https://stackoverflow.com/a/53825840
177 def run(["rollback", version]) do
178 prompt = "SEVERE WARNING: this operation may result in unrecoverable data loss. Continue?"
180 if shell_prompt(prompt, "n") in ~w(Yn Y y) do
182 Ecto.Migrator.with_repo(Pleroma.Repo, fn repo ->
183 version = String.to_integer(version)
184 re = ~r/^#{version}_.*\.exs/
185 path = Ecto.Migrator.migrations_path(repo)
187 with {:find, "" <> file} <- {:find, Enum.find(File.ls!(path), &String.match?(&1, re))},
188 {:compile, [{mod, _} | _]} <- {:compile, Code.compile_file(Path.join(path, file))},
189 {:rollback, :ok} <- {:rollback, Ecto.Migrator.down(repo, version, mod)} do
190 {:ok, "Reversed migration: #{file}"}
192 {:find, _} -> {:error, "No migration found with version prefix: #{version}"}
193 {:compile, e} -> {:error, "Problem compiling migration module: #{inspect(e)}"}
194 {:rollback, e} -> {:error, "Problem reversing migration: #{inspect(e)}"}
195 e -> {:error, "Something unexpected happened: #{inspect(e)}"}