Tài liệu MySQL Administrator''''s Bible- P8 doc

50 384 0
Tài liệu MySQL Administrator''''s Bible- P8 doc

Đ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

MySQL Views 8 Note that updating the view presents a logical error. Even if Benjamin had privileges to the base tables, updating the view would generate no warning or error, but produces incorrect results. Changing a View Definition There are two ways to change a view. One method has already been discussed — using the CREATE OR REPLACE when defining a view. In addition, MySQL has an ALTER VIEW command. ALTER VIEW works much like ALTER TABLE.TheSELECT statement that defines the view must always be included in the ALTER VIEW statement, even if that part of the view definition is not being modified. You may have noticed that in the CREATE VIEW statement, four different clauses may come between the words CREATE and VIEW: CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER} ] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION] Similarly, the syntax of the ALTER VIEW statement is: ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER} ] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION] Only the view’s definer or a user with the SUPER privilege can ALTER aview. Replication and Views In both row- and statement-based replication, MySQL treats a view the same way it treats a base table. In statement-based replication, CREATE VIEW, ALTER VIEW,andDROP VIEW statements are written to the binary log, and thus replicated. In row-based replication, the underlying data is replicated. The replicate-do-table and replicate-ignore-table replication options are applied to views and tables in both statement- and row-based replication, with the following outcomes: 317 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part II Developing with MySQL ■ A view that matches a replicate-do-table pattern will be written to the binary log, and thus replicated. ■ A view that matches a replicate-ignore-table pattern will not be written to the binary log, and thus not be replicated. ■ replicate-do-table and replicate-ignore-table patterns match the object name only. Therefore, those options will only be applied to views matching the pattern — even if the view references a matching table name. Summary In this chapter, we have described: ■ How to create, change, and drop views ■ Invalid SELECT statements in view definitions ■ Using views to limit field and row data for security purposes ■ How views can simplify and abstract queries ■ Performance implications of views ■ Using views as check constraints ■ How to update underlying base tables using an updatable view ■ Reasons a view may not be updatable ■ Logical errors that may occur when updating data using an updatable view ■ How replication handles views 318 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Transactions in MySQL IN THIS CHAPTER Understanding ACID compliance Using transactional statements Using isolation levels Explaining locking and deadlocks Recovering MySQL transactions W hen reading about relational database management systems (RDBMSs), you will see the terms transaction and ACID compliance.Atransaction is a set of SQL statements that are executed as if they were one statement. For a transaction to be finished and save data changes permanently, all the statements in the transaction have to be completed. If a transaction is not completed for any reason, the changes to the dataset that the transaction already made are removed, placing the database in its original state before the transaction began. A transaction is a transaction only if it is ACID-compliant.ACIDisan acronym that stands for atomicity, consistency, isolation, and durability. A proper implementation of these properties guarantees reliable processing of database transactions. The properties of ACID are explained in detail in the next section. To begin understanding what transactions are and why they are important, it will be helpful to walk through an example of how transactions are used. The classic transaction example is the database system used by a bank. Consider the following situation: Ziesel wants to move $1,000 from her checking account to the checking account of her neighbor Hudson, who is selling Ziesel his car. If Ziesel has an account id of 145356 and Hudson has an account id of 118254, the following two SQL statements might be used to accomplish this bank transaction: UPDATE checking SET balance = balance - 1000 WHERE id = 145356; UPDATE checking SET balance = balance + 1000 WHERE id = 118254; 319 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part II Developing with MySQL The inherent problem with this is that it takes two statements to accomplish the goal of moving the money from one account to another. What happens if the server experiences a system failure between execution of the first and second statement? The $1000 is lost somewhere — poor Ziesel is left with $1000 less in her checking account and Hudson has the same amount of money as when things started. To keep this situation from happening, a transactional wrapper is used. This tells the database server that unless all the statements are completed the results of the statements should not be savedtothedatabase.Todothis: START TRANSACTION; UPDATE checking SET balance = balance - 1000 WHERE id = 145356; UPDATE savings SET balance = balance + 1000 WHERE id = 118254; COMMIT; The START TRANSACTION and COMMIT statements are wrapped around the statements to denote the beginning and end of a transaction. In MySQL, transactions can start with START TRANSAC- TION , and transactions are ended with COMMIT (successful transaction) or ROLLBACK (indicating the data should be reset back to the original). See the next section, ‘‘Using Transactional State- ments,’’ for more information. Revisiting the scenario of the server experiencing a system failure while executing the second UPDATE statement, this time after the server starts up it will realize the transaction was not finished and issue a ROLLBACK, which resets any changes left unfinished that were made before system failure. Wrapping both statements in a transaction means that either both statements happen, or neither statement happens. If there is a failure, Ziesel gets her money back and the transaction can be executed again. mysqld supports multiple storage engines. Storage engines are the server components that are used to create and support database tables. These storage engines have dif- ferent characteristics. Some of them do not support transactions, including the MyISAM storage engine. However, there are storage engines that do support transactions, including the InnoDB and Falcon storage engines. There is more information about storage engines in Chapter 11, ‘‘Stor- age Engines.’’ Understanding ACID Compliance As previously mentioned, ACID compliance is an acronym for the characteristics of a transac- tionally safe database. Enforcing atomicity, consistency, isolation, and durability is what ensures that a series of statements is indeed a transaction. That is, it ensures that a series of statements either completes with the resulting changes reliably stored, or, if interrupted, the set of state- ments is rolled back to where it began so the database is not changed. 320 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Transactions in MySQL 9 Atomicity Atomicity refers to concept that either all of the statements inside a transaction are completed, or none of them are performed. As with the previous example, in a banking system, the transfer of funds can be completed or it could fail. However, the transfer of funds is not allowed to fail leaving the work half-done. The atomicity property guarantees that one account will not be debited unless the other account is credited. Each transaction is said to be atomic (indivisible) — even though there are actually two statements, they act as if they are one statement. If any part of the transaction fails, the entire transaction must fail. Consistency The consistency property ensures that the database moves from one consistent state to another. If the server were to fail while executing the transfer of money from Ziesel’s account to Hud- son’s account, the database would be left in an inconsistent state. The only way to resolve this inconsistency is to undo changes already made. Before a transaction begins the database should be in a consistent state. Once the transaction either completes successfully or is rolled back the database should still be in a consistent state. In a transactional system (ACID-compliant by definition), if one or more statements in the transaction do not succeed, the entire transaction must be rolled back to a consistent state. If a transaction is successful, the database moves from one consistent state to another. Isolation The isolation property specifies that data being modified for one transaction cannot be viewed or modified by a second transaction until the completion of the first transaction. This is impor- tant to support concurrent execution of queries, which is critical in any modern database sys- tem. With isolation, separate transactions can run at the same time without compromising the consistency of the data. In MySQL, the level of isolation that transactions have can be config- ured. The meanings of different isolation levels and how to set the isolation level are discussed in more detail in the section ‘‘Using Isolation Levels’’ later in this chapter. Durability Durability describes the principle that once a transaction has been successfully completed, the results are recorded by the database server permanently. After this point the transaction is complete, and the data changes must survive even if the database or operating system fails. This is important, because modern-day operating systems do not always perform operations imme- diately. If there is an operating system failure between the time that a transaction successfully completes and the time the data is actually written to the disk permanently, the database has marked the transaction as complete but the data has not been changed appropriately. 321 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part II Developing with MySQL Many databases implement durability by writing complete transactions into a log that can be played back to re-create the database state right before a failure. A transaction is considered successfully committed only after it has been written to this log, called a redo log. Using Transactional Statements Now that you have some theory under your belt it is time to see how you actually work with transactions in MySQL. It has been touched on previously, but it is important to understand that with MySQL you have a choice of the type of storage engine to use for each table. To utilize transactions the storage engine used for each table involved in the transaction must support transactions. Failure to do so will lead to inconsistent results. Five SQL commands are used to work with transactions. We cover each of these in the following subsections. BEGIN, BEGIN WORK, and START TRANSACTION BEGIN, BEGIN WORK,andSTART TRANSACTION all can be used to start a transaction. Techni- cally, both BEGIN and BEGIN WORK are aliases of the START TRANSACTION command. If you execute any of these statements, it causes an implicit COMMIT of any previous pending transactions that are open by the client thread. In addition, if you had previously executed a LOCK TABLES statement the tables will be unlocked just as though you had issued an UNLOCK TABLES statement. COMMIT The COMMIT statement is used to signify the end of a transaction. At this point all changes to the tables are considered to be durable and will survive server failure. ROLLBACK ROLLBACK is used to roll back a transaction to either the state it was in before execution of the transaction or to a certain point prior to where execution is currently occurring. This point is called the SAVEPOINT. Some statements cannot be rolled back, because they perform an implicit COMMIT when they complete. These include DDL (Data Definition Lan- guage) statements like CREATE DATABASE, CREATE TABLE, DROP DATABASE, DROP TABLE,andALTER TABLE. If you have issued a DDL statement early in a transaction and another statement fails, you cannot roll back the transaction by issuing the ROLL- BACK statement. Many of these statements also perform an implicit COMMIT when they begin, too. For the full, up-to-date list of statements that perform an implicit COMMIT,see http://dev.mysql.com/doc/refman/6.0/en/implicit-commit.html. 322 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Transactions in MySQL 9 Savepoints A savepoint is a defined point in a transaction. The SAVEPOINT statement is used to set a save- point with a name. The ROLLBACK TO SAVEPOINT statement is used to roll back the transac- tion to the named savepoint specified. Instead of rolling back all the changes in the transaction, ROLLBACK TO SAVEPOINT savepointname rolls back modifications to rows made in the cur- rent transaction after the savepoint at savepointname. The data is in the same state it was in at the time the savepoint was reached by the transaction. To remove the named savepoint from the set of defined savepoints in the current transaction, use the RELEASE SAVEPOINT command. Here is an example showing the use of SAVEPOINT and RELEASE SAVEPOINT: mysql> use test; Database changed mysql> DROP TABLE IF EXISTS trans_test; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> CREATE TABLE trans_test (id INT PRIMARY KEY AUTO_INCREMENT, -> name VARCHAR(8)) ENGINE=InnoDB; Query OK, 0 rows affected (0.12 sec) mysql> INSERT INTO trans_test (name) VALUES (’a’), (’b’); Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT id,name FROM trans_test; + + + | id | name | + + + |1|a | |2|b | + + + 2 rows in set (0.00 sec) mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) mysql> UPDATE trans_test SET name=’z’ WHERE id = 1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SAVEPOINT savepoint_one; Query OK, 0 rows affected (0.00 sec) mysql> UPDATE trans_test SET name=’y’ WHERE id = 2; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 323 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part II Developing with MySQL mysql> SELECT id,name FROM trans_test; + + + | id | name | + + + |1|z | |2|y | + + + 2 rows in set (0.00 sec) mysql> ROLLBACK TO SAVEPOINT savepoint_one; Query OK, 0 rows affected (0.00 sec) mysql> SELECT id,name FROM trans_test; + + + | id | name | + + + |1|z | |2|b | + + + 2 rows in set (0.00 sec) mysql> COMMIT; Query OK, 0 rows affected (0.03 sec) Notice that the first row still has a NAME field value of z, whereas the last row, whose NAME field value was changed to y, has reverted to l. AUTOCOMMIT The use of the AUTOCOMMIT statement is another way to work with transactions rather than the more traditional START TRANSACTION or BEGIN. To a transactional storage engine such as InnoDB or Falcon every statement is considered a transactional state- ment in itself if AUTOCOMMIT is enabled (AUTOCOMMIT = 1). The result of this is that if AUTOCOMMIT is enabled, which it is by default, mysqld wraps every statement with START TRANSACTION and COMMIT statements. However, if you explicitly start a transaction with START TRANSACTION, a new transaction is started and AUTOCOMMIT is off for the new transaction. After execution of a transaction using the START TRANSACTION and COMMIT commands mysqld reverts to the autocommit mode it was in before the transaction began. This can cause unpredictable and undesirable results. From our previous example of Ziesel and Hudson at the bank, here are the SQL statements we initially used to update the two accounts: UPDATE checking SET balance = balance - 1000 WHERE id = 145356; UPDATE checking SET balance = balance + 1000 WHERE id = 118254; 324 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Transactions in MySQL 9 If you have AUTOCOMMIT enabled (which it is by default), here is what mysqld actually executes: START TRANSACTION; UPDATE checking SET balance = balance - 1000 WHERE id = 145356; COMMIT; START TRANSACTION; UPDATE checking SET balance = balance + 1000 WHERE id = 118254; COMMIT; This ensures that each modification is actually committed to the database, performing everything that happens on COMMIT, including issuing a disk flush if the storage engine is configured to do so. Disabling AUTOCOMMIT (using SET AUTOCOMMIT=0) is equivalent to executing a START TRANSACTION statement for every statement in the session. You now have a transaction open that will not be closed until a COMMIT or ROLLBACK is issued. mysql> SELECT id,name FROM trans_test; + + + | id | name | + + + |1|z | |2|b | + + + 2 rows in set (0.00 sec) mysql> SET AUTOCOMMIT=0; Query OK, 0 rows affected (0.00 sec) mysql> UPDATE trans_test SET name=’a’ WHERE id=’1’; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> COMMIT; Query OK, 0 rows affected (0.06 sec) As you can see the SET AUTOCOMMIT=0 statement works just as a BEGIN or START TRANSACTION statement. After the COMMIT, a new transaction is started without needing to use START TRANSACTION, BEGIN,orBEGIN WORK. Using Isolation Levels Isolation levels determine how data is isolated among different transactions. If you begin a transaction, read a row from a table, change the row, read the same row from the table, and then commit, what do you see at each step? What does another transaction reading the 325 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part II Developing with MySQL same row see at each step? The exact nature of what is isolated and under what conditions is determined by the isolation level. In MySQL, the server can be set to a particular isolation level, and connections can also set their isolation level, overriding the global isolation level. For the purpose of defining isolation levels, we will describe the behavior when all connections have the same isolation level as the server. After describing each level, we go into detailed examples of each isolation level. MySQL supports the four standard isolation levels: ■ READ UNCOMMITTED — This setting allows all transactions to see all uncommitted changes, whether within their own transaction or in another transaction. These are called dirty reads — the data is said to be dirty because the change is not permanent yet. Queries inside one transaction are affected by uncommitted changes in another transaction. This is not desirable, and in fact violates ACID compliance. Setting the isolation level to READ UNCOMMITTED gets rid of transaction support — though you can still wrap transactions with START TRANSACTION, ROLLBACK,andCOMMIT, there is no isolation and thus your system is no longer transactional. ■ READ COMMITTED — Only data changed by committed transactions are visible to other transactions. However, within a transaction, dirty data can still be read. This means iden- tical queries within a transaction can return differing results. For example, if a transaction reads a row, changes the row, and reads the row again, both reads will produce different data, because the data was changed inside the transaction. Other connections will see only the unchanged data, until the transaction is committed. READ COMMITTED is the default isolation level for SQL Server and Oracle. ■ REPEATABLE READ — The default isolation level for MySQL is REPEATABLE READ.At the time of this writing, only the Falcon and InnoDB storage engines are transactional, so changing isolation levels only applies to transactions that query tables that use Falcon or InnoDB. Using the REPEATABLE READ isolation level, all reads within a transaction show the same data values, even if a second transaction has committed a data change while the first transaction was still running. If a transaction starts, reads a row, waits 60 seconds, and reads the same row again, both data reads will be the same — even if in those 60 seconds another transaction has changed and committed data. The first transaction has the same data when it repeats the read. Any transactions started after the data commit will see the new data. REPEATABLE READ may not seem like a good idea — after all, if the data changes, shouldn’t a transaction be aware of that? The problem is that a transaction may take different actions based on the values of the data. Data values changing in the middle of a transaction may lead to unexpected consequences. Consider what would happen if the schema changed in the middle of a transaction, and the desired fields or tables cease to exist! ■ SERIALIZABLE —IntheSERIALIZABLE isolation level of MySQL, data reads are implicitly run with a read lock (the LOCK IN SHARE MODE clause; see the example in the 326 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... watermark MySQL Server Tuning T here are four main areas of a server running mysqld that the database administrator can analyze and optimize for best performance These areas are SQL tuning, schema and index tuning, mysqld tuning, and operating system tuning SQL tuning and index optimizations are covered in Chapter 18 This chapter covers tuning mysqld for top performance In addition to tuning mysqld,... run the following: mysql> COMMIT; Query OK, 0 rows affected (0.00 sec) At this point your second connection now completes the update 342 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Transactions in MySQL Storage Engines and Locking ocking is implemented by both mysqld and particular storage engines Falcon and InnoDB implement row-level locking, and mysqld implements table-level... by starting mysqld with the low-priority-updates option, or by issuing: mysql> SET GLOBAL low_priority_updates=1; 340 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Transactions in MySQL Though this is a dynamic system variable, only new connections will use the new value To set all writes in a session as lower priorities than reads, use the following command: mysql> SET... level of your connection: mysql> SHOW SESSION VARIABLES LIKE ’tx_isolation’; + -+ + | Variable_name | Value | + -+ + | tx_isolation | READ-UNCOMMITTED | + -+ + 1 row in set (0.00 sec) mysql> SELECT @@session.tx_isolation; + + | @@session.tx_isolation | + + | READ-UNCOMMITTED | + + 1 row in set (0.00 sec) mysql> SELECT VARIABLE_NAME,... Chapter 4 for more details Lock acquisition behavior can also be controlled with the max_write_lock_count and concurrent_insert system variables The MySQL manual has this tip and many ideas on how to work around table locking issues at http://dev .mysql. com /doc/ refman/6.0/en/table-locking.html Page-level locks Page-level locking is when a memory page is locked This will lock a group of rows instead of... Part II Developing with MySQL + -+ + | VARIABLE_NAME | VARIABLE_VALUE | + -+ + | TX_ISOLATION | READ-UNCOMMITTED | + -+ + 1 row in set (0.07 sec) To see the isolation level for the server: mysql> SELECT @@global.tx_isolation; + -+ | @@global.tx_isolation | + -+ | REPEATABLE-READ | + -+ 1 row in set (0.00 sec) mysql> SHOW SESSION GLOBAL... of locking in Maria is unknown Note that storage engines that implement their own locking can also use the default mysqld implementation of table-level locking L Storage engines other than Falcon, InnoDB, and Maria can only use the mysqld implementation of table-level locking Recovering MySQL Transactions To be ACID-compliant, a database system must resolve situations where a transaction is interrupted... engine defines the exact redo log implementation When mysqld starts up after a crash, it checks and applies all redo logs This application of the redo logs provides the durability part of ACID compliance in transactional storage engines within MySQL Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 343 9 Part II Developing with MySQL Undo logs are used to roll back uncommitted... chapter covered how transactions work in MySQL Specifically, it covered: ■ The four parts of ACID compliance ■ How to use transactions in MySQL and interactions with AUTOCOMMIT ■ Isolation levels — Read Uncommitted, Read Committed, Repeatable Read, Serializable ■ MVCC 344 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Transactions in MySQL ■ Types of levels of locking ■ Deadlocks... Split-Merge on www.verypdf.com to remove this watermark 345 9 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Core MySQL Administration IN THIS PART Chapter 10 MySQL Server Tuning Chapter 11 Storage Engines Chapter 12 Caching in MySQL Chapter 13 Backups and Recovery Chapter 14 User Management Chapter 15 Partitioning Chapter 16 Logging and Replication Chapter 17 Measuring . COMMIT,see http://dev .mysql. com /doc/ refman/6.0/en/implicit-commit.html. 322 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Transactions in MySQL. SAVEPOINT: mysql& gt; use test; Database changed mysql& gt; DROP TABLE IF EXISTS trans_test; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql& gt; CREATE

