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/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 prune_hashtags_query = """
100 DELETE FROM hashtags AS ht
102 SELECT 1 FROM hashtags_objects hto
103 WHERE ht.id = hto.hashtag_id)
106 Repo.query(prune_hashtags_query)
108 if Keyword.get(options, :vacuum) do
109 Maintenance.vacuum("full")
113 def run(["prune_task"]) do
117 |> Pleroma.Workers.Cron.PruneDatabaseWorker.perform()
121 def run(["fix_likes_collections"]) do
124 from(object in Object,
125 where: fragment("(?)->>'likes' is not null", object.data),
126 select: %{id: object.id, likes: fragment("(?)->>'likes'", object.data)}
128 |> Pleroma.Repo.chunk_stream(100, :batches)
129 |> Stream.each(fn objects ->
132 |> Enum.filter(fn object -> object.likes |> Jason.decode!() |> is_map() end)
136 |> where([object], object.id in ^ids)
141 "safe_jsonb_set(?, '{likes}', '[]'::jsonb, true)",
146 |> Repo.update_all([], timeout: :infinity)
151 def run(["vacuum", args]) do
154 Maintenance.vacuum(args)
157 def run(["ensure_expiration"]) do
159 days = Pleroma.Config.get([:mrf_activity_expiration, :days], 365)
162 |> join(:inner, [a], o in Object,
165 "(?->>'id') = COALESCE((?)->'object'->> 'id', (?)->>'object')",
171 |> where(local: true)
172 |> where([a], fragment("(? ->> 'type'::text) = 'Create'", a.data))
173 |> where([_a, o], fragment("?->>'type' = 'Note'", o.data))
174 |> Pleroma.Repo.chunk_stream(100, :batches)
175 |> Stream.each(fn activities ->
176 Enum.each(activities, fn activity ->
179 |> DateTime.from_naive!("Etc/UTC")
180 |> Timex.shift(days: days)
182 Pleroma.Workers.PurgeExpiredActivity.enqueue(%{
183 activity_id: activity.id,
184 expires_at: expires_at
191 def run(["set_text_search_config", tsconfig]) do
193 %{rows: [[tsc]]} = Ecto.Adapters.SQL.query!(Pleroma.Repo, "SHOW default_text_search_config;")
194 shell_info("Current default_text_search_config: #{tsc}")
196 %{rows: [[db]]} = Ecto.Adapters.SQL.query!(Pleroma.Repo, "SELECT current_database();")
197 shell_info("Update default_text_search_config: #{tsconfig}")
200 Ecto.Adapters.SQL.query!(
202 "ALTER DATABASE #{db} SET default_text_search_config = '#{tsconfig}';"
205 # non-exist config will not raise excpetion but only give >0 messages
206 if length(msg) > 0 do
207 shell_info("Error: #{inspect(msg, pretty: true)}")
209 rum_enabled = Pleroma.Config.get([:database, :rum_enabled])
210 shell_info("Recreate index, RUM: #{rum_enabled}")
212 # Note SQL below needs to be kept up-to-date with latest GIN or RUM index definition in future
214 Ecto.Adapters.SQL.query!(
216 "CREATE OR REPLACE FUNCTION objects_fts_update() RETURNS trigger AS $$ BEGIN
217 new.fts_content := to_tsvector(new.data->>'content');
220 $$ LANGUAGE plpgsql",
225 shell_info("Refresh RUM index")
226 Ecto.Adapters.SQL.query!(Pleroma.Repo, "UPDATE objects SET updated_at = NOW();")
228 Ecto.Adapters.SQL.query!(Pleroma.Repo, "DROP INDEX IF EXISTS objects_fts;")
230 Ecto.Adapters.SQL.query!(
232 "CREATE INDEX CONCURRENTLY objects_fts ON objects USING gin(to_tsvector('#{tsconfig}', data->>'content')); ",
242 # Rolls back a specific migration (leaving subsequent migrations applied).
243 # WARNING: imposes a risk of unrecoverable data loss — proceed at your own responsibility.
244 # Based on https://stackoverflow.com/a/53825840
245 def run(["rollback", version]) do
246 prompt = "SEVERE WARNING: this operation may result in unrecoverable data loss. Continue?"
248 if shell_prompt(prompt, "n") in ~w(Yn Y y) do
250 Ecto.Migrator.with_repo(Pleroma.Repo, fn repo ->
251 version = String.to_integer(version)
252 re = ~r/^#{version}_.*\.exs/
253 path = Ecto.Migrator.migrations_path(repo)
255 with {_, "" <> file} <- {:find, Enum.find(File.ls!(path), &String.match?(&1, re))},
256 {_, [{mod, _} | _]} <- {:compile, Code.compile_file(Path.join(path, file))},
257 {_, :ok} <- {:rollback, Ecto.Migrator.down(repo, version, mod)} do
258 {:ok, "Reversed migration: #{file}"}
260 {:find, _} -> {:error, "No migration found with version prefix: #{version}"}
261 {:compile, e} -> {:error, "Problem compiling migration module: #{inspect(e)}"}
262 {:rollback, e} -> {:error, "Problem reversing migration: #{inspect(e)}"}
266 shell_info(inspect(result))