1. Trang chủ
  2. » Công Nghệ Thông Tin

Pro MySQL experts voice in open source phần 10 ppt

76 184 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Troubleshooting MySQL Connection And Server Issues
Trường học Unknown School
Chuyên ngành Database Management
Thể loại Guide
Năm xuất bản 2005
Thành phố Unknown City
Định dạng
Số trang 76
Dung lượng 562,16 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

• Check the following MySQL documentation: • What to do if MySQL keeps crashing: http://dev.mysql.com/doc/mysql/en/reproduceable-test-case.html • Table maintenance: http://dev.mysql.com/

Trang 1

The following are a few ways of discovering the cause of a broken MySQL connection:

• To verify that it was a connection problem, reconnect and issue the statement again

If the statement runs successfully, you probably encountered a timeout

• If the connection is broken when you run the query a second time, check the value

of your max-allowed-packet setting You can also look in the error log to see if aPacket too largemessage is logged If so, increase the max-allowed-packet value

• Check with your database administrator to see if he killed your connection

Note The database administrator should immediately contact users with a notification that their

connec-tion was causing a problem and was killed, and help them work through the problem

• If you don’t have a problem with the packet size, carefully examine the syntax of yourquery MySQL will sometimes close the connection if the query syntax is incorrect

Make sure all of your join fields are specified You may want to reduce the complexity

of the query, and gradually build it piece by piece to get back to the original complexquery

• If, in building a query, you find that some combination of valid SQL syntax generatesthis error, you may have stumbled into a MySQL bug (rare, but possible) See the “How

to Report MySQL Bugs” section later in this chapter for information about finding andreporting bugs to MySQL AB

For more information, refer to http://dev.mysql.com/doc/mysql/en/gone-away.html andhttp://dev.mysql.com/doc/mysql/en/communication-errors.html

Troubleshooting Start, Restart, and Shutdown Issues

In this section, we’ll discuss common problems related to starting and shutting down the

server properly, including the following:

• Determining whether the server crashed

• Problems starting the MySQL server

• Problems stopping the MySQL server

• Unexpected restarts

Note While MySQL aims to make every server installation a bump-free and quick process, you may run

into trouble when installing or upgrading your server See Chapter 14 for information that will help if you

have problems installing or upgrading a MySQL database

Trang 2

Did the Server Crash?

Depending on the message you get from the client, you may not be sure if the database serverrestarted or if you just had an issue with a client or a query It is sometimes confusing trying

to determine how significant the event was Although a client connection getting closed isimportant to resolve, most administrators would consider a server restart far more serious.Being aware of where the problem occurred is important

You have several ways to determine when the server last restarted One way is to use themysqladmin versioncommand and check the uptime to determine if the server has recentlyrestarted Output from this command is shown in Listing 20-7 As you can see on the Uptimeline, the server has been up for ten days, meaning that, in this example, the message you justgot from the client was not because the server restarted

Listing 20-7.Output from mysqladmin version

# mysqladmin version

mysqladmin Ver 8.41 Distrib 5.0.6-beta, for unknown-linux-gnu on x86_64

Server version 5.0.6-beta-max-log

Protocol version 10

Connection Localhost via UNIX socket

UNIX socket /tmp/mysql.sock

Uptime: 10 days 21 hours 58 min 21 sec

Threads: 1 Questions: 858 Slow queries: 0 Opens: 0 Flush tables: 1

Open tables: 3 Queries per second avg: 0.001

You can also get the uptime in seconds from within the MySQL shell, by using the SHOW VARIABLES LIKE 'uptime'command The output of this command is shown in Listing 20-8

Listing 20-8.Uptime from MySQL Client

mysql> SHOW VARIABLES like 'uptime';

1 row in set (0.00 sec)

Another method for seeing if the database has recently restarted, and to get the history

of activity over time, is to check the error log Listing 20-9 shows the output of the log with anegrepfor messages that indicate the server has stopped, started, or restarted If you find unex-plained entries in this output, you should look more closely at the error log and general querylog to compare database activity with the unexplained server restarts to determine what might

be the cause of the problem

Trang 3

Listing 20-9.egrep of Error Log

shell> egrep "(ended|started|restarted)" promysql.err

For more information about the mysqld_safe startup script, see http://dev.mysql.com/

doc/mysql/en/mysqld-safe.html For what to do if MySQL keeps crashing, refer to http://

dev.mysql.com/doc/mysql/en/crashing.html

Problems Starting MySQL Server

Have you ever started the MySQL server only to find that, before you can connect, the MySQL

server daemon ended? In MySQL version 5.0.4, the mysql.server script changed a bit to

pre-vent the server from indicating it started up only to shut right back down As of MySQL 5.0.4,

when you issue the start command, you wait until the database has started, and then get a

success message:

/etc/init.d/mysql start

Starting MySQL SUCCESS!

Evidence of the Problem

The most common way to find that your server won’t start is to wait in suspense as the server

startup process runs, and then see it finally indicates an error occurred:

/etc/init.d/mysql start

Starting MySQL ERROR!

If you aren’t using the startup script, the common indicator is the mysql ended message

in the logs or on the console where the server was started Also, starting the server using

the MySQL binary itself will keep the process and messages in the forefront, as shown in

Listing 20-10

Trang 4

Listing 20-10.Running MySQL Without a Startup Script

./bin/mysqld

050430 14:56:32 [Warning] Can't create test file /data/mysql/promysql.lower-test./bin/mysqld: Can't change dir to '/data/mysql/' (Errcode: 2)

050430 14:56:32 [ERROR] Aborting

Seeing the error about /data/mysql shown in Listing 20-10, you would check what’s going

on in the /data/mysql directory where your data files are stored You might learn that the datadirectory is not properly mounted

Solutions

Following are some steps to take when you have problems starting up MySQL:

• Check to see if MySQL is already running, or if the network port you are using forMySQL is being used by another process

• Check the error logs to determine if any abnormal event was logged

• Be sure your directories and data file permissions are set for the MySQL user and group

• If the startup fails with an unknown option, fix the offending option

• Check to see if there are missing data or log directories specified in the configuration file

• If all of your existing options seem correct and your directories are fine, but you still are not seeing any log information, start MySQL using just the daemon itself with./bin/mysqld, and see what kind of output is generated

For more information about the MySQL startup script, see http://dev.mysql.com/doc/mysql/en/mysql-server.html

Problems Stopping MySQL Server

In rare cases, you may find that you cannot seem to stop the MySQL server Most often, this isrelated to a thread being busy in the database

Evidence of the Problem

You’ll see this problem when you attempt to stop the MySQL server:

sudo /etc/init.d/mysql stop

And instead of the typical, few seconds to stop the database, the wait continues until yourdatabase indicates it can’t be stopped:

Killing mysqld with pid 32441

Wait for mysqld to exit gave up waiting!

Or, with the MySQL 5.0.4 and later mysql.server script, you’ll see that the stop processends in an error:

/etc/init.d/mysql stop

Shutting down MySQL ERROR!

Trang 5

Here are a few things to check and do if you are having a problem shutting down MySQL:

• You may have a thread that is busy and is preventing the server from stopping Use theSHOW PROCESSLISTcommand to identify queries that are in progress Killing the connec-tion may be what’s required to stop MySQL

• Before stopping the database, stop resources (like Apache) that maintain connections

to MySQL that could prevent the database from stopping

• Is the MySQL server actually running? Look at processes and verify that MySQL is ning If the PID file exists, the error will come back even if the process isn’t running Ifyour server stopped abnormally and didn’t have a chance to remove the PID file, it willattempt to shut down as if it were running

run-■ Caution When you’re having issues with shutting down a server, you may be tempted to use the

operat-ing system to force MySQL to exit If MySQL won't shut down because it's busy writoperat-ing data and you force it

