MySQL Shell 9.0  /  ...  /  Registering SQL Handler

10.4.1 Registering SQL Handler

You can register an SQL handler in either of the following ways:

Registering SQL Handler with MySQL Shell API

register_Sql_Handler has the following syntax:

    shell.register_sql_handler(name, description, prefixes, callback)
  • name: the unique identifier of the SQL handler.

  • description: a brief description of the SQL extensions provided by the handler.

  • prefixes: a list of prefixes (string) identifying the SQL statements processed by this handler. You must define at least one prefix.

  • callback: name of the function to execute when a statement matching the prefix is identified.

    The function must have the following signature:

    function(session, sql): [Result]

Registering SQL Handler with a Python Decorator

You can also use the Python decorator @sql_handler to register the SQL handler. The decorator uses shell.registerSqlHandler to register the handler. The same restrictions apply for parameters.

For example:

        from mysqlsh.plugin_manager import sql_handler
        
        @sql_handler(prefixes=['SHOW '])
        "Prints a notice when a SHOW command is executed"
        def show_preprocessor(session, sql):
        
        print(f"SHOW COMMAND EXECUTED: {sql}")

Listing the Registered SQL Handlers

To list the registered SQL handlers, use shell.list_sql_handlers. This function returns the name and description of all registered SQL handlers.