#!/usr/bin/env python3 """ Update file_size and modified_time for existing files in videos table. This script reads file metadata from the filesystem and updates the database. """ import os import sys import time from datetime import datetime import psycopg2 from psycopg2.extras import RealDictCursor def get_db_connection(): """Get database connection from environment or defaults.""" db_url = os.environ.get('DATABASE_URL', 'postgres://accusys@localhost:5432/momentry') return psycopg2.connect(db_url) def update_file_metadata(conn): """Update file_size and modified_time for all files in videos table.""" cursor = conn.cursor(cursor_factory=RealDictCursor) # Get all files cursor.execute(""" SELECT file_uuid, file_path FROM videos WHERE file_size IS NULL OR modified_time IS NULL ORDER BY id """) files = cursor.fetchall() print(f"Found {len(files)} files to update") updated = 0 skipped = 0 errors = 0 for file in files: file_path = file['file_path'] file_uuid = file['file_uuid'] if not os.path.exists(file_path): print(f" ⚠️ File not found: {file_path}") skipped += 1 continue try: # Get file metadata stat = os.stat(file_path) file_size = stat.st_size modified_time = datetime.fromtimestamp(stat.st_mtime) # Update database cursor.execute(""" UPDATE videos SET file_size = %s, modified_time = %s WHERE file_uuid = %s """, (file_size, modified_time, file_uuid)) updated += 1 if updated % 100 == 0: print(f" ✓ Updated {updated} files...") conn.commit() except Exception as e: print(f" ✗ Error updating {file_path}: {e}") errors += 1 conn.commit() print(f"\n✅ Done!") print(f" Updated: {updated}") print(f" Skipped (file not found): {skipped}") print(f" Errors: {errors}") def main(): print("🔧 Updating file_size and modified_time for existing files...") print() conn = get_db_connection() try: update_file_metadata(conn) finally: conn.close() if __name__ == '__main__': main()