to, you may end up with corrupt or missing data Use the operating system-level process termination

com-mand or tool only as a last resort

For more information, see http://dev.mysql.com/doc/mysql/en/mysql-server.html

Problems with Unexpected Restarts

A server unexpectedly restarting can lead to a lot of stress If you are in an environment where

every second counts, not knowing when the next server restart is going to happen may be

unac-ceptable For other database uses, unexpected restarts are less damaging, but still unnerving If

you have experienced unexpected restarts, you’ll want to know what caused them and how to

prevent them in the future

Evidence of the Problem

Although a restart by mysqld_safe happens quickly, it is easily noticed by an application under

heavy usage when connections can’t be made for the small amount of time the server is down

during the restart If a restart goes unnoticed, or to figure out the exact timing, you can see the

entry (or entries) by doing a grep "restarted" host.err

Trang 6

• Server restarts are a sign of corruption in the database tables You should go throughthe steps to check the status of your tables and repair them if necessary The next sec-tion provides more information about data corruption.

• Perform troubleshooting tasks on the operating system and hardware A defective disk,damaged RAID controller, or faulty RAM can affect MySQL’s ability to function and maycause the database to restart during certain failures

• Check the following MySQL documentation:

• What to do if MySQL keeps crashing: http://dev.mysql.com/doc/mysql/en/reproduceable-test-case.html

• Table maintenance: http://dev.mysql.com/doc/mysql/en/table-maintenance.html

• Check MyISAM tables: http://dev.mysql.com/doc/mysql/en/myisamchk-syntax.html

• Repair MyISAM tables: http://dev.mysql.com/doc/mysql/en/repair.html

Resolving Data Corruption

As hard as MySQL developers work to perfect the database software, and database tors work to keep their systems protected, data corruption does occur The MySQL developmentteam takes data corruption very seriously and provides a set of instructions to follow to create areproducible bug that will allow them to identify where the corruption is happening

administra-Evidence of the Problem

The corrupted data files often show up in the form of a server crash or unexpected restart.They cause queries to fail or to return unexpected results (or no results) A more proactiveapproach for databases using the MyISAM storage engine is to regularly run the mysqlcheckscript to determine if any tables are corrupted

The following are some reasons that you might experience data file corruption:

• The server was killed in the middle of an update

• A bug caused MySQL to stop while writing to disk

• An external program is manipulating the data files

• Multiple servers are pointed to the same data files

• A corrupted data file caused the server to act improperly and corrupt other data

• A storage engine bug caused bad data to be written

• The operating system, hardware, or disks may be faulty

Trang 7

If you encounter a corrupt data file, here are some areas to look into:

• Be sure you have backups of your data Yes, once you’ve discovered there is corruption

it may be too late, but we hope you’ve had enough foresight to create regular backups(see Chapter 17 for details about backing up MySQL)

• If you are using MyISAM tables, run the mysqlcheck or myisamchk script to repair the table

• If you can still get your database to run and use the table, do a mysqldump of the table,DROPthe table, and then import the data from the dump (Chapter 17 describes how touse mysqldump.)

• Follow MySQL’s steps to create a repeatable situation and contact MySQL with the essary information You can find these steps at http://dev.mysql.com/doc/mysql/en/

nec-reproduceable-test-case.html

You can refer to the MySQL documentation for checking and recovering MyISAM tables,

at http://dev.mysql.com/doc/mysql/en/myisamchk-syntax.html and http://dev.mysql.com/

doc/mysql/en/crash-recovery.html, respectively

How to Report MySQL Bugs

It is possible that, in your use of MySQL, you encounter a bug MySQL doesn’t release software

marked as production-ready until all known fatal bugs are resolved MySQL defines a fatal bug

as one that causes the server to crash under normal use, gives the wrong answer for a normal

query, or contains a security problem That being said, there is an active bug-tracking system

that allows database users to submit bugs and track their status as they go through the system

If you think you’ve found a bug, follow the steps outlined in the MySQL documentationfor submitting a bug report (http://dev.mysql.com/doc/mysql/en/bug-reports.html) This

involves the following steps:

• Make sure it’s a repeatable bug test-case.html)

