First
[anni] / priv / repo / optional_migrations / rum_indexing / 20190510135645_add_fts_index_to_objects_two.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.AddFtsIndexToObjectsTwo do
6   use Ecto.Migration
7
8   def up do
9     execute("create extension if not exists rum")
10
11     drop_if_exists(
12       index(:objects, ["(to_tsvector('english', data->>'content'))"],
13         using: :gin,
14         name: :objects_fts
15       )
16     )
17
18     alter table(:objects) do
19       add(:fts_content, :tsvector)
20     end
21
22     execute("CREATE FUNCTION objects_fts_update() RETURNS trigger AS $$
23     begin
24     new.fts_content := to_tsvector(new.data->>'content');
25     return new;
26     end
27     $$ LANGUAGE plpgsql")
28
29     execute(
30       "create index if not exists objects_fts on objects using RUM (fts_content rum_tsvector_addon_ops, inserted_at) with (attach = 'inserted_at', to = 'fts_content');"
31     )
32
33     execute("CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON objects
34     FOR EACH ROW EXECUTE PROCEDURE objects_fts_update()")
35
36     execute("UPDATE objects SET updated_at = NOW()")
37   end
38
39   def down do
40     execute("drop index if exists objects_fts")
41     execute("drop trigger if exists tsvectorupdate on objects")
42     execute("drop function if exists objects_fts_update()")
43
44     alter table(:objects) do
45       remove(:fts_content, :tsvector)
46     end
47
48     create_if_not_exists(
49       index(:objects, ["(to_tsvector('english', data->>'content'))"],
50         using: :gin,
51         name: :objects_fts
52       )
53     )
54   end
55 end