© Charles Bell 2018
Charles BellIntroducing the MySQL 8 Document Storehttps://doi.org/10.1007/978-1-4842-2725-1_4

4. The MySQL Shell

Charles Bell1 
(1)
Warsaw, Virginia, USA
 

One of the largest missing features in the old MySQL client (mysql) was the absence of any form of scripting capability. However, it is possible to use the old client to process a batch of SQL commands and there is limited support in the client for writing stored routines (procedures and functions). For those who wanted to create and use scripts for managing their databases (and server), to date there have been external tool options including the MySQL Workbench and MySQL Utilities but nothing dedicated to incorporating multiple scripting languages.

MySQL Workbench is a fantastically popular product from Oracle. MySQL Workbench is a GUI tool designed as a workstation-based administration tool. It provides a host of features including tools for database design and modeling, SQL development, database administration, database migration, and scripting support with Python. For more information about MySQL Workbench, see http://dev.mysql.com/doc/workbench/en/ .

MySQL Utilities on the other hand, is a set of Python tools that are used to assist in maintaining and administering MySQL servers, achieving with a single command what would otherwise involve many steps or complex scripting. There are tools for administering the server, working with replication, and more. A library of Python classes is included for those who want to write their own Python scripts. For more information about MySQL Utilities, see https://dev.mysql.com/doc/mysql-utilities/1.6/en/ .

Note

MySQL Utilities is currently limited for use with MySQL 5.7. There is no release available that works with MySQL 8.0 or the document store.

Aside from these products, there has been no answer to requests to add scripting languages to the MySQL client. That is, until now. However, rather than retool the existing (and quite long lived) MySQL client tool, Oracle has released a new client called the MySQL Shell, which supports scripting languages, the X DevAPI, as well as SQL commands and more. But there is far more to the new shell than that.

In this chapter, we explore the MySQL Shell in more detail. We saw the shell in action in Chapter 3, but in this chapter we learn more about its major features and options as well as see how to use the new shell to execute scripts interactively. As you will see, the MySQL Shell is another critical element of the future of MySQL.

I recommend reading through the sections in this chapter leading up to the examples at least once before trying out the MySQL Shell yourself. The information presented will help you adjust to using the new commands and connections, which can sometimes be a bit confusing until you understand the concepts.

Note

I use the term, shell to refer to features or objects supported by the MySQL Shell. I use MySQL Shell to refer to the product itself.

Getting Started

MySQL Shell is a new and exciting addition to the MySQL portfolio. MySQL Shell represents the first modern and advanced client for connecting to and interacting with MySQL. The shell can be used as a scripting environment for developing new tools and applications for working with data. Although it does support an SQL mode, its main purpose is to permit access to data with the JavaScript and Python languages. That’s right; you can write Python scripts and execute them within the shell interactively or as a batch. Cool!

Recall from Chapter 1, that the MySQL Shell is designed to use the new X Protocol for communicating with the server via the X Plugin. However, the shell can also connect to the server using the older protocol albeit with limited features in the scripting modes. What this means is, the shell allows you to work with both relational (SQL), JSON documents (NoSQL), or both.

The addition of the SQL mode provides an excellent stepping-stone to learn how to manage your data with scripts. That is, you can continue to use your SQL commands (or batches) until you convert them to JavaScript or Python. Furthermore, you can use both to ensure your migration is complete. Figure 4-1 shows an example of launching MySQL Shell. Note the nifty prompt that displays the MySQL logo, connection information, and mode. Nice!
../images/432285_1_En_4_Chapter/432285_1_En_4_Fig1_HTML.jpg
Figure 4-1

The MySQL Shell

The following sections present the major features of the shell at a high level. We will not explore every detail of every feature or option, rather, this chapter provides a broad overview so that you can get started quickly and, more important, learn enough about the shell so that you can follow along with the examples in this book.

For more information about the MySQL Shell, see the section entitled, “MySQL Shell User Guide” in the online MySQL reference manual.

Features

The MySQL Shell has many features including support for traditional SQL command processing, script prototyping, and even support for customizing the shell. In the following I list some of the major features of the shell. Most of the features can be controlled via command line options or with special shell commands. I take a deeper look at some of the more critical features in later sections.
  • Logging: You can create a log of your session for later analysis or to keep a record of messages. You can set the level of detail with the --log-level option ranging from 1 (nothing logged) to 8 (max debug).

  • Output formats: The shell supports three format options: table (--table), which is the traditional grid format you’re used to from the old client; tabbed, which presents information using tabs for spacing and is used for batch execution; and JSON (--json), which formats the JSON documents in an easier to read manner. These are command-line options you specify when launching the shell.

  • Interactive code execution: The default mode for using the shell is interactive mode, which works as a traditional client where you enter a command and get a response.

  • Batch code execution: If you want to run your script without the interactive session, you can use the shell to run the script in batch mode. However, the output is limited to nonformatted output (but can be overridden with the --interactive option).

  • Scripting languages: The shell supports both JavaScript and Python although you can use only one at a time.

  • Sessions: Sessions are essentially connections to servers. The shell allows you to store and remove sessions. We will see more about sessions in a later section.

  • Startup scripts: you can define a script to execute when the shell starts. You can write the script in either JavaScript or Python.

  • Command history and command completion: The shell saves the commands you enter allowing you to recalling them using the up and down arrow keys. The shell also provides code completion for known keywords, API functions, and SQL keywords.

  • Global variables: The shell provides a few global variables you can access when in interactive mode. These include the following:
    • session: global session object if established

    • db: schema if established via a connection

    • dba: the AdminAPI object for working with the InnoDB Cluster

    • shell: general purpose functions for using the shell

    • util: utility functions for working with servers

  • Customize the prompt: You also can change the default prompt by updating a configuration file named ~/.mysqlsh/prompt.json using a special format or by defining an environment variable named MYSQLSH_PROMPT_THEME. See the MySQL Shell reference manual for more details about changing the prompt.

  • Auto completion: Starting in 8.0.4, the shell permits users to press the TAB key to auto complete keywords in SQL mode and the major classes and methods in JavaScript and Python modes.

Shell Commands

As with the original MySQL client, there are some special commands that control the application itself rather than interact with data (via SQL or the X DevAPI). To execute a shell command, issue the command with a slash (). For example, help prints the help for all of the shell commands. Table 4-1 lists some of the more frequently used shell commands.
Table 4-1

