Skip to content

Instantly share code, notes, and snippets.

@Pymmdrza
Created December 28, 2024 01:01
Show Gist options
  • Save Pymmdrza/70f696452188bf744df1d855949cfa8c to your computer and use it in GitHub Desktop.
Save Pymmdrza/70f696452188bf744df1d855949cfa8c to your computer and use it in GitHub Desktop.
Wordpress Website Migrate Database 2 website model with python
import mysql.connector
# Source database connection configuration
SOURCE_DB_CONFIG = {
'host': 'source_db_host',
'user': 'source_db_user',
'password': 'source_db_password',
'database': 'source_db_name'
}
# Destination database connection configuration
DEST_DB_CONFIG = {
'host': 'destination_db_host',
'user': 'destination_db_user',
'password': 'destination_db_password',
'database': 'destination_db_name'
}
# Domain replacement settings
OLD_DOMAIN = 'site1.com'
NEW_DOMAIN = 'site2.com'
def connect_to_database(config):
"""Establishes a database connection."""
try:
cnx = mysql.connector.connect(**config)
return cnx
except mysql.connector.Error as err:
print(f"Error connecting to database: {err}")
return None
def get_wordpress_tables(cursor):
"""Retrieves a list of WordPress database tables."""
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall() if table[0].startswith('wp_')]
return tables
def table_exists(cursor, table_name):
"""Checks if a table exists in the database."""
cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
result = cursor.fetchone()
return result is not None
def copy_table_structure(source_cursor, dest_cursor, table_name):
"""Copies the table structure from the source to the destination database."""
source_cursor.execute(f"SHOW CREATE TABLE {table_name}")
create_table_statement = source_cursor.fetchone()[1]
try:
dest_cursor.execute(create_table_statement)
print(f"Table structure for '{table_name}' copied successfully.")
except mysql.connector.Error as err:
print(f"Error copying table structure for '{table_name}': {err}")
def copy_table_data(source_cnx, dest_cnx, table_name):
"""Copies table data from the source to the destination database and replaces the domain."""
source_cursor = source_cnx.cursor(dictionary=True)
dest_cursor = dest_cnx.cursor()
source_cursor.execute(f"SELECT * FROM {table_name}")
rows = source_cursor.fetchall()
if rows:
columns = ', '.join(f'`{col}`' for col in rows[0].keys())
placeholders = ', '.join(['%s'] * len(rows[0]))
insert_query = f"INSERT INTO `{table_name}` ({columns}) VALUES ({placeholders})"
for row in rows:
values = list(row.values())
# Replace domain in string values
updated_values = [value.replace(OLD_DOMAIN, NEW_DOMAIN) if isinstance(value, str) else value for value in values]
try:
dest_cursor.execute(insert_query, updated_values)
except mysql.connector.Error as err:
print(f"Error inserting data into table '{table_name}': {err}")
dest_cnx.rollback() # Rollback transaction on error
return False
dest_cnx.commit()
print(f"Data for table '{table_name}' copied and domain replaced successfully.")
return True
else:
print(f"Table '{table_name}' is empty.")
return True
def main():
"""Main function of the script."""
source_cnx = connect_to_database(SOURCE_DB_CONFIG)
dest_cnx = connect_to_database(DEST_DB_CONFIG)
if not source_cnx or not dest_cnx:
return
source_cursor = source_cnx.cursor()
dest_cursor = dest_cnx.cursor()
wordpress_tables = get_wordpress_tables(source_cursor)
print(f"Found WordPress tables: {wordpress_tables}")
for table_name in wordpress_tables:
print(f"\nProcessing table: {table_name}")
if not table_exists(dest_cursor, table_name):
copy_table_structure(source_cursor, dest_cursor, table_name)
copy_table_data(source_cnx, dest_cnx, table_name)
else:
print(f"Table '{table_name}' already exists in the destination database. Skipping.")
source_cursor.close()
dest_cursor.close()
source_cnx.close()
dest_cnx.close()
print("\nWordPress table migration completed.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment