-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate_database_pymysql.py
More file actions
193 lines (159 loc) Β· 6.51 KB
/
Copy pathmigrate_database_pymysql.py
File metadata and controls
193 lines (159 loc) Β· 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
"""
Alternative Database Migration Script using PyMySQL (already in requirements.txt)
Run this on your production server to add new profile fields
"""
import pymysql
import os
from datetime import datetime
def get_db_connection():
"""Get database connection from environment or user input"""
try:
# Try to get from environment first
connection = pymysql.connect(
host=os.getenv('DATABASE_HOST', 'localhost'),
user=os.getenv('DATABASE_USER', input("Database username: ")),
password=os.getenv('DATABASE_PASSWORD', input("Database password: ")),
database=os.getenv('DATABASE_NAME', input("Database name: ")),
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
return connection
except pymysql.Error as e:
print(f"β Database connection failed: {e}")
return None
def check_column_exists(cursor, table_name, column_name):
"""Check if a column already exists in the table"""
cursor.execute(f"""
SELECT COUNT(*) as count
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '{table_name}'
AND COLUMN_NAME = '{column_name}'
AND TABLE_SCHEMA = DATABASE()
""")
result = cursor.fetchone()
return result['count'] > 0
def migrate_user_table():
"""Add new profile fields to user table"""
print("ποΈ Starting User Table Migration...")
print(f"π
Migration Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
connection = get_db_connection()
if not connection:
return False
try:
cursor = connection.cursor()
# Define the new columns to add
new_columns = [
("first_name", "VARCHAR(100)"),
("last_name", "VARCHAR(100)"),
("phone", "VARCHAR(20)"),
("address", "TEXT"),
("city", "VARCHAR(100)"),
("state", "VARCHAR(100)"),
("postal_code", "VARCHAR(20)"),
("country", "VARCHAR(100)"),
("profile_completed", "BOOLEAN DEFAULT FALSE"),
("updated_at", "DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
]
print("π Checking existing columns...")
# Check which columns already exist
existing_columns = []
missing_columns = []
for column_name, column_type in new_columns:
if check_column_exists(cursor, 'user', column_name):
existing_columns.append(column_name)
print(f" β
Column '{column_name}' already exists")
else:
missing_columns.append((column_name, column_type))
print(f" β Column '{column_name}' needs to be added")
if not missing_columns:
print("\nπ All columns already exist! No migration needed.")
return True
print(f"\nπ Adding {len(missing_columns)} new columns...")
# Add missing columns
for column_name, column_type in missing_columns:
try:
alter_sql = f"ALTER TABLE user ADD COLUMN {column_name} {column_type}"
print(f" Adding {column_name}...")
cursor.execute(alter_sql)
print(f" β
Successfully added {column_name}")
except pymysql.Error as e:
print(f" β Failed to add {column_name}: {e}")
return False
# Commit all changes
connection.commit()
print("\nβ
Migration completed successfully!")
print("π Migration Summary:")
print(f" β’ Existing columns: {len(existing_columns)}")
print(f" β’ Added columns: {len(missing_columns)}")
print(f" β’ Total profile fields: {len(new_columns)}")
return True
except pymysql.Error as e:
print(f"β Migration failed: {e}")
connection.rollback()
return False
finally:
if connection:
cursor.close()
connection.close()
print("π Database connection closed.")
def verify_migration():
"""Verify that all columns were added correctly"""
print("\nπ Verifying migration...")
connection = get_db_connection()
if not connection:
return False
try:
cursor = connection.cursor()
# Get all columns in user table
cursor.execute("""
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'user'
AND TABLE_SCHEMA = DATABASE()
ORDER BY ORDINAL_POSITION
""")
columns = cursor.fetchall()
print("π Current User Table Structure:")
print("-" * 60)
for column in columns:
column_name = column['COLUMN_NAME']
data_type = column['DATA_TYPE']
is_nullable = column['IS_NULLABLE']
column_default = column['COLUMN_DEFAULT']
nullable = "NULL" if is_nullable == "YES" else "NOT NULL"
default = f"DEFAULT {column_default}" if column_default else ""
print(f" {column_name:<20} {data_type:<15} {nullable:<10} {default}")
print("-" * 60)
print(f"β
Total columns: {len(columns)}")
return True
except pymysql.Error as e:
print(f"β Verification failed: {e}")
return False
finally:
if connection:
cursor.close()
connection.close()
def main():
"""Main migration function"""
print("π Database Migration for Enhanced User Model")
print("This script will add profile fields to your user table.")
print("Make sure you have a backup of your database before proceeding!")
print("=" * 60)
# Ask for confirmation
confirm = input("Do you want to proceed with the migration? (yes/no): ").lower()
if confirm not in ['yes', 'y']:
print("β Migration cancelled.")
return
# Run migration
success = migrate_user_table()
if success:
verify_migration()
print("\nπ Migration completed successfully!")
print("Your denncathy.co.ke site now supports enhanced user profiles!")
else:
print("\nβ Migration failed. Please check the errors above.")
print("Contact your hosting provider if you need assistance.")
if __name__ == "__main__":
main()