Shell Commands

Command

Shortcut

Description

 

Start multiline input (SQL mode only)

connect

(c)

Connect to a server

help

(?,h)

Print the help text

js

 

Switch to JavaScript mode

owarnings

(w)

Don't show warnings

py

 

Switch to Python mode

quit

(q,exit)

Quit

source

(.)

Executes the script file specified

sql

 

Switch to SQL mode

status

(s)

Print information about the connection

use

(u)

Set the schema for the session

warnings

(W)

Show warnings after each statement

Note that you can use the sql, js, and py shell commands to switch the mode on the fly. This makes working with SQL and NoSQL data much easier because you don’t have to exit the application to switch modes. Furthermore, you can use these shell commands even if you used the startup option to set the mode.

Tip

To get help with any shell command, use the help command. For example, to learn more about the connect command, enter help connect.

Finally, note the way you exit the shell (q or quit). If you type quit as you used to in the old client, the shell will respond differently depending on the mode you’re in. The following presents an example of what happens in each mode.

MySQL  SQL > quit;
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'quit' at line 1
 MySQL  SQL > js
Switching to JavaScript mode...
 MySQL  JS > quit
ReferenceError: quit is not defined
 MySQL  JS > py
Switching to Python mode...
 MySQL  Py > quit
Use quit() or Ctrl-D (i.e. EOF) to exit
 MySQL  Py > q
Bye!

You may see similar oddities if you are used to the old MySQL client and accidentally use an old client command, but it only takes a bit of regular use to remind you of the correct commands to use. Now, let’s look at the startup options for the shell.

Note

Unlike the old client, which requires a server connection to launch, when you launch the shell without specifying a server connection, the shell will run but it is not connected to a server. You must use the connect shell command to connect to a server.

Options

The shell can be launched using several startup options that control the mode, connection, behavior, and more. This section introduces some of the more common options that you may want to use. We will see more about connection options in a later section. Table 4-2 shows a list of common shell options.
Table 4-2

Common MySQL Shell Options

Option

Description

-f, --file=file

Processes file for execution

-e, --execute=<cmd>

Executes command and quit

--uri

Connects via a Uniform Resource Identifier (URI)

-h, --host=name

Hostname to use for connection

-P, --port=#

Port number to use for connection

-S, --socket=sock

Socket name to use for connection in UNIX or a named pipe name in Windows (only classic sessions)

-u, --dbuser=name

User to use for the connection

--user=name

An alias for dbuser

--dbpassword=name

Password to use when connecting to server

--password=name

An alias for dbpassword

-p

Requests password prompt to set the password

-D --schema=name

Schema to use

--database=name

An alias for --schema

--sql

Starts in SQL mode

--sqlc

Starts in SQL mode using a classic session

--sqlx

Starts in SQL mode using Creating an X protocol session

--js

Starts in JavaScript mode

--py

Starts in Python mode

--json

Produces output in JSON format

--table

Produces output in table format (default for interactive mode)

-i, --interactive[=full]

To use in batch mode, it forces emulation of interactive mode processing. Each line on the batch is processed as if it were in interactive mode.

--log-level=value

The log level; value must be an integer between 1 and 8 or any of [none, internal, error, warning, info, debug, debug2, debug3]

--mx --mysqlx

Creates an X protocol session (simply called Session)

--mc --mysql

Creates a classic (old protocol) session

--ma

Creates session with automatic protocol selection

--nw, --no-wizard

Disables wizard mode (noninteractive) for executing scripts.

--ssl-mode

Enables SSL for connection (automatically enabled with other flags)

--ssl-key=name

X509 keys in PEM format

--ssl-cert=name

X509 certs in PEM format

--ssl-ca=name

CA file in PEM format (check OpenSSL docs)

--ssl-capath=dir

CA directory.

--ssl-cipher=name

SSL Cipher to use.

--ssl-crl=name

Certificate revocation list.

--ssl-crlpath=dir

Certificate revocation list path.

--tls-version=version

TLS version to use, permitted values are: TLSv1, TLSv1.1.

--auth-method=method

Authentication method to use.

--dba=enableXProtocol

Enables the X Protocol in the server connected to. Must be used with --mysql.

Note that there are aliases for some of the options that have the same purpose as the original client. This makes switching to the shell a bit easier if you have scripts for launching the client to perform operations. Note that there is also a set of options for using a secure socket layer (SSL) connection.

Most of these are self-explanatory and we’ve seen several of these previously. Let’s now look at the sessions and connections available and how to use them.

For a complete list of options, execute the shell with the --help option as shown in the following.

$ mysqlsh --help
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Usage: mysqlsh [OPTIONS] [URI]
       mysqlsh [OPTIONS] [URI] -f <path> [script args...]
       mysqlsh [OPTIONS] [URI] --dba [command]
       mysqlsh [OPTIONS] [URI] --cluster
  -?, --help                  Display this help and exit.
  -e, --execute=<cmd>         Execute command and quit.
  -f, --file=file             Process file.
  --uri=value                 Connect to Uniform Resource Identifier. Format:
                              [user[:pass]@]host[:port][/db]
  -h, --host=name             Connect to host.
  -P, --port=#                Port number to use for connection.
  -S, --socket=sock           Socket name to use in UNIX, pipe name to use in
                              Windows (only classic sessions).
  -u, --dbuser=name           User for the connection to the server.
  --user=name                 see above
  -p, --password[=name]       Password to use when connecting to server.
  --dbpassword[=name]         see above
  -p                          Request password prompt to set the password
  -D, --schema=name           Schema to use.
  --database=name             see above
  --recreate-schema           Drop and recreate the specified schema.Schema
                              will be deleted if it exists!
  -mx, --mysqlx               Uses connection data to create Creating an X
                              protocol session.
  -mc, --mysql                Uses connection data to create a Classic Session.
  -ma                         Uses the connection data to create the session
                              withautomatic protocol detection.
...

Sessions and Modes

As with the original client and indeed most MySQL client applications, you will need to connect to a MySQL server so that you can run commands. The MySQL Shell supports several ways to connect to a MySQL server and a variety of options for interacting with the server (called a session). Within a session, you can change the way the shell accepts commands (called modes) to include SQL, JavaScript, or Python commands.

