MySQL Shell API 9.1.0
Unified development interface for MySQL Products
|
Gives access to general purpose functions and properties. More...
Methods | |
std::shared_ptr< ShellBaseSession > | get_session () |
Returns the global session. | |
void | disconnect () |
Disconnects the global session. | |
bool | reconnect () |
Reconnect the global session. | |
void | status () |
Shows connection status info for the shell. More... | |
dict | parse_uri (str uri) |
Utility function to parse a URI string. More... | |
str | unparse_uri (dict options) |
Formats the given connection options to a URI string suitable for mysqlsh. More... | |
str | prompt (str message, dict options) |
Utility function to prompt data from the user. More... | |
Session | connect (ConnectionData connectionData, str password) |
Establishes the shell global session. More... | |
Session | connect_to_primary (ConnectionData connectionData, str password) |
Establishes the shell global session, connecting to a primary of an InnoDB cluster or ReplicaSet. More... | |
Session | open_session (ConnectionData connectionData, str password) |
Establishes and returns session. More... | |
None | set_session (Session session) |
Sets the global session. More... | |
None | set_current_schema (str name) |
Sets the active schema on the global session. More... | |
None | log (str level, str message) |
Logs an entry to the shell's log file. More... | |
list | list_credential_helpers () |
Returns a list of strings, where each string is a name of a helper available on the current platform. More... | |
None | store_credential (str url, str password) |
Stores given credential using the configured helper. More... | |
None | delete_credential (str url) |
Deletes credential for the given URL using the configured helper. More... | |
None | delete_all_credentials () |
Deletes all credentials managed by the configured helper. More... | |
list | list_credentials () |
Retrieves a list of all URLs stored by the configured helper. More... | |
ShellContextWrapper | create_context (dict options) |
Create a shell context wrapper used in multiuser environments. The returned object should be explicitly deleted when no longer needed. More... | |
list | list_ssh_connections () |
Retrieves a list of all active SSH tunnels. More... | |
None | enable_pager () |
Enables pager specified in shell.options.pager for the current scripting mode. More... | |
None | disable_pager () |
Disables pager for the current scripting mode. More... | |
None | register_report (str name, str type, Function report, dict description) |
Registers a new user-defined report. More... | |
UserObject | create_extension_object () |
Creates an extension object, it can be used to extend shell functionality. More... | |
None | add_extension_object_member (Object object, str name, Value member, dict definition) |
Adds a member to an extension object. More... | |
None | register_global (str name, Object object, dict definition) |
Registers an extension object as a shell global object. More... | |
int | dump_rows (ShellBaseResult result, str format) |
Formats and dumps the given resultset object to the console. More... | |
dict | auto_complete_sql (str statement, dict options) |
Auto-completes the given SQL statement. More... | |
None | register_sql_handler (str name, str description, list prefixes, function callback) |
Registers a custom SQL Handler to intercept and handle matching SQL statements. More... | |
list | list_sql_handlers () |
Lists the name and description of any registered SQL handlers. More... | |
ShellResult | create_result (dict data) |
Creates a ShellResult object from the given data. More... | |
ShellResult | create_result (list data) |
Creates a ShellResult object from the given data. More... | |
Properties | |
Options | options |
Gives access to the options that modify the shell behavior. | |
Reports | reports |
Gives access to built-in and user-defined reports. | |
str | version |
MySQL Shell version information. | |
Gives access to general purpose functions and properties.
void status | ( | ) |
Shows connection status info for the shell.
This shows the same information shown by the \status command.
dict parse_uri | ( | str | uri | ) |
Utility function to parse a URI string.
uri | a URI string. |
Parses a URI string and returns a dictionary containing an item for each found element.
A basic URI string has the following format:
[scheme://][user[:password]@]<host[:port]|socket>[/schema][?option=value&option=value...]
For more information about the URI format as well as the returned dictionary please look at Connection Data
str unparse_uri | ( | dict | options | ) |
Formats the given connection options to a URI string suitable for mysqlsh.
options | a dictionary with the connection options. |
This function assembles a MySQL connection string which can be used in the shell or X DevAPI connectors.
str prompt | ( | str | message, |
dict | options | ||
) |
Utility function to prompt data from the user.
message | a string with the message to be shown to the user. |
options | Optional dictionary with options that change the function behavior. |
This function allows creating scripts that require interaction with the user to gather data.
The options dictionary may contain the following options:
General Behavior
The 'title' option is not used in the Shell but it might be useful for better integration with external plugins handling prompts.
When the 'description' option is provided, each entry will be printed as a separate paragraph.
Once the description is printed, the content of the message parameter will be printed and input from the user will be required.
The value of the 'defaultValue' option and the returned value will depend on the 'type' option, as explained on the following sections.
Open Prompts
These represent prompts without a pre-defined set of valid answers, the prompt types on this category include: text, password, fileOpen, fileSave and directory.
The 'defaultValue' on these prompts can be set to a string to be returned by the function if the user replies to the prompt with an empty string, if not defined then the prompt will accept and return the empty string.
The returned value on these prompts will be either the value set on 'defaultValue' option or the value entered by the user.
In the case of password type prompts, the data entered by the user will not be displayed on the screen.
Confirm Prompts
The default behaviour of these prompts if to allow the user answering Yes/No questions, however, the default '&Yes' and '&No' options can be overriden through the 'yes' and 'no' options.
An additional option can be added to the prompt by defining the 'alt' option.
The 'yes', 'no' and 'alt' options are used to define the valid answers for the prompt. The ampersand (&) symbol can be used to define a single character which acts as a shortcut for the user to select the indicated answer.
i.e. using an option like: '&Yes' causes the following to be valid answers (case insensitive): 'Yes', '&Yes', 'Y'.
All the valid answers must be unique within the prompt call.
If the 'defaultValue' option is defined, it must be set equal to any of the valid prompt answers, i.e. if the 'yes', 'no' and 'alt' options are not defined, then 'defaultValue' can be set to one of '&Yes', 'Yes', 'Y', '&No', 'No' or 'N', case insensitive, otherwise, it must be set to one of the valid answers based on the values defined in the 'yes', 'no' or 'alt' options.
This prompt will be shown repeatedly until the user explicitly replies with one of the valid answers unless a 'defaultValue' is provided, which will be used in case the user replies with an empty answer.
The returned value will be the label associated to the user provided answer.
i.e. if the prompt is using the default options ('&Yes' and '&No') and the user response is 'n' the prompt function will return '&No'.
Select Prompts
These prompts allow the user selecting an option from a pre-defined list of options.
To define the list of options to be used in the prompt the 'options' option should be used.
If the 'defaultValue' option is defined, it must be a number representing the 1 based index of the option to be selected by default.
This prompt will be shown repeatedly until the user explicitly replies with the 1 based index of the option to be selected unless a default option is pre-defined through the 'defaultValue' option.
The returned value will be the text of the selected option.
Session connect | ( | ConnectionData | connectionData, |
str | password | ||
) |
Establishes the shell global session.
connectionData | the connection data to be used to establish the session. |
password | Optional the password to be used when establishing the session. |
This function will establish the global session with the received connection data.
The password may be included on the connectionData, the optional parameter should be used only if the connectionData does not contain it already. If both are specified the password parameter will override the password defined on the connectionData.
The connection data may be specified in the following formats:
A basic URI string has the following format:
[scheme://][user[:password]@]<host[:port]|socket>[/schema][?option=value&option=value...]
Connection Options
The following options are valid for use either in a URI or in a dictionary:
When these options are defined in a URI, their values must be URL encoded.
The following options are also valid when a dictionary is used:
Base Connection Options
SSH Tunnel Connection Options
The connection options are case insensitive and can only be defined once.
If an option is defined more than once, an error will be generated.
Detailed description of the connection data format is available at Connection Data
Session connect_to_primary | ( | ConnectionData | connectionData, |
str | password | ||
) |
Establishes the shell global session, connecting to a primary of an InnoDB cluster or ReplicaSet.
connectionData | Optional The connection data to be used to establish the session. |
password | Optional The password to be used when establishing the session. |
Ensures that the target server is a member of an InnoDB cluster or ReplicaSet and if it is not a PRIMARY, finds the PRIMARY and connects to it. Sets the global session object to the established session and returns that object.
If connectionData is not given, this function uses the global shell session, if there is none, an exception is raised.
The password may be included on the connectionData, the optional parameter should be used only if the connectionData does not contain it already. If both are specified the password parameter will override the password defined on the connectionData.
The connection data may be specified in the following formats:
A basic URI string has the following format:
[scheme://][user[:password]@]<host[:port]|socket>[/schema][?option=value&option=value...]
Connection Options
The following options are valid for use either in a URI or in a dictionary:
When these options are defined in a URI, their values must be URL encoded.
The following options are also valid when a dictionary is used:
Base Connection Options
SSH Tunnel Connection Options
The connection options are case insensitive and can only be defined once.
If an option is defined more than once, an error will be generated.
For additional information about MySQL connection data, see Connection Data.
RuntimeError | in the following scenarios:
|
Session open_session | ( | ConnectionData | connectionData, |
str | password | ||
) |
Establishes and returns session.
connectionData | Optional the connection data to be used to establish the session. If none given, duplicates the shell's active session. |
password | Optional the password to be used when establishing the session. |
This function will establish the session with the received connection data.
The password may be included on the connectionData, the optional parameter should be used only if the connectionData does not contain it already. If both are specified the password parameter will override the password defined on the connectionData.
The connection data may be specified in the following formats:
A basic URI string has the following format:
[scheme://][user[:password]@]<host[:port]|socket>[/schema][?option=value&option=value...]
Connection Options
The following options are valid for use either in a URI or in a dictionary:
When these options are defined in a URI, their values must be URL encoded.
The following options are also valid when a dictionary is used:
Base Connection Options
SSH Tunnel Connection Options
The connection options are case insensitive and can only be defined once.
If an option is defined more than once, an error will be generated.
For additional information about MySQL connection data, see Connection Data.
Detailed description of the connection data format is available at Connection Data
void set_session | ( | Session | session | ) |
Sets the global session.
session | The session object to be used as global session. |
Sets the global session using a session from a variable.
void set_current_schema | ( | str | name | ) |
Sets the active schema on the global session.
name | The name of the schema to be set as active. |
Once the schema is set as active, it will be available through the db global object.
None log | ( | str | level, |
str | message | ||
) |
Logs an entry to the shell's log file.
level | one of ERROR, WARNING, INFO, DEBUG, DEBUG2, DEBUG3 as a string |
message | the text to be logged |
Only messages that have a level value equal to or lower than the active one (set via --log-level) are logged.
shcore::Array_t list_credential_helpers | ( | ) |
Returns a list of strings, where each string is a name of a helper available on the current platform.
The special values "default" and "<disabled>" are not on the list. Only values on this list (plus "default" and "<disabled>") can be used to set the "credentialStore.helper" option.
None store_credential | ( | str | url, |
str | password | ||
) |
Stores given credential using the configured helper.
url | URL of the server for the password to be stored. |
password | Optional Password for the given URL. |
Throws ArgumentError if URL has invalid form.
Throws RuntimeError in the following scenarios:
If password is not provided, displays password prompt. If URL is already in storage, it's value is overwritten. URL needs to be in the following form: user@(host[:port]|socket).
None delete_credential | ( | str | url | ) |
Deletes credential for the given URL using the configured helper.
url | URL of the server to delete. |
Throws ArgumentError if URL has invalid form.
Throws RuntimeError in the following scenarios:
URL needs to be in the following form: user@(host[:port]|socket).
void delete_all_credentials | ( | ) |
Deletes all credentials managed by the configured helper.
Throws RuntimeError in the following scenarios:
shcore::Array_t list_credentials | ( | ) |
Retrieves a list of all URLs stored by the configured helper.
Throws RuntimeError in the following scenarios:
ShellContextWrapper create_context | ( | dict | options | ) |
Create a shell context wrapper used in multiuser environments. The returned object should be explicitly deleted when no longer needed.
options | Dictionary that holds optional callbacks and additional options. |
This function is meant to be used only inside of the Python in new thread. It's creating a scope which will isolate logger, interrupt handlers and delegates. All the delegates can run into infinite loop if one would try to print to stdout directly from the callback functions.
shcore::Array_t list_ssh_connections | ( | ) |
Retrieves a list of all active SSH tunnels.
void enable_pager | ( | ) |
Enables pager specified in shell.options.pager for the current scripting mode.
All subsequent text output (except for prompts and user interaction) is going to be forwarded to the pager.
This behavior is in effect until disable_pager() is called or current scripting mode is changed.
Changing the scripting mode has the same effect as calling disable_pager().
If the value of shell.options.pager option is changed after this method has been called, the new pager will be automatically used.
If shell.options.pager option is set to an empty string when this method is called, pager will not be active until shell.options.pager is set to a non-empty string.
This method has no effect in non-interactive mode.
void disable_pager | ( | ) |
Disables pager for the current scripting mode.
The current value of shell.options.pager option is not changed by calling this method.
This method has no effect in non-interactive mode.
None register_report | ( | str | name, |
str | type, | ||
Function | report, | ||
dict | description | ||
) |
Registers a new user-defined report.
name | Name of the registered report. |
type | Type of the registered report, one of: 'list', 'report' or 'print'. |
report | Function to be called when the report is requested. |
description | Optional Dictionary describing the report being registered. |
Throws ArgumentError in the following scenarios:
The name of the report must be unique and a valid scripting identifier. A case-insensitive comparison is used to validate the uniqueness.
The type of the report must be one of: 'list', 'report' or 'print'. This option specifies the expected result of calling this report as well as the output format if it is invoked using \show or \watch commands.
The report function must have the following signature: Dict report(Session session, List argv, Dict options), where:
Each report returns a dictionary with the following keys:
The description dictionary may contain the following optional keys:
The optional options list must hold dictionaries with the following keys:
The optional examples list must hold dictionaries with the following keys:
The type of the report determines the expected result of a report invocation:
The type of the report also determines the output form when report is called using \show or \watch commands:
The registered report is can be called using \show or \watch commands in any of the scripting modes. The registered report is also going to be available as a method of the shell.reports object.
Users may create custom report files in the init.d folder located in the Shell configuration path (by default it is ~/.mysqlsh/init.d in Unix and %AppData%\MySQL\mysqlsh\init.d in Windows). Custom reports may be written in either JavaScript or Python. The standard file extension for each case should be used to get them properly loaded. All reports registered in those files using the register_report() method will be available when Shell starts.
std::shared_ptr< Extensible_object > create_extension_object | ( | ) |
Creates an extension object, it can be used to extend shell functionality.
An extension object is defined by adding members in it (properties and functions).
An extension object can be either added as a property of another extension object or registered as a shell global object.
An extension object is usable only when it has been registered as a global object or when it has been added into another extension object that is member in an other registered object.
None add_extension_object_member | ( | Object | object, |
str | name, | ||
Value | member, | ||
dict | definition | ||
) |
Adds a member to an extension object.
object | The object to which the member will be added. |
name | The name of the member being added. |
member | The member being added. |
definition | Optional dictionary with help information about the member. |
The name parameter must be a valid identifier, this is, it should follow the pattern [_|a..z|A..Z]([_|a..z|A..Z|0..9])*
The member parameter can be any of:
When an extension object is added as a member, a read only property will be added into the target extension object.
When a function is added as member, it will be callable on the extension object but it will not be possible to overwrite it with a new value or function.
When any of the other types are added as a member, a read/write property will be added into the target extension object, it will be possible to update the value without any restriction.
IMPORTANT: every member added into an extensible object will be available only when the object is registered, this is, registered as a global shell object, or added as a member of another object that is already registered.
The definition parameter is an optional and can be used to define additional information for the member.
The member definition accepts the following attributes:
This information will be integrated into the shell help to be available through the built in help system (\?).
When adding a function, the following attribute is also allowed on the member definition:
A parameter definition is a dictionary with the following attributes:
The information defined on the brief and details attributes will also be added to the function help on the built in help system (\?).
If a parameter's type is 'string' the following attribute is also allowed on the parameter definition dictionary:
If a parameter's type is 'object' the following attributes are also allowed on the parameter definition dictionary:
The values for the class(es) properties must be a valid class exposed through the different APIs. For details use:
To get the class name for a global object or a registered extension call the print function passing as parameter the object, i.e. "Shell" is the class name for the built in shell global object:
If a parameter's type is 'dictionary' the following attribute is also allowed on the parameter definition dictionary:
An option definition dictionary follows exactly the same rules as the parameter definition dictionary except for one: on a parameter definition dictionary, required parameters must be defined first, option definition dictionaries do not have this restriction.
UserObject register_global | ( | str | name, |
Object | object, | ||
dict | definition | ||
) |
Registers an extension object as a shell global object.
name | The name to be given to the registered global object. |
object | The extension object to be registered as a global object. |
definition | optional dictionary containing help information about the object. |
An extension object is created with the shell.create_extension_object function. Once registered, the functionality it provides will be available for use.
The name parameter must comply with the following restrictions:
The name used to register an object will be exactly the name under which the object will be available for both Python and JavaScript modes, this is, no naming convention is enforced on global objects.
The definition parameter is a dictionary with help information about the object being registered, it allows the following properties:
When the object is registered, the help data on the definition parameter as well as the object members is made available through the shell built in help system. (\?).
None dump_rows | ( | ShellBaseResult | result, |
str | format | ||
) |
Formats and dumps the given resultset object to the console.
result | The resultset object to dump |
format | One of table, tabbed, vertical, json, ndjson, json/raw, json/array, json/pretty. Default is table. |
This function shows a resultset object returned by a DB Session query in the same formats supported by the shell.
Note that the resultset will be consumed by the function.
dict auto_complete_sql | ( | str | statement, |
dict | options | ||
) |
Auto-completes the given SQL statement.
statement | A SQL statement to be auto-completed. |
options | A dictionary with the auto-completion options. |
The following options are supported:
Return value
This function returns a dictionary describing candidates which can be used to auto-complete the given statement at the given caret position:
where:
The references list contains dictionaries with the following keys:
The candidates list contains one or more of the following values:
None register_sql_handler | ( | str | name, |
str | description, | ||
list | prefixes, | ||
function | callback | ||
) |
Registers a custom SQL Handler to intercept and handle matching SQL statements.
name | A name that uniquely identifies the SQL handler. |
description | A brief description of the SQL extensions provided by the SQL handler. |
prefixes | List of prefixes to identify the SQL statements to be processed by this handler. |
callback | The function to be executed when a statement implemented on this SQL handler is identified. |
SQL statements are intercepted in user created sessions and when applicable, they are processed using the corresponding SQL Handler.
User created sessions include the MySQL Shell Global Session and the sessions created with the different API functions available.
The function provided on the callback parameter is expected to have the following signature:
function(session, sql): [Result]
The Session used to execute the SQL statement will first identify if a specific SQL handler should be used to process it. If that is the case, the associated callback will be executed.
If the function returns a Result object the SQL processing will be considered complete; if no data is returned, the Session will proceed to execute the SQL statement.
The selection of a custom SQL handler for execution will be done by matching the SQL with the prefixes defined on the handler by ignoring leading white spaces and coalescing multiple white spaces between non space characters.
The callback function may return a Result object, which can be created by calling shell.create_result.
shcore::Array_t list_sql_handlers | ( | ) |
Lists the name and description of any registered SQL handlers.
Each element of the list is a dictionary with the following keys:
ShellResult create_result | ( | dict | data | ) |
Creates a ShellResult object from the given data.
data | Optional Either a dictionary or a list of dictionaries with the data to be used in the result. |
A result can be created using a dictionary with the following elements (all of them optional):
Creating a Result using an empty Dictionary is the same as creating an OK result with no data.
A warning is defined as a dictionary with the following elements:
When defining warnings, both level and message are mandatory.
It is possible to create a multi-result Result object, to do so, instead of using a single data dictionary, provide a list of data dictionaries following the specification mentioned above.
ShellResult create_result | ( | list | data | ) |
Creates a ShellResult object from the given data.
data | Optional Either a dictionary or a list of dictionaries with the data to be used in the result. |
A result can be created using a dictionary with the following elements (all of them optional):
Creating a Result using an empty Dictionary is the same as creating an OK result with no data.
A warning is defined as a dictionary with the following elements:
When defining warnings, both level and message are mandatory.
It is possible to create a multi-result Result object, to do so, instead of using a single data dictionary, provide a list of data dictionaries following the specification mentioned above.