I have a database x
with some amount of data filled in every tables. I want to create a copy of that database (with same schema and exact data). First I create a Declaritive Base class of x
using automap_base.
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session as s
def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
name = referred_cls.__name__.lower() + "_ref"
return name
Base = automap_base()
# engine, refering to the original database
engine = create_engine("mysql+pymysql://root:password1@localhost:3306/x")
# reflect the tables
Base.prepare(engine, reflect=True, name_for_scalar_relationship=name_for_scalar_relationship)
Router = Base.classes.router
########check the data in Router table
session = s(engine)
r1 = session.query(Router).all()
for n in r1:
print(n.name) #This returns all the router names
Getting some help from here I use alembic
to upgrade the database y
located at different place mysql+pymysql://anum:Anum-6630@localhost:3306/y
.
from sqlalchemy.orm import sessionmaker as sm
from sqlalchemy import create_engine
from alembic import op
# revision identifiers, used by Alembic.
revision = 'fae98f65a6ff'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
bind = op.get_bind()
session = sm(bind=bind)
Base.metadata.create_all(bind=bind)
# session._add_bind(session, bind=bind)
session.add(Router(id=uuid.uuid().bytes, serial="Test1"))
session.commit()
The line Base.metadata.create_all(bind=bind)
actually add all the tables (including proper FK constraints) into database y
, but all the tables are empty, except one entry in Router table which I added manually. I tried using create_all() but that didn't worked aswel.
Is there a way to copy all the data from x
to y
database ?