Files
TODO_list_system/backend/test_db.py
beabigegg f3f2b7d596 2nd
2025-08-29 19:02:19 +08:00

181 lines
5.7 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test database connection and check data"""
import os
import sys
from dotenv import load_dotenv
import pymysql
from datetime import datetime
# Load environment variables
load_dotenv()
def test_db_connection():
"""Test database connection and list tables"""
print("=" * 60)
print("Testing Database Connection")
print("=" * 60)
# Get database configuration
db_config = {
'host': os.getenv('MYSQL_HOST', 'mysql.theaken.com'),
'port': int(os.getenv('MYSQL_PORT', 33306)),
'user': os.getenv('MYSQL_USER', 'A060'),
'password': os.getenv('MYSQL_PASSWORD', 'WLeSCi0yhtc7'),
'database': os.getenv('MYSQL_DATABASE', 'db_A060'),
'charset': 'utf8mb4'
}
print(f"Host: {db_config['host']}")
print(f"Port: {db_config['port']}")
print(f"Database: {db_config['database']}")
print(f"User: {db_config['user']}")
print("-" * 60)
try:
# Connect to database
connection = pymysql.connect(**db_config)
cursor = connection.cursor()
print("[OK] Successfully connected to database")
# List all tables
print("\n[1] Listing all todo tables:")
cursor.execute("SHOW TABLES LIKE 'todo%'")
tables = cursor.fetchall()
if tables:
for table in tables:
print(f" - {table[0]}")
else:
print(" No todo tables found")
# Check todo_item table
print("\n[2] Checking todo_item table:")
cursor.execute("SELECT COUNT(*) FROM todo_item")
count = cursor.fetchone()[0]
print(f" Total records: {count}")
if count > 0:
print("\n Sample data from todo_item:")
cursor.execute("""
SELECT id, title, status, priority, due_date, creator_ad
FROM todo_item
ORDER BY created_at DESC
LIMIT 5
""")
items = cursor.fetchall()
for item in items:
print(f" - {item[0][:8]}... | {item[1][:30]}... | {item[2]} | {item[5]}")
# Check todo_user_pref table
print("\n[3] Checking todo_user_pref table:")
cursor.execute("SELECT COUNT(*) FROM todo_user_pref")
count = cursor.fetchone()[0]
print(f" Total users: {count}")
if count > 0:
print("\n Sample users:")
cursor.execute("""
SELECT ad_account, display_name, email
FROM todo_user_pref
LIMIT 5
""")
users = cursor.fetchall()
for user in users:
print(f" - {user[0]} | {user[1]} | {user[2]}")
# Check todo_item_responsible table
print("\n[4] Checking todo_item_responsible table:")
cursor.execute("SELECT COUNT(*) FROM todo_item_responsible")
count = cursor.fetchone()[0]
print(f" Total assignments: {count}")
# Check todo_item_follower table
print("\n[5] Checking todo_item_follower table:")
cursor.execute("SELECT COUNT(*) FROM todo_item_follower")
count = cursor.fetchone()[0]
print(f" Total followers: {count}")
cursor.close()
connection.close()
print("\n" + "=" * 60)
print("[OK] Database connection test successful!")
print("=" * 60)
return True
except Exception as e:
print(f"\n[ERROR] Database connection failed: {str(e)}")
print(f"Error type: {type(e).__name__}")
return False
def create_sample_todo():
"""Create a sample todo item for testing"""
print("\n" + "=" * 60)
print("Creating Sample Todo Item")
print("=" * 60)
db_config = {
'host': os.getenv('MYSQL_HOST', 'mysql.theaken.com'),
'port': int(os.getenv('MYSQL_PORT', 33306)),
'user': os.getenv('MYSQL_USER', 'A060'),
'password': os.getenv('MYSQL_PASSWORD', 'WLeSCi0yhtc7'),
'database': os.getenv('MYSQL_DATABASE', 'db_A060'),
'charset': 'utf8mb4'
}
try:
connection = pymysql.connect(**db_config)
cursor = connection.cursor()
# Generate a UUID
import uuid
todo_id = str(uuid.uuid4())
# Insert sample todo
sql = """
INSERT INTO todo_item
(id, title, description, status, priority, due_date, created_at, creator_ad, creator_display_name, creator_email, starred)
VALUES
(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
values = (
todo_id,
'Test Todo Item - ' + datetime.now().strftime('%Y-%m-%d %H:%M'),
'This is a test todo item created from Python script',
'NEW',
'MEDIUM',
'2025-09-15',
datetime.now(),
'test_user',
'Test User',
'test@panjit.com.tw',
False
)
cursor.execute(sql, values)
connection.commit()
print(f"[OK] Created todo item with ID: {todo_id}")
cursor.close()
connection.close()
return True
except Exception as e:
print(f"[ERROR] Failed to create todo: {str(e)}")
return False
if __name__ == "__main__":
# Test database connection
if test_db_connection():
# Ask if user wants to create sample data
response = input("\nDo you want to create a sample todo item? (y/n): ")
if response.lower() == 'y':
create_sample_todo()
else:
print("\n[WARNING] Please check your database configuration in .env file")
sys.exit(1)