[#1335] User: refactored :blocks field into :blocked_users relation.

Introduced UserBlock.
This commit is contained in:
Ivan Tashkinov 2019-11-10 16:30:21 +03:00
commit 3db988250b
20 changed files with 234 additions and 69 deletions

View file

@ -0,0 +1,14 @@
defmodule Pleroma.Repo.Migrations.CreateUserBlocks do
use Ecto.Migration
def change do
create_if_not_exists table(:user_blocks) do
add(:blocker_id, references(:users, type: :uuid, on_delete: :delete_all))
add(:blockee_id, references(:users, type: :uuid, on_delete: :delete_all))
timestamps(updated_at: false)
end
create_if_not_exists(unique_index(:user_blocks, [:blocker_id, :blockee_id]))
end
end

View file

@ -0,0 +1,50 @@
defmodule Pleroma.Repo.Migrations.DataMigrationPopulateUserBlocks do
use Ecto.Migration
alias Ecto.Adapters.SQL
alias Pleroma.Repo
require Logger
def up do
{:ok, %{rows: block_rows}} =
SQL.query(Repo, "SELECT id, blocks FROM users WHERE blocks != '{}'")
blockee_ap_ids =
Enum.flat_map(
block_rows,
fn [_, ap_ids] -> ap_ids end
)
|> Enum.uniq()
# Selecting ids of all blockees at once in order to reduce the number of SELECT queries
{:ok, %{rows: blockee_ap_id_id}} =
SQL.query(Repo, "SELECT ap_id, id FROM users WHERE ap_id = ANY($1)", [blockee_ap_ids])
blockee_id_by_ap_id = Enum.into(blockee_ap_id_id, %{}, fn [k, v] -> {k, v} end)
Enum.each(
block_rows,
fn [blocker_id, blockee_ap_ids] ->
blocker_uuid = Ecto.UUID.cast!(blocker_id)
for blockee_ap_id <- blockee_ap_ids do
blockee_id = blockee_id_by_ap_id[blockee_ap_id]
blockee_uuid = blockee_id && Ecto.UUID.cast!(blockee_id)
with {:ok, blockee_uuid} <- Ecto.UUID.cast(blockee_id) do
execute(
"INSERT INTO user_blocks(blocker_id, blockee_id, inserted_at) " <>
"VALUES('#{blocker_uuid}'::uuid, '#{blockee_uuid}'::uuid, now()) " <>
"ON CONFLICT (blocker_id, blockee_id) DO NOTHING"
)
else
_ -> Logger.warn("Missing reference: (#{blocker_uuid}, #{blockee_id})")
end
end
end
)
end
def down, do: :noop
end