SQLAlchemy:遍历反射数据库中的所有相关表以生成用于测试的样本数据 背景、目的目前的方法问题

问题描述

背景、目的

给定现有数据库生成用于测试的样本数据:

  1. 应由实际行组成,
  2. 应该允许使用跨任何层次结构深度的联接(例如父/子/孙...等)跨相关表进行查询

目前的方法

我已经反映了数据库,并且正在使用 SLQAlchemy 的 inspect 查找所有相关表。迭代这个方法 n 次应该让我遍历 n 个深度级别的层次结构:

from sqlalchemy import create_engine,select,MetaData,Table,func,inspect
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
import pyMysqL

Metadata = MetaData()
db_connection_str = f'MysqL+pyMysqL://{db_user}:{db_password}@localhost/{db_name}'
Base = automap_base()
Base.prepare(db_connection,reflect=False)

Event = Base.classes.event # Here,'Event' is the root/main table from where the traversal begins
num_rows = 10 # Sample
stmt = select(*inspect(Event).persist_selectable.columns).limit(num_rows)
with Session(db_connection) as session:
    resultlist = session.execute(
         stmt
     ).all()


'''
Store the Event table query result somehow
'''
'''
Following section is a first-level traversal. This needs to be iterated to get nth-level traversals
'''

sample_event_id_list = [row[0] for row in resultlist] # 1st column is ID,is there a better way that involves key mapping rather than integer indexing?
sample_event_id_list

for rel in inspect(Event).relationships:
    object_class = rel.mapper.class_ 
    stmt  = select(*inspect(object_class).persist_selectable.columns).\
            join(Event).\
            where(Event.id.in_(sample_event_id_list))
    '''
    Store the Event table query result somehow
    '''

问题

是否有更好、更全面的方法生成样本数据?

我看过 Factory Boy,它与 sqlAlchemy 集成,还可以从实际数据生成行样本。但是否可以遍历数据库中所有相关表尚不清楚。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...