Skip to content

Commit b0decac

Browse files
refactor: sql migrations (#1295)
* refactor: cleanup parameters of open_library and open_sqlite_library * doc: notes on what tables are affected by which migration steps * refactor(migration order): move DBv6 repairs * refactor(migration order): move DBv8 repairs * refactor(migration order): move DBv9 repairs * refactor(migration order): move DBv100 repairs * refactor(migration order): move DBv102 repairs * refactor: merge migration methods * doc: final comment changes * fix: query tag ids independent of future DB changes
1 parent 910d2b7 commit b0decac

1 file changed

Lines changed: 39 additions & 42 deletions

File tree

src/tagstudio/core/library/alchemy/library.py

Lines changed: 39 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -423,8 +423,8 @@ def open_sqlite_library(
423423
logger.info(f"[Library] DB_VERSION: {loaded_db_version}")
424424
make_tables(self.engine)
425425

426-
# Add default tag color namespaces.
427426
if is_new:
427+
# Add default tag color namespaces.
428428
namespaces = default_color_groups.namespaces()
429429
try:
430430
session.add_all(namespaces)
@@ -433,8 +433,7 @@ def open_sqlite_library(
433433
logger.error("[Library] Couldn't add default tag color namespaces", error=e)
434434
session.rollback()
435435

436-
# Add default tag colors.
437-
if is_new:
436+
# Add default tag colors.
438437
tag_colors: list[TagColorGroup] = default_color_groups.standard()
439438
tag_colors += default_color_groups.pastels()
440439
tag_colors += default_color_groups.shades()
@@ -449,8 +448,7 @@ def open_sqlite_library(
449448
logger.error("[Library] Couldn't add default tag colors", error=e)
450449
session.rollback()
451450

452-
# Add default tags.
453-
if is_new:
451+
# Add default tags.
454452
tags = get_default_tags()
455453
try:
456454
session.add_all(tags)
@@ -531,35 +529,36 @@ def open_sqlite_library(
531529

532530
# Apply any post-SQL migration patches.
533531
if not is_new:
532+
assert loaded_db_version >= 6
533+
534534
# save backup if patches will be applied
535535
if loaded_db_version < DB_VERSION:
536536
self.library_dir = library_dir
537537
self.save_library_backup_to_disk()
538538
self.library_dir = None
539539

540-
# NOTE: Depending on the data, some data and schema changes need to be applied in
541-
# different orders. This chain of methods can likely be cleaned up and/or moved.
540+
# migrate DB step by step from one version to the next
541+
if loaded_db_version < 7:
542+
# changes: value_type, tags
543+
self.__apply_db7_migration(session)
542544
if loaded_db_version < 8:
543-
self.__apply_db8_schema_changes(session)
544-
if loaded_db_version < 9:
545-
self.__apply_db9_schema_changes(session)
546-
if loaded_db_version < 103:
547-
self.__apply_db103_schema_changes(session)
548-
if loaded_db_version == 6:
549-
self.__apply_repairs_for_db6(session)
550-
551-
if loaded_db_version >= 6 and loaded_db_version < 8:
552-
self.__apply_db8_default_data(session)
545+
# changes: tag_colors
546+
self.__apply_db8_migration(session)
553547
if loaded_db_version < 9:
554-
self.__apply_db9_filename_population(session)
548+
# changes: entries
549+
self.__apply_db9_migration(session)
555550
if loaded_db_version < 100:
556-
self.__apply_db100_parent_repairs(session)
551+
# changes: tag_parents
552+
self.__apply_db100_migration(session)
557553
if loaded_db_version < 102:
558-
self.__apply_db102_repairs(session)
554+
# changes: tag_parents
555+
self.__apply_db102_migration(session)
559556
if loaded_db_version < 103:
560-
self.__apply_db103_default_data(session)
557+
# changes: tags
558+
self.__apply_db103_migration(session)
561559

562560
# Convert file extension list to ts_ignore file, if a .ts_ignore file does not exist
561+
# TODO: do this in the migration step that will remove the preferences table
563562
self.migrate_sql_to_ts_ignore(library_dir)
564563

565564
# Update DB_VERSION
@@ -570,8 +569,8 @@ def open_sqlite_library(
570569
self.library_dir = library_dir
571570
return LibraryStatus(success=True, library_path=library_dir)
572571

573-
def __apply_repairs_for_db6(self, session: Session):
574-
"""Apply database repairs introduced in DB_VERSION 7."""
572+
def __apply_db7_migration(self, session: Session):
573+
"""Migrate DB from DB_VERSION 6 to 7."""
575574
logger.info("[Library][Migration] Applying patches to DB_VERSION: 6 library...")
576575
with session:
577576
# Repair "Description" fields with a TEXT_LINE key instead of a TEXT_BOX key.
@@ -584,7 +583,7 @@ def __apply_repairs_for_db6(self, session: Session):
584583
session.flush()
585584

586585
# Repair tags that may have a disambiguation_id pointing towards a deleted tag.
587-
all_tag_ids: set[int] = {tag.id for tag in self.tags}
586+
all_tag_ids = session.scalars(text("SELECT DISTINCT id FROM tags")).all()
588587
disam_stmt = (
589588
update(Tag)
590589
.where(Tag.disambiguation_id.not_in(all_tag_ids))
@@ -593,9 +592,8 @@ def __apply_repairs_for_db6(self, session: Session):
593592
session.execute(disam_stmt)
594593
session.commit()
595594

596-
def __apply_db8_schema_changes(self, session: Session):
597-
"""Apply database schema changes introduced in DB_VERSION 8."""
598-
# TODO: Use Alembic for this part instead
595+
def __apply_db8_migration(self, session: Session):
596+
"""Migrate DB from DB_VERSION 7 to 8."""
599597
# Add the missing color_border column to the TagColorGroups table.
600598
color_border_stmt = text(
601599
"ALTER TABLE tag_colors ADD COLUMN color_border BOOLEAN DEFAULT FALSE NOT NULL"
@@ -611,8 +609,7 @@ def __apply_db8_schema_changes(self, session: Session):
611609
)
612610
session.rollback()
613611

614-
def __apply_db8_default_data(self, session: Session):
615-
"""Apply default data changes introduced in DB_VERSION 8."""
612+
# collect new default tag colors
616613
tag_colors: list[TagColorGroup] = default_color_groups.standard()
617614
tag_colors += default_color_groups.pastels()
618615
tag_colors += default_color_groups.shades()
@@ -661,8 +658,9 @@ def __apply_db8_default_data(self, session: Session):
661658
)
662659
session.rollback()
663660

664-
def __apply_db9_schema_changes(self, session: Session):
665-
"""Apply database schema changes introduced in DB_VERSION 9."""
661+
def __apply_db9_migration(self, session: Session):
662+
"""Migrate DB from DB_VERSION 8 to 9."""
663+
# Apply database schema changes
666664
add_filename_column = text(
667665
"ALTER TABLE entries ADD COLUMN filename TEXT NOT NULL DEFAULT ''"
668666
)
@@ -677,15 +675,14 @@ def __apply_db9_schema_changes(self, session: Session):
677675
)
678676
session.rollback()
679677

680-
def __apply_db9_filename_population(self, session: Session):
681-
"""Populate the filename column introduced in DB_VERSION 9."""
678+
# Populate the new filename column.
682679
for entry in self.all_entries():
683680
session.merge(entry).filename = entry.path.name
684681
session.commit()
685682
logger.info("[Library][Migration] Populated filename column in entries table")
686683

687-
def __apply_db100_parent_repairs(self, session: Session):
688-
"""Swap the child_id and parent_id values in the TagParent table."""
684+
def __apply_db100_migration(self, session: Session):
685+
"""Migrate DB to DB_VERSION 100."""
689686
with session:
690687
# Repair parent-child tag relationships that are the wrong way around.
691688
stmt = update(TagParent).values(
@@ -696,17 +693,18 @@ def __apply_db100_parent_repairs(self, session: Session):
696693
session.commit()
697694
logger.info("[Library][Migration] Refactored TagParent table")
698695

699-
def __apply_db102_repairs(self, session: Session):
700-
"""Repair tag_parents rows with references to deleted tags."""
696+
def __apply_db102_migration(self, session: Session):
697+
"""Migrate DB to DB_VERSION 102."""
701698
with session:
702-
all_tag_ids: list[int] = [t.id for t in self.tags]
699+
all_tag_ids = session.scalars(text("SELECT DISTINCT id FROM tags")).all()
703700
stmt = delete(TagParent).where(TagParent.parent_id.not_in(all_tag_ids))
704701
session.execute(stmt)
705702
session.commit()
706703
logger.info("[Library][Migration] Verified TagParent table data")
707704

708-
def __apply_db103_schema_changes(self, session: Session):
709-
"""Apply database schema changes introduced in DB_VERSION 103."""
705+
def __apply_db103_migration(self, session: Session):
706+
"""Migrate DB from DB_VERSION 102 to 103."""
707+
# add the new hidden column for tags
710708
add_is_hidden_column = text(
711709
"ALTER TABLE tags ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT 0"
712710
)
@@ -721,8 +719,7 @@ def __apply_db103_schema_changes(self, session: Session):
721719
)
722720
session.rollback()
723721

724-
def __apply_db103_default_data(self, session: Session):
725-
"""Apply default data changes introduced in DB_VERSION 103."""
722+
# mark the "Archived" tag as hidden
726723
try:
727724
session.query(Tag).filter(Tag.id == TAG_ARCHIVED).update({"is_hidden": True})
728725
session.commit()

0 commit comments

Comments
 (0)