Ngày đăng: 26/01/2014, 11:20

Mục lục

  • MySQL® Administrator's Bible

    • About the Authors

    • Contents at a Glance

    • Introduction

      • Who Should Read This Book

      • How This Book Is Organized

      • What’s on the Companion Website

      • Where To Go From Here

      • Part I: First Steps with MySQL

        • Chapter 1: Introduction to MySQL

          • MySQL Mission—Speed, Reliability, and Ease of Use

          • Chapter 2: Installing and Upgrading MySQL Server

            • Before Installation

            • MySQL Configuration Wizard on Windows

            • MySQL Post-Install Configuration on Unix

            • Windows PATH Variable Configuration

            • Chapter 3: Accessing MySQL

              • Accessing mysqld with Command-Line Tools

              • Part II: Developing with MySQL

                • Chapter 4: How MySQL Extends and Deviates from SQL

                  • Learning MySQL Language Structure

                  • Chapter 5: MySQL Data Types

                    • Looking at MySQL Data Types

                    • National Character String Types

                    • Binary Large Object String Types

                    • ENUM and SET Types

                    • Finding an Optimal Data Type for Existing Data

                    • Chapter 6: MySQL Index Types

                      • Looking at Keys and Indexes

                      • Using Indexes to Speed Up Lookups

Tài liệu cùng người dùng

Tài liệu liên quan