Given all the different and new concepts of working with servers, those new to using the shell may find the difference subtle and even at times confusing. Indeed, the online MySQL Shell reference manual and various blogs and other reports sometimes use mode and session interchangeably, but as you will see, they are different (however subtle). The following sections clarify each of the major concepts including sessions, modes, and connections so that you can get accustomed to the new methods faster. I introduce the concepts first with some simple examples then discuss making connections in detail with examples. Let’s begin by looking at the session objects available.

Session Objects

The first thing to understand about sessions is that a session is a connection to a single server. The second thing to understand is that each session can be started using one of two session objects that exposes a specific object for use in working with the MySQL server using a specific communication protocol. That is, sessions are connections to servers (with all parameters defined), and a session object is what the shell uses to interact with a server in one of several ways. More specific, a MySQL Shell session object simply defines how you interact with the server including what modes are supported and even how the shell communicates with the server. The shell supports two session objects as in the following:
  • Session: An X Protocol session is used for application development and supports the JavaScript, Python, and SQL modes. Typically used to develop scripts or execute scripts. To start the shell with this option, use the --mx (--mysqlx) option.

  • Classic session: Uses the older server communication protocol with very limited support for the DevAPI. Use this mode with older servers that do not have the X Plugin or do not support the X Protocol. Typically used for SQL mode with older servers. To start the shell with this option, use the --mc (--mysqlc) option.

Note

A classic session is only available in the MySQL Shell. It is not part of the X DevAPI. Only the session connection via the X Protocol is available via the X DevAPI.

You can specify the session object (protocol) to use when you use the connect shell command by specifying -mc for classic session, -mx for X Protocol session, or -ma for automatic protocol selection. The following shows each of these in turn. Note that <URI> specifies a uniform resource identifier.
  • connect -mx <URI>: Use the X Protocol (session)

  • connect -mc <URI>: Use the classic protocol (classic session)

  • connect -ma <URI>: Use automatic protocol selection

Recall sessions are loosely synonymous with a connection. However, a session is a bit more than just a connection because all the settings used to establish the connection including the session object are included as well as the communication protocol used with the server. Thus, we sometimes encounter the term, “protocol” for describing a session. We will see more examples of using sessions in later sections.

Wait, What Session Was That???

It is likely you will see the sessions described using several names. In particular, the normal, default session is called Session, X Protocol Session, or more rarely, X Session. These refer to a session object (connection) that communicates with MySQL via the X Protocol. The older server communication protocol is supported in a session called Classic Session, Classic, or more rarely, Old Protocol. These refer to a session object (connection) that communicates with a MySQL server via the old protocol. Sadly, these multiple names can make reading different texts a challenge. You should strive to read Session and Classic Session whenever these alternative terms are used.

For more information about using sessions programmatically, see the online MySQL Shell reference manual.

Modes Supported

The shell supports three modes (also called language support or simply the active language); SQL, JavaScript, and Python. Recall that we can initiate any one of these modes by using a shell command. You can switch modes (languages) as often as you want without disconnection each time. The following lists the three modes and how to switch to each.
  • sql: Switch to the SQL language

  • js: Switch to the JavaScript language (default mode)

  • py: Switch to the Python language

Now that we understand sessions, session objects, modes, we can look at how to make connections to MySQL servers.

Connections

Making connections in the shell is one area that may take some getting used to doing differently than the original MySQL client.1 You can use a specially formatted URI string or connect to a server using individual options by name (like the old client). SSL connections are also supported. Connections can be made via startup options, shell commands, and in scripts. However, all connections are expected to use a password. Thus, unless you state otherwise, the shell will prompt for a password if one is not given.

Note

If you want to use a connection without a password (not recommended), you must use the --password option or, if using an URI, include an extra colon to take the place of the password.

Rather than discuss all the available ways to connect and all the options to do so, the following presents one example of each method of making a connection in the following sections.

Using a URI

A URI in the case of a MySQL Shell connection is a special string coded using the following format: <dbuser>[:<dbpassword>]@host[:port][/schema/] where <> indicates string values for the various parameters. Note that the password, port, and schema are optional but the user and host are required. Schema in this case is the default schema (database) that you want to use when connecting.

Note

The default port for the X Protocol is 33060.

To connect to a server using a URI on the command line when starting the shell, specify it with the --uri option as follows.

$ mysqlsh --uri root:secret@localhost:33060

The shell assumes all connections require a password and will prompt for a password if one is not provided.2 Listing 4-1 shows the same connection earlier made without the password. Note how the shell prompts for the password.

Tip

The world_x database is a sample database you can download from https://dev.mysql.com/doc/index-other.html .

$ mysqlsh --uri root@localhost:33060/world_x
Creating a session to 'root@localhost:33060/world_x'
Enter password:
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
Default schema `world_x` accessible through db.
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help' or '?' for help; 'quit' to exit.
 MySQL  localhost:33060+  world_x  JS >
Listing 4-1

Connecting with a URI

Note that I also specified the default schema (world_x) with the /schema option in the URI.

Using Individual Options

