There are various approaches to copying metadata from one database to another using SQLAlchemy. Here's one approach that involves creating a separate engine for the source database and target database, and then using the MetaData object to copy the schema from one to the other:
from sqlalchemy import create_engine
source_engine = create_engine('postgres://user:password@source_host/source_db')
target_engine = create_engine('mysql://user:password@target_host/target_db')
from sqlalchemy import MetaData
metadata = MetaData(bind= source_engine, reflect=True)
metadata.create_all(bind= target_engine)
with source_engine.begin() as source_conn:
for table in metadata.sorted_tables:
target_engine.execute(f'DESC {table.name}')
for constraint in table._sorted_constraints:
target_engine.execute(str(constraint).replace("CREATE", "CREATE IF NOT EXISTS"))
This code loops through all the tables in the metadata object and fetches a description of each one for the target database in order to determine its columns and primary/foreign keys. Then, it executes the create statements for any other constraints in the source database.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-07-01 11:00:00 +0000
Seen: 9 times
Last updated: Sep 15 '22
In PySpark, how does the lead function work when the value of a column changes?
How can SQL output be structured in a column-based XML format instead of row-based?
How can pgcrypto be used to secure data on Postgres?
What is the SQL grammar used for addSql in Doctrine?
How can Django Admin accommodate a variety of formats and locales for its input fields?