在Python脚本中MySQL Workbench 5.2.34,grt.root.wb没有physicalModels

1 投票
3 回答
3179 浏览
提问于 2025-04-16 20:48

对象 'wb'(还有它的上级对象)是用来加载和保存信息的,但要获取数据库的物理模型的树状结构却没有加载出来。到目前为止,我在网上搜索也没找到什么有用的信息。

我本来是想写一个程序,检查某些列是否存在,并自动添加合适的触发器。我用正则表达式和数据库导出搞了个临时解决办法,但这让我有点不爽。

是不是缺少什么简单的激活步骤?(可能是连接的问题)

下面的代码运行时出现了错误:“AttributeError: 'NoneType' object has no attribute 'physicalModels'”:

# -*- coding: utf-8 -*-
# MySQL Workbench Python script
# <description>
# Written in MySQL Workbench 5.2.34

import grt
#import mforms #??
stOut=""
stTrigger="""
delimiter $$ 
create trigger `docdb_mk2`.tsi_{t} before insert on `docdb_mk2`.`{t}` 
for each row begin
set new.inserted=now();
end$$"""

# iterate through all tables from schema"""
schema = grt.root.wb.doc.physicalModels[0].catalog.schemata[0]
for table in schema.tables:
    #print table.name
    #if table. 
    #check to make sure both inserted and Updated are in the table
    #Since I have no clue how to do that in here, I'll skip it for now.
    stOut=stOut+stTrigger(t=table.name)

连这个也失败了:

# -*- coding: utf-8 -*-
# MySQL Workbench Python script
# <description>
# Written in MySQL Workbench 5.2.34
import grt
#import mforms
# iterate through all schemas

for schema in grt.root.wb.doc.physicalModels[0].catalog.schemata:
    print schema.name

请注意,我现在并不是在询问我的SQL代码,只是在问这个让人烦恼的脚本障碍。

补充:显然,有些对象是通过在用户界面中加载这些元素来加载的。如果有其他方法可以让它们加载出来,我会很感激。但似乎如果你从主工作台界面加载脚本模块,你得到的 'wb' 对象是部分初始化的。如果你从其他子系统加载,比如数据建模模块(脚本 > 运行工作台脚本文件...),其他部分会被加载并开始工作。嗯。

3 个回答

2

我找到了解决办法:

print results.rowCount()  
# the above throws an exception because what is returned from executeScript() differs from the docs 

如果你直接对db_query_Resultset列表中的第一个元素写代码,不加括号,就能正常工作。
也就是说,print results[0].rowCount 这样写是可以的。

2

你需要从你的工作台打开一个模型文件(*.mwb 文件),如果没有这个文件,就创建一个新的(选择“从现有数据库创建 EER 模型”)。这样应该就能解决你的错误了。

2

虽然这不是一个完整的解决方案,但这是我在努力搞清楚这个问题时的进展。从我了解到的情况来看,wb.docs.physicalModels这个对象只有在“设计/模型”模式下才能使用,而我需要在SQL编辑器模式下运行一个脚本。下面的代码确实可以执行查询并返回结果,但我发现文档和我现在看到的对象不太一致,这让我有点困惑。希望这对你有一些帮助。

import grt

for editor in grt.root.wb.sqlEditors:
    # add some text to the 'Output' tab
    editor.addToOutput("Test", 0)

    results = editor.executeScript("show tables")
    #print results.rowCount()
    # the above throws an exception because what is returned from executeScript() differs from the docs
    print results

    for buffer in editor.queryBuffers:
        print buffer.replaceContents("test")

撰写回答