[Python] Copy one database to another using SQLAlchemy

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to copy a database using SQLAlchemy. The first attempt was:

    from from sqlalchemy import create_engine, MetaData
    from sqlalchemy.orm import sessionmaker

    from urls import engine_urls

    engine1 = create_engine(engine_urls[0])
    engine2 = create_engine(engine_urls[1])

    metadata = MetaData()
    metadata.reflect(engine1)
    tables = metadata.tables
    metadata.create_all(engine2)


    Session1 = sessionmaker(bind=engine1)

    from sqlalchemy import insert

    with Session1.begin() as session:
    for key in tables:
    table_object = tables[key]
    for row in session.query(table_object):
    s = insert(table_object).\
    values(**dict(zip(row.keys(), row)))
    engine2.execute(s)


    But this code does not work since the order in which inserts are done is arbitrary and this violates FK constraints. For example, inserting a child before a parent will cause such a violation. How could I achieve this task? Is there a part of the framework that would do this easily? I can't find it.

    Continue reading...

Compartilhe esta Página