-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupdate_title_flavours_from_books.py
More file actions
executable file
·90 lines (72 loc) · 2.8 KB
/
Copy pathupdate_title_flavours_from_books.py
File metadata and controls
executable file
·90 lines (72 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
# ruff: noqa: T201
"""This script sets the title flavours from the set of all books belonging to the title.
It also fixes books whose flavours start with an underscore.
"""
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session as OrmSession
from cms_backend import logger
from cms_backend.db import Session
from cms_backend.db.models import Book, Title
from cms_backend.db.title import get_title_by_id
def update_title_flavour(session: OrmSession, title: Title) -> tuple[bool, str]:
if title.archived:
logger.info(f"Skipping archived title {title.id} ({title.name})")
return (False, "Title is archived")
books = session.scalars(
select(Book)
.join(Title, Book.title_id == Title.id)
.order_by(Book.flavour)
.where(Book.flavour.isnot(None), Book.title_id == title.id)
).all()
for book in books:
if book.flavour and book.flavour.startswith("_"):
new_flavour = book.flavour[1:]
logger.info(
f"Updated book {book.name} from {book.flavour} to {new_flavour}"
)
book.flavour = new_flavour
session.add(book)
flavours = {book.flavour for book in books if book.flavour is not None}
title.flavours = list(flavours)
session.add(title)
session.flush()
if not flavours:
logger.info(
f"No flavours found in books belonging to title {title.id} ({title.name})"
)
return (
False,
f"No flavours found in books belonging to title {title.id} ({title.name})",
)
logger.info(f"✓ Updated title {title.id} ({title.name}) flavours to {flavours}")
return (True, "")
def main():
with Session.begin() as session:
title_ids = session.scalars(select(Title.id)).all()
logger.info(f"Found {len(title_ids)} titles to process")
nb_titles_updated = 0
nb_titles_skipped = 0
reasons: list[dict[str, Any]] = []
for title_id in title_ids:
title = get_title_by_id(session, title_id=title_id)
processed, reason = update_title_flavour(session, title)
if processed:
nb_titles_updated += 1
else:
nb_titles_skipped += 1
reasons.append({title.name: reason})
logger.info(
f"Updated {nb_titles_updated} title(s) metadata, skipped "
f"{nb_titles_skipped} titles(s)"
)
if reasons:
print("\nSkipped titles summary:")
print("| Title Name | Reason |")
print("|------------|--------|")
for entry in reasons:
for title_name, reason in entry.items():
print(f"| {title_name} | {reason} |")
if __name__ == "__main__":
main()