c36aee1d4026739e8fdbdde6e12dce31a51d3207
[wolnelektury.git] / src / catalogue / migrations / 0003_populate_ancestors.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.db import migrations
5
6
7 def populate_ancestors(apps, schema_editor):
8     """Fixes the ancestry cache."""
9     # TODO: table names
10     from django.db import connection, transaction
11     if connection.vendor == 'postgres':
12         cursor = connection.cursor()
13         cursor.execute("""
14             WITH RECURSIVE ancestry AS (
15                 SELECT book.id, book.parent_id
16                 FROM catalogue_book AS book
17                 WHERE book.parent_id IS NOT NULL
18                 UNION
19                 SELECT ancestor.id, book.parent_id
20                 FROM ancestry AS ancestor, catalogue_book AS book
21                 WHERE ancestor.parent_id = book.id
22                     AND book.parent_id IS NOT NULL
23                 )
24             INSERT INTO catalogue_book_ancestor
25                 (from_book_id, to_book_id)
26                 SELECT id, parent_id
27                 FROM ancestry
28                 ORDER BY id;
29             """)
30     else:
31         Book = apps.get_model("catalogue", "Book")
32         for book in Book.objects.exclude(parent=None):
33             parent = book.parent
34             while parent is not None:
35                 book.ancestor.add(parent)
36                 parent = parent.parent
37
38
39 def remove_book_tags(apps, schema_editor):
40     Tag = apps.get_model("catalogue", "Tag")
41     Book = apps.get_model("catalogue", "Book")
42     Tag.objects.filter(category='book').delete()
43
44
45 class Migration(migrations.Migration):
46
47     dependencies = [
48         ('catalogue', '0002_book_ancestor'),
49     ]
50
51     operations = [
52         migrations.RunPython(populate_ancestors),
53         migrations.RunPython(remove_book_tags),
54     ]