MySQL Shell 或 Mysqlsh 是非常可扩展的,并且很容易为一些方便的例程创建插件。例程可以进入函数,下面有示例。棘手的部分是必须告诉 Mysqlsh 正在创建一个扩展,然后将函数连接到该扩展对象。最后,扩展对象必须注册到 shell。
所以下面有两个函数查询 MySQL World Database 的 world.city 和 world.country 表的内容。这两个函数的第一件事是确保我们连接到 MySQL 数据库实例,或者换句话说,我们的 shell 与服务器建立了会话。然后是快速查询并转储结果。
现在是棘手的事情!
我们需要为我们的推广对象plugin_obj = shell.create_extension_object()
,然后我们提供informationfor我们的功能与shell.add_extension_object_member(plugin_obj, “city”, show_tables, {“brief” : “Dave’s demo 2 - city”} ) and
shell.add_extension_object_member(plugin_obj, “countryinfo”, show_country, {“brief” : “Dave’s demo 2 - country”} ) 在我们告诉 shell 使用我们的新插件 shell.register_global(" world ", plugin_obj, {"brief ": “A 2nd demo for Dave”})告诉 shell 我们希望这些函数在名称world下可用。
当一个新的 Mysqlsh 会话启动时,我们可以使用\h 列出可用的插件。我们寻找我们的新插件。

如果你输入’world’然后按TAB键,你将能够看到这两个功能已经准备好了!

您可以键入所需函数的名称,然后查询将运行。

我省略了查询的输出。请注意,您=可以使用用 JavaScript 或 Python 编写的插件,并且也可以从其他语言模式运行以任一语言编写的程序。
代码
def show_tables(session=None):
""" Lists all the records in the world.city table
Simple function to query records in table
Args:
session (object): Option session object or use current mysqlsh session
Returns:
Nothing
"""
if session is None:
session = shell.get_session()
if session is None:
print("No session specified - pass a session or connect shell to database")
return
if session is not None:
r = session.run_sql("SELECT * FROM world.city")
shell.dump_rows(r)
def show_country(session=None):
""" Yada - yada -> see above function
"""
if session is None:
session = shell.get_session()
if session is None:
print("No session specified - pass a session or connect shell to database")
return
if session is not None:
r = session.run_sql("SELECT * FROM world.country")
shell.dump_rows(r)
plugin_obj = shell.create_extension_object()
shell.add_extension_object_member(plugin_obj, "city", show_tables, {"brief" : "Dave's demo 2 - city"} )
shell.add_extension_object_member(plugin_obj, "countryinfo", show_country, {"brief" : "Dave's demo 2 - country"} )
shell.register_global("world", plugin_obj, {"brief": "A 2nd demo for Dave"})
原文地址:https://elephantdolphin.blogspot.com/2021/05/extending-mysql-shell-with-python.html?yw




