DecisionTree/migrations/add_node_images_table.py

39 lines
1.6 KiB
Python

from app import app, db
from models import NodeImage
def upgrade_database():
"""Add NodeImage table for multiple images per node"""
with app.app_context():
# Check if table already exists
with db.engine.connect() as conn:
result = conn.execute(db.text("SELECT name FROM sqlite_master WHERE type='table' AND name='node_image'"))
table_exists = result.fetchone() is not None
if not table_exists:
# Create the node_image table
conn.execute(db.text("""
CREATE TABLE node_image (
id INTEGER PRIMARY KEY AUTOINCREMENT,
node_id INTEGER NOT NULL,
image_url VARCHAR(500) NOT NULL,
caption VARCHAR(200),
display_order INTEGER DEFAULT 0,
FOREIGN KEY (node_id) REFERENCES node (id) ON DELETE CASCADE
)
"""))
print("Created node_image table")
# Migrate existing single images to the new table
conn.execute(db.text("""
INSERT INTO node_image (node_id, image_url, display_order)
SELECT id, image_url, 0 FROM node
WHERE image_url IS NOT NULL AND image_url != ''
"""))
print("Migrated existing images to node_image table")
conn.commit()
print("Database migration for multiple images completed successfully")
if __name__ == "__main__":
upgrade_database()