kinda working safe point
This commit is contained in:
parent
b9a82af12f
commit
6dda02141e
31 changed files with 4302 additions and 2937 deletions
81
app/migrations/__init__.py
Normal file
81
app/migrations/__init__.py
Normal file
|
@ -0,0 +1,81 @@
|
|||
"""
|
||||
Automatic database migrations system
|
||||
"""
|
||||
import logging
|
||||
from sqlalchemy import inspect
|
||||
from .. import db
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class Migration:
|
||||
"""Base migration class"""
|
||||
# Higher version numbers run later
|
||||
version = 0
|
||||
description = "Base migration"
|
||||
|
||||
def should_run(self, inspector):
|
||||
"""Determine if this migration should run"""
|
||||
return True
|
||||
|
||||
def run(self):
|
||||
"""Execute the migration"""
|
||||
raise NotImplementedError
|
||||
|
||||
class AddFolderIdToFiles(Migration):
|
||||
"""Add folder_id column to files table"""
|
||||
version = 1
|
||||
description = "Add folder_id column to files table"
|
||||
|
||||
def should_run(self, inspector):
|
||||
"""Check if folder_id column exists in files table"""
|
||||
if 'files' not in inspector.get_table_names():
|
||||
return False
|
||||
|
||||
columns = [col['name'] for col in inspector.get_columns('files')]
|
||||
return 'folder_id' not in columns
|
||||
|
||||
def run(self):
|
||||
"""Add the folder_id column and foreign key constraint"""
|
||||
try:
|
||||
db.engine.execute('ALTER TABLE files ADD COLUMN folder_id INTEGER;')
|
||||
db.engine.execute('ALTER TABLE files ADD CONSTRAINT fk_files_folder_id FOREIGN KEY (folder_id) REFERENCES folders (id);')
|
||||
logger.info("Added folder_id column to files table")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Error adding folder_id column: {str(e)}")
|
||||
return False
|
||||
|
||||
# Add all migrations here
|
||||
MIGRATIONS = [
|
||||
AddFolderIdToFiles(),
|
||||
# Remove the Share table migration since we're not using it
|
||||
]
|
||||
|
||||
def run_migrations():
|
||||
"""Run all pending migrations"""
|
||||
logger.info("Checking for pending database migrations...")
|
||||
inspector = inspect(db.engine)
|
||||
|
||||
# Sort migrations by version
|
||||
pending_migrations = sorted([m for m in MIGRATIONS if m.should_run(inspector)],
|
||||
key=lambda m: m.version)
|
||||
|
||||
if not pending_migrations:
|
||||
logger.info("No pending migrations found.")
|
||||
return
|
||||
|
||||
logger.info(f"Found {len(pending_migrations)} pending migrations.")
|
||||
|
||||
success_count = 0
|
||||
for migration in pending_migrations:
|
||||
logger.info(f"Running migration {migration.version}: {migration.description}")
|
||||
try:
|
||||
success = migration.run()
|
||||
if success:
|
||||
success_count += 1
|
||||
else:
|
||||
logger.warning(f"Migration {migration.version} reported failure")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in migration {migration.version}: {str(e)}")
|
||||
|
||||
logger.info(f"Migration complete. {success_count}/{len(pending_migrations)} migrations successful.")
|
29
app/migrations/add_folder_id_to_files.py
Normal file
29
app/migrations/add_folder_id_to_files.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
"""
|
||||
Migration script to add folder_id column to files table
|
||||
"""
|
||||
from flask import Flask
|
||||
from app import create_app, db
|
||||
from app.models import File, Folder
|
||||
|
||||
def run_migration():
|
||||
"""Add folder_id column to files table if it doesn't exist"""
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
# Check if the column exists
|
||||
from sqlalchemy import inspect
|
||||
inspector = inspect(db.engine)
|
||||
columns = [col['name'] for col in inspector.get_columns('files')]
|
||||
|
||||
if 'folder_id' not in columns:
|
||||
print("Adding folder_id column to files table...")
|
||||
# Add the column
|
||||
db.engine.execute('ALTER TABLE files ADD COLUMN folder_id INTEGER;')
|
||||
# Add foreign key constraint
|
||||
db.engine.execute('ALTER TABLE files ADD CONSTRAINT fk_files_folder_id FOREIGN KEY (folder_id) REFERENCES folders (id);')
|
||||
print("Column added successfully!")
|
||||
else:
|
||||
print("folder_id column already exists")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_migration()
|
36
app/migrations/add_share_table.py
Normal file
36
app/migrations/add_share_table.py
Normal file
|
@ -0,0 +1,36 @@
|
|||
"""
|
||||
Add Share table for file and folder sharing
|
||||
"""
|
||||
from sqlalchemy import inspect
|
||||
from .. import db
|
||||
|
||||
class AddShareTable:
|
||||
"""Migration to add the shares table"""
|
||||
version = 2
|
||||
description = "Add Share table for file/folder sharing"
|
||||
|
||||
def should_run(self, inspector):
|
||||
"""Check if the shares table exists"""
|
||||
return 'shares' not in inspector.get_table_names()
|
||||
|
||||
def run(self):
|
||||
"""Create the shares table"""
|
||||
try:
|
||||
db.engine.execute('''
|
||||
CREATE TABLE shares (
|
||||
id INTEGER PRIMARY KEY,
|
||||
item_type VARCHAR(10) NOT NULL,
|
||||
item_id INTEGER NOT NULL,
|
||||
owner_id INTEGER NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
permission VARCHAR(10) NOT NULL DEFAULT 'view',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (owner_id) REFERENCES users (id),
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
)
|
||||
''')
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error creating shares table: {str(e)}")
|
||||
return False
|
52
app/migrations/add_storage_name.py
Normal file
52
app/migrations/add_storage_name.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
"""
|
||||
Script to add storage_name column to the file table.
|
||||
Run this once from the command line:
|
||||
python migrations/add_storage_name.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import sqlite3
|
||||
|
||||
# Add the parent directory to the path so we can import the app
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
from config import Config
|
||||
from app import create_app
|
||||
|
||||
def add_storage_name_column():
|
||||
"""Add storage_name column to file table"""
|
||||
# Get database path from config
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
db_path = app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
|
||||
|
||||
print(f"Database path: {db_path}")
|
||||
|
||||
# Connect to the database
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
# Check if column already exists
|
||||
cursor.execute("PRAGMA table_info(file)")
|
||||
columns = [column[1] for column in cursor.fetchall()]
|
||||
|
||||
if 'storage_name' not in columns:
|
||||
print("Adding storage_name column to file table...")
|
||||
cursor.execute("ALTER TABLE file ADD COLUMN storage_name TEXT")
|
||||
|
||||
# Update existing files to use name as storage_name
|
||||
cursor.execute("UPDATE file SET storage_name = name WHERE is_folder = 0")
|
||||
|
||||
conn.commit()
|
||||
print("Column added successfully!")
|
||||
else:
|
||||
print("Column already exists.")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
add_storage_name_column()
|
Loading…
Add table
Add a link
Reference in a new issue