首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用automap_base和alembic迁移/复制数据库

使用automap_base和alembic迁移/复制数据库
EN

Stack Overflow用户
提问于 2018-11-22 15:34:21
回答 1查看 1.3K关注 0票数 0

我有一个数据库x,每个表中都填充了一定数量的数据。我希望创建该数据库的副本(具有相同的模式和准确的数据)。首先,我使用x创建了一个Declaritive基类。

代码语言:javascript
复制
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

这里的帮助下,我使用alembic来升级位于不同位置的数据库y ( mysql+pymysql://anum:Anum-6630@localhost:3306/y )。

代码语言:javascript
复制
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()

Base.metadata.create_all(bind=bind)实际上将所有表(包括适当的FK约束)添加到数据库y中,但是所有表都是空的,除了我手动添加的Router表中的一个条目。我试过使用create_all(),但这并没有奏效。是否有方法将所有数据从x复制到y数据库?

EN

回答 1

Stack Overflow用户

发布于 2018-11-23 14:32:22

由于没有人回答,下面是我执行复制的野生方法:因为表需要按顺序创建(为了避免FK约束错误),我必须定义一个包含每个表的有序列表。

慢且不可靠的解决方案:

代码语言:javascript
复制
allTables = ["tableA", 
             "tableB", # <table B points to FK constraint of tableA>
             "tableC", # <table C points to FK constraint of tableB>
             ...]

def copyAllContent():
    global allTables
    s = Session(bind=origEngine)  # session bind to original table
    se = Session(bind=op.get_bind()) # session bind to cloned table (currently empty)
try:
    for table in allTables:
        # print(table)
        rows = s.query(Base.classes._data[table]).all()
        for row in rows:
            local_object = se.merge(row)  #merging both sessions
            se.add(local_object)
            se.commit()
except Exception as e:
    print(e)

上述方法适用于大多数表,但不适用于所有表。例如,原始数据库中存在表router,但在s.query(Base.classes._data[table]).all()中仍然存在错误--没有名称router的键。还没有足够的时间去解决这个问题。

快速可靠的解决方案:

后来,我找到了另一种使用从这里开始的快速而安静的可靠解决方案-- mysqldump

代码语言:javascript
复制
#copy sql dump from x database
mysqldump --column-statistics=0 -P 8000 -h localhost -u root -p --hex-blob x > x_dump.sql

上面的命令行mysqldump命令创建一个名为x_dump.sql的sql转储文件,该文件包含重新生成数据库所需的所有必要的SQL脚本。现在,我们需要做的就是将这个sql转储文件应用到另一个数据库y中。

代码语言:javascript
复制
#clone the database contents into y database
mysql -P 3306 -h localhost -u anum -p y < x_dump.sql

下面是做同样事情的pythonic版本

代码语言:javascript
复制
import subprocess

#copy sql dump from x database - blocking call (use Popen for non-blocking)
print(subprocess.call(["mysqldump", "--column-statistics=0", '-P', '8000', '-h', 'localhost', '-u', '<user>', '-p<password>',
                        '--hex-blob', 'x', '>', 'x_dump.sql'], shell=True))

print("done taking dump.")

#clone the database contents into y database - blocking call
print(subprocess.call(["mysql", '-P', '3306', '-h', 'localhost', '-u', '<user>', '-p<password>',
                        'y', '<', 'x_dump.sql'], shell=True))

print("done cloning the sqlDump.")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53434215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档