You also can specify connections on the shell command line using individual options. The available connection options available are those shown in Table 4-1. For backward compatibility (and to make the transition to the MySQL Shell easier, the shell also supports --user in place of --dbuser, --password in place of --dbpassword, and --database in place of --schema. Listing 4-2 shows how to connect to a MySQL server using individual options.

$ mysqlsh --dbuser root --host localhost --port 33060 --schema world_x --py -mx
Creating an X protocol session to 'root@localhost:33060/world_x'
Enter password:
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 14 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
Default schema `world_x` accessible through db.
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help' or '?' for help; 'quit' to exit.
 MySQL  localhost:33060+  world_x  Py >
Listing 4-2

Connecting Using Individual Options

Note that I changed the mode (language) to Python with the --py option.

Using Connections in Scripts

If you plan to use the shell to create scripts or simply as a prototyping tool, you also will want to use sessions in your scripts. In this case, we will create a variable to contain the session once it is fetched. A session created in this manner is called a global session because once it is created, it is available to any of the modes.

However, depending on the session object we’re using (recall this is classic or X Protocol), we will use a different method of the mysqlx object to create an X or classic session. We use the getSession() method for an X Protocol session object, and the getClassicSession() method for a classic session object.

Tip

If you want to know more about the internals of the MySQL Shell including more about the mysql and mysqlx modules, see http://dev.mysql.com/doc/dev/mysqlsh-devapi/ .

The following demonstrates getting an X Protocol session object in JavaScript. Note that I specify the password in an URI as the method parameter.

 MySQL  JS > var js_session = mysqlx.getSession('root@localhost:33060', 'secret')
 MySQL  JS > print(js_session)
<Session:root@localhost:33060>

The following demonstrates getting a Classic session object in JavaScript.

 MySQL  JS > var js_session = mysql.getClassicSession('root@localhost:3306', 'secret')
 MySQL  JS > print(js_session)
<ClassicSession:root@localhost:3306>

What Happened To Port 3306?

If you’ve been following along with the examples in this section, you may have noticed that the port we are using is 33060. That is not a typographical error. The X Plugin listens on port 33060 by default rather than port 3306 as the original default port of the server. In fact, port 3306 is still the default for the old protocol and you can connect to the server using port 3306, but you must use the classic session (mysqlsh --classic -uroot -hlocalhost --port=3306). Although this shows that you can connect to a server using the old protocol, recall that it does limit what you can do because the DevAPI is not fully supported in the classic session object.

Using SSL Connections

You also can create SSL connections for secure connections to your servers. To use SSL, you must configure your server to use SSL. To use SSL on the same machine where MySQL is running, you can use the --ssl-mode=REQUIRED option. You also can specify the SSL options as shown in Table 4-1. You can specify them on the command line using the command line options or as an extension to the connect shell command. The following shows how to connect to a server using SSL and command line options.

$ mysqlsh -uroot -h127.0.0.1 --port=33060 --ssl-mode=REQUIRED

Tip

See the section, “Using Encrypted Connections” in the online MySQL Shell reference manual for more details about encrypted connections.

Now that we know how to connect to our servers, let’s review how to set up and install the shell and, more important, ensure the X Plugin is set up correctly.

Set Up and Install

Recall from Chapter 2, we need to install the MySQL Shell as a separate product from the server. We also must enable the X Plugin in the server. The following sections demonstrate the steps needed to install the MySQL Shell and how to configure the X Plugin for use. Although we saw a short example of how to install the X Plugin in Chapter 2, this section goes into greater detail including how to automatically install the X Plugin using the MySQL Shell.

Caution

If you are installing the MySQL Shell version 8.0.4 or later to be used with MySQL Server version 8.0.4 or later, you will be using the new caching_sha2_password authentication plugin to use SSL connections. This is normally done during setup by default, but if you installed the server without the automatic installation, or you are using an older version of the server, you may need to configure the server to use SSL connections. See the online MySQL reference manual for more information or for more information about the change to the authentication default, read the engineering blog at https://mysqlserverteam.com/mysql-8-0-4-new-default-authentication-plugin-caching_sha2_password .

Install the MySQL Shell

Installing the MySQL Shell follows the same pattern as installing the MySQL server. That is, you can simply download the installer for your platform and install it by clicking through the dialog panels. There is one exception, however. At the time of this writing, the latest release of the MySQL Shell is not part of the MySQL Windows Installer.

You can find the installation package on http://dev.mysql.com/downloads/shell/ . Just select the latest version and package for your platform (in this case, macOS) and install the shell.

When you launch the installer (.pkg or .dmg), you will be presented with a welcome dialog that contains the name and version of the product you are going to install. Figure 4-2 shows the welcome panel for the MySQL Shell installer.
../images/432285_1_En_4_Chapter/432285_1_En_4_Fig2_HTML.jpg
Figure 4-2

Installer welcome panel

Note that in Figure 4-2 I am installing a release candidate version of the MySQL Shell, namely, version 8.0.11. You should install the latest version of the shell available for your platform to ensure you have the latest features.

Once you are ready, click Continue. You will then be presented with the end-user license agreement as shown in Figure 4-3.
../images/432285_1_En_4_Chapter/432285_1_En_4_Fig3_HTML.jpg
Figure 4-3

License panel

Once you have read the license,3 click Continue. You will be asked to accept the license as shown in Figure 4-4. Click Agree to continue.
../images/432285_1_En_4_Chapter/432285_1_En_4_Fig4_HTML.jpg
Figure 4-4

Destination folder panel

Once you’ve accepted the license, and are okay with installing in the default location (for macOS that’s always a good idea), click Continue. You will be asked to approve the installation as shown in Figure 4-5. Click Install when ready to begin the installation.

Tip

When installing on Windows, you may be asked by Windows to approve the escalation of the installation.

../images/432285_1_En_4_Chapter/432285_1_En_4_Fig5_HTML.jpg
Figure 4-5

Installation panel

This will begin the copy of files to the destination along with settings on your system to ensure you can launch the application correctly. Depending on the speed of your system, it should only take about 2 to 3 minutes at the most to complete.

Once the installation is complete, you will be presented with a completion dialog as shown in Figure 4-6. When ready, click Close to complete the installation. If you choose to launch the shell, you will see a new command window open and the shell will start.

Recall you can launch the shell without specifying a server and the shell will run but it is not connected to any MySQL server. You must use the connect shell command to connect to a server if you do not specify a server connection (URI or individual options) on the command line.
../images/432285_1_En_4_Chapter/432285_1_En_4_Fig6_HTML.jpg
Figure 4-6

Installation complete

Now that the MySQL Shell is installed, we need to configure the X Plugin.

Setup the X Plugin

If you installed MySQL 8.0.11 or later on your system, you already have the X Plugin installed and enabled. However, some of the older installations do not setup or enable the X Plugin by default. Thus, you may need to enable the plugin to connect to your server with the shell. Although you can still use the shell to connect using a classic session object, you won’t be able to use the X Protocol session object until the X Plugin is enabled.

Furthermore, if you installed the server on Windows using the Windows Installer, you can enable the X Plugin during installation by checking the Enable X Protocol/MySQL as a Document Store checkbox. If you did not do that or are installing on a different platform, there are at least two other methods for enabling the X Plugin; you can use the new MySQL Shell or you can use the old client. The following demonstrates each option.

Tip

If you have trouble connecting to a MySQL server on a fresh installation of MySQL, be sure to enable the X Plugin as shown in this section.

Enable the X Plugin Using the MySQL Shell

To enable the X Plugin using the MySQL Shell, start a classic session using individual options for the user and host as well as specifying the --mysql and --dba enableXProtocol options as shown following. We use a classic session object because we do not have the X Protocol enabled yet.

$ mysqlsh -uroot -hlocalhost --mysql --dba enableXProtocol
Creating a Classic session to 'root@localhost'
Enter password:
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 285
Server version: 8.0.11 MySQL Community Server (GPL)
No default schema selected; type use <schema> to set one.
enableXProtocol: Installing plugin mysqlx...
enableXProtocol: done

Enable the X Plugin Using the MySQL Client

To enable the X Plugin using the old MySQL client, you must connect to the server and install the plugin manually. That is, there is no new magical command option to turn it on for you. This involves using the INSTALL PLUGIN SQL command as shown in Listing 4-3.

$ mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 343
Server version: 8.0.11 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql> INSTALL PLUGIN mysqlx SONAME 'mysqlx.so';
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW PLUGINS G
*************************** 1. row ***************************
   Name: keyring_file
 Status: ACTIVE
   Type: KEYRING
Library: keyring_file.so
License: GPL
...
*************************** 43. row ***************************
   Name: mysqlx
 Status: ACTIVE
   Type: DAEMON
Library: mysqlx.so
License: GPL
43 rows in set (0.00 sec)
Listing 4-3

Enabling the X Plugin Using the MySQL Client

Note that I used the SHOW PLUGINS SQL command to list the plugins installed before and after the command. I omit some of the lengthy output for clarity.

Tip

You can perform these operations in the shell using a classic session object. I show the commands using the old client for readers accustomed to using the old client.

It is interesting that you also can uninstall a plugin using the UNINSTALL PLUGIN SQL command as follows. This may be helpful if you need to diagnose connections using the X Protocol or want to test scripts with the MySQL Shell using only the classic session object.

mysql> UNINSTALL PLUGIN mysqlx;
Query OK, 0 rows affected (0.80 sec)

Now, let’s see the MySQL Shell in action by way of a demonstration of executing a simple task in each of the three modes (SQL, JavaScript, and Python).

Tutorial: MySQL Shell by Example

The following sections demonstrate how to use the MySQL shell in each of the three modes. The example is inserting new data in the world_x database. A brief overview of the built-in X DevAPI objects via the shell will be presented along with how to get started installing the sample database.

This tutorial is designed to present a complete example of how to use the MySQL Shell to solve a task in all the modes (languages) supported. Thus, we will see the same tasks performed using SQL, JavaScript, and Python commands.

The task is to insert new data in the database then conduct a search to retrieve rows that meet criteria that contains the new data. I use a relational table to illustrate the concepts because that is easier for those of us familiar with “normal” database operations. However, we will see in later chapters how to work with pure documents (collections) in the document store.

Each session presented begins with an example of how to connect to the server, learn about what the server supports (what databases exist), how to insert new data, and how to query for data. As you will see, some of the commands are quite different but they all produce the same results. Although the SQL commands shown will be familiar to most readers, I include them here to show how to equate those commands with your scripting language of choice.

Note

Recall from Chapter 3, it is not a requirement to be a JavaScript master or even a Pythonista4 to get started writing scripts in the shell. Indeed, most of what you need to do can be found by way of examples in this book and the online MySQL Shell reference manual.

The operations we will see for JavaScript and Python work with CRUD operations on relational tables. As such, we aren’t using collections; rather, we’re using a relational table that has a JSON data type column. We will see examples of inserting data (create), select data (read), updating data (updated), and deleting data (delete).

Before we begin our journey, let’s take a moment to install the sample database we will need, the world_x sample MySQL database from Oracle.

Installing the Sample Database

Oracle provides several sample databases for you to use in testing and developing your applications. Sample databases can be downloaded from http://dev.mysql.com/doc/index-other.html . The sample database we want to use is named world_x to indicate it contains JSON documents and is intended for testing with the X DevAPI, the shell, and so forth. Go ahead and navigate to that page and download the database.

The sample database contains several relational tables (country, city, and countrylanguage) as well as a collection (countryinfo). We will only use the relational tables in this chapter, but will see more examples working with collections in later chapters.

Once you’ve downloaded the file, uncompress it and note the location of the files. You will need that when we import it. Next, start the MySQL Shell and make a connection to your server. Use the sql shell command to switch to SQL mode then the source shell command to read the world_x.sql file and process all its statements.

Listing 4-4 shows an excerpt of the commands and the responses you should see. I highlight the commands and a row in the output to show that this world database does indeed permit storing of JSON documents in a table.

 MySQL  JS > connect root@localhost:33060
Creating a session to 'root@localhost:33060'
Enter password:
Your MySQL connection id is 9 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
No default schema selected; type use <schema> to set one.
 MySQL  localhost:33060+ ssl  JS > sql
Switching to SQL mode... Commands end with ;
 MySQL  localhost:33060+ ssl  SQL > source /Users/cbell/Downloads/world_x-db/world_x.sql
...
Query OK, 0 rows affected (0.00 sec)
MySQL  localhost:33060+ ssl  SQL > SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| animals            |
| contact_list1      |
| contact_list2      |
| contact_list3      |
| greenhouse         |
| information_schema |
| library_v1         |
| library_v2         |
| library_v3         |
| mysql              |
| performance_schema |
| rolodex            |
| sys                |
| test               |
| world_x            |
+--------------------+
15 rows in set (0.00 sec)
 MySQL  localhost:33060+ ssl  SQL > USE world_x;
Query OK, 0 rows affected (0.00 sec)
 MySQL  localhost:33060+ ssl  SQL > SHOW TABLES;
+-------------------+
| Tables_in_world_x |
+-------------------+
| city              |
| country           |
| countryinfo       |
| countrylanguage   |
+-------------------+
4 rows in set (0.00 sec)
MySQL  localhost:33060+ ssl  SQL > EXPLAIN city;
+-------------+----------+------+-----+---------+----------------+
| Field       | Type     | Null | Key | Default | Extra          |
+-------------+----------+------+-----+---------+----------------+
| ID          | int(11)  | NO   | PRI | NULL    | auto_increment |
| Name        | char(35) | NO   |     |         |                |
| CountryCode | char(3)  | NO   |     |         |                |
| District    | char(20) | NO   |     |         |                |
| Info        | json     | YES  |     | NULL    |                |
+-------------+----------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Listing 4-4

Installing the world_x Database in SQL Mode

Note that the source shell command is a way to load a file and execute the commands in a batch. This is a very popular method of replaying frequently used command sequences and it does work for JavaScript and Python commands too.

Tip

If the path to the file has spaces in it, you should include the path within double quotes.

You can also install the sample database using the --recreate-schema option on the command line as follows. Note that this will delete and recreate the database if it already exists. This is another example of running the SQL commands as a batch.

$ mysqlsh -uroot -hlocalhost --sql --recreate-schema --schema=world_x < ~/Downloads/world_x-db/world_x.sql
Enter password:
Recreating schema world_x...

Of course, you could install the sample database with the old client by using the similar source command, but where’s the fun in that?

Now, let’s see our example task in SQL mode.

SQL

The task we want to do is to insert two rows into the city table adding a JSON document in each and then read data from the table only those rows that have the extra data. More specific, we are going to be adding a list of places of interest to the table so that we can ask questions later about which cities have places of interest. Think of it as a way to add your own comments about places you’ve visited in those cities that you found interesting and would recommend to others.

Because this exercise is an example, we will also see how to delete the data we added so that we return the database to its original state. It also helps to do this if you plan to follow along with these examples so that completing one doesn’t affect trying out the next.

Let’s begin with listing the databases on the server then listing the tables in the world_x database. Listing 4-5 shows a transcript of the familiar SQL commands to accomplish these steps. I omit some of the messages for brevity. Note that I started the shell in the SQL mode using the command option.

$ mysqlsh -uroot -hlocalhost --sql
Creating a session to 'root@localhost'
Enter password:
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
No default schema selected; type use <schema> to set one.
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help' or '?' for help; 'quit' to exit.
 MySQL  localhost:33060+ ssl  SQL > SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| animals            |
| contact_list1      |
| contact_list2      |
| contact_list3      |
| greenhouse         |
| information_schema |
| library_v1         |
| library_v2         |
| library_v3         |
| mysql              |
| performance_schema |
| rolodex            |
| sys                |
| test               |
| world_x            |
+--------------------+
15 rows in set (0.00 sec)
 MySQL  localhost:33060+ ssl  SQL > USE world_x;
Query OK, 0 rows affected (0.00 sec)
 MySQL  localhost:33060+ ssl  SQL > SHOW TABLES;
+-------------------+
| Tables_in_world_x |
+-------------------+
| city              |
| country           |
| countryinfo       |
| countrylanguage   |
+-------------------+
4 rows in set (0.00 sec)                                ... ;
Query OK, 0 rows affected (0.00 sec)
 MySQL  localhost:33060+ ssl  SQL > SHOW TABLES;
+-------------------+
| Tables_in_rolodex |
+-------------------+
| contacts          |
+-------------------+
1 row in set (0.00 sec)
Listing 4-5

Listing and Using Databases—SQL Mode

Next, let’s insert some data. We will insert two rows into the table; one for each city I’ve visited recently (Charlotte, North Carolina and Daytona, Florida). In this step, we will use the INSERT SQL command to insert data. Recall from earlier, we need to format our JSON document carefully so that we don’t encounter errors. In particular, we want to add structured data including the name, country code, and district but we also want to add a JSON document that contains the population and a list (array) of places of interest. Recall from Chapter 1, we can do this in the INSERT statement by creating the JSON document inline. The following shows each of the commands we would use to insert the rows.

INSERT INTO world_x.city (Name, CountryCode, District, Info) VALUES ('Charlotte', 'USA', 'North Carolina', '{"Population": 792862, "Places_of_interest": [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]}');
INSERT INTO world_x.city (Name, CountryCode, District, Info) VALUES ('Daytona', 'USA', 'Florida', '{"Population": 590280, "Places_of_interest": [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]}');

Caution

Do not use spaces in key names in JSON documents. The SQL functions cannot correctly identify keys with spaces in them.

Although that seems a bit messy (and it is), if you read the statements carefully, you will see the JSON document is encoded as a string. For example, a well-formatted version of the JSON document for the first insert is shown following. Clearly, that’s a lot easier to read. You could enter the statement using formatting like this, but the results will be shown without the extra formatting.

Note that we retain the population key per the other rows in the table (select some and see) and we also add an array named Places_of_interest to list those places we may want to visit.

{
  "Population": 792862,
  "Places_of_interest": [
    {
      "name": "NASCAR Hall of Fame"
    },
    {
      "name": "Charlotte Motor Speedway"
    }
  ]
}

Note

I truncated the table formatting rows (the dashed lines) from the examples for brevity.

Now, let’s see how the data looks if we use a SELECT SQL statement. In this case, we’ll just select the two rows by city name because they are unique in the table. The following is an excerpt of the results.

MySQL  localhost:33060+ ssl  SQL > SELECT * FROM city WHERE Name in ('Charlotte', 'Daytona') G
*************************** 1. row ***************************
         ID: 3818
       Name: Charlotte
CountryCode: USA
   District: North Carolina
       Info: {"Population": 540828}
*************************** 2. row ***************************
         ID: 4080
       Name: Charlotte
CountryCode: USA
   District: North Carolina
       Info: {"Population": 792862, "Places_of_interest": [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]}
*************************** 3. row ***************************
         ID: 4081
       Name: Daytona
CountryCode: USA
   District: Florida
       Info: {"Population": 590280, "Places_of_interest": [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]}

That’s interesting, but it doesn’t answer the question we want to ask. That is, which cities have places of interest? To do that, we need to use a number of special functions designed for the JSON data type. All of the functions begin with the name JSON_*. Let’s see each of these in turn starting with a way to search for rows that have a specific key in the JSON document. In this case, we select all of the data for rows that have places of interest.

To determine if a JSON document has a specific key, we use the JSON_CONTAINS_PATH() function. Recall a path is simply a resolution of the keys in the document. In this case, we want to know if the JSON document contains a path for Places_of_interest. Because the function returns a 0 for no match and 1 for at least one match, we check to see if it is equal to 1. You can omit the equality, but it is best to be pedantic when experimenting with new features and commands. We also use the ‘all’ option to tell the function to return all of the matches (values) as opposed to ‘one’, which returns only the first occurrence. You can also use the slightly more correct IS NOT NULL comparison.

MySQL  localhost:33060+ ssl  SQL > SELECT * FROM city WHERE JSON_CONTAINS_PATH(info, 'all', '$.Places_of_interest') = 1 G
*************************** 1. row ***************************
         ID: 4080
       Name: Charlotte
CountryCode: USA
   District: North Carolina
       Info: {"Population": 792862, "Places_of_interest": [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]}
*************************** 2. row ***************************
         ID: 4081
       Name: Daytona
CountryCode: USA
   District: Florida
       Info: {"Population": 590280, "Places_of_interest": [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]}
2 rows in set (0.00 sec)

Now, let’s say we only want to see those places of interest and not the entire JSON document. In this case, we need to use the JSON_EXTRACT() function to extract the values from the document. In particular, we want to search the info column for all values in the array Places_of_interest. Although that seems complicated, it isn’t too bad as you can see in the following.

MySQL  localhost:33060+ ssl  SQL > SELECT Name, District, JSON_EXTRACT(info, '$.Places_of_interest') as Sights FROM city WHERE JSON_EXTRACT(info, '$.Places_of_interest') IS NOT NULL G
*************************** 1. row ***************************
    Name: Charlotte
District: North Carolina
  Sights: [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]
*************************** 2. row ***************************
    Name: Daytona
District: Florida
  Sights: [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]
2 rows in set (0.00 sec)

Now, what if we wanted to only retrieve the values for the Places_of_interest array? In this case, we can use a special format of the JSON access to get these values from the array. The following demonstrates the technique. Note the portion highlighted in bold.

MySQL  localhost:33060+ ssl  SQL > SELECT Name, District, JSON_EXTRACT(info, '$.Places_of_interest[*].name') as Sights FROM city WHERE JSON_EXTRACT(info, '$.Places_of_interest') IS NOT NULL G
*************************** 1. row ***************************
    Name: Charlotte
District: North Carolina
  Sights: ["NASCAR Hall of Fame", "Charlotte Motor Speedway"]
*************************** 2. row ***************************
    Name: Daytona
District: Florida
  Sights: ["Daytona Beach", "Motorsports Hall of Fame of America", "Daytona Motor Speedway"]
2 rows in set (0.00 sec)

Okay, now that’s a lot easier to read, isn’t it? It’s also a bit messy SQL command. And if all of that seemed a bit painful, you’re right, it was. Working with JSON data in SQL works with the help of the JSON functions, but it is an extra step and can be a bit confusing in syntax. See the online MySQL reference manual for full explanations of each of the JSON_* functions.

If you’ve used the old MySQL client much to query data with wide rows, chances are you’ve used the G option to display the results in a vertical format, which makes reading the data easier. With the shell, we don’t have that option but we can display data using the --json option. Although the option is easier to read, it tends to be a bit verbose. We will see this in action in the Python section.

Finally, we can remove the rows with the DELETE SQL command as shown in the following.

MySQL  localhost:33060+ ssl  SQL > DELETE FROM city WHERE Name in ('Charlotte', 'Daytona');
Query OK, 3 rows affected (0.00 sec)

Now, let’s see the same operations performed using JavaScript.

JavaScript

To execute the example task in JavaScript, we’re going to start the shell with the X Protocol session object and pass in the world_x schema to demonstrate how you can save a step. We will then use the getTables() method of the global db object (sometimes called a variable) to get the list of tables the world_x database. Listing 4-6 demonstrates these commands.

$ mysqlsh -uroot -hlocalhost -mx --schema=world_x
Creating an X protocol session to 'root@localhost/world_x'
Enter password:
Your MySQL connection id is 15 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
Default schema `world_x` accessible through db.
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help' or '?' for help; 'quit' to exit.
 MySQL  localhost:33060+ ssl  world_x  JS > db
<Schema:world_x>
 MySQL  localhost:33060+ ssl  world_x  JS > db.getTables();
[
    <Table:city>,
    <Table:country>,
    <Table:countrylanguage>
]
Listing 4-6

Listing and Using Databases—JavaScript Mode

Now, let’s insert the data. Note that in Listing 4-6, the result of the db.getTables() method shows three tables. We can use the table name to reference a table object by name. For example, to access the city table, we use db.city. To insert data, we will use the db.city.insert() method as shown in the following.

 MySQL  localhost:33060+ ssl  world_x  JS > db.city.insert("Name", "CountryCode", "District", "Info").values('Charlotte', 'USA', 'North Carolina', '{"Population": 792862, "Places_of_interest": [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]}');
Query OK, 1 item affected (0.00 sec)
 MySQL  localhost:33060+ ssl  world_x  JS > db.city.insert("Name", "CountryCode", "District", "Info").values('Daytona', 'USA', 'Florida', '{"Population": 590280, "Places_of_interest": [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]}');
Query OK, 1 item affected (0.00 sec)

Note

When running code interactively, you can omit the execute() function call for most create, read, update, and delete operations because the MySQL Shell explicitly executes the statements in interactive mode. For example, the insert() function would normally require chaining the execute() function to complete the operation, but you can omit it in interactive mode.

Now that we have the data, let’s select the rows with the following code. Here we use the db.city.select() method along with the where() method for the TableSelect object (the object returned from db.city.select). Note that we specify the list of columns quoted and listed inside square brackets. Within that list, we can specify data in a JSON document using the column name and the special -> operator to extract a key. In this case, we want the Places_of_interest key (path) in the document stored in the Info column.

MySQL  localhost:33060+ ssl  world_x  JS > db.city.select(["Name", "District", "Info->'$.Places_of_interest'"]).where("Info->'$.Places_of_interest' IS NOT NULL");
+-----------+----------------+--------------------------------------------+
| Name      | District       | JSON_EXTRACT(`Info`,'$.Places_of_interest')|
+-----------+----------------+--------------------------------------------+
| Charlotte | North Carolina | [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]               |
| Daytona   | Florida        | [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]        |
+-----------+----------------+--------------------------------------------+
2 rows in set (0.00 sec)

Note the column type in the result. It’s a JSON function! That means we can use a JSON function in our code to narrow the resulting column data to only the values for the Places_of_interest array as we did in the SQL example as shown in the following. How cool is that?

MySQL  localhost:33060+ ssl  world_x  JS > db.city.select(["Name", "District", "JSON_EXTRACT(info, '$.Places_of_interest[*].name')"]).where("Info->'$.Places_of_interest' IS NOT NULL");
+-----------+----------------+--------------------------------------------+
| Name      | District       | JSON_EXTRACT(`info`,'$.Places_of_interest[*].name')                         |
+-----------+----------------+--------------------------------------------+
| Charlotte | North Carolina | ["NASCAR Hall of Fame", "Charlotte Motor Speedway"]                                 |
| Daytona   | Florida        | ["Daytona Beach", "Motorsports Hall of Fame of America", "Daytona Motor Speedway"]     |
+-----------+----------------+--------------------------------------------+
2 rows in set (0.00 sec)

Now, let’s remove the rows we added to restore the data.

MySQL  localhost:33060+ ssl  world_x  JS > db.city.delete().where("Name in ('Charlotte', 'Daytona')");
Query OK, 2 items affected (0.00 sec)

Okay, that wasn’t so bad. If you’re thinking it seems more programmatic than SQL and perhaps even a bit more intuitive, they you’re on the right track. Don’t worry if it seems a bit strange. The more you use scripting in the shell, the easier and more natural it will become. It is also good practice because the future of working with MySQL is the MySQL Shell and scripting languages!

Now, let’s see the same script executed as Python.

Python

Because we’ve already seen the task demonstrated twice, I skip the details of the execution of each step and show you the transcript of my Python session.

One thing you will notice right away is that once we get the tables from the db object, the code is the same as the JavaScript example except the names of the functions are spelled a bit different. This is by design. Because the db object is actually a special variable in the shell, it has the same syntax in both languages. You only see differences when you start using the X DevAPI objects, which we will see in more detail in Chapter 5.

Note

The general rule is that JavaScript uses camelCase and Python uses underscore_separated names when the function is composed by multiple names. For example, createCluster() and create_cluster(), respectively. In cases where the functions are a single word, the names are the same, that is, “select”, “insert”, “delete”.

Listing 4-7 shows the complete transcript of running the task using Python. Note that the only difference is the call for getting tables. In this case, we use db.get_tables() method in Python. It’s the same method with the same functionality only it is named differently in accordance with typical Python naming conventions.

$ mysqlsh -uroot -hlocalhost -mx --py --schema=world_x
Creating an X protocol session to 'root@localhost/world_x'
Enter password:
Your MySQL connection id is 19 (X protocol)
Server version: 8.0.11 MySQL Community Server (GPL)
Default schema `world_x` accessible through db.
MySQL Shell 8.0.11
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help' or '?' for help; 'quit' to exit.
 MySQL  localhost:33060+ ssl  world_x  Py > db
<Schema:world_x>
 MySQL  localhost:33060+ ssl  world_x  Py > db.get_tables()
[
    <Table:city>,
    <Table:country>,
    <Table:countrylanguage>
]
 MySQL  localhost:33060+ ssl  world_x  Py > db.city.insert("Name", "CountryCode", "District", "Info").values ('Charlotte', 'USA', 'North Carolina', '{"Population": 792862, "Places_of_interest": [{"name": "NASCAR Hall of Fame"}, {"name": "Charlotte Motor Speedway"}]}')
Query OK, 1 item affected (0.00 sec)
 MySQL  localhost:33060+ ssl  world_x  Py > db.city.insert("Name", "CountryCode", "District", "Info").values('Daytona', 'USA', 'Florida', '{"Population": 590280, "Places_of_interest": [{"name": "Daytona Beach"}, {"name": "Motorsports Hall of Fame of America"}, {"name": "Daytona Motor Speedway"}]}')
Query OK, 1 item affected (0.00 sec)
 MySQL  localhost:33060+ ssl  world_x  Py > db.city.select(["Name", "District", "JSON_EXTRACT(info, '$.Places_of_interest[*].name')"]).where("Info->'$.Places_of_interest' IS NOT NULL")
+-----------+----------------+--------------------------------------------+
| Name      | District       | JSON_EXTRACT(`info`,'$.Places_of_interest[*].name')                         |
+-----------+----------------+--------------------------------------------+
| Charlotte | North Carolina | ["NASCAR Hall of Fame", "Charlotte Motor Speedway"]                                 |
| Daytona   | Florida        | ["Daytona Beach", "Motorsports Hall of Fame of America", "Daytona Motor Speedway"]     |
+-----------+----------------+--------------------------------------------+
2 rows in set (0.00 sec)
 MySQL  localhost:33060+ ssl  world_x  Py > db.city.delete().where("Name in ('Charlotte', 'Daytona')")
Query OK, 2 items affected (0.00 sec)
Listing 4-7

Listing, Inserting, Selecting, and Deleting in Databases—Python Mode

Note how the code is similar to the JavaScript version. This makes learning the X DevAPI easier because you can use your favorite language and even when you must use another language, everything is familiar. Cool.

What About Other Languages?

Although the shell currently only supports JavaScript and Python, the X DevAPI is not limited to these languages. In fact, you can also use Java, .Net, and also C++ via the appropriate connector to work with the X DevAPI. See the links under the X DevAPI heading on http://dev.mysql.com/doc/ for more information about writing applications with the X DevAPI using the respective connector.

Summary

The MySQL Shell is a huge leap forward in technology for MySQL clients. Not only is it designed to work with SQL in MySQL in a smarter way; it is also designed to enable prototyping of JavaScript and Python. You can work with any language you want and switch between them easily without having to restart the application or drop the connection. How cool is that?

If that wasn’t enough, the added benefit of the X DevAPI and built-in objects make using the shell as a front end to the document store means you don’t have to write separate applications to manage your data. You simply choose the mode (language) that fits your needs, switch to that language, and perform the tasks. As we learned in Chapter 1, the shell also forms the front end to the newest features including the InnoDB Cluster giving you a one-stop client for all your MySQL administrative, programming, and high availability needs.

In this chapter, we learned how to use the MySQL Shell including a look at the start-up options, shell commands, connections, sessions, and we even learned how to do a bit of interactive scripting in JavaScript and Python. This chapter therefore is the key chapter for learning how to get started with the MySQL Shell and working with JSON and relational data. Although this chapter is not an exhaustive coverage of all the features of the MySQL Shell, it provides a broad tutorial for how to use it for the most common tasks.

In Chapter 5, I explore X DevAPI in more detail including a closer look at the objects and facilities available for writing applications and scripts. I discuss full scripts in both JavaScript and Python to access the document store.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.15.43