MySQL Locking

After experimenting a bit with MySQL locking today, I thought I’d make a note of what I’d discovered:

To create a lock, you need to use:

<code>LOCK TABLES table1 [READ |WRITE], table2 [READ |WRITE]</code>

READ is used to stop other people changing the table while you read from it. WRITE is used to stop other people reading the table while you write to it.

Once you have issued a LOCK TABLES statement, you will not have access to any tables you didn’t include.

When you have finished, you can issue the UNLOCK TABLES command.

The lock remains until you issue the UNLOCK TABLES command, your session ends, you start a transaction or your client is disconnected.

The MySQL locking mechanism is no use if you need to lock something between PHP requests, unless you have a separate process running persistently to maintain the connection to the database.

If you find that after rebooting your MySQL slave it stops replicating with the master and you see the “Failed to open the relay log” error in the logs it is probably caused by MySQL putting it’s relay logs in /var/run by default, which gets cleared out on boot.

To fix this, you need to change the location MySQL uses for the logging by adding the following line to the [mysqld] section of /etc/my.cnf

relay-log = /var/lib/mysql/relay-bin

Then edit /var/lib/mysql/ to point to the first new relay log (leaving the master information the same.

/var/lib/mysql/relay-bin.000001 1 mysql-bin.12345 123456789

Then from the mysql prompt start the slave:


(Source: Arjen’s Journal)

Make sure that expire_logs_days is set to ensure that log rotation takes place