(http://dev.mysql.com/doc/mysql/en/reproduceable-• Search the existing documentation and mailing lists to see if there is a resolution

• Search through the bug reports to see if it has been reported(http://dev.mysql.com/doc/mysql/en/open-bugs.html)

• Finally, submit the bug report with information about your environment and how toduplicate the bug

The MySQL team follows the bug-tracking system very closely and usually gets to work on

a bug report within just a few hours

Trang 8

Support Options

A chapter on troubleshooting wouldn’t be complete without mentioning support options.Each organization has different needs, and you have a wide spectrum of options when you’relooking for support for your MySQL installation What matches your needs will depend onwhat assistance you require and when you require it

Here are some support options:

Mailing lists: If you have some expertise with MySQL, and your troubleshooting priorities

allow you time to search and post, you can get a lot of information and help from theMySQL mailing lists The collective group of people who participate have a great deal ofexpertise, and response time is typically pretty good (provided you have good manners).Even if you have a critical problem that is happening in real time, it’s still worth trying out

a mailing list to get help exploring the issue and formulating a strategy to resolve it Thereare several MySQL mailing lists Unless you have a specific question about a particularpiece of MySQL that has its own mailing list, the general user mailing list is the place to

go For a list of all of MySQL mailing lists, along with the list archives and instructions forsubscription, visit http://lists.mysql.com/

Consultants: If you are running an instance of MySQL, but don’t have the time, interest, or

ability to resolve a problem, a consultant may be the right person to step in A web searchfor “MySQL consultant” brings up hundreds of links leading to people who have experi-ence with MySQL and are looking for opportunities to apply their knowledge andexperience

Help from MySQL AB: If you are looking for MySQL expertise, why not turn to the folks

who are building the database? MySQL AB offers several consulting packages, including aone-day rapid response service for urgent needs (a certified consultant will work with you

on troubleshooting, performance, architecture, or any of your MySQL needs) Anotheroption from MySQL AB is the MySQL Network (http://www.mysql.com/network/), a serv-ice that gives you access to production support and MySQL developers to help solve yourunique issues The MySQL Network also provides certified releases of the MySQL database

Summary

Troubleshooting a database server can be a stressful experience, especially if the problem isoccurring in your production environment and affecting the availability of your application

A good database administrator is familiar with the details of MySQL and knows exactly what

to do when a situation arises This includes having a thorough knowledge of how to use thetroubleshooting tools and where to look for answers

We spent a significant portion of the chapter discussing the various tools and logs that arethe foundation for dealing with specific problems We then went through a number of differ-ent common problems and gave details on possible causes and solutions Our goal was toprovide some detailed information, as well as to show you examples of the methodology forworking through problems

As you combine the knowledge of MySQL administration with the honing of your time problem-solving skills, you will become more capable of surviving a problem in yourdatabase without unnecessary stress and wasted time This, in turn, will please the users ofyour database, as well as your manager, customers, and clients

Trang 9

real-MySQL Data Dictionary

In this chapter, we’ll be taking a closer look at a feature of MySQL 5 that’s receiving

consider-able attention As of version 5.0.2, the INFORMATION_SCHEMA virtual database is availconsider-able, which

offers a standardized way of reading meta information about the database server and its

schemas In this chapter, we’ll examine what exactly the INFORMATION_SCHEMA data store is,

how you can use it, and what information is contained inside it

Before we go further, we want to discuss a few terms used in this chapter The discussion

of a database server’s meta information commonly involves the following terms:

• metadata

• data dictionary or system catalog

• INFORMATION_SCHEMA The definition of metadata is simply data about other data Metadata describes or sum-

marizes another piece of data Examples of metadata include the number of rows in a table,

the type of index structure used on a set of columns, or the statement used to create a stored

procedure Each of these pieces of data describes another piece of data or structure

All major database vendors have a repository, or container, for metadata, but differentdatabase vendors refer to this repository differently The two most common terms, however,

are data dictionary and system catalog We consider them synonymous, but when referring to

the metadata repository, we’ll use the term data dictionary

The term INFORMATION_SCHEMA describes the ANSI standard interface to the database

server’s metadata The INFORMATION_SCHEMA is not an actual schema (database), but the data

contained inside this virtual database can be accessed just like any other database on the

server In this way, the INFORMATION_SCHEMA interface acts as a standardizing component for

accessing information about the database server and its actual schema The “tables” inside

this virtual database aren’t tables at all, but rather table-like data that is pulled from a variety

of sources, including the underlying mysql system database, and the MySQL server system

variables and counters

In this way, the INFORMATION_SCHEMA tables are more like views than tables If you’re comingfrom a Microsoft SQL Server background, you’ll recognize this concept, as the INFORMATION_SCHEMA

supported by Microsoft SQL Server are views that pull actual data from the Microsoft SQL Server

system tables, such as sys_objects and sys_indexes INFORMATION_SCHEMA views are read-only,

partly because the data contained in the INFORMATION_SCHEMA views isn’t contained in a single

location, but instead pulled from the storage areas noted earlier

669

C H A P T E R 2 1

■ ■ ■

Trang 10

In this chapter, we’ll be looking at the following topics related to the new INFORMATION_SCHEMAfeature of MySQL 5:

• Benefits of a standardized interface

• The INFORMATION_SCHEMA views

• Examples of usage

Benefits of a Standardized Interface

Before we get into the specific tables that comprise the MySQL Data Dictionary, we want you

to understand why the data dictionary has been added as a feature to the MySQL 5 sourcecode For those of you without much experience with MySQL’s SHOW commands, the transition

to using the INFORMATION_SCHEMA database might take some getting used to, but we highly ommend taking the time to do so

rec-There are three main advantages to the INFORMATION_SCHEMA interface versus the SHOWcommands:

• Adherence to standards

• Using SELECT to retrieve metadata

• More information than SHOW commands

Adherence to Standards

MySQL’s SHOW commands are proprietary and not standards-compliant By contrast, theINFORMATION_SCHEMAinterface is a standard outlined by ANSI/ISO as part of the SQL-99 andSQL:2003 standards

One advantage to complying with these standards is that applications that rely on queryingfor metadata—for example, a monitoring application—can be written in a portable fashion Thedatabases supporting INFORMATION_SCHEMA views are MySQL, Microsoft SQL Server, and, to someextent, IBM’s DB2 database Hopefully, in the future, all major database vendors will move to fullcompliance, and application code can be truly vendor-agnostic Having metadata queries writtenfor the INFORMATION_SCHEMA interface is a proactive stance for future portability needs

To adhere completely to the SQL standard, MySQL’s implementation of the INFORMATION_SCHEMAshows columns for which MySQL has no equivalent data For these columns—forinstance, the INFORMATION_SCHEMA.TABLES.TABLE_CATALOG column—MySQL simply displays

a NULL value, because MySQL has no concept of a database “catalog.” In addition, MySQL displays certain additional data pieces in the INFORMATION_SCHEMA output where MySQL storesnonstandard or extension information This is done to provide complete equivalency to theMySQL SHOW commands We’ll detail later where the MySQL implementation diverges from the ANSI standard

Using SELECT to Retrieve Metadata

Perhaps the best reason to use the INFORMATION_SCHEMA views is that you can access metadatathrough your standard SQL SELECT statements Instead of various SHOW commands—such asSHOW TABLES, SHOW FULL COLUMNS, and so on—you access the data through the old familiarSELECTstatement

Trang 11

This means you’ll have to learn the INFORMATION_SCHEMA views, to ensure you know where

to look for information However, the advantage to using SELECT here is that you don’t have

to learn any new syntax to read information from the INFORMATION_SCHEMA You can use the

various joins you learned in Chapter 7 to present views of related metadata in a way that was

impossible before Because the INFORMATION_SCHEMA is accessible through standard SQL

state-ments, you can operate on the data sets returned from a query on the INFORMATION_SCHEMA

tables as you would any other SQL statement This makes it easy to construct complex SELECT

statements that use the information in the INFORMATION_SCHEMA views like any other table in

your other databases

More Information than SHOW Commands

As you’ll see in the following section, the INFORMATION_SCHEMA offers you more detailed

infor-mation than equivalent SHOW commands In some cases, a single SELECT statement against the

INFORMATION_SCHEMAviews can output more than what multiple SHOW commands could provide

Note To use the INFORMATION_SCHEMAviews, the user must be granted privileges on the object that

the view represents Therefore, although no special privilege is needed to issue a SELECTagainst the

INFORMATION_SCHEMA, the results of certain SELECTs on the metadata repository depend on which

schema, tables, or columns the user has been granted access to

The INFORMATION_SCHEMA Views

In this section, we cover each of the views available under the INFORMATION_SCHEMA, and

out-line which columns returned from the view equate to the prior SHOW command, if one existed

We use simple examples in this section to highlight the information available from the

follow-ing INFORMATION_SCHEMA views:

Trang 12

It’s worth noting again here that the results displayed from the INFORMATION_SCHEMA viewsare specific to the user logged in That means that only schemata, tables, or columns to whichthe user has been granted access appear in the resultsets

In the following subsections, for each INFORMATION_SCHEMA view, we show you the DESCRIBE

of the view, a simple SELECT on the view, then in a bulleted list, we define what each of the output columns contains For each section, you’ll see a note block detailing which SHOWcommands, if any, correspond to the new INFORMATION_SCHEMA view

Instead of arranging the views in alphabetical order, we’ve ordered them in groups thatmost closely relate to one another For instance, we’ve grouped the privileges views togetherand the character set and collation views together This order will help give you an idea of therelationship of the view data

In the following sections, fields that are not part of the ANSI standard appear in italics to

denote that the column is a MySQL-specific data element These fields have been left in theINFORMATION_SCHEMAoutputs as an extension to allow equivalent output to some SHOW com-mands If you’re attempting to create cross-platform portable SQL code, please be aware ofthese extension fields

Note Two quick notes before we get into the views First, some of the following examples were issuedagainst the test.http_authtable created and used in Chapter 6 If you get an empty resultset for some ofthe examples, either follow along in the reading, or refer to Chapter 6 for creation of the http_authtable inthe testdatabase

Second, depending on your operating system and version of MySQL, you may notice slight differences in some

of the output Notably, depending on the version of MySQL you use, a VARCHAR(4096) column displayed inresults in this chapter may appear as VARCHAR(4095), or in a Windows environment,VARCHAR(512) Theseare minor discrepancies, and as the data dictionary features of MySQL 5 are an evolving work, these data typesmay have changed by the time we go to print

Trang 13

The SCHEMATA view shows information about the databases on the server Listing 21-1 shows

the columns displayed by the view

4 rows in set (0.04 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.SCHEMATA;

+ -+ -+ -+ -+

| CATALOG_NAME | SCHEMA_NAME | DEFAULT_CHARACTER_SET_NAME | SQL_PATH |

+ -+ -+ -+ -+

| NULL | information_schema | utf8 | NULL |

| NULL | mysql | latin1 | NULL |

| NULL | test | latin1 | NULL |

+ -+ -+ -+ -+

3 rows in set (0.02 sec)

The fields contained in INFORMATION_SCHEMA.SCHEMATA are as follows:

• CATALOG_NAME: This field will always be NULL, as MySQL doesn’t have any concept of acatalog It’s provided to maintain the ANSI standard output

• SCHEMA_NAME: This is the name of the database

• DEFAULT_CHARACTER_SET_NAME: This is the name of the default character set for the base We discuss the INFORMATION_SCHEMA.CHARACTER_SETS view later in the chapter

data-• SQL_PATH: This field will always be NULL MySQL doesn’t use this value to “find” the filesassociated with the database It’s included for compatibility with the ANSI standard

Although the SCHEMATA view isn’t the most useful of the INFORMATION_SCHEMA views, it doescontain the database’s default character set, while the corresponding SHOW DATABASES command

doesn’t

Note The SHOW DATABASEScommand is the closest command to SELECT * FROM INFORMATION_

SCHEMA.SCHEMATA

Trang 14

| ENGINE | varchar(64) | YES | | NULL | |

| VERSION | bigint(21) | YES | | NULL | |

| ROW_FORMAT | varchar(10) | YES | | NULL | |

| TABLE_ROWS | bigint(21) | YES | | NULL | |

| AVG_ROW_LENGTH | bigint(21) | YES | | NULL | |

| DATA_LENGTH | bigint(21) | YES | | NULL | |

| MAX_DATA_LENGTH | bigint(21) | YES | | NULL | |

| INDEX_LENGTH | bigint(21) | YES | | NULL | |

| DATA_FREE | bigint(21) | YES | | NULL | |

| AUTO_INCREMENT | bigint(21) | YES | | NULL | |

| CREATE_TIME | datetime | YES | | NULL | |

| UPDATE_TIME | datetime | YES | | NULL | |

| CHECK_TIME | datetime | YES | | NULL | |

| TABLE_COLLATION | varchar(64) | YES | | NULL | |

| CHECKSUM | bigint(21) | YES | | NULL | |

| CREATE_OPTIONS | varchar(255) | YES | | NULL | |

| TABLE_COMMENT | varchar(80) | NO | | | |

+ -+ -+ -+ -+ -+ -+

21 rows in set (0.01 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.TABLES

-> WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME = 'http_auth' \G

*************************** 1 row ***************************

TABLE_CATALOG: NULLTABLE_SCHEMA: testTABLE_NAME: http_authTABLE_TYPE: BASE TABLEENGINE: MyISAMVERSION: 9ROW_FORMAT: FixedTABLE_ROWS: 90000AVG_ROW_LENGTH: 59

DATA_LENGTH: 5310000

Trang 15

MAX_DATA_LENGTH: 253403070463

INDEX_LENGTH: 3716096DATA_FREE: 0AUTO_INCREMENT: NULL

CREATE_TIME: 2005-03-08 23:25:28UPDATE_TIME: 2005-03-08 23:29:38CHECK_TIME: NULL

TABLE_COLLATION: latin1_swedish_ci

CHECKSUM: NULLCREATE_OPTIONS:

TABLE_COMMENT:

1 row in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.TABLES are as follows:

• TABLE_CATALOG: Again, will always be NULL Shown for compatibility purposes

• TABLE_SCHEMA: The name of the database to which this table belongs

• TABLE_NAME: The name of the table

• TABLE_TYPE: Either BASE TABLE, TEMPORARY, or VIEW Those entries having a VIEW valuealso appear in INFORMATION_SCHEMA.VIEWS More details about this view come later inthe chapter

• ENGINE: The storage engine handling this table’s data.

• VERSION: The internal versioning of the table’s frm file Indicates how many times the

table’s definition has changed

• ROW_FORMAT: Either FIXED, COMPRESSED, or DYNAMIC Indicates the format of table rows

See Chapter 5 for more details on the difference between the row formats

• TABLE_ROWS: Shows the number of rows in a table.

• AVG_ROW_LENGTH: Shows the average length, in bytes, of the table’s rows.

• DATA_LENGTH: Shows the total length, in bytes, of the table’s data.

• MAX_DATA_LENGTH: Shows the maximum storage length, in bytes, that the table’s data can

consume

• INDEX_LENGTH: Shows the total length, in bytes, of the table’s indexes.

• DATA_FREE: Shows the number of bytes that have been allocated to the table’s data, but

that haven’t yet been filled with table data

• AUTO_INCREMENT: Shows the next integer number to be used on the table’s AUTO_INCREMENT

column, or NULL if no such sequence is used on the table

• CREATE_TIME: Timestamp of the table’s initial creation.

• UPDATE_TIME: Timestamp of the last ALTER TABLE command on this table If there have

been no ALTER TABLE commands, then shows the same timestamp as CREATE_TIME

Trang 16

• CHECK_TIME: Timestamp of the last time a table check was performed on the table, or

NULLif the table has never been checked for consistency

• TABLE_COLLATION: Shows the table’s default character set and collation combination

See INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY for more details

• CHECKSUM: Internal live checksum for the table, or NULL if none is available.

• CREATE_OPTIONS: Shows any options used at table creation, or nothing if none has

been used

• TABLE_COMMENT: Shows any comment used during table creation.

Clearly, the INFORMATION_SCHEMA.TABLES view has a wealth of useful information about the database tables on your MySQL server The vast majority of the columns, as you may wellhave noticed, are extension fields that MySQL has included to provide compatibility with theSHOW TABLE STATUScommand

Note The SHOW TABLE STATUScommand displays most of the information that a SELECT * FROM ➥INFORMATION_SCHEMA.TABLESwould output

INFORMATION_SCHEMA.TABLE_CONSTRAINTS

The INFORMATION_SCHEMA.TABLE_CONSTRAINTS view shows columns related to all tables forwhich a constraining index exists Listing 21-3 shows a DESCRIBE and a simple SELECT from this view

Trang 17

mysql> SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS

-> WHERE CONSTRAINT_SCHEMA = 'test' \G

*************************** 1 row ***************************

CONSTRAINT_CATALOG: NULL

CONSTRAINT_SCHEMA: test

CONSTRAINT_NAME: PRIMARYTABLE_SCHEMA: testTABLE_NAME: http_authCONSTRAINT_TYPE: PRIMARY KEY

*************************** 2 row ***************************

CONSTRAINT_CATALOG: NULL

CONSTRAINT_SCHEMA: test

CONSTRAINT_NAME: PRIMARYTABLE_SCHEMA: testTABLE_NAME: http_auth_idbCONSTRAINT_TYPE: PRIMARY KEY

2 rows in set (0.31 sec)

The fields contained in INFORMATION_SCHEMA.TABLE_CONSTRAINTS are as follows:

• CONSTRAINT_CATALOG: Again, always NULL

• CONSTRAINT_SCHEMA: Name of the database in which the table constraint (index) resides

This is always the same as the value of TABLE_SCHEMA

• CONSTRAINT_NAME: Name of the constraint

• TABLE_SCHEMA: Name of the database for the table on which the index is built

• TABLE_NAME: Name of the table on which the index is built

• CONSTRAINT_TYPE: Either PRIMARY KEY, FOREIGN KEY, or UNIQUE, depending on what engine

is handling the table, and how the key was referenced in a CREATE TABLE statement In thefuture, MyISAM tables will fully support FOREIGN KEY constraints Currently, you only seeFOREIGN KEYpop up when an InnoDB table is referenced during create time

Tip The SHOW INDEXcommand most closely resembles the output from INFORMATION_SCHEMA

TABLE_CONSTRAINTS The CONSTRAINT_TYPEcolumn contains similar information to the KEY_NAME

column returned by SHOW INDEXfor entries with a NON_UNIQUEvalue of 0

Trang 18

The INFORMATION_SCHEMA.COLUMNS view shows detailed information about the columns tained in the server’s database tables Listing 21-4 shows a DESCRIBE and a simple SELECTfrom the view

| NUMERIC_PRECISION | bigint(21) | YES | | NULL | |

| NUMERIC_SCALE | bigint(21) | YES | | NULL | |

| CHARACTER_SET_NAME | varchar(64) | YES | | NULL | |

| COLLATION_NAME | varchar(64) | YES | | NULL | |

19 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.COLUMNS

-> WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME = 'http_auth' \G

*************************** 1 row ***************************

TABLE_CATALOG: NULLTABLE_SCHEMA: testTABLE_NAME: http_authCOLUMN_NAME: usernameORDINAL_POSITION: 1COLUMN_DEFAULT:

IS_NULLABLE: NODATA_TYPE: charCHARACTER_MAXIMUM_LENGTH: 25

CHARACTER_OCTET_LENGTH: 25

Trang 19

NUMERIC_PRECISION: NULLNUMERIC_SCALE: NULLCHARACTER_SET_NAME: latin1COLLATION_NAME: latin1_swedish_ciCOLUMN_TYPE: char(25)

COLUMN_KEY: PRIEXTRA:

PRIVILEGES: select,insert,update,referencesCOLUMN_COMMENT:

… omitted

*************************** 4 row ***************************

TABLE_CATALOG: NULLTABLE_SCHEMA: testTABLE_NAME: http_authCOLUMN_NAME: gidORDINAL_POSITION: 4COLUMN_DEFAULT: 0IS_NULLABLE: NODATA_TYPE: intCHARACTER_MAXIMUM_LENGTH: 11

CHARACTER_OCTET_LENGTH: 11NUMERIC_PRECISION: 11NUMERIC_SCALE: 0CHARACTER_SET_NAME: NULLCOLLATION_NAME: NULLCOLUMN_TYPE: int(11)COLUMN_KEY:

EXTRA:

PRIVILEGES: select,insert,update,referencesCOLUMN_COMMENT:

4 rows in set (0.01 sec)

The fields contained in INFORMATION_SCHEMA.COLUMNS are as follows:

• TABLE_CATALOG: Again, always NULL

• TABLE_SCHEMA: Name of the database

• TABLE_NAME: Name of the database table or view

• COLUMN_NAME: Name of the column

• ORDINAL_POSITION: Starting with 1, position of a column in the table

• COLUMN_DEFAULT: Default value for a column in the table

• IS_NULLABLE: Either YES or NO, describing whether the column allows for NULL values

• DATA_TYPE: Shows only the data type keyword, not the entire field definition, for the column

Trang 20

• CHARACTER_MAXIMUM_LENGTH: Shows the maximum number of characters that the fieldmay contain.

• CHARACTER_OCTET_LENGTH: Shows the maximum length of the field in octets

• NUMERIC_PRECISION: Shows the precision of numeric fields, or NULL if a non-numericfield type

• NUMERIC_SCALE: Shows the scale of numeric fields, or NULL if a non-numeric field type

• CHARACTER_SET_NAME: Shows the character field character set, or NULL if a noncharacterfield type See the section “INFORMATION_SCHEMA.CHARACTER_SETS.”

• COLLATION_NAME: Shows the character field collation set, or NULL if a noncharacter fieldtype See the section “INFORMATION_SCHEMA.COLLATIONS.”

• COLUMN_TYPE: Shows the full field definition for the column.

• COLUMN_KEY: Shows any of PRI, UNI, MUL, or blank PRI appears when the column is part

of a PRIMARY KEY UNI appears when the column is part of a UNIQUE INDEX MUL appearswhen the column is part of an index that allows for duplicates Blank appears for allother columns

• EXTRA: Shows any extra information about the column that MySQL stores; for instance,

the AUTO_INCREMENT keyword

• PRIVILEGES: Shows a list of privileges available to the current user for this column.

• COLUMN_COMMENT: Shows the comment used during table creation.

Note The SHOW FULL COLUMNScommand is the closest equivalent to a SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'table_name'

The COLUMNS view has a wealth of information that doesn’t appear in the SHOW FULL ➥COLUMNS output The most useful part of the view output is that you get a normalized output fornumeric precision and scale, the data type, and the ordinal position of the column within thetable This means you can avoid scripts that must parse out the non-normalized SHOW COLUMNSoutput You’ll see an example of this usage later in the chapter

INFORMATION_SCHEMA.KEY_COLUMN_USAGE

The INFORMATION_SCHEMA.KEY_COLUMN_USAGE view details information about the columns used

in a table’s indexes or constraints Listing 21-5 shows an output from DESCRIBE and a simpleSELECTfrom the view

Trang 21

9 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE

-> WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME = 'http_auth' \G

*************************** 1 row ***************************

CONSTRAINT_CATALOG: NULLCONSTRAINT_SCHEMA: testCONSTRAINT_NAME: PRIMARYTABLE_CATALOG: NULLTABLE_SCHEMA: testTABLE_NAME: http_authCOLUMN_NAME: usernameORDINAL_POSITION: 1POSITION_IN_UNIQUE_CONSTRAINT: NULL

1 row in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.KEY_COLUMN_USAGE are as follows:

• CONSTRAINT_CATALOG: Always NULL

• CONSTRAINT_SCHEMA: Name of the database containing the constraint

• CONSTRAINT_NAME: Name of the constraint

• TABLE_CATALOG: Always NULL

• TABLE_SCHEMA: Name of the database containing the table in which the constraint can

be found Is always the same value as CONSTRAINT_SCHEMA

• TABLE_NAME: Name of the table on which the constraint or index operates

Trang 22

• COLUMN_NAME: Name of the column in the constraint.

• ORDINAL_POSITION: Position of the column within the index or constraint, starting at thenumber 1

• POSITION_IN_UNIQUE_CONSTRAINT: Either NULL, or the position of the column in a enced FOREIGN KEY constraint that happens to be a UNIQUE INDEX

refer-The KEY_COLUMN_USAGE data is useful for identifying column positioning in constraints ontables There’s no equivalent SHOW command that returns the same information

INFORMATION_SCHEMA.STATISTICS

The INFORMATION_SCHEMA.STATISTICS view displays information regarding the indexes ing on the server’s tables or views Listing 21-6 shows a DESCRIBE and a simple SELECT from the view

| COLLATION | varchar(1) | YES | | NULL | |

| CARDINALITY | bigint(21) | YES | | NULL | |

| SUB_PART | bigint(3) | YES | | NULL | |

| PACKED | varchar(10) | YES | | NULL | |

| NULLABLE | varchar(3) | NO | | | |

| INDEX_TYPE | varchar(16) | NO | | | |

| COMMENT | varchar(16) | YES | | NULL | |

+ -+ -+ -+ -+ -+ -+

15 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.STATISTICS

-> WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME = 'http_auth' \G

*************************** 1 row ***************************

TABLE_CATALOG: NULL

TABLE_SCHEMA: test

TABLE_NAME: http_authNON_UNIQUE: 0

INDEX_SCHEMA: test

Trang 23

INDEX_NAME: PRIMARYSEQ_IN_INDEX: 1

COLUMN_NAME: usernameCOLLATION: ACARDINALITY: 90000SUB_PART: NULLPACKED: NULLNULLABLE:

INDEX_TYPE: BTREECOMMENT:

1 row in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.STATISTICS are as follows:

• TABLE_CATALOG: Always NULL

• TABLE_SCHEMA: Name of the database in which the table resides

• TABLE_NAME: Name of the table on which the index operates

• NON_UNIQUE: Either 0 or 1 Indicates whether the index can contain duplicate values

Note that NON_UNIQUE returns a numeric Boolean representation, as opposed to YES

or NO

• INDEX_SCHEMA: Name of the database in which the index is housed It’s always the same

as TABLE_SCHEMA

• INDEX_NAME: Name of the index within the schema

• SEQ_IN_INDEX: Shows the position of this column within the index key, starting at position 1

• COLUMN_NAME: Name of the column in the index key

• COLLATION: The column’s collation Will either be A for an ascending index order, or NULLfor descending

• CARDINALITY: The number of unique values contained in this column for this index key

• SUB_PART: If a prefix on a character field was used in the creation of the index, SUB_PARTwill show the number of characters that the index column uses; otherwise NULL

• PACKED: Either 0, 1, or DEFAULT depending on whether the index is packed See Chapter 5for more information about MyISAM key packing

• NULLABLE: Either YES or NO, indicating whether the column can contain NULL values

• INDEX_TYPE: Any of BTREE, RTREE, HASH, or FULLTEXT

• COMMENT: Any comment used during creation of the index; otherwise blank

The STATISTICS view has a wealth of information about the columns used in your indexes

We’ll be using this table in the following examples to get a feel for the selectivity of your

indexes, so stay tuned

Trang 24

Note The SHOW INDEXcommand most closely resembles the output from a SELECT * FROM ➥INFORMATION_SCHEMA.STATISTICS WHERE TABLE_NAME = 'table_name';.

INFORMATION_SCHEMA.ROUTINES

The INFORMATION_SCHEMA.ROUTINES view details information about the stored procedures anduser-defined functions created on your system Listing 21-7 shows the output of DESCRIBEand a simple SELECT on the view

| EXTERNAL_NAME | varchar(64) | YES | | NULL | |

| EXTERNAL_LANGUAGE | varchar(64) | YES | | NULL | |

20 rows in set (0.01 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.ROUTINES \G

*************************** 1 row ***************************

SPECIFIC_NAME: test_proc1ROUTINE_CATALOG: NULLROUTINE_SCHEMA: testROUTINE_NAME: test_proc1ROUTINE_TYPE: PROCEDURE

Trang 25

DTD_IDENTIFIER: NULLROUTINE_BODY: SQLROUTINE_DEFINITION: BEGIN

SELECT COUNT(*) INTO param1 FROM http_auth;

END

EXTERNAL_NAME: NULLEXTERNAL_LANGUAGE: NULL

PARAMETER_STYLE: SQLIS_DETERMINISTIC: NOSQL_DATA_ACCESS: CONTAINS SQLSQL_PATH: NULL

SECURITY_TYPE: DEFINERCREATED: 2005-04-10 13:21:58LAST_ALTERED: 2005-04-10 13:21:58SQL_MODE:

ROUTINE_COMMENT:

DEFINER: root@localhost

1 row in set (0.00 sec)

The listing shows a simple test procedure we’ve created in the test schema for illustrationpurposes If you’re unfamiliar with stored procedures, please refer to Chapter 9

The fields contained in INFORMATION_SCHEMA.ROUTINES are as follows:

• SPECIFIC_NAME: The name of the stored procedure or function

• ROUTINE_CATALOG: Always NULL

• ROUTINE_SCHEMA: The name of the database to which the procedure is tied

• ROUTINE_NAME: Same as SPECIFIC_NAME

• ROUTINE_TYPE: Either PROCEDURE or FUNCTION

• DTD_IDENTIFIER: For functions, returns the complete data type definition of the tion, otherwise NULL for procedures

func-• ROUTINE_BODY: Shows the language in which the procedure is written Currently, only thevalue SQL appears, but in future versions of MySQL, other extension languages may beused to write procedures

• ROUTINE_DEFINITION: For procedures, shows either the whole procedure definition, orfor long procedures, a truncated part of the definition

• EXTERNAL_NAME: Always NULL, because all stored procedures in MySQL are kept internal

to the database

• EXTERNAL_LANGUAGE: Again, always NULL

• PARAMETER_STYLE: Currently, only the value SQL appears for this column

• IS_DETERMINISTIC: Either YES or NO Shows whether the stored procedure or functionwill return the same value for the same passed input parameters

• SQL_DATA_ACCESS: Any of NO SQL, CONTAINS SQL, READS SQL DATA, or MODIFIES SQL DATA

See Chapter 9 for an explanation of these various values

Trang 26

• SQL_PATH: Always NULL.

• SECURITY_TYPE: Either DEFINER or INVOKER, depending on what type of security modelwas used during creation Again, for more information check out Chapter 9

• CREATED: Timestamp of when the procedure or function was created

• LAST_ALTERED: Timestamp of the last alteration to the procedure or function

• SQL_MODE: Shows the sql_mode server variable setting that was in effect at the time the

procedure was created This is done to ensure that the procedure is always run underthe same mode as when it was created

• ROUTINE_COMMENT: Any comment issued at procedure creation time.

• DEFINER: User who created the procedure in user@host format.

There’s no SHOW command equivalent for the data contained in INFORMATION_SCHEMA.ROUTINES However, the mysql.proc system table contains all the information available in the view

INFORMATION_SCHEMA.VIEWS

The INFORMATION_SCHEMA.VIEWS view details information about the views created on the server.Listing 21-8 shows a DESCRIBE and a simple SELECT displaying a test view created for illustra-tion purposes For more information on views, check out Chapter 10

6 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.VIEWS \G;

*************************** 1 row ***************************

TABLE_CATALOG: NULLTABLE_SCHEMA: testTABLE_NAME: UserPassVIEW_DEFINITION: select `test`.`http_auth`.`username` AS `username`, \

`test`.`http_auth`.`pass` AS `pass` from `test`.`http_auth`

CHECK_OPTION: NONEIS_UPDATABLE: YES

1 row in set (0.04 sec)

Trang 27

The fields contained in INFORMATION_SCHEMA.VIEWS are as follows:

• TABLE_CATALOG: Always NULL

• TABLE_SCHEMA: Database on which the view operates

• TABLE_NAME: Name of the view

• VIEW_DEFINITION: Complete definition of the view

• CHECK_OPTION: Either NONE, LOCAL, or CASCADE, depending on the value of the WITH CHECK ➥

OPTIONdone during view creation See Chapter 10 for details

• IS_UPDATABLE: Either YES or NO, depending on whether the view supports updating

As you can see, Listing 21-8 shows a simple view, called UserPass, in the test schema,which simply outputs the username and password columns from the http_auth table The

INFORMATION_SCHEMA.VIEWSview provides useful information about whether the view is

updat-able and its checking options There is no equivalent SHOW command, though the mysql.views

system table stores all the basic information displayed here

INFORMATION_SCHEMA.CHARACTER_SETS

The INFORMATION_SCHEMA.CHARACTER_SETS view shows the available character sets on the

data-base server Listing 21-9 shows a DESCRIBE and limited SELECT on the view

4 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.CHARACTER_SETS LIMIT 5;

+ -+ -+ -+ -+

| CHARACTER_SET_NAME | DEFAULT_COLLATE_NAME | DESCRIPTION | MAXLEN |

+ -+ -+ -+ -+

| dec8 | dec8_swedish_ci | DEC West European | 1 |

| cp850 | cp850_general_ci | DOS West European | 1 |

| hp8 | hp8_english_ci | HP West European | 1 |

| koi8r | koi8r_general_ci | KOI8-R Relcom Russian | 1 |

| latin1 | latin1_swedish_ci | ISO 8859-1 West European | 1 |

+ -+ -+ -+ -+

5 rows in set (0.00 sec)

Trang 28

The fields contained in INFORMATION_SCHEMA.CHARACTER_SETS are as follows:

• CHARACTER_SET_NAME: Name of the character set

• DEFAULT_COLLATION_NAME: Name of the default collation for this character set See thefollowing section, “INFORMATION_SCHEMA.COLLATIONS.”

• DESCRIPTION: Description of the character set.

• MAXLEN: Shows the number of bytes used to store a single character in the set.

This view isn’t the most useful in the world, but the extension field MAXLEN can come inhandy when you want to get a list of character sets needing more than 1 byte to store characters

Note The SHOW CHARACTER SETcommand contains equivalent information to the INFORMATION_SCHEMA.CHARACTER_SETSview

6 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.COLLATIONS LIMIT 5;

5 rows in set (0.00 sec)

Trang 29

The fields contained in INFORMATION_SCHEMA.COLLATIONS are as follows:

• COLLATION_NAME: Name of the collation

• CHARACTER_SET_NAME: Name of the character set to which the collation applies

• ID: A numeric identifier for the collation.

• IS_DEFAULT: Either YES or NO, indicating whether this collation is the server default for

this character set

• IS_COMPILED: Either YES or blank Indicates whether the server has been compiled with

The INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY view shows the relation

between character sets and collations Listing 21-11 shows a DESCRIBE and a simple SELECT

from the view

2 rows in set (0.01 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.COLLATION_CHARACTER_SET_APPLICABILITY

Trang 30

This view isn’t terribly useful, and merely represents the first two columns of the INFORMATION_SCHEMA.COLLATIONSview.

INFORMATION_SCHEMA.SCHEMA_PRIVILEGES

The INFORMATION_SCHEMA.SCHEMA_PRIVILEGES table houses the database privileges on the

server This view is not part of the ANSI standard, and is provided so that a common interface

can be used to gather information from the mysql.db system table for privileges associatedwith the database Because MySQL tracks a separate level of permission at the database level,this view was added as a complement to the TABLE_PRIVILEGES and COLUMN_PRIVILEGES stan-dard views Listing 21-12 shows a DESCRIBE and a simple SELECT from the view

5 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.SCHEMA_PRIVILEGES LIMIT 5;

+ -+ -+ -+ -+ -+

| GRANTEE | TABLE_CATALOG | TABLE_SCHEMA | PRIVILEGE_TYPE | IS_GRANTABLE |

+ -+ -+ -+ -+ -+

| ''@'%' | NULL | test | SELECT | NO |

| ''@'%' | NULL | test | INSERT | NO |

| ''@'%' | NULL | test | UPDATE | NO |

| ''@'%' | NULL | test | DELETE | NO |

| ''@'%' | NULL | test | CREATE | NO |

+ -+ -+ -+ -+ -+

5 rows in set (0.01 sec)

The fields contained in INFORMATION_SCHEMA.SCHEMA_PRIVILEGES are as follows:

• GRANTEE: Shows the 'user'@'host' format for the user having this database access.

• TABLE_CATALOG: Always NULL.

• TABLE_SCHEMA: Shows the database for which the user has been granted access.

• PRIVILEGE_TYPE: Any of the standard privileges on a MySQL system dealing with

database-level permissions

• IS_GRANTABLE: Either YES or NO Indicates whether the WITH GRANT OPTION was used in

assigning access permissions

Trang 31

The advantage of using this view over the mysql.db system table is that the SCHEMA_

PRIVILEGESview shows a normalized version of the grant information, with each privilege

provided in a separate row entry However, unfortunately the User and Host columns of the

mysql.dbtable are combined in the view as the GRANTEE column There’s no equivalent SHOW

command for this operation

INFORMATION_SCHEMA.USER_PRIVILEGES

Like the previous view, INFORMATION_SCHEMA.USER_PRIVILEGES is not part of the ANSI standard

It shows information pertaining to the global privileges of the system users Listing 21-13

shows a DESCRIBE and a simple SELECT from the view

4 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.USER_PRIVILEGES LIMIT 5;

+ -+ -+ -+ -+

| GRANTEE | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |

+ -+ -+ -+ -+

| 'root'@'localhost' | NULL | SELECT | YES |

| 'root'@'localhost' | NULL | INSERT | YES |

| 'root'@'localhost' | NULL | UPDATE | YES |

| 'root'@'localhost' | NULL | DELETE | YES |

| 'root'@'localhost' | NULL | CREATE | YES |

+ -+ -+ -+ -+

5 rows in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.USER_PRIVILEGES are as follows:

• GRANTEE: Again, the 'user'@'host' format for the privileged user.

• TABLE_CATALOG: Always NULL.

• PRIVILEGE_TYPE: Any of the MySQL standard global privilege types.

• IS_GRANTABLE: Either YES or NO Was this user given the right to assign similar privileges

using the WITH GRANT OPTION during creation?

Trang 32

Again, the advantage here is that privileges are normalized to appear as separate rowentries There’s no SHOW command equivalent, but the information appearing in the viewcomes from the mysql.user system table, which stores the information in a different, non-normalized layout.

INFORMATION_SCHEMA.TABLE_PRIVILEGES

The INFORMATION_SCHEMA.TABLE_PRIVILEGES view is an ANSI standard view It displays

informa-tion about the user’s table-level MySQL privileges Listing 21-14 shows a DESCRIBE and a simpleSELECTfor a mock user having limited access to the http_auth table in the test schema

6 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.TABLE_PRIVILEGES

-> LIMIT 2 \G

*************************** 1 row ***************************

GRANTEE: 'mkruck'@'localhost'TABLE_CATALOG: NULL

TABLE_SCHEMA: ToyStoreTABLE_NAME: CustomerPRIVILEGE_TYPE: SELECT

IS_GRANTABLE: NO

*************************** 2 row ***************************

GRANTEE: 'mkruck'@'localhost'TABLE_CATALOG: NULL

TABLE_SCHEMA: ToyStoreTABLE_NAME: CustomerPRIVILEGE_TYPE: INSERT

IS_GRANTABLE: NO

2 rows in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.TABLE_PRIVILEGES are as follows:

• GRANTEE: Again, the user in a 'user'@'host' format

• TABLE_CATALOG: Always NULL

Trang 33

• TABLE_SCHEMA: Name of the database housing the table.

• TABLE_NAME: Name of the table

• PRIVILEGE_TYPE: Any of the MySQL table-level privileges available to the user

• IS_GRANTABLE: Either YES or NO, depending on whether the WITH GRANT OPTION was used

Finally, the INFORMATION_SCHEMA.COLUMN_PRIVILEGES view is an ANSI standard view that shows

grant information at the column level Listing 21-15 shows a DESCRIBE and a simple SELECT

from the view

7 rows in set (0.00 sec)

mysql> SELECT * FROM INFORMATION_SCHEMA.COLUMN_PRIVILEGES \G

*************************** 1 row ***************************

GRANTEE: 'test_user2'@'localhost'TABLE_CATALOG: NULL

TABLE_SCHEMA: testTABLE_NAME: http_authCOLUMN_NAME: uidPRIVILEGE_TYPE: UPDATE

IS_GRANTABLE: NO

*************************** 2 row ***************************

GRANTEE: 'test_user2'@'localhost'TABLE_CATALOG: NULL

TABLE_SCHEMA: testTABLE_NAME: http_auth

Trang 34

COLUMN_NAME: usernamePRIVILEGE_TYPE: UPDATE

IS_GRANTABLE: NO

2 rows in set (0.00 sec)

The fields contained in INFORMATION_SCHEMA.COLUMN_PRIVILEGES are as follows:

• GRANTEE: The user in 'user'@'host' format

• TABLE_CATALOG: Always NULL

• TABLE_SCHEMA: Name of the database housing the table

• TABLE_NAME: Name of the table

• COLUMN_NAME: Name of the column

• PRIVILEGE_TYPE: Any of the MySQL column-level privileges available to the user

• IS_GRANTABLE: Either YES or NO, depending on whether the WITH GRANT OPTION was used

in assignment of privileges

Again, the results from the view show a mixed combination of the results from SHOW GRANTSand SHOW FULL COLUMNS, but in a normalized output Internally, the view is pulling from themysql.columns_privsystem table

Usage Examples

Now that you’re familiar with the INFORMATION_SCHEMA views, we’re going to take you a step further than simple SELECTs, and create some examples that should highlight the power andflexibility of this new interface We’ll work through the following examples:

• How to gather selectivity numbers on indexes

• How to summarize table sizes by engine

Example 1: Gathering Selectivity Numbers on Indexes

In the first part of the book, you learned about the importance of knowing the selectivity ofyour indexes, and you should understand how a low selectivity may lead to poor performance

of certain queries using your indexes In this example, we’ll create a SQL script that looks atthe INFORMATION_SCHEMA views and outputs the selectivity numbers for each of your indexes.The goal of our script is as follows:

• Limit results only to indexes with a selectivity lower than 1.0 Index selectivity of 1.0means that the index is unique We’re not interested in identifying unique indexes, asthey’re generally not performance problems

• Sort the results based on the lowest selectivity to the highest Remember, the selectivity

of an index can be viewed as the number of unique values in the index divided by thetotal number of entries in the index

Listing 21-16 shows our script

Trang 35

Listing 21-16.ShowIndexSelectivity.sql

SELECT

t.TABLE_SCHEMA, t.TABLE_NAME, s.INDEX_NAME, s.COLUMN_NAME, s.SEQ_IN_INDEX, (

SELECT MAX(SEQ_IN_INDEX) FROM INFORMATION_SCHEMA.STATISTICS s2WHERE s.TABLE_SCHEMA = s2.TABLE_SCHEMAAND s.TABLE_NAME = s2.TABLE_NAMEAND s.INDEX_NAME = s2.INDEX_NAME) AS "COLS_IN_INDEX"

AND t.TABLE_ROWS > 10AND s.CARDINALITY IS NOT NULLAND (s.CARDINALITY / IFNULL(t.TABLE_ROWS, 0.01)) < 1.00ORDER BY t.TABLE_SCHEMA, t.TABLE_NAME, s.INDEX_NAME, "SEL %" \G

Here we see the true power of the INFORMATION_SCHEMA interface This would have beenimpossible to do with a single SQL SELECT before Instead, to get the same information, we

would have had to use a scripting language to make multiple calls to SHOW INDEX and SHOW ➥

TABLE STATUS, combining the results into a table format In the ShowIndexSelectivity script,

we use a correlated scalar subquery to find the total number of columns in the index (see

Chapter 8) We then join the STATISTICS and TABLES views to get all the information we need,

and use a calculated column to output the selectivity percentage for the Index part

Listing 21-17 shows the output of our script when run against a small sample databasecontaining some Job (as in Career) data tables

Listing 21-17.Output from ShowIndexSelectivity

mysql> source ShowIndexSelectivity.sql

*************************** 1 row ***************************

TABLE_SCHEMA: jobs

TABLE_NAME: JobINDEX_NAME: EmployerExpiresOnCOLUMN_NAME: Employer

SEQ_IN_INDEX: 1

COLS_IN_INDEX: 2

Trang 36

CARD: 31ROWS: 56895SEL %: 0.05

*************************** 2 row ***************************TABLE_SCHEMA: jobs

TABLE_NAME: JobINDEX_NAME: EmployerExpiresOnCOLUMN_NAME: ExpiresOn

SEQ_IN_INDEX: 2

COLS_IN_INDEX: 2

CARD: 49ROWS: 56895SEL %: 0.09

*************************** 3 row ***************************TABLE_SCHEMA: jobs

TABLE_NAME: JobINDEX_NAME: ExpiresOnLocationCOLUMN_NAME: Location

SEQ_IN_INDEX: 2

COLS_IN_INDEX: 2

CARD: 28447ROWS: 56895SEL %: 50.00

*************************** 4 row ***************************TABLE_SCHEMA: jobs

TABLE_NAME: JobINDEX_NAME: ExpiresOnLocationCOLUMN_NAME: ExpiresOn

SEQ_IN_INDEX: 1

COLS_IN_INDEX: 2

CARD: 38ROWS: 56895SEL %: 0.07 omitted

*************************** 13 row ***************************TABLE_SCHEMA: jobs

TABLE_NAME: EmployerRegionINDEX_NAME: PRIMARYCOLUMN_NAME: EmployerSEQ_IN_INDEX: 1

COLS_IN_INDEX: 2

CARD: 9ROWS: 495SEL %: 1.82

*************************** 14 row ***************************TABLE_SCHEMA: jobs

TABLE_NAME: JobSeekerJob

Trang 37

INDEX_NAME: PRIMARYCOLUMN_NAME: JobSeekerSEQ_IN_INDEX: 1

COLS_IN_INDEX: 3

CARD: 7687ROWS: 23062SEL %: 33.33

14 rows in set (0.47 sec)

Tip In Listing 21-17, you see an example of using the MySQL client sourcecommand, which simply

takes a filename parameter and executes the SQL source in the file

It’s important to recognize here that the STATISTICS.CARDINALITY field contains the

num-ber of unique entries for the current column and all columns in the index of a lower ordinal

position This means that the value returned for the second column in a three-part index

includes the total number of unique tuples, or entries, for all combinations of the first and

second index part This is tracked in this way because you can only use an index if all parts

of the index to the left of the current column are used in a WHERE or ON condition

In the preceding results, what have we identified for the Job table? It seems that theEmployerExpiresOn index, which is a two-part index comprised of the Employer and ExpiresOn

columns of the Job table, has extremely low selectivity for both parts of the index keys This

query has shown us an index that, more than likely, the optimizer won’t use, because the

distribution of values is so sparse

Example 2: Summarizing Table Sizes by Engine

In our second example, we want to display a report that does the following:

• Summarizes the total size, in megabytes, of all our database tables, grouped by storageengine

• Shows a running total size We’ll use our knowledge of running totals from Chapter 8

Listing 21-18 shows the EngineStorageSummary.sql script

Listing 21-18.EngineStorageSummary.sql

SELECT

t1.ENGINE, t1.SIZE_IN_MB / (1024 * 1024) AS "ENGINE MB"

, SUM(t2.SIZE_IN_MB) / (1024 * 1024) AS "Total MB"

FROM(SELECT ENGINE, SUM(DATA_LENGTH) AS "SIZE_IN_MB"

FROM INFORMATION_SCHEMA.TABLESWHERE ENGINE IS NOT NULL

Trang 38

GROUP BY ENGINE) as t1

INNER JOIN (

SELECT ENGINE, SUM(DATA_LENGTH) AS "SIZE_IN_MB"

FROM INFORMATION_SCHEMA.TABLESWHERE ENGINE IS NOT NULLGROUP BY ENGINE

) as t2

ON t1.ENGINE >= t2.ENGINEGROUP BY t1.ENGINE;

Here, we’ve demonstrated the use of running sum calculations by joining two identicalderived tables using the >= operator The outermost SELECT statement simply divides the sumand the running sum by the (1024 * 1024) constant to produce the storage needed in terms ofmegabytes Listing 21-19 shows the result on our test system

Listing 21-19.Results of EngineStorageSummary.sql

mysql> source EngineStorageSummary.sql

3 rows in set (0.10 sec)

Note that the MEMORY engine doesn’t take up any storage space; everything is in RAM.Although these are simple examples of what can be done with the INFORMATION_SCHEMAviews, we hope they illustrate the power and flexibility of this new standards interface

Summary

In this final chapter, you’ve learned about one of the newest features of the MySQL 5 server:INFORMATION_SCHEMA You were introduced to some of the advantages of using this virtual database for reviewing metadata about your database objects, most notably the benefits ofstandardization and the ability to use SELECT to view metadata We detailed the fields available

in each of the views in INFORMATION_SCHEMA Afterwards, we demonstrated how valuable thevirtual database interface can be through two examples that wouldn’t previously have beenpossible in a single SELECT statement

Because this is a new feature, be sure to check http://www.mysql.com in case newcolumns or views become available We hope that you’ll take some time to experiment withthe INFORMATION_SCHEMA views, and create some of your own scripts summarizing the meta-data stored in MySQL

Ngày đăng: 08/08/2014, 20:21

TỪ KHÓA LIÊN QUAN