improved changes
This commit is contained in:
@ -1,38 +1,123 @@
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.exc import OperationalError
|
||||
"""
|
||||
Database Migration Script for Categories Table
|
||||
"""
|
||||
|
||||
def wait_for_db(max_retries=30, retry_delay=2):
|
||||
"""Wait for database to be ready"""
|
||||
from app import db, create_app
|
||||
from sqlalchemy import text
|
||||
|
||||
def create_categories_table():
|
||||
"""Create categories table"""
|
||||
|
||||
mysql_host = os.getenv('MYSQL_HOST', 'db')
|
||||
mysql_user = os.getenv('MYSQL_USER', 'vendinguser')
|
||||
mysql_password = os.getenv('MYSQL_PASSWORD', 'vendingpass')
|
||||
mysql_db = os.getenv('MYSQL_DATABASE', 'vending')
|
||||
create_table_sql = """
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
category_id VARCHAR(50) UNIQUE NOT NULL,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
image VARCHAR(255),
|
||||
brand_id VARCHAR(50) NOT NULL,
|
||||
brand_name VARCHAR(100) NOT NULL,
|
||||
branch_id VARCHAR(50) NOT NULL,
|
||||
branch_name VARCHAR(100) NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (brand_id) REFERENCES brands(brand_id),
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(branch_id)
|
||||
);
|
||||
"""
|
||||
|
||||
db_uri = f'mysql+pymysql://{mysql_user}:{mysql_password}@{mysql_host}:3306/{mysql_db}'
|
||||
create_index_sqls = [
|
||||
"CREATE INDEX IF NOT EXISTS idx_category_id ON categories(category_id);",
|
||||
"CREATE INDEX IF NOT EXISTS idx_category_brand_id ON categories(brand_id);",
|
||||
"CREATE INDEX IF NOT EXISTS idx_category_branch_id ON categories(branch_id);",
|
||||
"CREATE INDEX IF NOT EXISTS idx_category_name ON categories(name);"
|
||||
]
|
||||
|
||||
print(f"⏳ Waiting for MySQL at {mysql_host}:3306...")
|
||||
try:
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
with db.engine.connect() as connection:
|
||||
# Create the categories table
|
||||
connection.execute(text(create_table_sql))
|
||||
|
||||
# Create each index separately (SQLite limitation)
|
||||
for sql in create_index_sqls:
|
||||
connection.execute(text(sql))
|
||||
|
||||
connection.commit()
|
||||
|
||||
print("✓ Categories table created successfully!")
|
||||
print("✓ Indexes created successfully!")
|
||||
|
||||
# Optional: add sample categories
|
||||
add_sample = input("\nAdd sample categories? (y/n): ")
|
||||
if add_sample.lower() == 'y':
|
||||
add_sample_categories()
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Error creating table: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
def add_sample_categories():
|
||||
"""Add sample category data"""
|
||||
from app.models.models import Category, Brand, Branch
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
engine = create_engine(db_uri)
|
||||
connection = engine.connect()
|
||||
connection.close()
|
||||
print("✓ MySQL is ready!")
|
||||
return True
|
||||
except OperationalError as e:
|
||||
if attempt < max_retries:
|
||||
print(f"Waiting for MySQL... (attempt {attempt}/{max_retries})")
|
||||
time.sleep(retry_delay)
|
||||
else:
|
||||
print(f"❌ Failed to connect to MySQL after {max_retries} attempts")
|
||||
print(f"Error: {e}")
|
||||
sys.exit(1)
|
||||
brands = Brand.query.all()
|
||||
branches = Branch.query.all()
|
||||
|
||||
return False
|
||||
if not brands or not branches:
|
||||
print("✗ Please create brands and branches first!")
|
||||
return
|
||||
|
||||
sample_categories = [
|
||||
{'name': 'Beverages', 'brand_id': brands[0].brand_id if len(brands) > 0 else None},
|
||||
{'name': 'Snacks', 'brand_id': brands[1].brand_id if len(brands) > 1 else brands[0].brand_id},
|
||||
{'name': 'Chocolates', 'brand_id': brands[1].brand_id if len(brands) > 1 else brands[0].brand_id}
|
||||
]
|
||||
|
||||
try:
|
||||
for cat_data in sample_categories:
|
||||
if not cat_data['brand_id']:
|
||||
continue
|
||||
|
||||
brand = Brand.query.filter_by(brand_id=cat_data['brand_id']).first()
|
||||
if not brand:
|
||||
continue
|
||||
|
||||
branch = Branch.query.filter_by(branch_id=brand.branch_id).first()
|
||||
if not branch:
|
||||
continue
|
||||
|
||||
category_id = Category.generate_category_id(cat_data['name'])
|
||||
|
||||
category = Category(
|
||||
category_id=category_id,
|
||||
name=cat_data['name'],
|
||||
brand_id=brand.brand_id,
|
||||
brand_name=brand.name,
|
||||
branch_id=branch.branch_id,
|
||||
branch_name=branch.name,
|
||||
image=None
|
||||
)
|
||||
|
||||
db.session.add(category)
|
||||
|
||||
db.session.commit()
|
||||
print(f"✓ Added sample categories successfully!")
|
||||
|
||||
# Display all created categories
|
||||
categories = Category.query.all()
|
||||
print("\nCreated categories:")
|
||||
for cat in categories:
|
||||
print(f" - {cat.category_id}: {cat.name} @ {cat.brand_name} ({cat.branch_name})")
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"✗ Error adding sample data: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
wait_for_db()
|
||||
create_categories_table()
|
||||
|
||||
Reference in New Issue
Block a user