mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 13:19:58 -05:00
Creating a new Collection model for use in organizing FileGroups.
Replacing Channels and Domains with Collection. Moving downloading relationships from Channel to Collection. Created domains.yaml config to manage tagged domain collections. Adding turn-key upgrade solution in the UI.
This commit is contained in:
parent
1f7b1c8744
commit
4fae4ae1b4
115 changed files with 13309 additions and 986 deletions
87
alembic/versions/66407d145b76_.py
Normal file
87
alembic/versions/66407d145b76_.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"""Create collection table for domain collections
|
||||
|
||||
Revision ID: 66407d145b76
|
||||
Revises: 4f03b9548f6e
|
||||
Create Date: 2025-10-26 10:57:16.462524
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '66407d145b76'
|
||||
down_revision = '4f03b9548f6e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Step 1: Create new collection table (keeping channel table separate for now)
|
||||
op.create_table(
|
||||
'collection',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('kind', sa.String(), nullable=False),
|
||||
sa.Column('directory', sa.Text(), nullable=True),
|
||||
sa.Column('tag_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_date', sa.DateTime(), server_default=sa.func.now(), nullable=False),
|
||||
sa.Column('item_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('total_size', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], name='collection_tag_id_fkey'),
|
||||
sa.UniqueConstraint('directory', name='uq_collection_directory')
|
||||
)
|
||||
|
||||
# Create indexes for collection
|
||||
op.create_index('idx_collection_kind', 'collection', ['kind'], unique=False)
|
||||
op.create_index('idx_collection_item_count', 'collection', ['item_count'], unique=False)
|
||||
op.create_index('idx_collection_total_size', 'collection', ['total_size'], unique=False)
|
||||
|
||||
# Step 2: Create collection_item junction table
|
||||
op.create_table(
|
||||
'collection_item',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('collection_id', sa.Integer(), nullable=False),
|
||||
sa.Column('file_group_id', sa.Integer(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('added_date', sa.DateTime(), server_default=sa.func.now(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['file_group_id'], ['file_group.id'], ondelete='CASCADE'),
|
||||
sa.UniqueConstraint('collection_id', 'file_group_id', name='uq_collection_file_group')
|
||||
)
|
||||
|
||||
# Create indexes for collection_item
|
||||
op.create_index('idx_collection_item_collection_id', 'collection_item', ['collection_id'], unique=False)
|
||||
op.create_index('idx_collection_item_file_group_id', 'collection_item', ['file_group_id'], unique=False)
|
||||
op.create_index('idx_collection_item_position', 'collection_item', ['position'], unique=False)
|
||||
op.create_index('idx_collection_item_collection_position', 'collection_item', ['collection_id', 'position'], unique=False)
|
||||
|
||||
# Ensure table owner in non-docker environments
|
||||
if not DOCKERIZED:
|
||||
session.execute(sa.text('ALTER TABLE public.collection OWNER TO wrolpi'))
|
||||
session.execute(sa.text('ALTER TABLE public.collection_item OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Drop collection_item table and its indexes
|
||||
op.drop_index('idx_collection_item_collection_position', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_position', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_file_group_id', table_name='collection_item')
|
||||
op.drop_index('idx_collection_item_collection_id', table_name='collection_item')
|
||||
op.drop_table('collection_item')
|
||||
|
||||
# Drop collection table and its indexes
|
||||
op.drop_index('idx_collection_total_size', table_name='collection')
|
||||
op.drop_index('idx_collection_item_count', table_name='collection')
|
||||
op.drop_index('idx_collection_kind', table_name='collection')
|
||||
op.drop_table('collection')
|
||||
95
alembic/versions/add_unique_collection_name_kind.py
Normal file
95
alembic/versions/add_unique_collection_name_kind.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
"""Add unique constraint on collection (name, kind)
|
||||
|
||||
This migration:
|
||||
1. Removes duplicate collections (keeping the one with most items/archives)
|
||||
2. Adds a unique constraint on (name, kind) to prevent future duplicates
|
||||
|
||||
Revision ID: add_unique_collection_name_kind
|
||||
Revises: migrate_download_to_collection
|
||||
Create Date: 2025-11-27
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'add_unique_collection_name_kind'
|
||||
down_revision = 'migrate_download_to_collection'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Add Unique Constraint on Collection (name, kind)")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
# Step 1: Find and remove duplicate collections
|
||||
print("Step 1: Finding duplicate collections...")
|
||||
|
||||
# Find duplicates - keep the one with the lowest id (first created)
|
||||
duplicates = session.execute(text("""
|
||||
SELECT name, kind, array_agg(id ORDER BY id) as ids
|
||||
FROM collection
|
||||
GROUP BY name, kind
|
||||
HAVING COUNT(*) > 1
|
||||
""")).fetchall()
|
||||
|
||||
if duplicates:
|
||||
print(f"Found {len(duplicates)} sets of duplicate collections")
|
||||
for name, kind, ids in duplicates:
|
||||
keep_id = ids[0] # Keep the first one (lowest id)
|
||||
remove_ids = ids[1:] # Remove the rest
|
||||
print(f" - '{name}' ({kind}): keeping id={keep_id}, removing ids={remove_ids}")
|
||||
|
||||
# Move any archives from duplicate collections to the one we're keeping
|
||||
for remove_id in remove_ids:
|
||||
session.execute(text("""
|
||||
UPDATE archive SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Move any downloads from duplicate collections
|
||||
session.execute(text("""
|
||||
UPDATE download SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Move any collection items
|
||||
session.execute(text("""
|
||||
UPDATE collection_item SET collection_id = :keep_id
|
||||
WHERE collection_id = :remove_id
|
||||
"""), {'keep_id': keep_id, 'remove_id': remove_id})
|
||||
|
||||
# Delete the duplicate collection
|
||||
session.execute(text("""
|
||||
DELETE FROM collection WHERE id = :remove_id
|
||||
"""), {'remove_id': remove_id})
|
||||
|
||||
session.commit()
|
||||
print("Duplicates removed\n")
|
||||
else:
|
||||
print("No duplicate collections found\n")
|
||||
|
||||
# Step 2: Add unique constraint
|
||||
print("Step 2: Adding unique constraint on (name, kind)...")
|
||||
op.create_unique_constraint('uq_collection_name_kind', 'collection', ['name', 'kind'])
|
||||
print("Done\n")
|
||||
|
||||
print("=" * 60)
|
||||
print("Migration Complete")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(text('ALTER TABLE public.collection OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('uq_collection_name_kind', 'collection', type_='unique')
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
"""Remove duplicate Channel fields delegated to Collection
|
||||
|
||||
This migration removes fields from Channel that now delegate to Collection:
|
||||
- name (now property: channel.name → collection.name)
|
||||
- directory (now property: channel.directory → collection.directory)
|
||||
- tag_id (now property: channel.tag_id → collection.tag_id)
|
||||
|
||||
These fields were already synced to Collection in previous migration.
|
||||
|
||||
Revision ID: b43f70f369d0
|
||||
Revises: ba98bd360b7a
|
||||
Create Date: 2025-11-19 21:48:58.488850
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b43f70f369d0'
|
||||
down_revision = 'ba98bd360b7a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
print("\n" + "="*60)
|
||||
print("Removing Duplicate Fields from Channel")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Step 1: Drop foreign key constraint on tag_id
|
||||
print("Step 1: Dropping tag_id foreign key constraint...")
|
||||
op.drop_constraint('channel_tag_id_fkey', 'channel', type_='foreignkey')
|
||||
print("✓ Dropped foreign key constraint\n")
|
||||
|
||||
# Step 2: Drop columns (data already in Collection)
|
||||
print("Step 2: Dropping duplicate columns...")
|
||||
op.drop_column('channel', 'name')
|
||||
print(" ✓ Dropped channel.name")
|
||||
op.drop_column('channel', 'directory')
|
||||
print(" ✓ Dropped channel.directory")
|
||||
op.drop_column('channel', 'tag_id')
|
||||
print(" ✓ Dropped channel.tag_id\n")
|
||||
|
||||
print("="*60)
|
||||
print("✓ Channel Cleanup Complete")
|
||||
print(" Channels now delegate name/directory/tag to Collection")
|
||||
print("="*60 + "\n")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Re-add the columns
|
||||
op.add_column('channel', sa.Column('name', sa.String(), nullable=True))
|
||||
op.add_column('channel', sa.Column('directory', sa.String(), nullable=True))
|
||||
op.add_column('channel', sa.Column('tag_id', sa.Integer(), nullable=True))
|
||||
|
||||
# Re-add foreign key
|
||||
op.create_foreign_key('channel_tag_id_fkey', 'channel', 'tag', ['tag_id'], ['id'], ondelete='CASCADE')
|
||||
|
||||
# Restore data from Collection
|
||||
bind = op.get_bind()
|
||||
bind.execute(text("""
|
||||
UPDATE channel
|
||||
SET name = collection.name,
|
||||
directory = collection.directory,
|
||||
tag_id = collection.tag_id
|
||||
FROM collection
|
||||
WHERE channel.collection_id = collection.id
|
||||
"""))
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
"""Add collection_id to Channel model
|
||||
|
||||
This migration:
|
||||
1. Adds collection_id column to channel table
|
||||
2. Creates Collection records for existing Channels
|
||||
3. Links Channels to their Collections
|
||||
4. Adds foreign key constraint
|
||||
|
||||
Revision ID: ba98bd360b7a
|
||||
Revises: migrate_domains_to_collections
|
||||
Create Date: 2025-11-19 21:10:56.472836
|
||||
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ba98bd360b7a'
|
||||
down_revision = 'migrate_domains_to_collections'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("Channel → Collection Migration")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Step 1: Add collection_id column to channel table (nullable initially)
|
||||
print("Step 1: Adding collection_id column to channel table...")
|
||||
op.add_column('channel', sa.Column('collection_id', sa.Integer(), nullable=True))
|
||||
print("✓ Added collection_id column\n")
|
||||
|
||||
# Step 2: Create Collection records for each Channel
|
||||
print("Step 2: Creating Collection records for existing Channels...")
|
||||
|
||||
# Fetch all channels
|
||||
result = session.execute(text("""
|
||||
SELECT id, name, directory, tag_id
|
||||
FROM channel
|
||||
ORDER BY name
|
||||
"""))
|
||||
|
||||
channels = []
|
||||
for row in result:
|
||||
channels.append({
|
||||
'id': row[0],
|
||||
'name': row[1],
|
||||
'directory': row[2],
|
||||
'tag_id': row[3],
|
||||
})
|
||||
|
||||
print(f"Found {len(channels)} Channel records to migrate")
|
||||
|
||||
if channels:
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
for channel in channels:
|
||||
channel_id = channel['id']
|
||||
channel_name = channel['name']
|
||||
|
||||
print(f" Processing Channel {channel_id}: {channel_name}")
|
||||
|
||||
# Check if Collection already exists
|
||||
existing = session.query(Collection).filter_by(
|
||||
name=channel_name,
|
||||
kind='channel'
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
print(f" Collection already exists (id={existing.id})")
|
||||
collection_id = existing.id
|
||||
else:
|
||||
# Create Collection
|
||||
collection = Collection(
|
||||
name=channel_name,
|
||||
kind='channel',
|
||||
directory=channel['directory'], # Channels always have directory
|
||||
tag_id=channel['tag_id'],
|
||||
)
|
||||
session.add(collection)
|
||||
session.flush([collection])
|
||||
collection_id = collection.id
|
||||
print(f" Created Collection id={collection_id}")
|
||||
|
||||
# Link Channel to Collection
|
||||
session.execute(
|
||||
text("UPDATE channel SET collection_id = :collection_id WHERE id = :channel_id"),
|
||||
{'collection_id': collection_id, 'channel_id': channel_id}
|
||||
)
|
||||
|
||||
session.commit()
|
||||
print(f"✓ Created Collections and linked Channels\n")
|
||||
else:
|
||||
print("No channels to migrate\n")
|
||||
|
||||
# Step 3: Add foreign key constraint
|
||||
print("Step 3: Adding foreign key constraint...")
|
||||
op.create_foreign_key(
|
||||
'fk_channel_collection_id',
|
||||
'channel',
|
||||
'collection',
|
||||
['collection_id'],
|
||||
['id'],
|
||||
ondelete='CASCADE'
|
||||
)
|
||||
print("✓ Added foreign key constraint\n")
|
||||
|
||||
print("="*60)
|
||||
print("✓ Channel → Collection Migration Complete")
|
||||
print("="*60 + "\n")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(text('ALTER TABLE public.channel OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Remove foreign key constraint
|
||||
op.drop_constraint('fk_channel_collection_id', 'channel', type_='foreignkey')
|
||||
|
||||
# Drop collection_id column
|
||||
op.drop_column('channel', 'collection_id')
|
||||
381
alembic/versions/migrate_domains_to_collections.py
Normal file
381
alembic/versions/migrate_domains_to_collections.py
Normal file
|
|
@ -0,0 +1,381 @@
|
|||
"""Migrate Domain model to Collection model
|
||||
|
||||
This migration:
|
||||
1. Adds collection_id column to archive table
|
||||
2. Runs the data migration to populate collections
|
||||
3. Makes collection_id NOT NULL
|
||||
4. Drops the old domain_id column and domains table
|
||||
|
||||
Revision ID: migrate_domains_to_collections
|
||||
Revises: 66407d145b76
|
||||
Create Date: 2025-10-29
|
||||
|
||||
"""
|
||||
import os
|
||||
from typing import Dict, List
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'migrate_domains_to_collections'
|
||||
down_revision = '66407d145b76'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
class DomainMigrationStats:
|
||||
"""Track migration statistics."""
|
||||
def __init__(self):
|
||||
self.domains_found = 0
|
||||
self.domains_migrated = 0
|
||||
self.collections_created = 0
|
||||
self.collection_items_created = 0
|
||||
self.archives_linked = 0
|
||||
self.errors: List[str] = []
|
||||
self.warnings: List[str] = []
|
||||
|
||||
def add_error(self, msg: str):
|
||||
self.errors.append(msg)
|
||||
print(f" ✗ ERROR: {msg}")
|
||||
|
||||
def add_warning(self, msg: str):
|
||||
self.warnings.append(msg)
|
||||
print(f" ⚠ WARNING: {msg}")
|
||||
|
||||
def print_summary(self, dry_run: bool = False):
|
||||
"""Print migration summary."""
|
||||
mode = "DRY-RUN" if dry_run else "ACTUAL"
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Domain → Collection Migration Summary ({mode})")
|
||||
print(f"{'='*60}")
|
||||
print(f"Domains found: {self.domains_found}")
|
||||
print(f"Domains migrated: {self.domains_migrated}")
|
||||
print(f"Collections created: {self.collections_created}")
|
||||
print(f"CollectionItems created: {self.collection_items_created}")
|
||||
print(f"Archives linked: {self.archives_linked}")
|
||||
|
||||
if self.warnings:
|
||||
print(f"\nWarnings: {len(self.warnings)}")
|
||||
for warning in self.warnings:
|
||||
print(f" ⚠ {warning}")
|
||||
|
||||
if self.errors:
|
||||
print(f"\nErrors: {len(self.errors)}")
|
||||
for error in self.errors:
|
||||
print(f" ✗ {error}")
|
||||
|
||||
if not self.errors:
|
||||
print(f"\n✓ Migration completed successfully")
|
||||
else:
|
||||
print(f"\n✗ Migration completed with {len(self.errors)} errors")
|
||||
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
|
||||
def get_domain_data(session: Session) -> List[Dict]:
|
||||
"""Fetch all Domain records from database."""
|
||||
result = session.execute(text("SELECT id, domain, directory FROM domains ORDER BY domain"))
|
||||
domains = []
|
||||
for row in result:
|
||||
domains.append({
|
||||
'id': row[0],
|
||||
'domain': row[1],
|
||||
'directory': row[2],
|
||||
})
|
||||
return domains
|
||||
|
||||
|
||||
def get_archives_for_domain(session: Session, domain_id: int) -> List[Dict]:
|
||||
"""Get all Archive IDs for a given domain."""
|
||||
result = session.execute(
|
||||
text("SELECT id, file_group_id FROM archive WHERE domain_id = :domain_id"),
|
||||
{'domain_id': domain_id}
|
||||
)
|
||||
archives = []
|
||||
for row in result:
|
||||
if row[1]: # file_group_id must not be null
|
||||
archives.append({
|
||||
'archive_id': row[0],
|
||||
'file_group_id': row[1],
|
||||
})
|
||||
return archives
|
||||
|
||||
|
||||
def validate_domain_name(domain: str) -> bool:
|
||||
"""Validate domain name format - must contain at least one dot."""
|
||||
if not domain or not isinstance(domain, str):
|
||||
return False
|
||||
if domain.startswith('.') or domain.endswith('.'):
|
||||
return False
|
||||
return '.' in domain
|
||||
|
||||
|
||||
def perform_domain_migration(session: Session, verbose: bool = True) -> DomainMigrationStats:
|
||||
"""
|
||||
Migrate all Domain records to Collection records.
|
||||
|
||||
This function is integrated into the alembic migration.
|
||||
"""
|
||||
from wrolpi.collections import Collection, CollectionItem
|
||||
|
||||
stats = DomainMigrationStats()
|
||||
|
||||
# Step 1: Fetch all domains
|
||||
print("Step 1: Fetching Domain records...")
|
||||
domains = get_domain_data(session)
|
||||
stats.domains_found = len(domains)
|
||||
print(f"Found {len(domains)} Domain records")
|
||||
|
||||
if not domains:
|
||||
print("No domains to migrate")
|
||||
return stats
|
||||
|
||||
# Step 2: Create Collections from Domains
|
||||
print("\nStep 2: Creating Collection records...")
|
||||
domain_to_collection: Dict[int, int] = {} # domain_id -> collection_id
|
||||
|
||||
for domain in domains:
|
||||
domain_id = domain['id']
|
||||
domain_name = domain['domain']
|
||||
|
||||
if verbose:
|
||||
print(f" Processing Domain {domain_id}: {domain_name}")
|
||||
|
||||
# Validate domain name
|
||||
if not validate_domain_name(domain_name):
|
||||
stats.add_error(f"Invalid domain name: {repr(domain_name)} (skipping)")
|
||||
continue
|
||||
|
||||
# Check if Collection already exists
|
||||
existing = session.query(Collection).filter_by(
|
||||
name=domain_name,
|
||||
kind='domain'
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
stats.add_warning(f"Collection already exists for domain {repr(domain_name)} (id={existing.id})")
|
||||
domain_to_collection[domain_id] = existing.id
|
||||
stats.domains_migrated += 1
|
||||
continue
|
||||
|
||||
# Create Collection
|
||||
collection = Collection(
|
||||
name=domain_name,
|
||||
kind='domain',
|
||||
directory=None, # Domains are unrestricted
|
||||
)
|
||||
session.add(collection)
|
||||
session.flush([collection])
|
||||
|
||||
domain_to_collection[domain_id] = collection.id
|
||||
stats.collections_created += 1
|
||||
stats.domains_migrated += 1
|
||||
|
||||
if verbose:
|
||||
print(f" Created Collection id={collection.id}")
|
||||
|
||||
print(f"Created {stats.collections_created} Collection records")
|
||||
|
||||
# Step 3: Update archive.collection_id for all Archives
|
||||
print("\nStep 3: Updating archive.collection_id...")
|
||||
|
||||
for domain in domains:
|
||||
domain_id = domain['id']
|
||||
domain_name = domain['domain']
|
||||
|
||||
if domain_id not in domain_to_collection:
|
||||
# Domain was skipped due to error
|
||||
continue
|
||||
|
||||
collection_id = domain_to_collection[domain_id]
|
||||
|
||||
# Update all archives for this domain
|
||||
result = session.execute(
|
||||
text("UPDATE archive SET collection_id = :collection_id WHERE domain_id = :domain_id"),
|
||||
{'collection_id': collection_id, 'domain_id': domain_id}
|
||||
)
|
||||
updated_count = result.rowcount
|
||||
|
||||
if verbose and updated_count > 0:
|
||||
print(f" Domain {repr(domain_name)}: Updated {updated_count} archives")
|
||||
|
||||
stats.archives_linked += updated_count
|
||||
|
||||
print(f"Updated {stats.archives_linked} Archives with collection_id")
|
||||
|
||||
# Step 4: Create CollectionItem records
|
||||
print("\nStep 4: Creating CollectionItem records...")
|
||||
|
||||
for domain in domains:
|
||||
domain_id = domain['id']
|
||||
domain_name = domain['domain']
|
||||
|
||||
if domain_id not in domain_to_collection:
|
||||
continue
|
||||
|
||||
collection_id = domain_to_collection[domain_id]
|
||||
|
||||
# Get all archives for this domain
|
||||
archives = get_archives_for_domain(session, domain_id)
|
||||
|
||||
if not archives:
|
||||
if verbose:
|
||||
print(f" Domain {repr(domain_name)}: No archives found")
|
||||
continue
|
||||
|
||||
if verbose:
|
||||
print(f" Domain {repr(domain_name)}: {len(archives)} archives")
|
||||
|
||||
for idx, archive in enumerate(archives, start=1):
|
||||
file_group_id = archive['file_group_id']
|
||||
archive_id = archive['archive_id']
|
||||
|
||||
# Check if CollectionItem already exists
|
||||
existing_item = session.query(CollectionItem).filter_by(
|
||||
collection_id=collection_id,
|
||||
file_group_id=file_group_id
|
||||
).first()
|
||||
|
||||
if existing_item:
|
||||
if verbose:
|
||||
print(f" Archive {archive_id} already linked to collection")
|
||||
continue
|
||||
|
||||
# Create CollectionItem
|
||||
item = CollectionItem(
|
||||
collection_id=collection_id,
|
||||
file_group_id=file_group_id,
|
||||
position=idx
|
||||
)
|
||||
session.add(item)
|
||||
stats.collection_items_created += 1
|
||||
|
||||
session.flush()
|
||||
print(f"Created {stats.collection_items_created} CollectionItem records")
|
||||
|
||||
# Step 5: Skip config export during migration
|
||||
# The config export requires a separate database session, but we're inside
|
||||
# an alembic transaction. The application will export on startup instead.
|
||||
print("\nStep 5: Skipping domains.yaml export during migration...")
|
||||
print(" (Config will be exported on next application startup)")
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""
|
||||
Migrate Domains to Collections.
|
||||
|
||||
This is a one-way migration - there is no downgrade path because:
|
||||
- Domain data is transformed into Collection data
|
||||
- Once migrated, the system uses Collections exclusively
|
||||
- Downgrade would require reimplementing Domain model
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("DOMAIN → COLLECTION MIGRATION")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Step 1: Add collection_id column to archive table (nullable initially)
|
||||
print("Step 1: Adding collection_id column to archive table...")
|
||||
op.add_column('archive',
|
||||
sa.Column('collection_id', sa.Integer(), nullable=True))
|
||||
|
||||
# Add foreign key to collection table
|
||||
op.create_foreign_key(
|
||||
'archive_collection_id_fkey',
|
||||
'archive', 'collection',
|
||||
['collection_id'], ['id'],
|
||||
ondelete='CASCADE'
|
||||
)
|
||||
print("✓ Added collection_id column\n")
|
||||
|
||||
# Step 2: Run data migration script
|
||||
print("Step 2: Running data migration script...")
|
||||
print("This will:")
|
||||
print(" - Create Collection records from Domain records")
|
||||
print(" - Create CollectionItem records for Archives\n")
|
||||
|
||||
try:
|
||||
# Commit the schema changes before running migration
|
||||
session.commit()
|
||||
|
||||
# Run the data migration
|
||||
stats = perform_domain_migration(session, verbose=True)
|
||||
|
||||
# Print summary
|
||||
stats.print_summary(dry_run=False)
|
||||
|
||||
if stats.errors:
|
||||
raise Exception(f"Migration completed with {len(stats.errors)} errors. See logs above.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n✗ Migration failed: {e}")
|
||||
raise
|
||||
|
||||
# Step 3: Make collection_id NOT NULL
|
||||
print("\nStep 3: Making collection_id NOT NULL...")
|
||||
|
||||
# Check if any archives don't have a collection_id
|
||||
result = session.execute(sa.text(
|
||||
"SELECT COUNT(*) FROM archive WHERE collection_id IS NULL"
|
||||
))
|
||||
null_count = result.scalar()
|
||||
|
||||
if null_count > 0:
|
||||
raise Exception(
|
||||
f"Cannot make collection_id NOT NULL: {null_count} archives have NULL collection_id. "
|
||||
f"The migration script should have assigned all archives to collections."
|
||||
)
|
||||
|
||||
op.alter_column('archive', 'collection_id', nullable=False)
|
||||
print("✓ collection_id is now NOT NULL\n")
|
||||
|
||||
# Step 4: Drop old domain_id column and foreign key
|
||||
print("Step 4: Dropping domain_id column and foreign key...")
|
||||
op.drop_constraint('archive_domain_id_fkey', 'archive', type_='foreignkey')
|
||||
op.drop_column('archive', 'domain_id')
|
||||
print("✓ Dropped domain_id column\n")
|
||||
|
||||
# Step 5: Drop domains table
|
||||
print("Step 5: Dropping domains table...")
|
||||
op.drop_table('domains')
|
||||
print("✓ Dropped domains table\n")
|
||||
|
||||
# Ensure table ownership in non-docker environments
|
||||
if not DOCKERIZED:
|
||||
print("Setting table ownership...")
|
||||
session.execute(sa.text('ALTER TABLE public.archive OWNER TO wrolpi'))
|
||||
session.commit()
|
||||
|
||||
print("="*60)
|
||||
print("MIGRATION COMPLETED SUCCESSFULLY")
|
||||
print("="*60 + "\n")
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""
|
||||
No downgrade path for this migration.
|
||||
|
||||
This is intentional because:
|
||||
1. Domain → Collection is a one-way data transformation
|
||||
2. The Domain model is being removed from the codebase
|
||||
3. Rolling back would require:
|
||||
- Recreating Domain model code
|
||||
- Reversing the data transformation (Collection → Domain)
|
||||
- Handling edge cases where Collections have features Domains didn't
|
||||
|
||||
If you need to rollback, you should:
|
||||
1. Restore from a database backup taken before migration
|
||||
2. Re-index all files to rebuild Domain records
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"This migration has no downgrade path. "
|
||||
"To rollback, reset database and re-index files."
|
||||
)
|
||||
110
alembic/versions/migrate_download_channel_to_collection.py
Normal file
110
alembic/versions/migrate_download_channel_to_collection.py
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
"""Migrate Download.channel_id to Download.collection_id
|
||||
|
||||
This migration:
|
||||
1. Adds collection_id column to download table
|
||||
2. Migrates existing channel_id references to collection_id via Channel.collection_id
|
||||
3. Drops channel_id column and foreign key
|
||||
|
||||
Revision ID: migrate_download_to_collection
|
||||
Revises: b43f70f369d0
|
||||
Create Date: 2025-11-27
|
||||
"""
|
||||
import os
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'migrate_download_to_collection'
|
||||
down_revision = 'b43f70f369d0'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Download channel_id -> collection_id Migration")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
# Step 1: Add collection_id column (nullable initially)
|
||||
print("Step 1: Adding collection_id column to download table...")
|
||||
op.add_column('download', sa.Column('collection_id', sa.Integer(), nullable=True))
|
||||
print("Done\n")
|
||||
|
||||
# Step 2: Migrate data - lookup collection_id through channel
|
||||
print("Step 2: Migrating channel_id to collection_id...")
|
||||
result = session.execute(text("""
|
||||
UPDATE download
|
||||
SET collection_id = channel.collection_id
|
||||
FROM channel
|
||||
WHERE download.channel_id = channel.id
|
||||
AND download.channel_id IS NOT NULL
|
||||
"""))
|
||||
print(f"Updated {result.rowcount} download records\n")
|
||||
|
||||
# Step 3: Add foreign key constraint
|
||||
print("Step 3: Adding foreign key constraint...")
|
||||
op.create_foreign_key(
|
||||
'fk_download_collection_id',
|
||||
'download',
|
||||
'collection',
|
||||
['collection_id'],
|
||||
['id'],
|
||||
ondelete='SET NULL'
|
||||
)
|
||||
print("Done\n")
|
||||
|
||||
# Step 4: Create index for performance
|
||||
print("Step 4: Creating index on collection_id...")
|
||||
op.create_index('idx_download_collection_id', 'download', ['collection_id'])
|
||||
print("Done\n")
|
||||
|
||||
# Step 5: Drop old channel_id foreign key and column
|
||||
print("Step 5: Dropping channel_id column...")
|
||||
op.drop_constraint('download_channel_id_fkey', 'download', type_='foreignkey')
|
||||
op.drop_column('download', 'channel_id')
|
||||
print("Done\n")
|
||||
|
||||
print("=" * 60)
|
||||
print("Migration Complete")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
if not DOCKERIZED:
|
||||
session.execute(text('ALTER TABLE public.download OWNER TO wrolpi'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
session = Session(bind=bind)
|
||||
|
||||
# Add back channel_id column
|
||||
op.add_column('download', sa.Column('channel_id', sa.Integer(), nullable=True))
|
||||
|
||||
# Migrate collection_id back to channel_id
|
||||
session.execute(text("""
|
||||
UPDATE download
|
||||
SET channel_id = channel.id
|
||||
FROM channel
|
||||
WHERE download.collection_id = channel.collection_id
|
||||
AND download.collection_id IS NOT NULL
|
||||
"""))
|
||||
|
||||
# Add foreign key constraint
|
||||
op.create_foreign_key(
|
||||
'download_channel_id_fkey',
|
||||
'download',
|
||||
'channel',
|
||||
['channel_id'],
|
||||
['id']
|
||||
)
|
||||
|
||||
# Drop collection_id
|
||||
op.drop_index('idx_download_collection_id', 'download')
|
||||
op.drop_constraint('fk_download_collection_id', 'download', type_='foreignkey')
|
||||
op.drop_column('download', 'collection_id')
|
||||
Loading…
Add table
Add a link
Reference in a new issue